- Minor fixes for handling structure constants and array values that are not sdecls
[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 #define DEBUG_SDP_BLOCKS 0
21 #define DEBUG_TRIPLE_COLOR 0
22
23 #warning "FIXME boundary cases with small types in larger registers"
24 #warning "FIXME give clear error messages about unused variables"
25 #warning "FIXME properly handle multi dimensional arrays"
26 #warning "FIXME fix scc_transform"
27
28 /*  Control flow graph of a loop without goto.
29  * 
30  *        AAA
31  *   +---/
32  *  /
33  * / +--->CCC
34  * | |    / \
35  * | |  DDD EEE    break;
36  * | |    \    \
37  * | |    FFF   \
38  *  \|    / \    \
39  *   |\ GGG HHH   |   continue;
40  *   | \  \   |   |
41  *   |  \ III |  /
42  *   |   \ | /  / 
43  *   |    vvv  /  
44  *   +----BBB /   
45  *         | /
46  *         vv
47  *        JJJ
48  *
49  * 
50  *             AAA
51  *     +-----+  |  +----+
52  *     |      \ | /     |
53  *     |       BBB  +-+ |
54  *     |       / \ /  | |
55  *     |     CCC JJJ / /
56  *     |     / \    / / 
57  *     |   DDD EEE / /  
58  *     |    |   +-/ /
59  *     |   FFF     /    
60  *     |   / \    /     
61  *     | GGG HHH /      
62  *     |  |   +-/
63  *     | III
64  *     +--+ 
65  *
66  * 
67  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
68  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
69  *
70  *
71  * [] == DFlocal(X) U DF(X)
72  * () == DFup(X)
73  *
74  * Dominator graph of the same nodes.
75  *
76  *           AAA     AAA: [ ] ()
77  *          /   \
78  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
79  *         |
80  *        CCC        CCC: [ ] ( BBB, JJJ )
81  *        / \
82  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
83  *      |
84  *     FFF           FFF: [ ] ( BBB )
85  *     / \         
86  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
87  *   |
88  *  III              III: [ BBB ] ()
89  *
90  *
91  * BBB and JJJ are definitely the dominance frontier.
92  * Where do I place phi functions and how do I make that decision.
93  *   
94  */
95 static void die(char *fmt, ...)
96 {
97         va_list args;
98
99         va_start(args, fmt);
100         vfprintf(stderr, fmt, args);
101         va_end(args);
102         fflush(stdout);
103         fflush(stderr);
104         exit(1);
105 }
106
107 #define MALLOC_STRONG_DEBUG
108 static void *xmalloc(size_t size, const char *name)
109 {
110         void *buf;
111         buf = malloc(size);
112         if (!buf) {
113                 die("Cannot malloc %ld bytes to hold %s: %s\n",
114                         size + 0UL, name, strerror(errno));
115         }
116         return buf;
117 }
118
119 static void *xcmalloc(size_t size, const char *name)
120 {
121         void *buf;
122         buf = xmalloc(size, name);
123         memset(buf, 0, size);
124         return buf;
125 }
126
127 static void xfree(const void *ptr)
128 {
129         free((void *)ptr);
130 }
131
132 static char *xstrdup(const char *str)
133 {
134         char *new;
135         int len;
136         len = strlen(str);
137         new = xmalloc(len + 1, "xstrdup string");
138         memcpy(new, str, len);
139         new[len] = '\0';
140         return new;
141 }
142
143 static void xchdir(const char *path)
144 {
145         if (chdir(path) != 0) {
146                 die("chdir to %s failed: %s\n",
147                         path, strerror(errno));
148         }
149 }
150
151 static int exists(const char *dirname, const char *filename)
152 {
153         int does_exist = 1;
154         xchdir(dirname);
155         if (access(filename, O_RDONLY) < 0) {
156                 if ((errno != EACCES) && (errno != EROFS)) {
157                         does_exist = 0;
158                 }
159         }
160         return does_exist;
161 }
162
163
164 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
165 {
166         int fd;
167         char *buf;
168         off_t size, progress;
169         ssize_t result;
170         struct stat stats;
171         
172         if (!filename) {
173                 *r_size = 0;
174                 return 0;
175         }
176         xchdir(dirname);
177         fd = open(filename, O_RDONLY);
178         if (fd < 0) {
179                 die("Cannot open '%s' : %s\n",
180                         filename, strerror(errno));
181         }
182         result = fstat(fd, &stats);
183         if (result < 0) {
184                 die("Cannot stat: %s: %s\n",
185                         filename, strerror(errno));
186         }
187         size = stats.st_size;
188         *r_size = size +1;
189         buf = xmalloc(size +2, filename);
190         buf[size] = '\n'; /* Make certain the file is newline terminated */
191         buf[size+1] = '\0'; /* Null terminate the file for good measure */
192         progress = 0;
193         while(progress < size) {
194                 result = read(fd, buf + progress, size - progress);
195                 if (result < 0) {
196                         if ((errno == EINTR) || (errno == EAGAIN))
197                                 continue;
198                         die("read on %s of %ld bytes failed: %s\n",
199                                 filename, (size - progress)+ 0UL, strerror(errno));
200                 }
201                 progress += result;
202         }
203         result = close(fd);
204         if (result < 0) {
205                 die("Close of %s failed: %s\n",
206                         filename, strerror(errno));
207         }
208         return buf;
209 }
210
211 /* Long on the destination platform */
212 typedef unsigned long ulong_t;
213 typedef long long_t;
214
215 struct file_state {
216         struct file_state *prev;
217         const char *basename;
218         char *dirname;
219         char *buf;
220         off_t size;
221         char *pos;
222         int line;
223         char *line_start;
224         int report_line;
225         const char *report_name;
226         const char *report_dir;
227 };
228 struct hash_entry;
229 struct token {
230         int tok;
231         struct hash_entry *ident;
232         int str_len;
233         union {
234                 ulong_t integer;
235                 const char *str;
236         } val;
237 };
238
239 /* I have two classes of types:
240  * Operational types.
241  * Logical types.  (The type the C standard says the operation is of)
242  *
243  * The operational types are:
244  * chars
245  * shorts
246  * ints
247  * longs
248  *
249  * floats
250  * doubles
251  * long doubles
252  *
253  * pointer
254  */
255
256
257 /* Machine model.
258  * No memory is useable by the compiler.
259  * There is no floating point support.
260  * All operations take place in general purpose registers.
261  * There is one type of general purpose register.
262  * Unsigned longs are stored in that general purpose register.
263  */
264
265 /* Operations on general purpose registers.
266  */
267
268 #define OP_SDIVT      0
269 #define OP_UDIVT      1
270 #define OP_SMUL       2
271 #define OP_UMUL       3
272 #define OP_SDIV       4
273 #define OP_UDIV       5
274 #define OP_SMOD       6
275 #define OP_UMOD       7
276 #define OP_ADD        8
277 #define OP_SUB        9
278 #define OP_SL        10
279 #define OP_USR       11
280 #define OP_SSR       12 
281 #define OP_AND       13 
282 #define OP_XOR       14
283 #define OP_OR        15
284 #define OP_POS       16 /* Dummy positive operator don't use it */
285 #define OP_NEG       17
286 #define OP_INVERT    18
287                      
288 #define OP_EQ        20
289 #define OP_NOTEQ     21
290 #define OP_SLESS     22
291 #define OP_ULESS     23
292 #define OP_SMORE     24
293 #define OP_UMORE     25
294 #define OP_SLESSEQ   26
295 #define OP_ULESSEQ   27
296 #define OP_SMOREEQ   28
297 #define OP_UMOREEQ   29
298                      
299 #define OP_LFALSE    30  /* Test if the expression is logically false */
300 #define OP_LTRUE     31  /* Test if the expression is logcially true */
301
302 #define OP_LOAD      32
303 #define OP_STORE     33
304 /* For OP_STORE ->type holds the type
305  * RHS(0) holds the destination address
306  * RHS(1) holds the value to store.
307  */
308
309 #define OP_NOOP      34
310
311 #define OP_MIN_CONST 50
312 #define OP_MAX_CONST 59
313 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
314 #define OP_INTCONST  50
315 /* For OP_INTCONST ->type holds the type.
316  * ->u.cval holds the constant value.
317  */
318 #define OP_BLOBCONST 51
319 /* For OP_BLOBCONST ->type holds the layout and size
320  * information.  u.blob holds a pointer to the raw binary
321  * data for the constant initializer.
322  */
323 #define OP_ADDRCONST 52
324 /* For OP_ADDRCONST ->type holds the type.
325  * MISC(0) holds the reference to the static variable.
326  * ->u.cval holds an offset from that value.
327  */
328
329 #define OP_WRITE     60 
330 /* OP_WRITE moves one pseudo register to another.
331  * RHS(0) holds the destination pseudo register, which must be an OP_DECL.
332  * RHS(1) holds the psuedo to move.
333  */
334
335 #define OP_READ      61
336 /* OP_READ reads the value of a variable and makes
337  * it available for the pseudo operation.
338  * Useful for things like def-use chains.
339  * RHS(0) holds points to the triple to read from.
340  */
341 #define OP_COPY      62
342 /* OP_COPY makes a copy of the psedo register or constant in RHS(0).
343  */
344 #define OP_PIECE     63
345 /* OP_PIECE returns one piece of a instruction that returns a structure.
346  * MISC(0) is the instruction
347  * u.cval is the LHS piece of the instruction to return.
348  */
349 #define OP_ASM       64
350 /* OP_ASM holds a sequence of assembly instructions, the result
351  * of a C asm directive.
352  * RHS(x) holds input value x to the assembly sequence.
353  * LHS(x) holds the output value x from the assembly sequence.
354  * u.blob holds the string of assembly instructions.
355  */
356
357 #define OP_DEREF     65
358 /* OP_DEREF generates an lvalue from a pointer.
359  * RHS(0) holds the pointer value.
360  * OP_DEREF serves as a place holder to indicate all necessary
361  * checks have been done to indicate a value is an lvalue.
362  */
363 #define OP_DOT       66
364 /* OP_DOT references a submember of a structure lvalue.
365  * RHS(0) holds the lvalue.
366  * ->u.field holds the name of the field we want.
367  *
368  * Not seen outside of expressions.
369  */
370 #define OP_VAL       67
371 /* OP_VAL returns the value of a subexpression of the current expression.
372  * Useful for operators that have side effects.
373  * RHS(0) holds the expression.
374  * MISC(0) holds the subexpression of RHS(0) that is the
375  * value of the expression.
376  *
377  * Not seen outside of expressions.
378  */
379 #define OP_LAND      68
380 /* OP_LAND performs a C logical and between RHS(0) and RHS(1).
381  * Not seen outside of expressions.
382  */
383 #define OP_LOR       69
384 /* OP_LOR performs a C logical or between RHS(0) and RHS(1).
385  * Not seen outside of expressions.
386  */
387 #define OP_COND      70
388 /* OP_CODE performas a C ? : operation. 
389  * RHS(0) holds the test.
390  * RHS(1) holds the expression to evaluate if the test returns true.
391  * RHS(2) holds the expression to evaluate if the test returns false.
392  * Not seen outside of expressions.
393  */
394 #define OP_COMMA     71
395 /* OP_COMMA performacs a C comma operation.
396  * That is RHS(0) is evaluated, then RHS(1)
397  * and the value of RHS(1) is returned.
398  * Not seen outside of expressions.
399  */
400
401 #define OP_CALL      72
402 /* OP_CALL performs a procedure call. 
403  * MISC(0) holds a pointer to the OP_LIST of a function
404  * RHS(x) holds argument x of a function
405  * 
406  * Currently not seen outside of expressions.
407  */
408 #define OP_VAL_VEC   74
409 /* OP_VAL_VEC is an array of triples that are either variable
410  * or values for a structure or an array.
411  * RHS(x) holds element x of the vector.
412  * triple->type->elements holds the size of the vector.
413  */
414
415 /* statements */
416 #define OP_LIST      80
417 /* OP_LIST Holds a list of statements, and a result value.
418  * RHS(0) holds the list of statements.
419  * MISC(0) holds the value of the statements.
420  */
421
422 #define OP_BRANCH    81 /* branch */
423 /* For branch instructions
424  * TARG(0) holds the branch target.
425  * RHS(0) if present holds the branch condition.
426  * ->next holds where to branch to if the branch is not taken.
427  * The branch target can only be a decl...
428  */
429
430 #define OP_LABEL     83
431 /* OP_LABEL is a triple that establishes an target for branches.
432  * ->use is the list of all branches that use this label.
433  */
434
435 #define OP_ADECL     84 
436 /* OP_DECL is a triple that establishes an lvalue for assignments.
437  * ->use is a list of statements that use the variable.
438  */
439
440 #define OP_SDECL     85
441 /* OP_SDECL is a triple that establishes a variable of static
442  * storage duration.
443  * ->use is a list of statements that use the variable.
444  * MISC(0) holds the initializer expression.
445  */
446
447
448 #define OP_PHI       86
449 /* OP_PHI is a triple used in SSA form code.  
450  * It is used when multiple code paths merge and a variable needs
451  * a single assignment from any of those code paths.
452  * The operation is a cross between OP_DECL and OP_WRITE, which
453  * is what OP_PHI is geneared from.
454  * 
455  * RHS(x) points to the value from code path x
456  * The number of RHS entries is the number of control paths into the block
457  * in which OP_PHI resides.  The elements of the array point to point
458  * to the variables OP_PHI is derived from.
459  *
460  * MISC(0) holds a pointer to the orginal OP_DECL node.
461  */
462
463 /* Architecture specific instructions */
464 #define OP_CMP         100
465 #define OP_TEST        101
466 #define OP_SET_EQ      102
467 #define OP_SET_NOTEQ   103
468 #define OP_SET_SLESS   104
469 #define OP_SET_ULESS   105
470 #define OP_SET_SMORE   106
471 #define OP_SET_UMORE   107
472 #define OP_SET_SLESSEQ 108
473 #define OP_SET_ULESSEQ 109
474 #define OP_SET_SMOREEQ 110
475 #define OP_SET_UMOREEQ 111
476
477 #define OP_JMP         112
478 #define OP_JMP_EQ      113
479 #define OP_JMP_NOTEQ   114
480 #define OP_JMP_SLESS   115
481 #define OP_JMP_ULESS   116
482 #define OP_JMP_SMORE   117
483 #define OP_JMP_UMORE   118
484 #define OP_JMP_SLESSEQ 119
485 #define OP_JMP_ULESSEQ 120
486 #define OP_JMP_SMOREEQ 121
487 #define OP_JMP_UMOREEQ 122
488
489 /* Builtin operators that it is just simpler to use the compiler for */
490 #define OP_INB         130
491 #define OP_INW         131
492 #define OP_INL         132
493 #define OP_OUTB        133
494 #define OP_OUTW        134
495 #define OP_OUTL        135
496 #define OP_BSF         136
497 #define OP_BSR         137
498 #define OP_RDMSR       138
499 #define OP_WRMSR       139
500 #define OP_HLT         140
501
502 struct op_info {
503         const char *name;
504         unsigned flags;
505 #define PURE   1
506 #define IMPURE 2
507 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
508 #define DEF    4
509 #define BLOCK  8 /* Triple stores the current block */
510         unsigned char lhs, rhs, misc, targ;
511 };
512
513 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
514         .name = (NAME), \
515         .flags = (FLAGS), \
516         .lhs = (LHS), \
517         .rhs = (RHS), \
518         .misc = (MISC), \
519         .targ = (TARG), \
520          }
521 static const struct op_info table_ops[] = {
522 [OP_SDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "sdivt"),
523 [OP_UDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "udivt"),
524 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
525 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
526 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
527 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
528 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
529 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
530 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
531 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
532 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
533 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
534 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
535 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
536 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
537 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
538 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
539 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
540 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
541
542 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
543 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
544 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
545 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
546 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
547 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
548 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
549 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
550 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
551 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
552 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
553 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
554
555 [OP_LOAD       ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "load"),
556 [OP_STORE      ] = OP( 0,  2, 0, 0, IMPURE | BLOCK , "store"),
557
558 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK, "noop"),
559
560 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
561 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE, "blobconst"),
562 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
563
564 [OP_WRITE      ] = OP( 0,  2, 0, 0, PURE | BLOCK, "write"),
565 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
566 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
567 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF, "piece"),
568 [OP_ASM        ] = OP(-1, -1, 0, 0, IMPURE, "asm"),
569 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
570 [OP_DOT        ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "dot"),
571
572 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
573 [OP_LAND       ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "land"),
574 [OP_LOR        ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "lor"),
575 [OP_COND       ] = OP( 0,  3, 0, 0, 0 | DEF | BLOCK, "cond"),
576 [OP_COMMA      ] = OP( 0,  2, 0, 0, 0 | DEF | BLOCK, "comma"),
577 /* Call is special most it can stand in for anything so it depends on context */
578 [OP_CALL       ] = OP(-1, -1, 1, 0, 0 | BLOCK, "call"),
579 /* The sizes of OP_CALL and OP_VAL_VEC depend upon context */
580 [OP_VAL_VEC    ] = OP( 0, -1, 0, 0, 0 | BLOCK, "valvec"),
581
582 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF, "list"),
583 /* The number of targets for OP_BRANCH depends on context */
584 [OP_BRANCH     ] = OP( 0, -1, 0, 1, PURE | BLOCK, "branch"),
585 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "label"),
586 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK, "adecl"),
587 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK, "sdecl"),
588 /* The number of RHS elements of OP_PHI depend upon context */
589 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
590
591 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
592 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
593 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
594 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
595 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
596 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
597 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
598 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
599 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
600 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
601 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
602 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
603 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK, "jmp"),
604 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_eq"),
605 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_noteq"),
606 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_sless"),
607 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_uless"),
608 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smore"),
609 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umore"),
610 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_slesseq"),
611 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_ulesseq"),
612 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_smoreq"),
613 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK, "jmp_umoreq"),
614
615 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
616 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
617 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
618 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
619 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
620 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
621 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
622 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
623 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
624 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
625 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
626 };
627 #undef OP
628 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
629
630 static const char *tops(int index) 
631 {
632         static const char unknown[] = "unknown op";
633         if (index < 0) {
634                 return unknown;
635         }
636         if (index > OP_MAX) {
637                 return unknown;
638         }
639         return table_ops[index].name;
640 }
641
642 struct asm_info;
643 struct triple;
644 struct block;
645 struct triple_set {
646         struct triple_set *next;
647         struct triple *member;
648 };
649
650 #define MAX_LHS  15
651 #define MAX_RHS  250
652 #define MAX_MISC 3
653 #define MAX_TARG 3
654
655 struct occurance {
656         int count;
657         const char *filename;
658         const char *function;
659         int line;
660         int col;
661         struct occurance *parent;
662 };
663 struct triple {
664         struct triple *next, *prev;
665         struct triple_set *use;
666         struct type *type;
667         unsigned char op;
668         unsigned char template_id;
669         unsigned short sizes;
670 #define TRIPLE_LHS(SIZES)  (((SIZES) >>  0) & 0x0f)
671 #define TRIPLE_RHS(SIZES)  (((SIZES) >>  4) & 0xff)
672 #define TRIPLE_MISC(SIZES) (((SIZES) >> 12) & 0x03)
673 #define TRIPLE_TARG(SIZES) (((SIZES) >> 14) & 0x03)
674 #define TRIPLE_SIZE(SIZES) \
675         (TRIPLE_LHS(SIZES)  + \
676          TRIPLE_RHS(SIZES)  + \
677          TRIPLE_MISC(SIZES) + \
678          TRIPLE_TARG(SIZES))
679 #define TRIPLE_SIZES(LHS, RHS, MISC, TARG) \
680         ((((LHS) & 0x0f) <<  0) | \
681         (((RHS)  & 0xff) <<  4) | \
682         (((MISC) & 0x03) << 12) | \
683         (((TARG) & 0x03) << 14))
684 #define TRIPLE_LHS_OFF(SIZES)  (0)
685 #define TRIPLE_RHS_OFF(SIZES)  (TRIPLE_LHS_OFF(SIZES) + TRIPLE_LHS(SIZES))
686 #define TRIPLE_MISC_OFF(SIZES) (TRIPLE_RHS_OFF(SIZES) + TRIPLE_RHS(SIZES))
687 #define TRIPLE_TARG_OFF(SIZES) (TRIPLE_MISC_OFF(SIZES) + TRIPLE_MISC(SIZES))
688 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF((PTR)->sizes) + (INDEX)])
689 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF((PTR)->sizes) + (INDEX)])
690 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF((PTR)->sizes) + (INDEX)])
691 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF((PTR)->sizes) + (INDEX)])
692         unsigned id; /* A scratch value and finally the register */
693 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
694 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
695 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
696         struct occurance *occurance;
697         union {
698                 ulong_t cval;
699                 struct block  *block;
700                 void *blob;
701                 struct hash_entry *field;
702                 struct asm_info *ainfo;
703         } u;
704         struct triple *param[2];
705 };
706
707 struct reg_info {
708         unsigned reg;
709         unsigned regcm;
710 };
711 struct ins_template {
712         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
713 };
714
715 struct asm_info {
716         struct ins_template tmpl;
717         char *str;
718 };
719
720 struct block_set {
721         struct block_set *next;
722         struct block *member;
723 };
724 struct block {
725         struct block *work_next;
726         struct block *left, *right;
727         struct triple *first, *last;
728         int users;
729         struct block_set *use;
730         struct block_set *idominates;
731         struct block_set *domfrontier;
732         struct block *idom;
733         struct block_set *ipdominates;
734         struct block_set *ipdomfrontier;
735         struct block *ipdom;
736         int vertex;
737         
738 };
739
740 struct symbol {
741         struct symbol *next;
742         struct hash_entry *ident;
743         struct triple *def;
744         struct type *type;
745         int scope_depth;
746 };
747
748 struct macro {
749         struct hash_entry *ident;
750         char *buf;
751         int buf_len;
752 };
753
754 struct hash_entry {
755         struct hash_entry *next;
756         const char *name;
757         int name_len;
758         int tok;
759         struct macro *sym_define;
760         struct symbol *sym_label;
761         struct symbol *sym_struct;
762         struct symbol *sym_ident;
763 };
764
765 #define HASH_TABLE_SIZE 2048
766
767 struct compile_state {
768         const char *label_prefix;
769         const char *ofilename;
770         FILE *output;
771         struct file_state *file;
772         struct occurance *last_occurance;
773         const char *function;
774         struct token token[4];
775         struct hash_entry *hash_table[HASH_TABLE_SIZE];
776         struct hash_entry *i_continue;
777         struct hash_entry *i_break;
778         int scope_depth;
779         int if_depth, if_value;
780         int macro_line;
781         struct file_state *macro_file;
782         struct triple *main_function;
783         struct block *first_block, *last_block;
784         int last_vertex;
785         int cpu;
786         int debug;
787         int optimize;
788 };
789
790 /* visibility global/local */
791 /* static/auto duration */
792 /* typedef, register, inline */
793 #define STOR_SHIFT         0
794 #define STOR_MASK     0x000f
795 /* Visibility */
796 #define STOR_GLOBAL   0x0001
797 /* Duration */
798 #define STOR_PERM     0x0002
799 /* Storage specifiers */
800 #define STOR_AUTO     0x0000
801 #define STOR_STATIC   0x0002
802 #define STOR_EXTERN   0x0003
803 #define STOR_REGISTER 0x0004
804 #define STOR_TYPEDEF  0x0008
805 #define STOR_INLINE   0x000c
806
807 #define QUAL_SHIFT         4
808 #define QUAL_MASK     0x0070
809 #define QUAL_NONE     0x0000
810 #define QUAL_CONST    0x0010
811 #define QUAL_VOLATILE 0x0020
812 #define QUAL_RESTRICT 0x0040
813
814 #define TYPE_SHIFT         8
815 #define TYPE_MASK     0x1f00
816 #define TYPE_INTEGER(TYPE)    (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG))
817 #define TYPE_ARITHMETIC(TYPE) (((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE))
818 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
819 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
820 #define TYPE_MKUNSIGNED(TYPE) ((TYPE) | 0x0100)
821 #define TYPE_RANK(TYPE)       ((TYPE) & ~0x0100)
822 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
823 #define TYPE_DEFAULT  0x0000
824 #define TYPE_VOID     0x0100
825 #define TYPE_CHAR     0x0200
826 #define TYPE_UCHAR    0x0300
827 #define TYPE_SHORT    0x0400
828 #define TYPE_USHORT   0x0500
829 #define TYPE_INT      0x0600
830 #define TYPE_UINT     0x0700
831 #define TYPE_LONG     0x0800
832 #define TYPE_ULONG    0x0900
833 #define TYPE_LLONG    0x0a00 /* long long */
834 #define TYPE_ULLONG   0x0b00
835 #define TYPE_FLOAT    0x0c00
836 #define TYPE_DOUBLE   0x0d00
837 #define TYPE_LDOUBLE  0x0e00 /* long double */
838 #define TYPE_STRUCT   0x1000
839 #define TYPE_ENUM     0x1100
840 #define TYPE_POINTER  0x1200 
841 /* For TYPE_POINTER:
842  * type->left holds the type pointed to.
843  */
844 #define TYPE_FUNCTION 0x1300 
845 /* For TYPE_FUNCTION:
846  * type->left holds the return type.
847  * type->right holds the...
848  */
849 #define TYPE_PRODUCT  0x1400
850 /* TYPE_PRODUCT is a basic building block when defining structures
851  * type->left holds the type that appears first in memory.
852  * type->right holds the type that appears next in memory.
853  */
854 #define TYPE_OVERLAP  0x1500
855 /* TYPE_OVERLAP is a basic building block when defining unions
856  * type->left and type->right holds to types that overlap
857  * each other in memory.
858  */
859 #define TYPE_ARRAY    0x1600
860 /* TYPE_ARRAY is a basic building block when definitng arrays.
861  * type->left holds the type we are an array of.
862  * type-> holds the number of elements.
863  */
864
865 #define ELEMENT_COUNT_UNSPECIFIED (~0UL)
866
867 struct type {
868         unsigned int type;
869         struct type *left, *right;
870         ulong_t elements;
871         struct hash_entry *field_ident;
872         struct hash_entry *type_ident;
873 };
874
875 #define MAX_REGISTERS      75
876 #define MAX_REG_EQUIVS     16
877 #define REGISTER_BITS      16
878 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
879 #define TEMPLATE_BITS      7
880 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
881 #define MAX_REGC           14
882 #define REG_UNSET          0
883 #define REG_UNNEEDED       1
884 #define REG_VIRT0          (MAX_REGISTERS + 0)
885 #define REG_VIRT1          (MAX_REGISTERS + 1)
886 #define REG_VIRT2          (MAX_REGISTERS + 2)
887 #define REG_VIRT3          (MAX_REGISTERS + 3)
888 #define REG_VIRT4          (MAX_REGISTERS + 4)
889 #define REG_VIRT5          (MAX_REGISTERS + 5)
890 #define REG_VIRT6          (MAX_REGISTERS + 5)
891 #define REG_VIRT7          (MAX_REGISTERS + 5)
892 #define REG_VIRT8          (MAX_REGISTERS + 5)
893 #define REG_VIRT9          (MAX_REGISTERS + 5)
894
895 /* Provision for 8 register classes */
896 #define REG_SHIFT  0
897 #define REGC_SHIFT REGISTER_BITS
898 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
899 #define REG_MASK (MAX_VIRT_REGISTERS -1)
900 #define ID_REG(ID)              ((ID) & REG_MASK)
901 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
902 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
903 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
904 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
905                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
906
907 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
908 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
909 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
910 static void arch_reg_equivs(
911         struct compile_state *state, unsigned *equiv, int reg);
912 static int arch_select_free_register(
913         struct compile_state *state, char *used, int classes);
914 static unsigned arch_regc_size(struct compile_state *state, int class);
915 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
916 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
917 static const char *arch_reg_str(int reg);
918 static struct reg_info arch_reg_constraint(
919         struct compile_state *state, struct type *type, const char *constraint);
920 static struct reg_info arch_reg_clobber(
921         struct compile_state *state, const char *clobber);
922 static struct reg_info arch_reg_lhs(struct compile_state *state, 
923         struct triple *ins, int index);
924 static struct reg_info arch_reg_rhs(struct compile_state *state, 
925         struct triple *ins, int index);
926 static struct triple *transform_to_arch_instruction(
927         struct compile_state *state, struct triple *ins);
928
929
930
931 #define DEBUG_ABORT_ON_ERROR    0x0001
932 #define DEBUG_INTERMEDIATE_CODE 0x0002
933 #define DEBUG_CONTROL_FLOW      0x0004
934 #define DEBUG_BASIC_BLOCKS      0x0008
935 #define DEBUG_FDOMINATORS       0x0010
936 #define DEBUG_RDOMINATORS       0x0020
937 #define DEBUG_TRIPLES           0x0040
938 #define DEBUG_INTERFERENCE      0x0080
939 #define DEBUG_ARCH_CODE         0x0100
940 #define DEBUG_CODE_ELIMINATION  0x0200
941 #define DEBUG_INSERTED_COPIES   0x0400
942
943 #define GLOBAL_SCOPE_DEPTH   1
944 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
945
946 static void compile_file(struct compile_state *old_state, const char *filename, int local);
947
948 static void do_cleanup(struct compile_state *state)
949 {
950         if (state->output) {
951                 fclose(state->output);
952                 unlink(state->ofilename);
953         }
954 }
955
956 static int get_col(struct file_state *file)
957 {
958         int col;
959         char *ptr, *end;
960         ptr = file->line_start;
961         end = file->pos;
962         for(col = 0; ptr < end; ptr++) {
963                 if (*ptr != '\t') {
964                         col++;
965                 } 
966                 else {
967                         col = (col & ~7) + 8;
968                 }
969         }
970         return col;
971 }
972
973 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
974 {
975         int col;
976         if (triple && triple->occurance) {
977                 struct occurance *spot;
978                 spot = triple->occurance;
979                 while(spot->parent) {
980                         spot = spot->parent;
981                 }
982                 fprintf(fp, "%s:%d.%d: ", 
983                         spot->filename, spot->line, spot->col);
984                 return;
985         }
986         if (!state->file) {
987                 return;
988         }
989         col = get_col(state->file);
990         fprintf(fp, "%s:%d.%d: ", 
991                 state->file->report_name, state->file->report_line, col);
992 }
993
994 static void __internal_error(struct compile_state *state, struct triple *ptr, 
995         char *fmt, ...)
996 {
997         va_list args;
998         va_start(args, fmt);
999         loc(stderr, state, ptr);
1000         if (ptr) {
1001                 fprintf(stderr, "%p %s ", ptr, tops(ptr->op));
1002         }
1003         fprintf(stderr, "Internal compiler error: ");
1004         vfprintf(stderr, fmt, args);
1005         fprintf(stderr, "\n");
1006         va_end(args);
1007         do_cleanup(state);
1008         abort();
1009 }
1010
1011
1012 static void __internal_warning(struct compile_state *state, struct triple *ptr, 
1013         char *fmt, ...)
1014 {
1015         va_list args;
1016         va_start(args, fmt);
1017         loc(stderr, state, ptr);
1018         fprintf(stderr, "Internal compiler warning: ");
1019         vfprintf(stderr, fmt, args);
1020         fprintf(stderr, "\n");
1021         va_end(args);
1022 }
1023
1024
1025
1026 static void __error(struct compile_state *state, struct triple *ptr, 
1027         char *fmt, ...)
1028 {
1029         va_list args;
1030         va_start(args, fmt);
1031         loc(stderr, state, ptr);
1032         vfprintf(stderr, fmt, args);
1033         va_end(args);
1034         fprintf(stderr, "\n");
1035         do_cleanup(state);
1036         if (state->debug & DEBUG_ABORT_ON_ERROR) {
1037                 abort();
1038         }
1039         exit(1);
1040 }
1041
1042 static void __warning(struct compile_state *state, struct triple *ptr, 
1043         char *fmt, ...)
1044 {
1045         va_list args;
1046         va_start(args, fmt);
1047         loc(stderr, state, ptr);
1048         fprintf(stderr, "warning: "); 
1049         vfprintf(stderr, fmt, args);
1050         fprintf(stderr, "\n");
1051         va_end(args);
1052 }
1053
1054 #if DEBUG_ERROR_MESSAGES 
1055 #  define internal_error fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_error
1056 #  define internal_warning fprintf(stderr,  "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__internal_warning
1057 #  define error fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__error
1058 #  define warning fprintf(stderr, "@ %s.%s:%d \t", __FILE__, __func__, __LINE__),__warning
1059 #else
1060 #  define internal_error __internal_error
1061 #  define internal_warning __internal_warning
1062 #  define error __error
1063 #  define warning __warning
1064 #endif
1065 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1066
1067 static void valid_op(struct compile_state *state, int op)
1068 {
1069         char *fmt = "invalid op: %d";
1070         if (op >= OP_MAX) {
1071                 internal_error(state, 0, fmt, op);
1072         }
1073         if (op < 0) {
1074                 internal_error(state, 0, fmt, op);
1075         }
1076 }
1077
1078 static void valid_ins(struct compile_state *state, struct triple *ptr)
1079 {
1080         valid_op(state, ptr->op);
1081 }
1082
1083 static void process_trigraphs(struct compile_state *state)
1084 {
1085         char *src, *dest, *end;
1086         struct file_state *file;
1087         file = state->file;
1088         src = dest = file->buf;
1089         end = file->buf + file->size;
1090         while((end - src) >= 3) {
1091                 if ((src[0] == '?') && (src[1] == '?')) {
1092                         int c = -1;
1093                         switch(src[2]) {
1094                         case '=': c = '#'; break;
1095                         case '/': c = '\\'; break;
1096                         case '\'': c = '^'; break;
1097                         case '(': c = '['; break;
1098                         case ')': c = ']'; break;
1099                         case '!': c = '!'; break;
1100                         case '<': c = '{'; break;
1101                         case '>': c = '}'; break;
1102                         case '-': c = '~'; break;
1103                         }
1104                         if (c != -1) {
1105                                 *dest++ = c;
1106                                 src += 3;
1107                         }
1108                         else {
1109                                 *dest++ = *src++;
1110                         }
1111                 }
1112                 else {
1113                         *dest++ = *src++;
1114                 }
1115         }
1116         while(src != end) {
1117                 *dest++ = *src++;
1118         }
1119         file->size = dest - file->buf;
1120 }
1121
1122 static void splice_lines(struct compile_state *state)
1123 {
1124         char *src, *dest, *end;
1125         struct file_state *file;
1126         file = state->file;
1127         src = dest = file->buf;
1128         end = file->buf + file->size;
1129         while((end - src) >= 2) {
1130                 if ((src[0] == '\\') && (src[1] == '\n')) {
1131                         src += 2;
1132                 }
1133                 else {
1134                         *dest++ = *src++;
1135                 }
1136         }
1137         while(src != end) {
1138                 *dest++ = *src++;
1139         }
1140         file->size = dest - file->buf;
1141 }
1142
1143 static struct type void_type;
1144 static void use_triple(struct triple *used, struct triple *user)
1145 {
1146         struct triple_set **ptr, *new;
1147         if (!used)
1148                 return;
1149         if (!user)
1150                 return;
1151         ptr = &used->use;
1152         while(*ptr) {
1153                 if ((*ptr)->member == user) {
1154                         return;
1155                 }
1156                 ptr = &(*ptr)->next;
1157         }
1158         /* Append new to the head of the list, 
1159          * copy_func and rename_block_variables
1160          * depends on this.
1161          */
1162         new = xcmalloc(sizeof(*new), "triple_set");
1163         new->member = user;
1164         new->next   = used->use;
1165         used->use   = new;
1166 }
1167
1168 static void unuse_triple(struct triple *used, struct triple *unuser)
1169 {
1170         struct triple_set *use, **ptr;
1171         if (!used) {
1172                 return;
1173         }
1174         ptr = &used->use;
1175         while(*ptr) {
1176                 use = *ptr;
1177                 if (use->member == unuser) {
1178                         *ptr = use->next;
1179                         xfree(use);
1180                 }
1181                 else {
1182                         ptr = &use->next;
1183                 }
1184         }
1185 }
1186
1187 static void push_triple(struct triple *used, struct triple *user)
1188 {
1189         struct triple_set *new;
1190         if (!used)
1191                 return;
1192         if (!user)
1193                 return;
1194         /* Append new to the head of the list,
1195          * it's the only sensible behavoir for a stack.
1196          */
1197         new = xcmalloc(sizeof(*new), "triple_set");
1198         new->member = user;
1199         new->next   = used->use;
1200         used->use   = new;
1201 }
1202
1203 static void pop_triple(struct triple *used, struct triple *unuser)
1204 {
1205         struct triple_set *use, **ptr;
1206         ptr = &used->use;
1207         while(*ptr) {
1208                 use = *ptr;
1209                 if (use->member == unuser) {
1210                         *ptr = use->next;
1211                         xfree(use);
1212                         /* Only free one occurance from the stack */
1213                         return;
1214                 }
1215                 else {
1216                         ptr = &use->next;
1217                 }
1218         }
1219 }
1220
1221 static void put_occurance(struct occurance *occurance)
1222 {
1223         occurance->count -= 1;
1224         if (occurance->count <= 0) {
1225                 if (occurance->parent) {
1226                         put_occurance(occurance->parent);
1227                 }
1228                 xfree(occurance);
1229         }
1230 }
1231
1232 static void get_occurance(struct occurance *occurance)
1233 {
1234         occurance->count += 1;
1235 }
1236
1237
1238 static struct occurance *new_occurance(struct compile_state *state)
1239 {
1240         struct occurance *result, *last;
1241         const char *filename;
1242         const char *function;
1243         int line, col;
1244
1245         function = "";
1246         filename = 0;
1247         line = 0;
1248         col  = 0;
1249         if (state->file) {
1250                 filename = state->file->report_name;
1251                 line     = state->file->report_line;
1252                 col      = get_col(state->file);
1253         }
1254         if (state->function) {
1255                 function = state->function;
1256         }
1257         last = state->last_occurance;
1258         if (last &&
1259                 (last->col == col) &&
1260                 (last->line == line) &&
1261                 (last->function == function) &&
1262                 (strcmp(last->filename, filename) == 0)) {
1263                 get_occurance(last);
1264                 return last;
1265         }
1266         if (last) {
1267                 state->last_occurance = 0;
1268                 put_occurance(last);
1269         }
1270         result = xmalloc(sizeof(*result), "occurance");
1271         result->count    = 2;
1272         result->filename = filename;
1273         result->function = function;
1274         result->line     = line;
1275         result->col      = col;
1276         result->parent   = 0;
1277         state->last_occurance = result;
1278         return result;
1279 }
1280
1281 static struct occurance *inline_occurance(struct compile_state *state,
1282         struct occurance *new, struct occurance *orig)
1283 {
1284         struct occurance *result, *last;
1285         last = state->last_occurance;
1286         if (last &&
1287                 (last->parent   == orig) &&
1288                 (last->col      == new->col) &&
1289                 (last->line     == new->line) &&
1290                 (last->function == new->function) &&
1291                 (last->filename == new->filename)) {
1292                 get_occurance(last);
1293                 return last;
1294         }
1295         if (last) {
1296                 state->last_occurance = 0;
1297                 put_occurance(last);
1298         }
1299         get_occurance(orig);
1300         result = xmalloc(sizeof(*result), "occurance");
1301         result->count    = 2;
1302         result->filename = new->filename;
1303         result->function = new->function;
1304         result->line     = new->line;
1305         result->col      = new->col;
1306         result->parent   = orig;
1307         state->last_occurance = result;
1308         return result;
1309 }
1310         
1311
1312 static struct occurance dummy_occurance = {
1313         .count    = 2,
1314         .filename = __FILE__,
1315         .function = "",
1316         .line     = __LINE__,
1317         .col      = 0,
1318         .parent   = 0,
1319 };
1320
1321 /* The zero triple is used as a place holder when we are removing pointers
1322  * from a triple.  Having allows certain sanity checks to pass even
1323  * when the original triple that was pointed to is gone.
1324  */
1325 static struct triple zero_triple = {
1326         .next      = &zero_triple,
1327         .prev      = &zero_triple,
1328         .use       = 0,
1329         .op        = OP_INTCONST,
1330         .sizes     = TRIPLE_SIZES(0, 0, 0, 0),
1331         .id        = -1, /* An invalid id */
1332         .u = { .cval = 0, },
1333         .occurance = &dummy_occurance,
1334         .param = { [0] = 0, [1] = 0, },
1335 };
1336
1337
1338 static unsigned short triple_sizes(struct compile_state *state,
1339         int op, struct type *type, int lhs_wanted, int rhs_wanted,
1340         struct occurance *occurance)
1341 {
1342         int lhs, rhs, misc, targ;
1343         struct triple dummy;
1344         dummy.op = op;
1345         dummy.occurance = occurance;
1346         valid_op(state, op);
1347         lhs = table_ops[op].lhs;
1348         rhs = table_ops[op].rhs;
1349         misc = table_ops[op].misc;
1350         targ = table_ops[op].targ;
1351         
1352         
1353         if (op == OP_CALL) {
1354                 struct type *param;
1355                 rhs = 0;
1356                 param = type->right;
1357                 while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
1358                         rhs++;
1359                         param = param->right;
1360                 }
1361                 if ((param->type & TYPE_MASK) != TYPE_VOID) {
1362                         rhs++;
1363                 }
1364                 lhs = 0;
1365                 if ((type->left->type & TYPE_MASK) == TYPE_STRUCT) {
1366                         lhs = type->left->elements;
1367                 }
1368         }
1369         else if (op == OP_VAL_VEC) {
1370                 rhs = type->elements;
1371         }
1372         else if ((op == OP_BRANCH) || (op == OP_PHI)) {
1373                 rhs = rhs_wanted;
1374         }
1375         else if (op == OP_ASM) {
1376                 rhs = rhs_wanted;
1377                 lhs = lhs_wanted;
1378         }
1379         if ((rhs < 0) || (rhs > MAX_RHS)) {
1380                 internal_error(state, &dummy, "bad rhs %d", rhs);
1381         }
1382         if ((lhs < 0) || (lhs > MAX_LHS)) {
1383                 internal_error(state, &dummy, "bad lhs");
1384         }
1385         if ((misc < 0) || (misc > MAX_MISC)) {
1386                 internal_error(state, &dummy, "bad misc");
1387         }
1388         if ((targ < 0) || (targ > MAX_TARG)) {
1389                 internal_error(state, &dummy, "bad targs");
1390         }
1391         return TRIPLE_SIZES(lhs, rhs, misc, targ);
1392 }
1393
1394 static struct triple *alloc_triple(struct compile_state *state, 
1395         int op, struct type *type, int lhs, int rhs,
1396         struct occurance *occurance)
1397 {
1398         size_t size, sizes, extra_count, min_count;
1399         struct triple *ret;
1400         sizes = triple_sizes(state, op, type, lhs, rhs, occurance);
1401
1402         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
1403         extra_count = TRIPLE_SIZE(sizes);
1404         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
1405
1406         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
1407         ret = xcmalloc(size, "tripple");
1408         ret->op        = op;
1409         ret->sizes     = sizes;
1410         ret->type      = type;
1411         ret->next      = ret;
1412         ret->prev      = ret;
1413         ret->occurance = occurance;
1414         return ret;
1415 }
1416
1417 struct triple *dup_triple(struct compile_state *state, struct triple *src)
1418 {
1419         struct triple *dup;
1420         int src_lhs, src_rhs, src_size;
1421         src_lhs = TRIPLE_LHS(src->sizes);
1422         src_rhs = TRIPLE_RHS(src->sizes);
1423         src_size = TRIPLE_SIZE(src->sizes);
1424         get_occurance(src->occurance);
1425         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
1426                 src->occurance);
1427         memcpy(dup, src, sizeof(*src));
1428         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
1429         return dup;
1430 }
1431
1432 static struct triple *new_triple(struct compile_state *state, 
1433         int op, struct type *type, int lhs, int rhs)
1434 {
1435         struct triple *ret;
1436         struct occurance *occurance;
1437         occurance = new_occurance(state);
1438         ret = alloc_triple(state, op, type, lhs, rhs, occurance);
1439         return ret;
1440 }
1441
1442 static struct triple *build_triple(struct compile_state *state, 
1443         int op, struct type *type, struct triple *left, struct triple *right,
1444         struct occurance *occurance)
1445 {
1446         struct triple *ret;
1447         size_t count;
1448         ret = alloc_triple(state, op, type, -1, -1, occurance);
1449         count = TRIPLE_SIZE(ret->sizes);
1450         if (count > 0) {
1451                 ret->param[0] = left;
1452         }
1453         if (count > 1) {
1454                 ret->param[1] = right;
1455         }
1456         return ret;
1457 }
1458
1459 static struct triple *triple(struct compile_state *state, 
1460         int op, struct type *type, struct triple *left, struct triple *right)
1461 {
1462         struct triple *ret;
1463         size_t count;
1464         ret = new_triple(state, op, type, -1, -1);
1465         count = TRIPLE_SIZE(ret->sizes);
1466         if (count >= 1) {
1467                 ret->param[0] = left;
1468         }
1469         if (count >= 2) {
1470                 ret->param[1] = right;
1471         }
1472         return ret;
1473 }
1474
1475 static struct triple *branch(struct compile_state *state, 
1476         struct triple *targ, struct triple *test)
1477 {
1478         struct triple *ret;
1479         ret = new_triple(state, OP_BRANCH, &void_type, -1, test?1:0);
1480         if (test) {
1481                 RHS(ret, 0) = test;
1482         }
1483         TARG(ret, 0) = targ;
1484         /* record the branch target was used */
1485         if (!targ || (targ->op != OP_LABEL)) {
1486                 internal_error(state, 0, "branch not to label");
1487                 use_triple(targ, ret);
1488         }
1489         return ret;
1490 }
1491
1492
1493 static void insert_triple(struct compile_state *state,
1494         struct triple *first, struct triple *ptr)
1495 {
1496         if (ptr) {
1497                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
1498                         internal_error(state, ptr, "expression already used");
1499                 }
1500                 ptr->next       = first;
1501                 ptr->prev       = first->prev;
1502                 ptr->prev->next = ptr;
1503                 ptr->next->prev = ptr;
1504                 if ((ptr->prev->op == OP_BRANCH) && 
1505                         TRIPLE_RHS(ptr->prev->sizes)) {
1506                         unuse_triple(first, ptr->prev);
1507                         use_triple(ptr, ptr->prev);
1508                 }
1509         }
1510 }
1511
1512 static int triple_stores_block(struct compile_state *state, struct triple *ins)
1513 {
1514         /* This function is used to determine if u.block 
1515          * is utilized to store the current block number.
1516          */
1517         int stores_block;
1518         valid_ins(state, ins);
1519         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
1520         return stores_block;
1521 }
1522
1523 static struct block *block_of_triple(struct compile_state *state, 
1524         struct triple *ins)
1525 {
1526         struct triple *first;
1527         first = RHS(state->main_function, 0);
1528         while(ins != first && !triple_stores_block(state, ins)) {
1529                 if (ins == ins->prev) {
1530                         internal_error(state, 0, "ins == ins->prev?");
1531                 }
1532                 ins = ins->prev;
1533         }
1534         if (!triple_stores_block(state, ins)) {
1535                 internal_error(state, ins, "Cannot find block");
1536         }
1537         return ins->u.block;
1538 }
1539
1540 static struct triple *pre_triple(struct compile_state *state,
1541         struct triple *base,
1542         int op, struct type *type, struct triple *left, struct triple *right)
1543 {
1544         struct block *block;
1545         struct triple *ret;
1546         /* If I am an OP_PIECE jump to the real instruction */
1547         if (base->op == OP_PIECE) {
1548                 base = MISC(base, 0);
1549         }
1550         block = block_of_triple(state, base);
1551         get_occurance(base->occurance);
1552         ret = build_triple(state, op, type, left, right, base->occurance);
1553         if (triple_stores_block(state, ret)) {
1554                 ret->u.block = block;
1555         }
1556         insert_triple(state, base, ret);
1557         if (block->first == base) {
1558                 block->first = ret;
1559         }
1560         return ret;
1561 }
1562
1563 static struct triple *post_triple(struct compile_state *state,
1564         struct triple *base,
1565         int op, struct type *type, struct triple *left, struct triple *right)
1566 {
1567         struct block *block;
1568         struct triple *ret;
1569         int zlhs;
1570         /* If I am an OP_PIECE jump to the real instruction */
1571         if (base->op == OP_PIECE) {
1572                 base = MISC(base, 0);
1573         }
1574         /* If I have a left hand side skip over it */
1575         zlhs = TRIPLE_LHS(base->sizes);
1576         if (zlhs) {
1577                 base = LHS(base, zlhs - 1);
1578         }
1579
1580         block = block_of_triple(state, base);
1581         get_occurance(base->occurance);
1582         ret = build_triple(state, op, type, left, right, base->occurance);
1583         if (triple_stores_block(state, ret)) {
1584                 ret->u.block = block;
1585         }
1586         insert_triple(state, base->next, ret);
1587         if (block->last == base) {
1588                 block->last = ret;
1589         }
1590         return ret;
1591 }
1592
1593 static struct triple *label(struct compile_state *state)
1594 {
1595         /* Labels don't get a type */
1596         struct triple *result;
1597         result = triple(state, OP_LABEL, &void_type, 0, 0);
1598         return result;
1599 }
1600
1601 static void display_triple(FILE *fp, struct triple *ins)
1602 {
1603         struct occurance *ptr;
1604         const char *reg;
1605         char pre, post;
1606         pre = post = ' ';
1607         if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
1608                 pre = '^';
1609         }
1610         if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
1611                 post = 'v';
1612         }
1613         reg = arch_reg_str(ID_REG(ins->id));
1614         if (ins->op == OP_INTCONST) {
1615                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s <0x%08lx>         ",
1616                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1617                         ins->u.cval);
1618         }
1619         else if (ins->op == OP_ADDRCONST) {
1620                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s %-10p <0x%08lx>",
1621                         ins, pre, post, reg, ins->template_id, tops(ins->op), 
1622                         MISC(ins, 0), ins->u.cval);
1623         }
1624         else {
1625                 int i, count;
1626                 fprintf(fp, "(%p) %c%c %-7s %-2d %-10s", 
1627                         ins, pre, post, reg, ins->template_id, tops(ins->op));
1628                 count = TRIPLE_SIZE(ins->sizes);
1629                 for(i = 0; i < count; i++) {
1630                         fprintf(fp, " %-10p", ins->param[i]);
1631                 }
1632                 for(; i < 2; i++) {
1633                         fprintf(fp, "           ");
1634                 }
1635         }
1636         fprintf(fp, " @");
1637         for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
1638                 fprintf(fp, " %s,%s:%d.%d",
1639                         ptr->function, 
1640                         ptr->filename,
1641                         ptr->line, 
1642                         ptr->col);
1643         }
1644         fprintf(fp, "\n");
1645 #if 0
1646         {
1647                 struct triple_set *user;
1648                 for(user = ptr->use; user; user = user->next) {
1649                         fprintf(fp, "use: %p\n", user->member);
1650                 }
1651         }
1652 #endif
1653         fflush(fp);
1654 }
1655
1656 static int triple_is_pure(struct compile_state *state, struct triple *ins)
1657 {
1658         /* Does the triple have no side effects.
1659          * I.e. Rexecuting the triple with the same arguments 
1660          * gives the same value.
1661          */
1662         unsigned pure;
1663         valid_ins(state, ins);
1664         pure = PURE_BITS(table_ops[ins->op].flags);
1665         if ((pure != PURE) && (pure != IMPURE)) {
1666                 internal_error(state, 0, "Purity of %s not known\n",
1667                         tops(ins->op));
1668         }
1669         return pure == PURE;
1670 }
1671
1672 static int triple_is_branch(struct compile_state *state, struct triple *ins)
1673 {
1674         /* This function is used to determine which triples need
1675          * a register.
1676          */
1677         int is_branch;
1678         valid_ins(state, ins);
1679         is_branch = (table_ops[ins->op].targ != 0);
1680         return is_branch;
1681 }
1682
1683 static int triple_is_cond_branch(struct compile_state *state, struct triple *ins)
1684 {
1685         /* A conditional branch has the condition argument as a single
1686          * RHS parameter.
1687          */
1688         return triple_is_branch(state, ins) &&
1689                 (TRIPLE_RHS(ins->sizes) == 1);
1690 }
1691
1692 static int triple_is_uncond_branch(struct compile_state *state, struct triple *ins)
1693 {
1694         /* A unconditional branch has no RHS parameters.
1695          */
1696         return triple_is_branch(state, ins) &&
1697                 (TRIPLE_RHS(ins->sizes) == 0);
1698 }
1699
1700 static int triple_is_def(struct compile_state *state, struct triple *ins)
1701 {
1702         /* This function is used to determine which triples need
1703          * a register.
1704          */
1705         int is_def;
1706         valid_ins(state, ins);
1707         is_def = (table_ops[ins->op].flags & DEF) == DEF;
1708         return is_def;
1709 }
1710
1711 static struct triple **triple_iter(struct compile_state *state,
1712         size_t count, struct triple **vector,
1713         struct triple *ins, struct triple **last)
1714 {
1715         struct triple **ret;
1716         ret = 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         }
1725         return ret;
1726         
1727 }
1728
1729 static struct triple **triple_lhs(struct compile_state *state,
1730         struct triple *ins, struct triple **last)
1731 {
1732         return triple_iter(state, TRIPLE_LHS(ins->sizes), &LHS(ins,0), 
1733                 ins, last);
1734 }
1735
1736 static struct triple **triple_rhs(struct compile_state *state,
1737         struct triple *ins, struct triple **last)
1738 {
1739         return triple_iter(state, TRIPLE_RHS(ins->sizes), &RHS(ins,0), 
1740                 ins, last);
1741 }
1742
1743 static struct triple **triple_misc(struct compile_state *state,
1744         struct triple *ins, struct triple **last)
1745 {
1746         return triple_iter(state, TRIPLE_MISC(ins->sizes), &MISC(ins,0), 
1747                 ins, last);
1748 }
1749
1750 static struct triple **triple_targ(struct compile_state *state,
1751         struct triple *ins, struct triple **last)
1752 {
1753         size_t count;
1754         struct triple **ret, **vector;
1755         ret = 0;
1756         count = TRIPLE_TARG(ins->sizes);
1757         vector = &TARG(ins, 0);
1758         if (count) {
1759                 if (!last) {
1760                         ret = vector;
1761                 }
1762                 else if ((last >= vector) && (last < (vector + count - 1))) {
1763                         ret = last + 1;
1764                 }
1765                 else if ((last == (vector + count - 1)) && 
1766                         TRIPLE_RHS(ins->sizes)) {
1767                         ret = &ins->next;
1768                 }
1769         }
1770         return ret;
1771 }
1772
1773
1774 static void verify_use(struct compile_state *state,
1775         struct triple *user, struct triple *used)
1776 {
1777         int size, i;
1778         size = TRIPLE_SIZE(user->sizes);
1779         for(i = 0; i < size; i++) {
1780                 if (user->param[i] == used) {
1781                         break;
1782                 }
1783         }
1784         if (triple_is_branch(state, user)) {
1785                 if (user->next == used) {
1786                         i = -1;
1787                 }
1788         }
1789         if (i == size) {
1790                 internal_error(state, user, "%s(%p) does not use %s(%p)",
1791                         tops(user->op), user, tops(used->op), used);
1792         }
1793 }
1794
1795 static int find_rhs_use(struct compile_state *state, 
1796         struct triple *user, struct triple *used)
1797 {
1798         struct triple **param;
1799         int size, i;
1800         verify_use(state, user, used);
1801         size = TRIPLE_RHS(user->sizes);
1802         param = &RHS(user, 0);
1803         for(i = 0; i < size; i++) {
1804                 if (param[i] == used) {
1805                         return i;
1806                 }
1807         }
1808         return -1;
1809 }
1810
1811 static void free_triple(struct compile_state *state, struct triple *ptr)
1812 {
1813         size_t size;
1814         size = sizeof(*ptr) - sizeof(ptr->param) +
1815                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr->sizes));
1816         ptr->prev->next = ptr->next;
1817         ptr->next->prev = ptr->prev;
1818         if (ptr->use) {
1819                 internal_error(state, ptr, "ptr->use != 0");
1820         }
1821         put_occurance(ptr->occurance);
1822         memset(ptr, -1, size);
1823         xfree(ptr);
1824 }
1825
1826 static void release_triple(struct compile_state *state, struct triple *ptr)
1827 {
1828         struct triple_set *set, *next;
1829         struct triple **expr;
1830         /* Remove ptr from use chains where it is the user */
1831         expr = triple_rhs(state, ptr, 0);
1832         for(; expr; expr = triple_rhs(state, ptr, expr)) {
1833                 if (*expr) {
1834                         unuse_triple(*expr, ptr);
1835                 }
1836         }
1837         expr = triple_lhs(state, ptr, 0);
1838         for(; expr; expr = triple_lhs(state, ptr, expr)) {
1839                 if (*expr) {
1840                         unuse_triple(*expr, ptr);
1841                 }
1842         }
1843         expr = triple_misc(state, ptr, 0);
1844         for(; expr; expr = triple_misc(state, ptr, expr)) {
1845                 if (*expr) {
1846                         unuse_triple(*expr, ptr);
1847                 }
1848         }
1849         expr = triple_targ(state, ptr, 0);
1850         for(; expr; expr = triple_targ(state, ptr, expr)) {
1851                 if (*expr) {
1852                         unuse_triple(*expr, ptr);
1853                 }
1854         }
1855         /* Reomve ptr from use chains where it is used */
1856         for(set = ptr->use; set; set = next) {
1857                 next = set->next;
1858                 expr = triple_rhs(state, set->member, 0);
1859                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
1860                         if (*expr == ptr) {
1861                                 *expr = &zero_triple;
1862                         }
1863                 }
1864                 expr = triple_lhs(state, set->member, 0);
1865                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
1866                         if (*expr == ptr) {
1867                                 *expr = &zero_triple;
1868                         }
1869                 }
1870                 expr = triple_misc(state, set->member, 0);
1871                 for(; expr; expr = triple_misc(state, set->member, expr)) {
1872                         if (*expr == ptr) {
1873                                 *expr = &zero_triple;
1874                         }
1875                 }
1876                 expr = triple_targ(state, set->member, 0);
1877                 for(; expr; expr = triple_targ(state, set->member, expr)) {
1878                         if (*expr == ptr) {
1879                                 *expr = &zero_triple;
1880                         }
1881                 }
1882                 unuse_triple(ptr, set->member);
1883         }
1884         free_triple(state, ptr);
1885 }
1886
1887 static void print_triple(struct compile_state *state, struct triple *ptr);
1888
1889 #define TOK_UNKNOWN     0
1890 #define TOK_SPACE       1
1891 #define TOK_SEMI        2
1892 #define TOK_LBRACE      3
1893 #define TOK_RBRACE      4
1894 #define TOK_COMMA       5
1895 #define TOK_EQ          6
1896 #define TOK_COLON       7
1897 #define TOK_LBRACKET    8
1898 #define TOK_RBRACKET    9
1899 #define TOK_LPAREN      10
1900 #define TOK_RPAREN      11
1901 #define TOK_STAR        12
1902 #define TOK_DOTS        13
1903 #define TOK_MORE        14
1904 #define TOK_LESS        15
1905 #define TOK_TIMESEQ     16
1906 #define TOK_DIVEQ       17
1907 #define TOK_MODEQ       18
1908 #define TOK_PLUSEQ      19
1909 #define TOK_MINUSEQ     20
1910 #define TOK_SLEQ        21
1911 #define TOK_SREQ        22
1912 #define TOK_ANDEQ       23
1913 #define TOK_XOREQ       24
1914 #define TOK_OREQ        25
1915 #define TOK_EQEQ        26
1916 #define TOK_NOTEQ       27
1917 #define TOK_QUEST       28
1918 #define TOK_LOGOR       29
1919 #define TOK_LOGAND      30
1920 #define TOK_OR          31
1921 #define TOK_AND         32
1922 #define TOK_XOR         33
1923 #define TOK_LESSEQ      34
1924 #define TOK_MOREEQ      35
1925 #define TOK_SL          36
1926 #define TOK_SR          37
1927 #define TOK_PLUS        38
1928 #define TOK_MINUS       39
1929 #define TOK_DIV         40
1930 #define TOK_MOD         41
1931 #define TOK_PLUSPLUS    42
1932 #define TOK_MINUSMINUS  43
1933 #define TOK_BANG        44
1934 #define TOK_ARROW       45
1935 #define TOK_DOT         46
1936 #define TOK_TILDE       47
1937 #define TOK_LIT_STRING  48
1938 #define TOK_LIT_CHAR    49
1939 #define TOK_LIT_INT     50
1940 #define TOK_LIT_FLOAT   51
1941 #define TOK_MACRO       52
1942 #define TOK_CONCATENATE 53
1943
1944 #define TOK_IDENT       54
1945 #define TOK_STRUCT_NAME 55
1946 #define TOK_ENUM_CONST  56
1947 #define TOK_TYPE_NAME   57
1948
1949 #define TOK_AUTO        58
1950 #define TOK_BREAK       59
1951 #define TOK_CASE        60
1952 #define TOK_CHAR        61
1953 #define TOK_CONST       62
1954 #define TOK_CONTINUE    63
1955 #define TOK_DEFAULT     64
1956 #define TOK_DO          65
1957 #define TOK_DOUBLE      66
1958 #define TOK_ELSE        67
1959 #define TOK_ENUM        68
1960 #define TOK_EXTERN      69
1961 #define TOK_FLOAT       70
1962 #define TOK_FOR         71
1963 #define TOK_GOTO        72
1964 #define TOK_IF          73
1965 #define TOK_INLINE      74
1966 #define TOK_INT         75
1967 #define TOK_LONG        76
1968 #define TOK_REGISTER    77
1969 #define TOK_RESTRICT    78
1970 #define TOK_RETURN      79
1971 #define TOK_SHORT       80
1972 #define TOK_SIGNED      81
1973 #define TOK_SIZEOF      82
1974 #define TOK_STATIC      83
1975 #define TOK_STRUCT      84
1976 #define TOK_SWITCH      85
1977 #define TOK_TYPEDEF     86
1978 #define TOK_UNION       87
1979 #define TOK_UNSIGNED    88
1980 #define TOK_VOID        89
1981 #define TOK_VOLATILE    90
1982 #define TOK_WHILE       91
1983 #define TOK_ASM         92
1984 #define TOK_ATTRIBUTE   93
1985 #define TOK_ALIGNOF     94
1986 #define TOK_FIRST_KEYWORD TOK_AUTO
1987 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
1988
1989 #define TOK_DEFINE      100
1990 #define TOK_UNDEF       101
1991 #define TOK_INCLUDE     102
1992 #define TOK_LINE        103
1993 #define TOK_ERROR       104
1994 #define TOK_WARNING     105
1995 #define TOK_PRAGMA      106
1996 #define TOK_IFDEF       107
1997 #define TOK_IFNDEF      108
1998 #define TOK_ELIF        109
1999 #define TOK_ENDIF       110
2000
2001 #define TOK_FIRST_MACRO TOK_DEFINE
2002 #define TOK_LAST_MACRO  TOK_ENDIF
2003          
2004 #define TOK_EOF         111
2005
2006 static const char *tokens[] = {
2007 [TOK_UNKNOWN     ] = "unknown",
2008 [TOK_SPACE       ] = ":space:",
2009 [TOK_SEMI        ] = ";",
2010 [TOK_LBRACE      ] = "{",
2011 [TOK_RBRACE      ] = "}",
2012 [TOK_COMMA       ] = ",",
2013 [TOK_EQ          ] = "=",
2014 [TOK_COLON       ] = ":",
2015 [TOK_LBRACKET    ] = "[",
2016 [TOK_RBRACKET    ] = "]",
2017 [TOK_LPAREN      ] = "(",
2018 [TOK_RPAREN      ] = ")",
2019 [TOK_STAR        ] = "*",
2020 [TOK_DOTS        ] = "...",
2021 [TOK_MORE        ] = ">",
2022 [TOK_LESS        ] = "<",
2023 [TOK_TIMESEQ     ] = "*=",
2024 [TOK_DIVEQ       ] = "/=",
2025 [TOK_MODEQ       ] = "%=",
2026 [TOK_PLUSEQ      ] = "+=",
2027 [TOK_MINUSEQ     ] = "-=",
2028 [TOK_SLEQ        ] = "<<=",
2029 [TOK_SREQ        ] = ">>=",
2030 [TOK_ANDEQ       ] = "&=",
2031 [TOK_XOREQ       ] = "^=",
2032 [TOK_OREQ        ] = "|=",
2033 [TOK_EQEQ        ] = "==",
2034 [TOK_NOTEQ       ] = "!=",
2035 [TOK_QUEST       ] = "?",
2036 [TOK_LOGOR       ] = "||",
2037 [TOK_LOGAND      ] = "&&",
2038 [TOK_OR          ] = "|",
2039 [TOK_AND         ] = "&",
2040 [TOK_XOR         ] = "^",
2041 [TOK_LESSEQ      ] = "<=",
2042 [TOK_MOREEQ      ] = ">=",
2043 [TOK_SL          ] = "<<",
2044 [TOK_SR          ] = ">>",
2045 [TOK_PLUS        ] = "+",
2046 [TOK_MINUS       ] = "-",
2047 [TOK_DIV         ] = "/",
2048 [TOK_MOD         ] = "%",
2049 [TOK_PLUSPLUS    ] = "++",
2050 [TOK_MINUSMINUS  ] = "--",
2051 [TOK_BANG        ] = "!",
2052 [TOK_ARROW       ] = "->",
2053 [TOK_DOT         ] = ".",
2054 [TOK_TILDE       ] = "~",
2055 [TOK_LIT_STRING  ] = ":string:",
2056 [TOK_IDENT       ] = ":ident:",
2057 [TOK_TYPE_NAME   ] = ":typename:",
2058 [TOK_LIT_CHAR    ] = ":char:",
2059 [TOK_LIT_INT     ] = ":integer:",
2060 [TOK_LIT_FLOAT   ] = ":float:",
2061 [TOK_MACRO       ] = "#",
2062 [TOK_CONCATENATE ] = "##",
2063
2064 [TOK_AUTO        ] = "auto",
2065 [TOK_BREAK       ] = "break",
2066 [TOK_CASE        ] = "case",
2067 [TOK_CHAR        ] = "char",
2068 [TOK_CONST       ] = "const",
2069 [TOK_CONTINUE    ] = "continue",
2070 [TOK_DEFAULT     ] = "default",
2071 [TOK_DO          ] = "do",
2072 [TOK_DOUBLE      ] = "double",
2073 [TOK_ELSE        ] = "else",
2074 [TOK_ENUM        ] = "enum",
2075 [TOK_EXTERN      ] = "extern",
2076 [TOK_FLOAT       ] = "float",
2077 [TOK_FOR         ] = "for",
2078 [TOK_GOTO        ] = "goto",
2079 [TOK_IF          ] = "if",
2080 [TOK_INLINE      ] = "inline",
2081 [TOK_INT         ] = "int",
2082 [TOK_LONG        ] = "long",
2083 [TOK_REGISTER    ] = "register",
2084 [TOK_RESTRICT    ] = "restrict",
2085 [TOK_RETURN      ] = "return",
2086 [TOK_SHORT       ] = "short",
2087 [TOK_SIGNED      ] = "signed",
2088 [TOK_SIZEOF      ] = "sizeof",
2089 [TOK_STATIC      ] = "static",
2090 [TOK_STRUCT      ] = "struct",
2091 [TOK_SWITCH      ] = "switch",
2092 [TOK_TYPEDEF     ] = "typedef",
2093 [TOK_UNION       ] = "union",
2094 [TOK_UNSIGNED    ] = "unsigned",
2095 [TOK_VOID        ] = "void",
2096 [TOK_VOLATILE    ] = "volatile",
2097 [TOK_WHILE       ] = "while",
2098 [TOK_ASM         ] = "asm",
2099 [TOK_ATTRIBUTE   ] = "__attribute__",
2100 [TOK_ALIGNOF     ] = "__alignof__",
2101
2102 [TOK_DEFINE      ] = "define",
2103 [TOK_UNDEF       ] = "undef",
2104 [TOK_INCLUDE     ] = "include",
2105 [TOK_LINE        ] = "line",
2106 [TOK_ERROR       ] = "error",
2107 [TOK_WARNING     ] = "warning",
2108 [TOK_PRAGMA      ] = "pragma",
2109 [TOK_IFDEF       ] = "ifdef",
2110 [TOK_IFNDEF      ] = "ifndef",
2111 [TOK_ELIF        ] = "elif",
2112 [TOK_ENDIF       ] = "endif",
2113
2114 [TOK_EOF         ] = "EOF",
2115 };
2116
2117 static unsigned int hash(const char *str, int str_len)
2118 {
2119         unsigned int hash;
2120         const char *end;
2121         end = str + str_len;
2122         hash = 0;
2123         for(; str < end; str++) {
2124                 hash = (hash *263) + *str;
2125         }
2126         hash = hash & (HASH_TABLE_SIZE -1);
2127         return hash;
2128 }
2129
2130 static struct hash_entry *lookup(
2131         struct compile_state *state, const char *name, int name_len)
2132 {
2133         struct hash_entry *entry;
2134         unsigned int index;
2135         index = hash(name, name_len);
2136         entry = state->hash_table[index];
2137         while(entry && 
2138                 ((entry->name_len != name_len) ||
2139                         (memcmp(entry->name, name, name_len) != 0))) {
2140                 entry = entry->next;
2141         }
2142         if (!entry) {
2143                 char *new_name;
2144                 /* Get a private copy of the name */
2145                 new_name = xmalloc(name_len + 1, "hash_name");
2146                 memcpy(new_name, name, name_len);
2147                 new_name[name_len] = '\0';
2148
2149                 /* Create a new hash entry */
2150                 entry = xcmalloc(sizeof(*entry), "hash_entry");
2151                 entry->next = state->hash_table[index];
2152                 entry->name = new_name;
2153                 entry->name_len = name_len;
2154
2155                 /* Place the new entry in the hash table */
2156                 state->hash_table[index] = entry;
2157         }
2158         return entry;
2159 }
2160
2161 static void ident_to_keyword(struct compile_state *state, struct token *tk)
2162 {
2163         struct hash_entry *entry;
2164         entry = tk->ident;
2165         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
2166                 (entry->tok == TOK_ENUM_CONST) ||
2167                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
2168                         (entry->tok <= TOK_LAST_KEYWORD)))) {
2169                 tk->tok = entry->tok;
2170         }
2171 }
2172
2173 static void ident_to_macro(struct compile_state *state, struct token *tk)
2174 {
2175         struct hash_entry *entry;
2176         entry = tk->ident;
2177         if (entry && 
2178                 (entry->tok >= TOK_FIRST_MACRO) &&
2179                 (entry->tok <= TOK_LAST_MACRO)) {
2180                 tk->tok = entry->tok;
2181         }
2182 }
2183
2184 static void hash_keyword(
2185         struct compile_state *state, const char *keyword, int tok)
2186 {
2187         struct hash_entry *entry;
2188         entry = lookup(state, keyword, strlen(keyword));
2189         if (entry && entry->tok != TOK_UNKNOWN) {
2190                 die("keyword %s already hashed", keyword);
2191         }
2192         entry->tok  = tok;
2193 }
2194
2195 static void symbol(
2196         struct compile_state *state, struct hash_entry *ident,
2197         struct symbol **chain, struct triple *def, struct type *type)
2198 {
2199         struct symbol *sym;
2200         if (*chain && ((*chain)->scope_depth == state->scope_depth)) {
2201                 error(state, 0, "%s already defined", ident->name);
2202         }
2203         sym = xcmalloc(sizeof(*sym), "symbol");
2204         sym->ident = ident;
2205         sym->def   = def;
2206         sym->type  = type;
2207         sym->scope_depth = state->scope_depth;
2208         sym->next = *chain;
2209         *chain    = sym;
2210 }
2211
2212 static void label_symbol(struct compile_state *state, 
2213         struct hash_entry *ident, struct triple *label)
2214 {
2215         struct symbol *sym;
2216         if (ident->sym_label) {
2217                 error(state, 0, "label %s already defined", ident->name);
2218         }
2219         sym = xcmalloc(sizeof(*sym), "label");
2220         sym->ident = ident;
2221         sym->def   = label;
2222         sym->type  = &void_type;
2223         sym->scope_depth = FUNCTION_SCOPE_DEPTH;
2224         sym->next  = 0;
2225         ident->sym_label = sym;
2226 }
2227
2228 static void start_scope(struct compile_state *state)
2229 {
2230         state->scope_depth++;
2231 }
2232
2233 static void end_scope_syms(struct symbol **chain, int depth)
2234 {
2235         struct symbol *sym, *next;
2236         sym = *chain;
2237         while(sym && (sym->scope_depth == depth)) {
2238                 next = sym->next;
2239                 xfree(sym);
2240                 sym = next;
2241         }
2242         *chain = sym;
2243 }
2244
2245 static void end_scope(struct compile_state *state)
2246 {
2247         int i;
2248         int depth;
2249         /* Walk through the hash table and remove all symbols
2250          * in the current scope. 
2251          */
2252         depth = state->scope_depth;
2253         for(i = 0; i < HASH_TABLE_SIZE; i++) {
2254                 struct hash_entry *entry;
2255                 entry = state->hash_table[i];
2256                 while(entry) {
2257                         end_scope_syms(&entry->sym_label,  depth);
2258                         end_scope_syms(&entry->sym_struct, depth);
2259                         end_scope_syms(&entry->sym_ident,  depth);
2260                         entry = entry->next;
2261                 }
2262         }
2263         state->scope_depth = depth - 1;
2264 }
2265
2266 static void register_keywords(struct compile_state *state)
2267 {
2268         hash_keyword(state, "auto",          TOK_AUTO);
2269         hash_keyword(state, "break",         TOK_BREAK);
2270         hash_keyword(state, "case",          TOK_CASE);
2271         hash_keyword(state, "char",          TOK_CHAR);
2272         hash_keyword(state, "const",         TOK_CONST);
2273         hash_keyword(state, "continue",      TOK_CONTINUE);
2274         hash_keyword(state, "default",       TOK_DEFAULT);
2275         hash_keyword(state, "do",            TOK_DO);
2276         hash_keyword(state, "double",        TOK_DOUBLE);
2277         hash_keyword(state, "else",          TOK_ELSE);
2278         hash_keyword(state, "enum",          TOK_ENUM);
2279         hash_keyword(state, "extern",        TOK_EXTERN);
2280         hash_keyword(state, "float",         TOK_FLOAT);
2281         hash_keyword(state, "for",           TOK_FOR);
2282         hash_keyword(state, "goto",          TOK_GOTO);
2283         hash_keyword(state, "if",            TOK_IF);
2284         hash_keyword(state, "inline",        TOK_INLINE);
2285         hash_keyword(state, "int",           TOK_INT);
2286         hash_keyword(state, "long",          TOK_LONG);
2287         hash_keyword(state, "register",      TOK_REGISTER);
2288         hash_keyword(state, "restrict",      TOK_RESTRICT);
2289         hash_keyword(state, "return",        TOK_RETURN);
2290         hash_keyword(state, "short",         TOK_SHORT);
2291         hash_keyword(state, "signed",        TOK_SIGNED);
2292         hash_keyword(state, "sizeof",        TOK_SIZEOF);
2293         hash_keyword(state, "static",        TOK_STATIC);
2294         hash_keyword(state, "struct",        TOK_STRUCT);
2295         hash_keyword(state, "switch",        TOK_SWITCH);
2296         hash_keyword(state, "typedef",       TOK_TYPEDEF);
2297         hash_keyword(state, "union",         TOK_UNION);
2298         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
2299         hash_keyword(state, "void",          TOK_VOID);
2300         hash_keyword(state, "volatile",      TOK_VOLATILE);
2301         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
2302         hash_keyword(state, "while",         TOK_WHILE);
2303         hash_keyword(state, "asm",           TOK_ASM);
2304         hash_keyword(state, "__asm__",       TOK_ASM);
2305         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
2306         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
2307 }
2308
2309 static void register_macro_keywords(struct compile_state *state)
2310 {
2311         hash_keyword(state, "define",        TOK_DEFINE);
2312         hash_keyword(state, "undef",         TOK_UNDEF);
2313         hash_keyword(state, "include",       TOK_INCLUDE);
2314         hash_keyword(state, "line",          TOK_LINE);
2315         hash_keyword(state, "error",         TOK_ERROR);
2316         hash_keyword(state, "warning",       TOK_WARNING);
2317         hash_keyword(state, "pragma",        TOK_PRAGMA);
2318         hash_keyword(state, "ifdef",         TOK_IFDEF);
2319         hash_keyword(state, "ifndef",        TOK_IFNDEF);
2320         hash_keyword(state, "elif",          TOK_ELIF);
2321         hash_keyword(state, "endif",         TOK_ENDIF);
2322 }
2323
2324 static int spacep(int c)
2325 {
2326         int ret = 0;
2327         switch(c) {
2328         case ' ':
2329         case '\t':
2330         case '\f':
2331         case '\v':
2332         case '\r':
2333         case '\n':
2334                 ret = 1;
2335                 break;
2336         }
2337         return ret;
2338 }
2339
2340 static int digitp(int c)
2341 {
2342         int ret = 0;
2343         switch(c) {
2344         case '0': case '1': case '2': case '3': case '4': 
2345         case '5': case '6': case '7': case '8': case '9':
2346                 ret = 1;
2347                 break;
2348         }
2349         return ret;
2350 }
2351 static int digval(int c)
2352 {
2353         int val = -1;
2354         if ((c >= '0') && (c <= '9')) {
2355                 val = c - '0';
2356         }
2357         return val;
2358 }
2359
2360 static int hexdigitp(int c)
2361 {
2362         int ret = 0;
2363         switch(c) {
2364         case '0': case '1': case '2': case '3': case '4': 
2365         case '5': case '6': case '7': case '8': case '9':
2366         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
2367         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
2368                 ret = 1;
2369                 break;
2370         }
2371         return ret;
2372 }
2373 static int hexdigval(int c) 
2374 {
2375         int val = -1;
2376         if ((c >= '0') && (c <= '9')) {
2377                 val = c - '0';
2378         }
2379         else if ((c >= 'A') && (c <= 'F')) {
2380                 val = 10 + (c - 'A');
2381         }
2382         else if ((c >= 'a') && (c <= 'f')) {
2383                 val = 10 + (c - 'a');
2384         }
2385         return val;
2386 }
2387
2388 static int octdigitp(int c)
2389 {
2390         int ret = 0;
2391         switch(c) {
2392         case '0': case '1': case '2': case '3': 
2393         case '4': case '5': case '6': case '7':
2394                 ret = 1;
2395                 break;
2396         }
2397         return ret;
2398 }
2399 static int octdigval(int c)
2400 {
2401         int val = -1;
2402         if ((c >= '0') && (c <= '7')) {
2403                 val = c - '0';
2404         }
2405         return val;
2406 }
2407
2408 static int letterp(int c)
2409 {
2410         int ret = 0;
2411         switch(c) {
2412         case 'a': case 'b': case 'c': case 'd': case 'e':
2413         case 'f': case 'g': case 'h': case 'i': case 'j':
2414         case 'k': case 'l': case 'm': case 'n': case 'o':
2415         case 'p': case 'q': case 'r': case 's': case 't':
2416         case 'u': case 'v': case 'w': case 'x': case 'y':
2417         case 'z':
2418         case 'A': case 'B': case 'C': case 'D': case 'E':
2419         case 'F': case 'G': case 'H': case 'I': case 'J':
2420         case 'K': case 'L': case 'M': case 'N': case 'O':
2421         case 'P': case 'Q': case 'R': case 'S': case 'T':
2422         case 'U': case 'V': case 'W': case 'X': case 'Y':
2423         case 'Z':
2424         case '_':
2425                 ret = 1;
2426                 break;
2427         }
2428         return ret;
2429 }
2430
2431 static int char_value(struct compile_state *state,
2432         const signed char **strp, const signed char *end)
2433 {
2434         const signed char *str;
2435         int c;
2436         str = *strp;
2437         c = *str++;
2438         if ((c == '\\') && (str < end)) {
2439                 switch(*str) {
2440                 case 'n':  c = '\n'; str++; break;
2441                 case 't':  c = '\t'; str++; break;
2442                 case 'v':  c = '\v'; str++; break;
2443                 case 'b':  c = '\b'; str++; break;
2444                 case 'r':  c = '\r'; str++; break;
2445                 case 'f':  c = '\f'; str++; break;
2446                 case 'a':  c = '\a'; str++; break;
2447                 case '\\': c = '\\'; str++; break;
2448                 case '?':  c = '?';  str++; break;
2449                 case '\'': c = '\''; str++; break;
2450                 case '"':  c = '"';  break;
2451                 case 'x': 
2452                         c = 0;
2453                         str++;
2454                         while((str < end) && hexdigitp(*str)) {
2455                                 c <<= 4;
2456                                 c += hexdigval(*str);
2457                                 str++;
2458                         }
2459                         break;
2460                 case '0': case '1': case '2': case '3': 
2461                 case '4': case '5': case '6': case '7':
2462                         c = 0;
2463                         while((str < end) && octdigitp(*str)) {
2464                                 c <<= 3;
2465                                 c += octdigval(*str);
2466                                 str++;
2467                         }
2468                         break;
2469                 default:
2470                         error(state, 0, "Invalid character constant");
2471                         break;
2472                 }
2473         }
2474         *strp = str;
2475         return c;
2476 }
2477
2478 static char *after_digits(char *ptr, char *end)
2479 {
2480         while((ptr < end) && digitp(*ptr)) {
2481                 ptr++;
2482         }
2483         return ptr;
2484 }
2485
2486 static char *after_octdigits(char *ptr, char *end)
2487 {
2488         while((ptr < end) && octdigitp(*ptr)) {
2489                 ptr++;
2490         }
2491         return ptr;
2492 }
2493
2494 static char *after_hexdigits(char *ptr, char *end)
2495 {
2496         while((ptr < end) && hexdigitp(*ptr)) {
2497                 ptr++;
2498         }
2499         return ptr;
2500 }
2501
2502 static void save_string(struct compile_state *state, 
2503         struct token *tk, char *start, char *end, const char *id)
2504 {
2505         char *str;
2506         int str_len;
2507         /* Create a private copy of the string */
2508         str_len = end - start + 1;
2509         str = xmalloc(str_len + 1, id);
2510         memcpy(str, start, str_len);
2511         str[str_len] = '\0';
2512
2513         /* Store the copy in the token */
2514         tk->val.str = str;
2515         tk->str_len = str_len;
2516 }
2517 static void next_token(struct compile_state *state, int index)
2518 {
2519         struct file_state *file;
2520         struct token *tk;
2521         char *token;
2522         int c, c1, c2, c3;
2523         char *tokp, *end;
2524         int tok;
2525 next_token:
2526         file = state->file;
2527         tk = &state->token[index];
2528         tk->str_len = 0;
2529         tk->ident = 0;
2530         token = tokp = file->pos;
2531         end = file->buf + file->size;
2532         tok = TOK_UNKNOWN;
2533         c = -1;
2534         if (tokp < end) {
2535                 c = *tokp;
2536         }
2537         c1 = -1;
2538         if ((tokp + 1) < end) {
2539                 c1 = tokp[1];
2540         }
2541         c2 = -1;
2542         if ((tokp + 2) < end) {
2543                 c2 = tokp[2];
2544         }
2545         c3 = -1;
2546         if ((tokp + 3) < end) {
2547                 c3 = tokp[3];
2548         }
2549         if (tokp >= end) {
2550                 tok = TOK_EOF;
2551                 tokp = end;
2552         }
2553         /* Whitespace */
2554         else if (spacep(c)) {
2555                 tok = TOK_SPACE;
2556                 while ((tokp < end) && spacep(c)) {
2557                         if (c == '\n') {
2558                                 file->line++;
2559                                 file->report_line++;
2560                                 file->line_start = tokp + 1;
2561                         }
2562                         c = *(++tokp);
2563                 }
2564                 if (!spacep(c)) {
2565                         tokp--;
2566                 }
2567         }
2568         /* EOL Comments */
2569         else if ((c == '/') && (c1 == '/')) {
2570                 tok = TOK_SPACE;
2571                 for(tokp += 2; tokp < end; tokp++) {
2572                         c = *tokp;
2573                         if (c == '\n') {
2574                                 file->line++;
2575                                 file->report_line++;
2576                                 file->line_start = tokp +1;
2577                                 break;
2578                         }
2579                 }
2580         }
2581         /* Comments */
2582         else if ((c == '/') && (c1 == '*')) {
2583                 int line;
2584                 char *line_start;
2585                 line = file->line;
2586                 line_start = file->line_start;
2587                 for(tokp += 2; (end - tokp) >= 2; tokp++) {
2588                         c = *tokp;
2589                         if (c == '\n') {
2590                                 line++;
2591                                 line_start = tokp +1;
2592                         }
2593                         else if ((c == '*') && (tokp[1] == '/')) {
2594                                 tok = TOK_SPACE;
2595                                 tokp += 1;
2596                                 break;
2597                         }
2598                 }
2599                 if (tok == TOK_UNKNOWN) {
2600                         error(state, 0, "unterminated comment");
2601                 }
2602                 file->report_line += line - file->line;
2603                 file->line = line;
2604                 file->line_start = line_start;
2605         }
2606         /* string constants */
2607         else if ((c == '"') ||
2608                 ((c == 'L') && (c1 == '"'))) {
2609                 int line;
2610                 char *line_start;
2611                 int wchar;
2612                 line = file->line;
2613                 line_start = file->line_start;
2614                 wchar = 0;
2615                 if (c == 'L') {
2616                         wchar = 1;
2617                         tokp++;
2618                 }
2619                 for(tokp += 1; tokp < end; tokp++) {
2620                         c = *tokp;
2621                         if (c == '\n') {
2622                                 line++;
2623                                 line_start = tokp + 1;
2624                         }
2625                         else if ((c == '\\') && (tokp +1 < end)) {
2626                                 tokp++;
2627                         }
2628                         else if (c == '"') {
2629                                 tok = TOK_LIT_STRING;
2630                                 break;
2631                         }
2632                 }
2633                 if (tok == TOK_UNKNOWN) {
2634                         error(state, 0, "unterminated string constant");
2635                 }
2636                 if (line != file->line) {
2637                         warning(state, 0, "multiline string constant");
2638                 }
2639                 file->report_line += line - file->line;
2640                 file->line = line;
2641                 file->line_start = line_start;
2642
2643                 /* Save the string value */
2644                 save_string(state, tk, token, tokp, "literal string");
2645         }
2646         /* character constants */
2647         else if ((c == '\'') ||
2648                 ((c == 'L') && (c1 == '\''))) {
2649                 int line;
2650                 char *line_start;
2651                 int wchar;
2652                 line = file->line;
2653                 line_start = file->line_start;
2654                 wchar = 0;
2655                 if (c == 'L') {
2656                         wchar = 1;
2657                         tokp++;
2658                 }
2659                 for(tokp += 1; tokp < end; tokp++) {
2660                         c = *tokp;
2661                         if (c == '\n') {
2662                                 line++;
2663                                 line_start = tokp + 1;
2664                         }
2665                         else if ((c == '\\') && (tokp +1 < end)) {
2666                                 tokp++;
2667                         }
2668                         else if (c == '\'') {
2669                                 tok = TOK_LIT_CHAR;
2670                                 break;
2671                         }
2672                 }
2673                 if (tok == TOK_UNKNOWN) {
2674                         error(state, 0, "unterminated character constant");
2675                 }
2676                 if (line != file->line) {
2677                         warning(state, 0, "multiline character constant");
2678                 }
2679                 file->report_line += line - file->line;
2680                 file->line = line;
2681                 file->line_start = line_start;
2682
2683                 /* Save the character value */
2684                 save_string(state, tk, token, tokp, "literal character");
2685         }
2686         /* integer and floating constants 
2687          * Integer Constants
2688          * {digits}
2689          * 0[Xx]{hexdigits}
2690          * 0{octdigit}+
2691          * 
2692          * Floating constants
2693          * {digits}.{digits}[Ee][+-]?{digits}
2694          * {digits}.{digits}
2695          * {digits}[Ee][+-]?{digits}
2696          * .{digits}[Ee][+-]?{digits}
2697          * .{digits}
2698          */
2699         
2700         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
2701                 char *next, *new;
2702                 int is_float;
2703                 is_float = 0;
2704                 if (c != '.') {
2705                         next = after_digits(tokp, end);
2706                 }
2707                 else {
2708                         next = tokp;
2709                 }
2710                 if (next[0] == '.') {
2711                         new = after_digits(next, end);
2712                         is_float = (new != next);
2713                         next = new;
2714                 }
2715                 if ((next[0] == 'e') || (next[0] == 'E')) {
2716                         if (((next + 1) < end) && 
2717                                 ((next[1] == '+') || (next[1] == '-'))) {
2718                                 next++;
2719                         }
2720                         new = after_digits(next, end);
2721                         is_float = (new != next);
2722                         next = new;
2723                 }
2724                 if (is_float) {
2725                         tok = TOK_LIT_FLOAT;
2726                         if ((next < end) && (
2727                                 (next[0] == 'f') ||
2728                                 (next[0] == 'F') ||
2729                                 (next[0] == 'l') ||
2730                                 (next[0] == 'L'))
2731                                 ) {
2732                                 next++;
2733                         }
2734                 }
2735                 if (!is_float && digitp(c)) {
2736                         tok = TOK_LIT_INT;
2737                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
2738                                 next = after_hexdigits(tokp + 2, end);
2739                         }
2740                         else if (c == '0') {
2741                                 next = after_octdigits(tokp, end);
2742                         }
2743                         else {
2744                                 next = after_digits(tokp, end);
2745                         }
2746                         /* crazy integer suffixes */
2747                         if ((next < end) && 
2748                                 ((next[0] == 'u') || (next[0] == 'U'))) { 
2749                                 next++;
2750                                 if ((next < end) &&
2751                                         ((next[0] == 'l') || (next[0] == 'L'))) {
2752                                         next++;
2753                                 }
2754                         }
2755                         else if ((next < end) &&
2756                                 ((next[0] == 'l') || (next[0] == 'L'))) {
2757                                 next++;
2758                                 if ((next < end) && 
2759                                         ((next[0] == 'u') || (next[0] == 'U'))) { 
2760                                         next++;
2761                                 }
2762                         }
2763                 }
2764                 tokp = next - 1;
2765
2766                 /* Save the integer/floating point value */
2767                 save_string(state, tk, token, tokp, "literal number");
2768         }
2769         /* identifiers */
2770         else if (letterp(c)) {
2771                 tok = TOK_IDENT;
2772                 for(tokp += 1; tokp < end; tokp++) {
2773                         c = *tokp;
2774                         if (!letterp(c) && !digitp(c)) {
2775                                 break;
2776                         }
2777                 }
2778                 tokp -= 1;
2779                 tk->ident = lookup(state, token, tokp +1 - token);
2780         }
2781         /* C99 alternate macro characters */
2782         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
2783                 tokp += 3; 
2784                 tok = TOK_CONCATENATE; 
2785         }
2786         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { tokp += 2; tok = TOK_DOTS; }
2787         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { tokp += 2; tok = TOK_SLEQ; }
2788         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { tokp += 2; tok = TOK_SREQ; }
2789         else if ((c == '*') && (c1 == '=')) { tokp += 1; tok = TOK_TIMESEQ; }
2790         else if ((c == '/') && (c1 == '=')) { tokp += 1; tok = TOK_DIVEQ; }
2791         else if ((c == '%') && (c1 == '=')) { tokp += 1; tok = TOK_MODEQ; }
2792         else if ((c == '+') && (c1 == '=')) { tokp += 1; tok = TOK_PLUSEQ; }
2793         else if ((c == '-') && (c1 == '=')) { tokp += 1; tok = TOK_MINUSEQ; }
2794         else if ((c == '&') && (c1 == '=')) { tokp += 1; tok = TOK_ANDEQ; }
2795         else if ((c == '^') && (c1 == '=')) { tokp += 1; tok = TOK_XOREQ; }
2796         else if ((c == '|') && (c1 == '=')) { tokp += 1; tok = TOK_OREQ; }
2797         else if ((c == '=') && (c1 == '=')) { tokp += 1; tok = TOK_EQEQ; }
2798         else if ((c == '!') && (c1 == '=')) { tokp += 1; tok = TOK_NOTEQ; }
2799         else if ((c == '|') && (c1 == '|')) { tokp += 1; tok = TOK_LOGOR; }
2800         else if ((c == '&') && (c1 == '&')) { tokp += 1; tok = TOK_LOGAND; }
2801         else if ((c == '<') && (c1 == '=')) { tokp += 1; tok = TOK_LESSEQ; }
2802         else if ((c == '>') && (c1 == '=')) { tokp += 1; tok = TOK_MOREEQ; }
2803         else if ((c == '<') && (c1 == '<')) { tokp += 1; tok = TOK_SL; }
2804         else if ((c == '>') && (c1 == '>')) { tokp += 1; tok = TOK_SR; }
2805         else if ((c == '+') && (c1 == '+')) { tokp += 1; tok = TOK_PLUSPLUS; }
2806         else if ((c == '-') && (c1 == '-')) { tokp += 1; tok = TOK_MINUSMINUS; }
2807         else if ((c == '-') && (c1 == '>')) { tokp += 1; tok = TOK_ARROW; }
2808         else if ((c == '<') && (c1 == ':')) { tokp += 1; tok = TOK_LBRACKET; }
2809         else if ((c == ':') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACKET; }
2810         else if ((c == '<') && (c1 == '%')) { tokp += 1; tok = TOK_LBRACE; }
2811         else if ((c == '%') && (c1 == '>')) { tokp += 1; tok = TOK_RBRACE; }
2812         else if ((c == '%') && (c1 == ':')) { tokp += 1; tok = TOK_MACRO; }
2813         else if ((c == '#') && (c1 == '#')) { tokp += 1; tok = TOK_CONCATENATE; }
2814         else if (c == ';') { tok = TOK_SEMI; }
2815         else if (c == '{') { tok = TOK_LBRACE; }
2816         else if (c == '}') { tok = TOK_RBRACE; }
2817         else if (c == ',') { tok = TOK_COMMA; }
2818         else if (c == '=') { tok = TOK_EQ; }
2819         else if (c == ':') { tok = TOK_COLON; }
2820         else if (c == '[') { tok = TOK_LBRACKET; }
2821         else if (c == ']') { tok = TOK_RBRACKET; }
2822         else if (c == '(') { tok = TOK_LPAREN; }
2823         else if (c == ')') { tok = TOK_RPAREN; }
2824         else if (c == '*') { tok = TOK_STAR; }
2825         else if (c == '>') { tok = TOK_MORE; }
2826         else if (c == '<') { tok = TOK_LESS; }
2827         else if (c == '?') { tok = TOK_QUEST; }
2828         else if (c == '|') { tok = TOK_OR; }
2829         else if (c == '&') { tok = TOK_AND; }
2830         else if (c == '^') { tok = TOK_XOR; }
2831         else if (c == '+') { tok = TOK_PLUS; }
2832         else if (c == '-') { tok = TOK_MINUS; }
2833         else if (c == '/') { tok = TOK_DIV; }
2834         else if (c == '%') { tok = TOK_MOD; }
2835         else if (c == '!') { tok = TOK_BANG; }
2836         else if (c == '.') { tok = TOK_DOT; }
2837         else if (c == '~') { tok = TOK_TILDE; }
2838         else if (c == '#') { tok = TOK_MACRO; }
2839         if (tok == TOK_MACRO) {
2840                 /* Only match preprocessor directives at the start of a line */
2841                 char *ptr;
2842                 for(ptr = file->line_start; spacep(*ptr); ptr++)
2843                         ;
2844                 if (ptr != tokp) {
2845                         tok = TOK_UNKNOWN;
2846                 }
2847         }
2848         if (tok == TOK_UNKNOWN) {
2849                 error(state, 0, "unknown token");
2850         }
2851
2852         file->pos = tokp + 1;
2853         tk->tok = tok;
2854         if (tok == TOK_IDENT) {
2855                 ident_to_keyword(state, tk);
2856         }
2857         /* Don't return space tokens. */
2858         if (tok == TOK_SPACE) {
2859                 goto next_token;
2860         }
2861 }
2862
2863 static void compile_macro(struct compile_state *state, struct token *tk)
2864 {
2865         struct file_state *file;
2866         struct hash_entry *ident;
2867         ident = tk->ident;
2868         file = xmalloc(sizeof(*file), "file_state");
2869         file->basename = xstrdup(tk->ident->name);
2870         file->dirname = xstrdup("");
2871         file->size = ident->sym_define->buf_len;
2872         file->buf = xmalloc(file->size +2,  file->basename);
2873         memcpy(file->buf, ident->sym_define->buf, file->size);
2874         file->buf[file->size] = '\n';
2875         file->buf[file->size + 1] = '\0';
2876         file->pos = file->buf;
2877         file->line_start = file->pos;
2878         file->line = 1;
2879         file->report_line = 1;
2880         file->report_name = file->basename;
2881         file->report_dir  = file->dirname;
2882         file->prev = state->file;
2883         state->file = file;
2884 }
2885
2886
2887 static int mpeek(struct compile_state *state, int index)
2888 {
2889         struct token *tk;
2890         int rescan;
2891         tk = &state->token[index + 1];
2892         if (tk->tok == -1) {
2893                 next_token(state, index + 1);
2894         }
2895         do {
2896                 rescan = 0;
2897                 if ((tk->tok == TOK_EOF) && 
2898                         (state->file != state->macro_file) &&
2899                         (state->file->prev)) {
2900                         struct file_state *file = state->file;
2901                         state->file = file->prev;
2902                         /* file->basename is used keep it */
2903                         if (file->report_dir != file->dirname) {
2904                                 xfree(file->report_dir);
2905                         }
2906                         xfree(file->dirname);
2907                         xfree(file->buf);
2908                         xfree(file);
2909                         next_token(state, index + 1);
2910                         rescan = 1;
2911                 }
2912                 else if (tk->ident && tk->ident->sym_define) {
2913                         compile_macro(state, tk);
2914                         next_token(state, index + 1);
2915                         rescan = 1;
2916                 }
2917         } while(rescan);
2918         /* Don't show the token on the next line */
2919         if (state->macro_line < state->macro_file->line) {
2920                 return TOK_EOF;
2921         }
2922         return state->token[index +1].tok;
2923 }
2924
2925 static void meat(struct compile_state *state, int index, int tok)
2926 {
2927         int next_tok;
2928         int i;
2929         next_tok = mpeek(state, index);
2930         if (next_tok != tok) {
2931                 const char *name1, *name2;
2932                 name1 = tokens[next_tok];
2933                 name2 = "";
2934                 if (next_tok == TOK_IDENT) {
2935                         name2 = state->token[index + 1].ident->name;
2936                 }
2937                 error(state, 0, "found %s %s expected %s", 
2938                         name1, name2, tokens[tok]);
2939         }
2940         /* Free the old token value */
2941         if (state->token[index].str_len) {
2942                 memset((void *)(state->token[index].val.str), -1, 
2943                         state->token[index].str_len);
2944                 xfree(state->token[index].val.str);
2945         }
2946         for(i = index; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
2947                 state->token[i] = state->token[i + 1];
2948         }
2949         memset(&state->token[i], 0, sizeof(state->token[i]));
2950         state->token[i].tok = -1;
2951 }
2952
2953 static long_t mcexpr(struct compile_state *state, int index);
2954
2955 static long_t mprimary_expr(struct compile_state *state, int index)
2956 {
2957         long_t val;
2958         int tok;
2959         tok = mpeek(state, index);
2960         while(state->token[index + 1].ident && 
2961                 state->token[index + 1].ident->sym_define) {
2962                 meat(state, index, tok);
2963                 compile_macro(state, &state->token[index]);
2964                 tok = mpeek(state, index);
2965         }
2966         switch(tok) {
2967         case TOK_LPAREN:
2968                 meat(state, index, TOK_LPAREN);
2969                 val = mcexpr(state, index);
2970                 meat(state, index, TOK_RPAREN);
2971                 break;
2972         case TOK_LIT_INT:
2973         {
2974                 char *end;
2975                 meat(state, index, TOK_LIT_INT);
2976                 errno = 0;
2977                 val = strtol(state->token[index].val.str, &end, 0);
2978                 if (((val == LONG_MIN) || (val == LONG_MAX)) &&
2979                         (errno == ERANGE)) {
2980                         error(state, 0, "Integer constant to large");
2981                 }
2982                 break;
2983         }
2984         default:
2985                 meat(state, index, TOK_LIT_INT);
2986                 val = 0;
2987         }
2988         return val;
2989 }
2990 static long_t munary_expr(struct compile_state *state, int index)
2991 {
2992         long_t val;
2993         switch(mpeek(state, index)) {
2994         case TOK_PLUS:
2995                 meat(state, index, TOK_PLUS);
2996                 val = munary_expr(state, index);
2997                 val = + val;
2998                 break;
2999         case TOK_MINUS:
3000                 meat(state, index, TOK_MINUS);
3001                 val = munary_expr(state, index);
3002                 val = - val;
3003                 break;
3004         case TOK_TILDE:
3005                 meat(state, index, TOK_BANG);
3006                 val = munary_expr(state, index);
3007                 val = ~ val;
3008                 break;
3009         case TOK_BANG:
3010                 meat(state, index, TOK_BANG);
3011                 val = munary_expr(state, index);
3012                 val = ! val;
3013                 break;
3014         default:
3015                 val = mprimary_expr(state, index);
3016                 break;
3017         }
3018         return val;
3019         
3020 }
3021 static long_t mmul_expr(struct compile_state *state, int index)
3022 {
3023         long_t val;
3024         int done;
3025         val = munary_expr(state, index);
3026         do {
3027                 long_t right;
3028                 done = 0;
3029                 switch(mpeek(state, index)) {
3030                 case TOK_STAR:
3031                         meat(state, index, TOK_STAR);
3032                         right = munary_expr(state, index);
3033                         val = val * right;
3034                         break;
3035                 case TOK_DIV:
3036                         meat(state, index, TOK_DIV);
3037                         right = munary_expr(state, index);
3038                         val = val / right;
3039                         break;
3040                 case TOK_MOD:
3041                         meat(state, index, TOK_MOD);
3042                         right = munary_expr(state, index);
3043                         val = val % right;
3044                         break;
3045                 default:
3046                         done = 1;
3047                         break;
3048                 }
3049         } while(!done);
3050
3051         return val;
3052 }
3053
3054 static long_t madd_expr(struct compile_state *state, int index)
3055 {
3056         long_t val;
3057         int done;
3058         val = mmul_expr(state, index);
3059         do {
3060                 long_t right;
3061                 done = 0;
3062                 switch(mpeek(state, index)) {
3063                 case TOK_PLUS:
3064                         meat(state, index, TOK_PLUS);
3065                         right = mmul_expr(state, index);
3066                         val = val + right;
3067                         break;
3068                 case TOK_MINUS:
3069                         meat(state, index, TOK_MINUS);
3070                         right = mmul_expr(state, index);
3071                         val = val - right;
3072                         break;
3073                 default:
3074                         done = 1;
3075                         break;
3076                 }
3077         } while(!done);
3078
3079         return val;
3080 }
3081
3082 static long_t mshift_expr(struct compile_state *state, int index)
3083 {
3084         long_t val;
3085         int done;
3086         val = madd_expr(state, index);
3087         do {
3088                 long_t right;
3089                 done = 0;
3090                 switch(mpeek(state, index)) {
3091                 case TOK_SL:
3092                         meat(state, index, TOK_SL);
3093                         right = madd_expr(state, index);
3094                         val = val << right;
3095                         break;
3096                 case TOK_SR:
3097                         meat(state, index, TOK_SR);
3098                         right = madd_expr(state, index);
3099                         val = val >> right;
3100                         break;
3101                 default:
3102                         done = 1;
3103                         break;
3104                 }
3105         } while(!done);
3106
3107         return val;
3108 }
3109
3110 static long_t mrel_expr(struct compile_state *state, int index)
3111 {
3112         long_t val;
3113         int done;
3114         val = mshift_expr(state, index);
3115         do {
3116                 long_t right;
3117                 done = 0;
3118                 switch(mpeek(state, index)) {
3119                 case TOK_LESS:
3120                         meat(state, index, TOK_LESS);
3121                         right = mshift_expr(state, index);
3122                         val = val < right;
3123                         break;
3124                 case TOK_MORE:
3125                         meat(state, index, TOK_MORE);
3126                         right = mshift_expr(state, index);
3127                         val = val > right;
3128                         break;
3129                 case TOK_LESSEQ:
3130                         meat(state, index, TOK_LESSEQ);
3131                         right = mshift_expr(state, index);
3132                         val = val <= right;
3133                         break;
3134                 case TOK_MOREEQ:
3135                         meat(state, index, TOK_MOREEQ);
3136                         right = mshift_expr(state, index);
3137                         val = val >= right;
3138                         break;
3139                 default:
3140                         done = 1;
3141                         break;
3142                 }
3143         } while(!done);
3144         return val;
3145 }
3146
3147 static long_t meq_expr(struct compile_state *state, int index)
3148 {
3149         long_t val;
3150         int done;
3151         val = mrel_expr(state, index);
3152         do {
3153                 long_t right;
3154                 done = 0;
3155                 switch(mpeek(state, index)) {
3156                 case TOK_EQEQ:
3157                         meat(state, index, TOK_EQEQ);
3158                         right = mrel_expr(state, index);
3159                         val = val == right;
3160                         break;
3161                 case TOK_NOTEQ:
3162                         meat(state, index, TOK_NOTEQ);
3163                         right = mrel_expr(state, index);
3164                         val = val != right;
3165                         break;
3166                 default:
3167                         done = 1;
3168                         break;
3169                 }
3170         } while(!done);
3171         return val;
3172 }
3173
3174 static long_t mand_expr(struct compile_state *state, int index)
3175 {
3176         long_t val;
3177         val = meq_expr(state, index);
3178         if (mpeek(state, index) == TOK_AND) {
3179                 long_t right;
3180                 meat(state, index, TOK_AND);
3181                 right = meq_expr(state, index);
3182                 val = val & right;
3183         }
3184         return val;
3185 }
3186
3187 static long_t mxor_expr(struct compile_state *state, int index)
3188 {
3189         long_t val;
3190         val = mand_expr(state, index);
3191         if (mpeek(state, index) == TOK_XOR) {
3192                 long_t right;
3193                 meat(state, index, TOK_XOR);
3194                 right = mand_expr(state, index);
3195                 val = val ^ right;
3196         }
3197         return val;
3198 }
3199
3200 static long_t mor_expr(struct compile_state *state, int index)
3201 {
3202         long_t val;
3203         val = mxor_expr(state, index);
3204         if (mpeek(state, index) == TOK_OR) {
3205                 long_t right;
3206                 meat(state, index, TOK_OR);
3207                 right = mxor_expr(state, index);
3208                 val = val | right;
3209         }
3210         return val;
3211 }
3212
3213 static long_t mland_expr(struct compile_state *state, int index)
3214 {
3215         long_t val;
3216         val = mor_expr(state, index);
3217         if (mpeek(state, index) == TOK_LOGAND) {
3218                 long_t right;
3219                 meat(state, index, TOK_LOGAND);
3220                 right = mor_expr(state, index);
3221                 val = val && right;
3222         }
3223         return val;
3224 }
3225 static long_t mlor_expr(struct compile_state *state, int index)
3226 {
3227         long_t val;
3228         val = mland_expr(state, index);
3229         if (mpeek(state, index) == TOK_LOGOR) {
3230                 long_t right;
3231                 meat(state, index, TOK_LOGOR);
3232                 right = mland_expr(state, index);
3233                 val = val || right;
3234         }
3235         return val;
3236 }
3237
3238 static long_t mcexpr(struct compile_state *state, int index)
3239 {
3240         return mlor_expr(state, index);
3241 }
3242 static void preprocess(struct compile_state *state, int index)
3243 {
3244         /* Doing much more with the preprocessor would require
3245          * a parser and a major restructuring.
3246          * Postpone that for later.
3247          */
3248         struct file_state *file;
3249         struct token *tk;
3250         int line;
3251         int tok;
3252         
3253         file = state->file;
3254         tk = &state->token[index];
3255         state->macro_line = line = file->line;
3256         state->macro_file = file;
3257
3258         next_token(state, index);
3259         ident_to_macro(state, tk);
3260         if (tk->tok == TOK_IDENT) {
3261                 error(state, 0, "undefined preprocessing directive `%s'",
3262                         tk->ident->name);
3263         }
3264         switch(tk->tok) {
3265         case TOK_LIT_INT:
3266         {
3267                 int override_line;
3268                 override_line = strtoul(tk->val.str, 0, 10);
3269                 next_token(state, index);
3270                 /* I have a cpp line marker parse it */
3271                 if (tk->tok == TOK_LIT_STRING) {
3272                         const char *token, *base;
3273                         char *name, *dir;
3274                         int name_len, dir_len;
3275                         name = xmalloc(tk->str_len, "report_name");
3276                         token = tk->val.str + 1;
3277                         base = strrchr(token, '/');
3278                         name_len = tk->str_len -2;
3279                         if (base != 0) {
3280                                 dir_len = base - token;
3281                                 base++;
3282                                 name_len -= base - token;
3283                         } else {
3284                                 dir_len = 0;
3285                                 base = token;
3286                         }
3287                         memcpy(name, base, name_len);
3288                         name[name_len] = '\0';
3289                         dir = xmalloc(dir_len + 1, "report_dir");
3290                         memcpy(dir, token, dir_len);
3291                         dir[dir_len] = '\0';
3292                         file->report_line = override_line - 1;
3293                         file->report_name = name;
3294                         file->report_dir = dir;
3295                 }
3296         }
3297                 break;
3298         case TOK_LINE:
3299                 meat(state, index, TOK_LINE);
3300                 meat(state, index, TOK_LIT_INT);
3301                 file->report_line = strtoul(tk->val.str, 0, 10) -1;
3302                 if (mpeek(state, index) == TOK_LIT_STRING) {
3303                         const char *token, *base;
3304                         char *name, *dir;
3305                         int name_len, dir_len;
3306                         meat(state, index, TOK_LIT_STRING);
3307                         name = xmalloc(tk->str_len, "report_name");
3308                         token = tk->val.str + 1;
3309                         name_len = tk->str_len - 2;
3310                         if (base != 0) {
3311                                 dir_len = base - token;
3312                                 base++;
3313                                 name_len -= base - token;
3314                         } else {
3315                                 dir_len = 0;
3316                                 base = token;
3317                         }
3318                         memcpy(name, base, name_len);
3319                         name[name_len] = '\0';
3320                         dir = xmalloc(dir_len + 1, "report_dir");
3321                         memcpy(dir, token, dir_len);
3322                         dir[dir_len] = '\0';
3323                         file->report_name = name;
3324                         file->report_dir = dir;
3325                 }
3326                 break;
3327         case TOK_UNDEF:
3328         case TOK_PRAGMA:
3329                 if (state->if_value < 0) {
3330                         break;
3331                 }
3332                 warning(state, 0, "Ignoring preprocessor directive: %s", 
3333                         tk->ident->name);
3334                 break;
3335         case TOK_ELIF:
3336                 error(state, 0, "#elif not supported");
3337 #warning "FIXME multiple #elif and #else in an #if do not work properly"
3338                 if (state->if_depth == 0) {
3339                         error(state, 0, "#elif without #if");
3340                 }
3341                 /* If the #if was taken the #elif just disables the following code */
3342                 if (state->if_value >= 0) {
3343                         state->if_value = - state->if_value;
3344                 }
3345                 /* If the previous #if was not taken see if the #elif enables the 
3346                  * trailing code.
3347                  */
3348                 else if ((state->if_value < 0) && 
3349                         (state->if_depth == - state->if_value))
3350                 {
3351                         if (mcexpr(state, index) != 0) {
3352                                 state->if_value = state->if_depth;
3353                         }
3354                         else {
3355                                 state->if_value = - state->if_depth;
3356                         }
3357                 }
3358                 break;
3359         case TOK_IF:
3360                 state->if_depth++;
3361                 if (state->if_value < 0) {
3362                         break;
3363                 }
3364                 if (mcexpr(state, index) != 0) {
3365                         state->if_value = state->if_depth;
3366                 }
3367                 else {
3368                         state->if_value = - state->if_depth;
3369                 }
3370                 break;
3371         case TOK_IFNDEF:
3372                 state->if_depth++;
3373                 if (state->if_value < 0) {
3374                         break;
3375                 }
3376                 next_token(state, index);
3377                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3378                         error(state, 0, "Invalid macro name");
3379                 }
3380                 if (tk->ident->sym_define == 0) {
3381                         state->if_value = state->if_depth;
3382                 } 
3383                 else {
3384                         state->if_value = - state->if_depth;
3385                 }
3386                 break;
3387         case TOK_IFDEF:
3388                 state->if_depth++;
3389                 if (state->if_value < 0) {
3390                         break;
3391                 }
3392                 next_token(state, index);
3393                 if ((line != file->line) || (tk->tok != TOK_IDENT)) {
3394                         error(state, 0, "Invalid macro name");
3395                 }
3396                 if (tk->ident->sym_define != 0) {
3397                         state->if_value = state->if_depth;
3398                 }
3399                 else {
3400                         state->if_value = - state->if_depth;
3401                 }
3402                 break;
3403         case TOK_ELSE:
3404                 if (state->if_depth == 0) {
3405                         error(state, 0, "#else without #if");
3406                 }
3407                 if ((state->if_value >= 0) ||
3408                         ((state->if_value < 0) && 
3409                                 (state->if_depth == -state->if_value)))
3410                 {
3411                         state->if_value = - state->if_value;
3412                 }
3413                 break;
3414         case TOK_ENDIF:
3415                 if (state->if_depth == 0) {
3416                         error(state, 0, "#endif without #if");
3417                 }
3418                 if ((state->if_value >= 0) ||
3419                         ((state->if_value < 0) &&
3420                                 (state->if_depth == -state->if_value))) 
3421                 {
3422                         state->if_value = state->if_depth - 1;
3423                 }
3424                 state->if_depth--;
3425                 break;
3426         case TOK_DEFINE:
3427         {
3428                 struct hash_entry *ident;
3429                 struct macro *macro;
3430                 char *ptr;
3431                 
3432                 if (state->if_value < 0) /* quit early when #if'd out */
3433                         break;
3434
3435                 meat(state, index, TOK_IDENT);
3436                 ident = tk->ident;
3437                 
3438
3439                 if (*file->pos == '(') {
3440 #warning "FIXME macros with arguments not supported"
3441                         error(state, 0, "Macros with arguments not supported");
3442                 }
3443
3444                 /* Find the end of the line to get an estimate of
3445                  * the macro's length.
3446                  */
3447                 for(ptr = file->pos; *ptr != '\n'; ptr++)  
3448                         ;
3449
3450                 if (ident->sym_define != 0) {
3451                         error(state, 0, "macro %s already defined\n", ident->name);
3452                 }
3453                 macro = xmalloc(sizeof(*macro), "macro");
3454                 macro->ident = ident;
3455                 macro->buf_len = ptr - file->pos +1;
3456                 macro->buf = xmalloc(macro->buf_len +2, "macro buf");
3457
3458                 memcpy(macro->buf, file->pos, macro->buf_len);
3459                 macro->buf[macro->buf_len] = '\n';
3460                 macro->buf[macro->buf_len +1] = '\0';
3461
3462                 ident->sym_define = macro;
3463                 break;
3464         }
3465         case TOK_ERROR:
3466         {
3467                 char *end;
3468                 int len;
3469                 /* Find the end of the line */
3470                 for(end = file->pos; *end != '\n'; end++)
3471                         ;
3472                 len = (end - file->pos);
3473                 if (state->if_value >= 0) {
3474                         error(state, 0, "%*.*s", len, len, file->pos);
3475                 }
3476                 file->pos = end;
3477                 break;
3478         }
3479         case TOK_WARNING:
3480         {
3481                 char *end;
3482                 int len;
3483                 /* Find the end of the line */
3484                 for(end = file->pos; *end != '\n'; end++)
3485                         ;
3486                 len = (end - file->pos);
3487                 if (state->if_value >= 0) {
3488                         warning(state, 0, "%*.*s", len, len, file->pos);
3489                 }
3490                 file->pos = end;
3491                 break;
3492         }
3493         case TOK_INCLUDE:
3494         {
3495                 char *name;
3496                 char *ptr;
3497                 int local;
3498                 local = 0;
3499                 name = 0;
3500                 next_token(state, index);
3501                 if (tk->tok == TOK_LIT_STRING) {
3502                         const char *token;
3503                         int name_len;
3504                         name = xmalloc(tk->str_len, "include");
3505                         token = tk->val.str +1;
3506                         name_len = tk->str_len -2;
3507                         if (*token == '"') {
3508                                 token++;
3509                                 name_len--;
3510                         }
3511                         memcpy(name, token, name_len);
3512                         name[name_len] = '\0';
3513                         local = 1;
3514                 }
3515                 else if (tk->tok == TOK_LESS) {
3516                         char *start, *end;
3517                         start = file->pos;
3518                         for(end = start; *end != '\n'; end++) {
3519                                 if (*end == '>') {
3520                                         break;
3521                                 }
3522                         }
3523                         if (*end == '\n') {
3524                                 error(state, 0, "Unterminated included directive");
3525                         }
3526                         name = xmalloc(end - start + 1, "include");
3527                         memcpy(name, start, end - start);
3528                         name[end - start] = '\0';
3529                         file->pos = end +1;
3530                         local = 0;
3531                 }
3532                 else {
3533                         error(state, 0, "Invalid include directive");
3534                 }
3535                 /* Error if there are any characters after the include */
3536                 for(ptr = file->pos; *ptr != '\n'; ptr++) {
3537                         switch(*ptr) {
3538                         case ' ':
3539                         case '\t':
3540                         case '\v':
3541                                 break;
3542                         default:
3543                                 error(state, 0, "garbage after include directive");
3544                         }
3545                 }
3546                 if (state->if_value >= 0) {
3547                         compile_file(state, name, local);
3548                 }
3549                 xfree(name);
3550                 next_token(state, index);
3551                 return;
3552         }
3553         default:
3554                 /* Ignore # without a following ident */
3555                 if (tk->tok == TOK_IDENT) {
3556                         error(state, 0, "Invalid preprocessor directive: %s", 
3557                                 tk->ident->name);
3558                 }
3559                 break;
3560         }
3561         /* Consume the rest of the macro line */
3562         do {
3563                 tok = mpeek(state, index);
3564                 meat(state, index, tok);
3565         } while(tok != TOK_EOF);
3566         return;
3567 }
3568
3569 static void token(struct compile_state *state, int index)
3570 {
3571         struct file_state *file;
3572         struct token *tk;
3573         int rescan;
3574
3575         tk = &state->token[index];
3576         next_token(state, index);
3577         do {
3578                 rescan = 0;
3579                 file = state->file;
3580                 if (tk->tok == TOK_EOF && file->prev) {
3581                         state->file = file->prev;
3582                         /* file->basename is used keep it */
3583                         xfree(file->dirname);
3584                         xfree(file->buf);
3585                         xfree(file);
3586                         next_token(state, index);
3587                         rescan = 1;
3588                 }
3589                 else if (tk->tok == TOK_MACRO) {
3590                         preprocess(state, index);
3591                         rescan = 1;
3592                 }
3593                 else if (tk->ident && tk->ident->sym_define) {
3594                         compile_macro(state, tk);
3595                         next_token(state, index);
3596                         rescan = 1;
3597                 }
3598                 else if (state->if_value < 0) {
3599                         next_token(state, index);
3600                         rescan = 1;
3601                 }
3602         } while(rescan);
3603 }
3604
3605 static int peek(struct compile_state *state)
3606 {
3607         if (state->token[1].tok == -1) {
3608                 token(state, 1);
3609         }
3610         return state->token[1].tok;
3611 }
3612
3613 static int peek2(struct compile_state *state)
3614 {
3615         if (state->token[1].tok == -1) {
3616                 token(state, 1);
3617         }
3618         if (state->token[2].tok == -1) {
3619                 token(state, 2);
3620         }
3621         return state->token[2].tok;
3622 }
3623
3624 static void eat(struct compile_state *state, int tok)
3625 {
3626         int next_tok;
3627         int i;
3628         next_tok = peek(state);
3629         if (next_tok != tok) {
3630                 const char *name1, *name2;
3631                 name1 = tokens[next_tok];
3632                 name2 = "";
3633                 if (next_tok == TOK_IDENT) {
3634                         name2 = state->token[1].ident->name;
3635                 }
3636                 error(state, 0, "\tfound %s %s expected %s",
3637                         name1, name2 ,tokens[tok]);
3638         }
3639         /* Free the old token value */
3640         if (state->token[0].str_len) {
3641                 xfree((void *)(state->token[0].val.str));
3642         }
3643         for(i = 0; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
3644                 state->token[i] = state->token[i + 1];
3645         }
3646         memset(&state->token[i], 0, sizeof(state->token[i]));
3647         state->token[i].tok = -1;
3648 }
3649
3650 #warning "FIXME do not hardcode the include paths"
3651 static char *include_paths[] = {
3652         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/include",
3653         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src/arch/i386/include",
3654         "/home/eric/projects/linuxbios/checkin/solo/freebios2/src",
3655         0
3656 };
3657
3658 static void compile_file(struct compile_state *state, const char *filename, int local)
3659 {
3660         char cwd[4096];
3661         const char *subdir, *base;
3662         int subdir_len;
3663         struct file_state *file;
3664         char *basename;
3665         file = xmalloc(sizeof(*file), "file_state");
3666
3667         base = strrchr(filename, '/');
3668         subdir = filename;
3669         if (base != 0) {
3670                 subdir_len = base - filename;
3671                 base++;
3672         }
3673         else {
3674                 base = filename;
3675                 subdir_len = 0;
3676         }
3677         basename = xmalloc(strlen(base) +1, "basename");
3678         strcpy(basename, base);
3679         file->basename = basename;
3680
3681         if (getcwd(cwd, sizeof(cwd)) == 0) {
3682                 die("cwd buffer to small");
3683         }
3684         
3685         if (subdir[0] == '/') {
3686                 file->dirname = xmalloc(subdir_len + 1, "dirname");
3687                 memcpy(file->dirname, subdir, subdir_len);
3688                 file->dirname[subdir_len] = '\0';
3689         }
3690         else {
3691                 char *dir;
3692                 int dirlen;
3693                 char **path;
3694                 /* Find the appropriate directory... */
3695                 dir = 0;
3696                 if (!state->file && exists(cwd, filename)) {
3697                         dir = cwd;
3698                 }
3699                 if (local && state->file && exists(state->file->dirname, filename)) {
3700                         dir = state->file->dirname;
3701                 }
3702                 for(path = include_paths; !dir && *path; path++) {
3703                         if (exists(*path, filename)) {
3704                                 dir = *path;
3705                         }
3706                 }
3707                 if (!dir) {
3708                         error(state, 0, "Cannot find `%s'\n", filename);
3709                 }
3710                 dirlen = strlen(dir);
3711                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
3712                 memcpy(file->dirname, dir, dirlen);
3713                 file->dirname[dirlen] = '/';
3714                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
3715                 file->dirname[dirlen + 1 + subdir_len] = '\0';
3716         }
3717         file->buf = slurp_file(file->dirname, file->basename, &file->size);
3718         xchdir(cwd);
3719
3720         file->pos = file->buf;
3721         file->line_start = file->pos;
3722         file->line = 1;
3723
3724         file->report_line = 1;
3725         file->report_name = file->basename;
3726         file->report_dir  = file->dirname;
3727
3728         file->prev = state->file;
3729         state->file = file;
3730         
3731         process_trigraphs(state);
3732         splice_lines(state);
3733 }
3734
3735 /* Type helper functions */
3736
3737 static struct type *new_type(
3738         unsigned int type, struct type *left, struct type *right)
3739 {
3740         struct type *result;
3741         result = xmalloc(sizeof(*result), "type");
3742         result->type = type;
3743         result->left = left;
3744         result->right = right;
3745         result->field_ident = 0;
3746         result->type_ident = 0;
3747         return result;
3748 }
3749
3750 static struct type *clone_type(unsigned int specifiers, struct type *old)
3751 {
3752         struct type *result;
3753         result = xmalloc(sizeof(*result), "type");
3754         memcpy(result, old, sizeof(*result));
3755         result->type &= TYPE_MASK;
3756         result->type |= specifiers;
3757         return result;
3758 }
3759
3760 #define SIZEOF_SHORT 2
3761 #define SIZEOF_INT   4
3762 #define SIZEOF_LONG  (sizeof(long_t))
3763
3764 #define ALIGNOF_SHORT 2
3765 #define ALIGNOF_INT   4
3766 #define ALIGNOF_LONG  (sizeof(long_t))
3767
3768 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
3769 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT*8)) - 1))
3770 static inline ulong_t mask_uint(ulong_t x)
3771 {
3772         if (SIZEOF_INT < SIZEOF_LONG) {
3773                 ulong_t mask = (((ulong_t)1) << ((ulong_t)(SIZEOF_INT*8))) -1;
3774                 x &= mask;
3775         }
3776         return x;
3777 }
3778 #define MASK_UINT(X)      (mask_uint(X))
3779 #define MASK_ULONG(X)    (X)
3780
3781 static struct type void_type   = { .type  = TYPE_VOID };
3782 static struct type char_type   = { .type  = TYPE_CHAR };
3783 static struct type uchar_type  = { .type  = TYPE_UCHAR };
3784 static struct type short_type  = { .type  = TYPE_SHORT };
3785 static struct type ushort_type = { .type  = TYPE_USHORT };
3786 static struct type int_type    = { .type  = TYPE_INT };
3787 static struct type uint_type   = { .type  = TYPE_UINT };
3788 static struct type long_type   = { .type  = TYPE_LONG };
3789 static struct type ulong_type  = { .type  = TYPE_ULONG };
3790
3791 static struct triple *variable(struct compile_state *state, struct type *type)
3792 {
3793         struct triple *result;
3794         if ((type->type & STOR_MASK) != STOR_PERM) {
3795                 if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
3796                         result = triple(state, OP_ADECL, type, 0, 0);
3797                 } else {
3798                         struct type *field;
3799                         struct triple **vector;
3800                         ulong_t index;
3801                         result = new_triple(state, OP_VAL_VEC, type, -1, -1);
3802                         vector = &result->param[0];
3803
3804                         field = type->left;
3805                         index = 0;
3806                         while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
3807                                 vector[index] = variable(state, field->left);
3808                                 field = field->right;
3809                                 index++;
3810                         }
3811                         vector[index] = variable(state, field);
3812                 }
3813         }
3814         else {
3815                 result = triple(state, OP_SDECL, type, 0, 0);
3816         }
3817         return result;
3818 }
3819
3820 static void stor_of(FILE *fp, struct type *type)
3821 {
3822         switch(type->type & STOR_MASK) {
3823         case STOR_AUTO:
3824                 fprintf(fp, "auto ");
3825                 break;
3826         case STOR_STATIC:
3827                 fprintf(fp, "static ");
3828                 break;
3829         case STOR_EXTERN:
3830                 fprintf(fp, "extern ");
3831                 break;
3832         case STOR_REGISTER:
3833                 fprintf(fp, "register ");
3834                 break;
3835         case STOR_TYPEDEF:
3836                 fprintf(fp, "typedef ");
3837                 break;
3838         case STOR_INLINE:
3839                 fprintf(fp, "inline ");
3840                 break;
3841         }
3842 }
3843 static void qual_of(FILE *fp, struct type *type)
3844 {
3845         if (type->type & QUAL_CONST) {
3846                 fprintf(fp, " const");
3847         }
3848         if (type->type & QUAL_VOLATILE) {
3849                 fprintf(fp, " volatile");
3850         }
3851         if (type->type & QUAL_RESTRICT) {
3852                 fprintf(fp, " restrict");
3853         }
3854 }
3855
3856 static void name_of(FILE *fp, struct type *type)
3857 {
3858         stor_of(fp, type);
3859         switch(type->type & TYPE_MASK) {
3860         case TYPE_VOID:
3861                 fprintf(fp, "void");
3862                 qual_of(fp, type);
3863                 break;
3864         case TYPE_CHAR:
3865                 fprintf(fp, "signed char");
3866                 qual_of(fp, type);
3867                 break;
3868         case TYPE_UCHAR:
3869                 fprintf(fp, "unsigned char");
3870                 qual_of(fp, type);
3871                 break;
3872         case TYPE_SHORT:
3873                 fprintf(fp, "signed short");
3874                 qual_of(fp, type);
3875                 break;
3876         case TYPE_USHORT:
3877                 fprintf(fp, "unsigned short");
3878                 qual_of(fp, type);
3879                 break;
3880         case TYPE_INT:
3881                 fprintf(fp, "signed int");
3882                 qual_of(fp, type);
3883                 break;
3884         case TYPE_UINT:
3885                 fprintf(fp, "unsigned int");
3886                 qual_of(fp, type);
3887                 break;
3888         case TYPE_LONG:
3889                 fprintf(fp, "signed long");
3890                 qual_of(fp, type);
3891                 break;
3892         case TYPE_ULONG:
3893                 fprintf(fp, "unsigned long");
3894                 qual_of(fp, type);
3895                 break;
3896         case TYPE_POINTER:
3897                 name_of(fp, type->left);
3898                 fprintf(fp, " * ");
3899                 qual_of(fp, type);
3900                 break;
3901         case TYPE_PRODUCT:
3902         case TYPE_OVERLAP:
3903                 name_of(fp, type->left);
3904                 fprintf(fp, ", ");
3905                 name_of(fp, type->right);
3906                 break;
3907         case TYPE_ENUM:
3908                 fprintf(fp, "enum %s", type->type_ident->name);
3909                 qual_of(fp, type);
3910                 break;
3911         case TYPE_STRUCT:
3912                 fprintf(fp, "struct %s", type->type_ident->name);
3913                 qual_of(fp, type);
3914                 break;
3915         case TYPE_FUNCTION:
3916         {
3917                 name_of(fp, type->left);
3918                 fprintf(fp, " (*)(");
3919                 name_of(fp, type->right);
3920                 fprintf(fp, ")");
3921                 break;
3922         }
3923         case TYPE_ARRAY:
3924                 name_of(fp, type->left);
3925                 fprintf(fp, " [%ld]", type->elements);
3926                 break;
3927         default:
3928                 fprintf(fp, "????: %x", type->type & TYPE_MASK);
3929                 break;
3930         }
3931 }
3932
3933 static size_t align_of(struct compile_state *state, struct type *type)
3934 {
3935         size_t align;
3936         align = 0;
3937         switch(type->type & TYPE_MASK) {
3938         case TYPE_VOID:
3939                 align = 1;
3940                 break;
3941         case TYPE_CHAR:
3942         case TYPE_UCHAR:
3943                 align = 1;
3944                 break;
3945         case TYPE_SHORT:
3946         case TYPE_USHORT:
3947                 align = ALIGNOF_SHORT;
3948                 break;
3949         case TYPE_INT:
3950         case TYPE_UINT:
3951         case TYPE_ENUM:
3952                 align = ALIGNOF_INT;
3953                 break;
3954         case TYPE_LONG:
3955         case TYPE_ULONG:
3956         case TYPE_POINTER:
3957                 align = ALIGNOF_LONG;
3958                 break;
3959         case TYPE_PRODUCT:
3960         case TYPE_OVERLAP:
3961         {
3962                 size_t left_align, right_align;
3963                 left_align  = align_of(state, type->left);
3964                 right_align = align_of(state, type->right);
3965                 align = (left_align >= right_align) ? left_align : right_align;
3966                 break;
3967         }
3968         case TYPE_ARRAY:
3969                 align = align_of(state, type->left);
3970                 break;
3971         case TYPE_STRUCT:
3972                 align = align_of(state, type->left);
3973                 break;
3974         default:
3975                 error(state, 0, "alignof not yet defined for type\n");
3976                 break;
3977         }
3978         return align;
3979 }
3980
3981 static size_t needed_padding(size_t offset, size_t align)
3982 {
3983         size_t padding;
3984         padding = 0;
3985         if (offset % align) {
3986                 padding = align - (offset % align);
3987         }
3988         return padding;
3989 }
3990 static size_t size_of(struct compile_state *state, struct type *type)
3991 {
3992         size_t size;
3993         size = 0;
3994         switch(type->type & TYPE_MASK) {
3995         case TYPE_VOID:
3996                 size = 0;
3997                 break;
3998         case TYPE_CHAR:
3999         case TYPE_UCHAR:
4000                 size = 1;
4001                 break;
4002         case TYPE_SHORT:
4003         case TYPE_USHORT:
4004                 size = SIZEOF_SHORT;
4005                 break;
4006         case TYPE_INT:
4007         case TYPE_UINT:
4008         case TYPE_ENUM:
4009                 size = SIZEOF_INT;
4010                 break;
4011         case TYPE_LONG:
4012         case TYPE_ULONG:
4013         case TYPE_POINTER:
4014                 size = SIZEOF_LONG;
4015                 break;
4016         case TYPE_PRODUCT:
4017         {
4018                 size_t align, pad;
4019                 size = 0;
4020                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4021                         align = align_of(state, type->left);
4022                         pad = needed_padding(size, align);
4023                         size = size + pad + size_of(state, type->left);
4024                         type = type->right;
4025                 }
4026                 align = align_of(state, type);
4027                 pad = needed_padding(size, align);
4028                 size = size + pad + sizeof(type);
4029                 break;
4030         }
4031         case TYPE_OVERLAP:
4032         {
4033                 size_t size_left, size_right;
4034                 size_left = size_of(state, type->left);
4035                 size_right = size_of(state, type->right);
4036                 size = (size_left >= size_right)? size_left : size_right;
4037                 break;
4038         }
4039         case TYPE_ARRAY:
4040                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4041                         internal_error(state, 0, "Invalid array type");
4042                 } else {
4043                         size = size_of(state, type->left) * type->elements;
4044                 }
4045                 break;
4046         case TYPE_STRUCT:
4047                 size = size_of(state, type->left);
4048                 break;
4049         default:
4050                 internal_error(state, 0, "sizeof not yet defined for type\n");
4051                 break;
4052         }
4053         return size;
4054 }
4055
4056 static size_t field_offset(struct compile_state *state, 
4057         struct type *type, struct hash_entry *field)
4058 {
4059         struct type *member;
4060         size_t size, align;
4061         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4062                 internal_error(state, 0, "field_offset only works on structures");
4063         }
4064         size = 0;
4065         member = type->left;
4066         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4067                 align = align_of(state, member->left);
4068                 size += needed_padding(size, align);
4069                 if (member->left->field_ident == field) {
4070                         member = member->left;
4071                         break;
4072                 }
4073                 size += size_of(state, member->left);
4074                 member = member->right;
4075         }
4076         align = align_of(state, member);
4077         size += needed_padding(size, align);
4078         if (member->field_ident != field) {
4079                 error(state, 0, "member %s not present", field->name);
4080         }
4081         return size;
4082 }
4083
4084 static struct type *field_type(struct compile_state *state, 
4085         struct type *type, struct hash_entry *field)
4086 {
4087         struct type *member;
4088         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4089                 internal_error(state, 0, "field_type only works on structures");
4090         }
4091         member = type->left;
4092         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4093                 if (member->left->field_ident == field) {
4094                         member = member->left;
4095                         break;
4096                 }
4097                 member = member->right;
4098         }
4099         if (member->field_ident != field) {
4100                 error(state, 0, "member %s not present", field->name);
4101         }
4102         return member;
4103 }
4104
4105 static struct type *next_field(struct compile_state *state,
4106         struct type *type, struct type *prev_member) 
4107 {
4108         struct type *member;
4109         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4110                 internal_error(state, 0, "next_field only works on structures");
4111         }
4112         member = type->left;
4113         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
4114                 if (!prev_member) {
4115                         member = member->left;
4116                         break;
4117                 }
4118                 if (member->left == prev_member) {
4119                         prev_member = 0;
4120                 }
4121                 member = member->right;
4122         }
4123         if (member == prev_member) {
4124                 prev_member = 0;
4125         }
4126         if (prev_member) {
4127                 internal_error(state, 0, "prev_member %s not present", 
4128                         prev_member->field_ident->name);
4129         }
4130         return member;
4131 }
4132
4133 static struct triple *struct_field(struct compile_state *state,
4134         struct triple *decl, struct hash_entry *field)
4135 {
4136         struct triple **vector;
4137         struct type *type;
4138         ulong_t index;
4139         type = decl->type;
4140         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4141                 return decl;
4142         }
4143         if (decl->op != OP_VAL_VEC) {
4144                 internal_error(state, 0, "Invalid struct variable");
4145         }
4146         if (!field) {
4147                 internal_error(state, 0, "Missing structure field");
4148         }
4149         type = type->left;
4150         vector = &RHS(decl, 0);
4151         index = 0;
4152         while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
4153                 if (type->left->field_ident == field) {
4154                         type = type->left;
4155                         break;
4156                 }
4157                 index += 1;
4158                 type = type->right;
4159         }
4160         if (type->field_ident != field) {
4161                 internal_error(state, 0, "field %s not found?", field->name);
4162         }
4163         return vector[index];
4164 }
4165
4166 static void arrays_complete(struct compile_state *state, struct type *type)
4167 {
4168         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
4169                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4170                         error(state, 0, "array size not specified");
4171                 }
4172                 arrays_complete(state, type->left);
4173         }
4174 }
4175
4176 static unsigned int do_integral_promotion(unsigned int type)
4177 {
4178         type &= TYPE_MASK;
4179         if (TYPE_INTEGER(type) && 
4180                 TYPE_RANK(type) < TYPE_RANK(TYPE_INT)) {
4181                 type = TYPE_INT;
4182         }
4183         return type;
4184 }
4185
4186 static unsigned int do_arithmetic_conversion(
4187         unsigned int left, unsigned int right)
4188 {
4189         left &= TYPE_MASK;
4190         right &= TYPE_MASK;
4191         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
4192                 return TYPE_LDOUBLE;
4193         }
4194         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
4195                 return TYPE_DOUBLE;
4196         }
4197         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
4198                 return TYPE_FLOAT;
4199         }
4200         left = do_integral_promotion(left);
4201         right = do_integral_promotion(right);
4202         /* If both operands have the same size done */
4203         if (left == right) {
4204                 return left;
4205         }
4206         /* If both operands have the same signedness pick the larger */
4207         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
4208                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
4209         }
4210         /* If the signed type can hold everything use it */
4211         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
4212                 return left;
4213         }
4214         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
4215                 return right;
4216         }
4217         /* Convert to the unsigned type with the same rank as the signed type */
4218         else if (TYPE_SIGNED(left)) {
4219                 return TYPE_MKUNSIGNED(left);
4220         }
4221         else {
4222                 return TYPE_MKUNSIGNED(right);
4223         }
4224 }
4225
4226 /* see if two types are the same except for qualifiers */
4227 static int equiv_types(struct type *left, struct type *right)
4228 {
4229         unsigned int type;
4230         /* Error if the basic types do not match */
4231         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4232                 return 0;
4233         }
4234         type = left->type & TYPE_MASK;
4235         /* If the basic types match and it is a void type we are done */
4236         if (type == TYPE_VOID) {
4237                 return 1;
4238         }
4239         /* if the basic types match and it is an arithmetic type we are done */
4240         if (TYPE_ARITHMETIC(type)) {
4241                 return 1;
4242         }
4243         /* If it is a pointer type recurse and keep testing */
4244         if (type == TYPE_POINTER) {
4245                 return equiv_types(left->left, right->left);
4246         }
4247         else if (type == TYPE_ARRAY) {
4248                 return (left->elements == right->elements) &&
4249                         equiv_types(left->left, right->left);
4250         }
4251         /* test for struct/union equality */
4252         else if (type == TYPE_STRUCT) {
4253                 return left->type_ident == right->type_ident;
4254         }
4255         /* Test for equivalent functions */
4256         else if (type == TYPE_FUNCTION) {
4257                 return equiv_types(left->left, right->left) &&
4258                         equiv_types(left->right, right->right);
4259         }
4260         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4261         else if (type == TYPE_PRODUCT) {
4262                 return equiv_types(left->left, right->left) &&
4263                         equiv_types(left->right, right->right);
4264         }
4265         /* We should see TYPE_OVERLAP */
4266         else {
4267                 return 0;
4268         }
4269 }
4270
4271 static int equiv_ptrs(struct type *left, struct type *right)
4272 {
4273         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4274                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4275                 return 0;
4276         }
4277         return equiv_types(left->left, right->left);
4278 }
4279
4280 static struct type *compatible_types(struct type *left, struct type *right)
4281 {
4282         struct type *result;
4283         unsigned int type, qual_type;
4284         /* Error if the basic types do not match */
4285         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
4286                 return 0;
4287         }
4288         type = left->type & TYPE_MASK;
4289         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4290         result = 0;
4291         /* if the basic types match and it is an arithmetic type we are done */
4292         if (TYPE_ARITHMETIC(type)) {
4293                 result = new_type(qual_type, 0, 0);
4294         }
4295         /* If it is a pointer type recurse and keep testing */
4296         else if (type == TYPE_POINTER) {
4297                 result = compatible_types(left->left, right->left);
4298                 if (result) {
4299                         result = new_type(qual_type, result, 0);
4300                 }
4301         }
4302         /* test for struct/union equality */
4303         else if (type == TYPE_STRUCT) {
4304                 if (left->type_ident == right->type_ident) {
4305                         result = left;
4306                 }
4307         }
4308         /* Test for equivalent functions */
4309         else if (type == TYPE_FUNCTION) {
4310                 struct type *lf, *rf;
4311                 lf = compatible_types(left->left, right->left);
4312                 rf = compatible_types(left->right, right->right);
4313                 if (lf && rf) {
4314                         result = new_type(qual_type, lf, rf);
4315                 }
4316         }
4317         /* We only see TYPE_PRODUCT as part of function equivalence matching */
4318         else if (type == TYPE_PRODUCT) {
4319                 struct type *lf, *rf;
4320                 lf = compatible_types(left->left, right->left);
4321                 rf = compatible_types(left->right, right->right);
4322                 if (lf && rf) {
4323                         result = new_type(qual_type, lf, rf);
4324                 }
4325         }
4326         else {
4327                 /* Nothing else is compatible */
4328         }
4329         return result;
4330 }
4331
4332 static struct type *compatible_ptrs(struct type *left, struct type *right)
4333 {
4334         struct type *result;
4335         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
4336                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
4337                 return 0;
4338         }
4339         result = compatible_types(left->left, right->left);
4340         if (result) {
4341                 unsigned int qual_type;
4342                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
4343                 result = new_type(qual_type, result, 0);
4344         }
4345         return result;
4346         
4347 }
4348 static struct triple *integral_promotion(
4349         struct compile_state *state, struct triple *def)
4350 {
4351         struct type *type;
4352         type = def->type;
4353         /* As all operations are carried out in registers
4354          * the values are converted on load I just convert
4355          * logical type of the operand.
4356          */
4357         if (TYPE_INTEGER(type->type)) {
4358                 unsigned int int_type;
4359                 int_type = type->type & ~TYPE_MASK;
4360                 int_type |= do_integral_promotion(type->type);
4361                 if (int_type != type->type) {
4362                         def->type = new_type(int_type, 0, 0);
4363                 }
4364         }
4365         return def;
4366 }
4367
4368
4369 static void arithmetic(struct compile_state *state, struct triple *def)
4370 {
4371         if (!TYPE_ARITHMETIC(def->type->type)) {
4372                 error(state, 0, "arithmetic type expexted");
4373         }
4374 }
4375
4376 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
4377 {
4378         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
4379                 error(state, def, "pointer or arithmetic type expected");
4380         }
4381 }
4382
4383 static int is_integral(struct triple *ins)
4384 {
4385         return TYPE_INTEGER(ins->type->type);
4386 }
4387
4388 static void integral(struct compile_state *state, struct triple *def)
4389 {
4390         if (!is_integral(def)) {
4391                 error(state, 0, "integral type expected");
4392         }
4393 }
4394
4395
4396 static void bool(struct compile_state *state, struct triple *def)
4397 {
4398         if (!TYPE_ARITHMETIC(def->type->type) &&
4399                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
4400                 error(state, 0, "arithmetic or pointer type expected");
4401         }
4402 }
4403
4404 static int is_signed(struct type *type)
4405 {
4406         return !!TYPE_SIGNED(type->type);
4407 }
4408
4409 /* Is this value located in a register otherwise it must be in memory */
4410 static int is_in_reg(struct compile_state *state, struct triple *def)
4411 {
4412         int in_reg;
4413         if (def->op == OP_ADECL) {
4414                 in_reg = 1;
4415         }
4416         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
4417                 in_reg = 0;
4418         }
4419         else if (def->op == OP_VAL_VEC) {
4420                 in_reg = is_in_reg(state, RHS(def, 0));
4421         }
4422         else if (def->op == OP_DOT) {
4423                 in_reg = is_in_reg(state, RHS(def, 0));
4424         }
4425         else {
4426                 internal_error(state, 0, "unknown expr storage location");
4427                 in_reg = -1;
4428         }
4429         return in_reg;
4430 }
4431
4432 /* Is this a stable variable location otherwise it must be a temporary */
4433 static int is_stable(struct compile_state *state, struct triple *def)
4434 {
4435         int ret;
4436         ret = 0;
4437         if (!def) {
4438                 return 0;
4439         }
4440         if ((def->op == OP_ADECL) || 
4441                 (def->op == OP_SDECL) || 
4442                 (def->op == OP_DEREF) ||
4443                 (def->op == OP_BLOBCONST)) {
4444                 ret = 1;
4445         }
4446         else if (def->op == OP_DOT) {
4447                 ret = is_stable(state, RHS(def, 0));
4448         }
4449         else if (def->op == OP_VAL_VEC) {
4450                 struct triple **vector;
4451                 ulong_t i;
4452                 ret = 1;
4453                 vector = &RHS(def, 0);
4454                 for(i = 0; i < def->type->elements; i++) {
4455                         if (!is_stable(state, vector[i])) {
4456                                 ret = 0;
4457                                 break;
4458                         }
4459                 }
4460         }
4461         return ret;
4462 }
4463
4464 static int is_lvalue(struct compile_state *state, struct triple *def)
4465 {
4466         int ret;
4467         ret = 1;
4468         if (!def) {
4469                 return 0;
4470         }
4471         if (!is_stable(state, def)) {
4472                 return 0;
4473         }
4474         if (def->op == OP_DOT) {
4475                 ret = is_lvalue(state, RHS(def, 0));
4476         }
4477         return ret;
4478 }
4479
4480 static void clvalue(struct compile_state *state, struct triple *def)
4481 {
4482         if (!def) {
4483                 internal_error(state, def, "nothing where lvalue expected?");
4484         }
4485         if (!is_lvalue(state, def)) { 
4486                 error(state, def, "lvalue expected");
4487         }
4488 }
4489 static void lvalue(struct compile_state *state, struct triple *def)
4490 {
4491         clvalue(state, def);
4492         if (def->type->type & QUAL_CONST) {
4493                 error(state, def, "modifable lvalue expected");
4494         }
4495 }
4496
4497 static int is_pointer(struct triple *def)
4498 {
4499         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
4500 }
4501
4502 static void pointer(struct compile_state *state, struct triple *def)
4503 {
4504         if (!is_pointer(def)) {
4505                 error(state, def, "pointer expected");
4506         }
4507 }
4508
4509 static struct triple *int_const(
4510         struct compile_state *state, struct type *type, ulong_t value)
4511 {
4512         struct triple *result;
4513         switch(type->type & TYPE_MASK) {
4514         case TYPE_CHAR:
4515         case TYPE_INT:   case TYPE_UINT:
4516         case TYPE_LONG:  case TYPE_ULONG:
4517                 break;
4518         default:
4519                 internal_error(state, 0, "constant for unkown type");
4520         }
4521         result = triple(state, OP_INTCONST, type, 0, 0);
4522         result->u.cval = value;
4523         return result;
4524 }
4525
4526
4527 static struct triple *do_mk_addr_expr(struct compile_state *state, 
4528         struct triple *expr, struct type *type, ulong_t offset)
4529 {
4530         struct triple *result;
4531         clvalue(state, expr);
4532
4533         type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
4534
4535         result = 0;
4536         if (expr->op == OP_ADECL) {
4537                 error(state, expr, "address of auto variables not supported");
4538         }
4539         else if (expr->op == OP_SDECL) {
4540                 result = triple(state, OP_ADDRCONST, type, 0, 0);
4541                 MISC(result, 0) = expr;
4542                 result->u.cval = offset;
4543         }
4544         else if (expr->op == OP_DEREF) {
4545                 result = triple(state, OP_ADD, type,
4546                         RHS(expr, 0),
4547                         int_const(state, &ulong_type, offset));
4548         }
4549         return result;
4550 }
4551
4552 static struct triple *mk_addr_expr(
4553         struct compile_state *state, struct triple *expr, ulong_t offset)
4554 {
4555         return do_mk_addr_expr(state, expr, expr->type, offset);
4556 }
4557
4558 static struct triple *mk_deref_expr(
4559         struct compile_state *state, struct triple *expr)
4560 {
4561         struct type *base_type;
4562         pointer(state, expr);
4563         base_type = expr->type->left;
4564         return triple(state, OP_DEREF, base_type, expr, 0);
4565 }
4566
4567 static struct triple *array_to_pointer(struct compile_state *state, struct triple *def)
4568 {
4569         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4570                 struct type *type;
4571                 type = new_type(
4572                         TYPE_POINTER | (def->type->type & QUAL_MASK),
4573                         def->type->left, 0);
4574                 if ((def->op == OP_SDECL) || is_const(def)) {
4575                         struct triple *addrconst;
4576                         if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
4577                                 internal_error(state, def, "bad array constant");
4578                         }
4579                         addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
4580                         MISC(addrconst, 0) = def;
4581                         def = addrconst;
4582                 }
4583                 else {
4584                         def = triple(state, OP_COPY, type, def, 0);
4585                 }
4586         }
4587         return def;
4588 }
4589
4590 static struct triple *deref_field(
4591         struct compile_state *state, struct triple *expr, struct hash_entry *field)
4592 {
4593         struct triple *result;
4594         struct type *type, *member;
4595         if (!field) {
4596                 internal_error(state, 0, "No field passed to deref_field");
4597         }
4598         result = 0;
4599         type = expr->type;
4600         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
4601                 error(state, 0, "request for member %s in something not a struct or union",
4602                         field->name);
4603         }
4604         member = field_type(state, type, field);
4605         if ((type->type & STOR_MASK) == STOR_PERM) {
4606                 /* Do the pointer arithmetic to get a deref the field */
4607                 ulong_t offset;
4608                 offset = field_offset(state, type, field);
4609                 result = do_mk_addr_expr(state, expr, member, offset);
4610                 result = mk_deref_expr(state, result);
4611         }
4612         else {
4613                 /* Find the variable for the field I want. */
4614                 result = triple(state, OP_DOT, member, expr, 0);
4615                 result->u.field = field;
4616         }
4617         return result;
4618 }
4619
4620 static struct triple *read_expr(struct compile_state *state, struct triple *def)
4621 {
4622         int op;
4623         if  (!def) {
4624                 return 0;
4625         }
4626         if (!is_stable(state, def)) {
4627                 return def;
4628         }
4629         /* Tranform an array to a pointer to the first element */
4630         
4631 #warning "CHECK_ME is this the right place to transform arrays to pointers?"
4632         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
4633                 return array_to_pointer(state, def);
4634         }
4635         if (is_in_reg(state, def)) {
4636                 op = OP_READ;
4637         } else {
4638                 op = OP_LOAD;
4639         }
4640         return triple(state, op, def->type, def, 0);
4641 }
4642
4643 static void write_compatible(struct compile_state *state,
4644         struct type *dest, struct type *rval)
4645 {
4646         int compatible = 0;
4647         /* Both operands have arithmetic type */
4648         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
4649                 compatible = 1;
4650         }
4651         /* One operand is a pointer and the other is a pointer to void */
4652         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
4653                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
4654                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
4655                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
4656                 compatible = 1;
4657         }
4658         /* If both types are the same without qualifiers we are good */
4659         else if (equiv_ptrs(dest, rval)) {
4660                 compatible = 1;
4661         }
4662         /* test for struct/union equality  */
4663         else if (((dest->type & TYPE_MASK) == TYPE_STRUCT) &&
4664                 ((rval->type & TYPE_MASK) == TYPE_STRUCT) &&
4665                 (dest->type_ident == rval->type_ident)) {
4666                 compatible = 1;
4667         }
4668         if (!compatible) {
4669                 error(state, 0, "Incompatible types in assignment");
4670         }
4671 }
4672
4673 static struct triple *write_expr(
4674         struct compile_state *state, struct triple *dest, struct triple *rval)
4675 {
4676         struct triple *def;
4677         int op;
4678
4679         def = 0;
4680         if (!rval) {
4681                 internal_error(state, 0, "missing rval");
4682         }
4683
4684         if (rval->op == OP_LIST) {
4685                 internal_error(state, 0, "expression of type OP_LIST?");
4686         }
4687         if (!is_lvalue(state, dest)) {
4688                 internal_error(state, 0, "writing to a non lvalue?");
4689         }
4690         if (dest->type->type & QUAL_CONST) {
4691                 internal_error(state, 0, "modifable lvalue expexted");
4692         }
4693
4694         write_compatible(state, dest->type, rval->type);
4695
4696         /* Now figure out which assignment operator to use */
4697         op = -1;
4698         if (is_in_reg(state, dest)) {
4699                 op = OP_WRITE;
4700         } else {
4701                 op = OP_STORE;
4702         }
4703         def = triple(state, op, dest->type, dest, rval);
4704         return def;
4705 }
4706
4707 static struct triple *init_expr(
4708         struct compile_state *state, struct triple *dest, struct triple *rval)
4709 {
4710         struct triple *def;
4711
4712         def = 0;
4713         if (!rval) {
4714                 internal_error(state, 0, "missing rval");
4715         }
4716         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
4717                 rval = read_expr(state, rval);
4718                 def = write_expr(state, dest, rval);
4719         }
4720         else {
4721                 /* Fill in the array size if necessary */
4722                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
4723                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
4724                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
4725                                 dest->type->elements = rval->type->elements;
4726                         }
4727                 }
4728                 if (!equiv_types(dest->type, rval->type)) {
4729                         error(state, 0, "Incompatible types in inializer");
4730                 }
4731                 MISC(dest, 0) = rval;
4732                 insert_triple(state, dest, rval);
4733                 rval->id |= TRIPLE_FLAG_FLATTENED;
4734                 use_triple(MISC(dest, 0), dest);
4735         }
4736         return def;
4737 }
4738
4739 struct type *arithmetic_result(
4740         struct compile_state *state, struct triple *left, struct triple *right)
4741 {
4742         struct type *type;
4743         /* Sanity checks to ensure I am working with arithmetic types */
4744         arithmetic(state, left);
4745         arithmetic(state, right);
4746         type = new_type(
4747                 do_arithmetic_conversion(
4748                         left->type->type, 
4749                         right->type->type), 0, 0);
4750         return type;
4751 }
4752
4753 struct type *ptr_arithmetic_result(
4754         struct compile_state *state, struct triple *left, struct triple *right)
4755 {
4756         struct type *type;
4757         /* Sanity checks to ensure I am working with the proper types */
4758         ptr_arithmetic(state, left);
4759         arithmetic(state, right);
4760         if (TYPE_ARITHMETIC(left->type->type) && 
4761                 TYPE_ARITHMETIC(right->type->type)) {
4762                 type = arithmetic_result(state, left, right);
4763         }
4764         else if (TYPE_PTR(left->type->type)) {
4765                 type = left->type;
4766         }
4767         else {
4768                 internal_error(state, 0, "huh?");
4769                 type = 0;
4770         }
4771         return type;
4772 }
4773
4774
4775 /* boolean helper function */
4776
4777 static struct triple *ltrue_expr(struct compile_state *state, 
4778         struct triple *expr)
4779 {
4780         switch(expr->op) {
4781         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
4782         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
4783         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
4784                 /* If the expression is already boolean do nothing */
4785                 break;
4786         default:
4787                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
4788                 break;
4789         }
4790         return expr;
4791 }
4792
4793 static struct triple *lfalse_expr(struct compile_state *state, 
4794         struct triple *expr)
4795 {
4796         return triple(state, OP_LFALSE, &int_type, expr, 0);
4797 }
4798
4799 static struct triple *cond_expr(
4800         struct compile_state *state, 
4801         struct triple *test, struct triple *left, struct triple *right)
4802 {
4803         struct triple *def;
4804         struct type *result_type;
4805         unsigned int left_type, right_type;
4806         bool(state, test);
4807         left_type = left->type->type;
4808         right_type = right->type->type;
4809         result_type = 0;
4810         /* Both operands have arithmetic type */
4811         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
4812                 result_type = arithmetic_result(state, left, right);
4813         }
4814         /* Both operands have void type */
4815         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
4816                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
4817                 result_type = &void_type;
4818         }
4819         /* pointers to the same type... */
4820         else if ((result_type = compatible_ptrs(left->type, right->type))) {
4821                 ;
4822         }
4823         /* Both operands are pointers and left is a pointer to void */
4824         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4825                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4826                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4827                 result_type = right->type;
4828         }
4829         /* Both operands are pointers and right is a pointer to void */
4830         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
4831                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
4832                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
4833                 result_type = left->type;
4834         }
4835         if (!result_type) {
4836                 error(state, 0, "Incompatible types in conditional expression");
4837         }
4838         /* Cleanup and invert the test */
4839         test = lfalse_expr(state, read_expr(state, test));
4840         def = new_triple(state, OP_COND, result_type, 0, 3);
4841         def->param[0] = test;
4842         def->param[1] = left;
4843         def->param[2] = right;
4844         return def;
4845 }
4846
4847
4848 static int expr_depth(struct compile_state *state, struct triple *ins)
4849 {
4850         int count;
4851         count = 0;
4852         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
4853                 count = 0;
4854         }
4855         else if (ins->op == OP_DEREF) {
4856                 count = expr_depth(state, RHS(ins, 0)) - 1;
4857         }
4858         else if (ins->op == OP_VAL) {
4859                 count = expr_depth(state, RHS(ins, 0)) - 1;
4860         }
4861         else if (ins->op == OP_COMMA) {
4862                 int ldepth, rdepth;
4863                 ldepth = expr_depth(state, RHS(ins, 0));
4864                 rdepth = expr_depth(state, RHS(ins, 1));
4865                 count = (ldepth >= rdepth)? ldepth : rdepth;
4866         }
4867         else if (ins->op == OP_CALL) {
4868                 /* Don't figure the depth of a call just guess it is huge */
4869                 count = 1000;
4870         }
4871         else {
4872                 struct triple **expr;
4873                 expr = triple_rhs(state, ins, 0);
4874                 for(;expr; expr = triple_rhs(state, ins, expr)) {
4875                         if (*expr) {
4876                                 int depth;
4877                                 depth = expr_depth(state, *expr);
4878                                 if (depth > count) {
4879                                         count = depth;
4880                                 }
4881                         }
4882                 }
4883         }
4884         return count + 1;
4885 }
4886
4887 static struct triple *flatten(
4888         struct compile_state *state, struct triple *first, struct triple *ptr);
4889
4890 static struct triple *flatten_generic(
4891         struct compile_state *state, struct triple *first, struct triple *ptr)
4892 {
4893         struct rhs_vector {
4894                 int depth;
4895                 struct triple **ins;
4896         } vector[MAX_RHS];
4897         int i, rhs, lhs;
4898         /* Only operations with just a rhs should come here */
4899         rhs = TRIPLE_RHS(ptr->sizes);
4900         lhs = TRIPLE_LHS(ptr->sizes);
4901         if (TRIPLE_SIZE(ptr->sizes) != lhs + rhs) {
4902                 internal_error(state, ptr, "unexpected args for: %d %s",
4903                         ptr->op, tops(ptr->op));
4904         }
4905         /* Find the depth of the rhs elements */
4906         for(i = 0; i < rhs; i++) {
4907                 vector[i].ins = &RHS(ptr, i);
4908                 vector[i].depth = expr_depth(state, *vector[i].ins);
4909         }
4910         /* Selection sort the rhs */
4911         for(i = 0; i < rhs; i++) {
4912                 int j, max = i;
4913                 for(j = i + 1; j < rhs; j++ ) {
4914                         if (vector[j].depth > vector[max].depth) {
4915                                 max = j;
4916                         }
4917                 }
4918                 if (max != i) {
4919                         struct rhs_vector tmp;
4920                         tmp = vector[i];
4921                         vector[i] = vector[max];
4922                         vector[max] = tmp;
4923                 }
4924         }
4925         /* Now flatten the rhs elements */
4926         for(i = 0; i < rhs; i++) {
4927                 *vector[i].ins = flatten(state, first, *vector[i].ins);
4928                 use_triple(*vector[i].ins, ptr);
4929         }
4930         
4931         /* Now flatten the lhs elements */
4932         for(i = 0; i < lhs; i++) {
4933                 struct triple **ins = &LHS(ptr, i);
4934                 *ins = flatten(state, first, *ins);
4935                 use_triple(*ins, ptr);
4936         }
4937         return ptr;
4938 }
4939
4940 static struct triple *flatten_land(
4941         struct compile_state *state, struct triple *first, struct triple *ptr)
4942 {
4943         struct triple *left, *right;
4944         struct triple *val, *test, *jmp, *label1, *end;
4945
4946         /* Find the triples */
4947         left = RHS(ptr, 0);
4948         right = RHS(ptr, 1);
4949
4950         /* Generate the needed triples */
4951         end = label(state);
4952
4953         /* Thread the triples together */
4954         val          = flatten(state, first, variable(state, ptr->type));
4955         left         = flatten(state, first, write_expr(state, val, left));
4956         test         = flatten(state, first, 
4957                 lfalse_expr(state, read_expr(state, val)));
4958         jmp          = flatten(state, first, branch(state, end, test));
4959         label1       = flatten(state, first, label(state));
4960         right        = flatten(state, first, write_expr(state, val, right));
4961         TARG(jmp, 0) = flatten(state, first, end); 
4962         
4963         /* Now give the caller something to chew on */
4964         return read_expr(state, val);
4965 }
4966
4967 static struct triple *flatten_lor(
4968         struct compile_state *state, struct triple *first, struct triple *ptr)
4969 {
4970         struct triple *left, *right;
4971         struct triple *val, *jmp, *label1, *end;
4972
4973         /* Find the triples */
4974         left = RHS(ptr, 0);
4975         right = RHS(ptr, 1);
4976
4977         /* Generate the needed triples */
4978         end = label(state);
4979
4980         /* Thread the triples together */
4981         val          = flatten(state, first, variable(state, ptr->type));
4982         left         = flatten(state, first, write_expr(state, val, left));
4983         jmp          = flatten(state, first, branch(state, end, left));
4984         label1       = flatten(state, first, label(state));
4985         right        = flatten(state, first, write_expr(state, val, right));
4986         TARG(jmp, 0) = flatten(state, first, end);
4987        
4988         
4989         /* Now give the caller something to chew on */
4990         return read_expr(state, val);
4991 }
4992
4993 static struct triple *flatten_cond(
4994         struct compile_state *state, struct triple *first, struct triple *ptr)
4995 {
4996         struct triple *test, *left, *right;
4997         struct triple *val, *mv1, *jmp1, *label1, *mv2, *middle, *jmp2, *end;
4998
4999         /* Find the triples */
5000         test = RHS(ptr, 0);
5001         left = RHS(ptr, 1);
5002         right = RHS(ptr, 2);
5003
5004         /* Generate the needed triples */
5005         end = label(state);
5006         middle = label(state);
5007
5008         /* Thread the triples together */
5009         val           = flatten(state, first, variable(state, ptr->type));
5010         test          = flatten(state, first, test);
5011         jmp1          = flatten(state, first, branch(state, middle, test));
5012         label1        = flatten(state, first, label(state));
5013         left          = flatten(state, first, left);
5014         mv1           = flatten(state, first, write_expr(state, val, left));
5015         jmp2          = flatten(state, first, branch(state, end, 0));
5016         TARG(jmp1, 0) = flatten(state, first, middle);
5017         right         = flatten(state, first, right);
5018         mv2           = flatten(state, first, write_expr(state, val, right));
5019         TARG(jmp2, 0) = flatten(state, first, end);
5020         
5021         /* Now give the caller something to chew on */
5022         return read_expr(state, val);
5023 }
5024
5025 struct triple *copy_func(struct compile_state *state, struct triple *ofunc, 
5026         struct occurance *base_occurance)
5027 {
5028         struct triple *nfunc;
5029         struct triple *nfirst, *ofirst;
5030         struct triple *new, *old;
5031
5032 #if 0
5033         fprintf(stdout, "\n");
5034         loc(stdout, state, 0);
5035         fprintf(stdout, "\n__________ copy_func _________\n");
5036         print_triple(state, ofunc);
5037         fprintf(stdout, "__________ copy_func _________ done\n\n");
5038 #endif
5039
5040         /* Make a new copy of the old function */
5041         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
5042         nfirst = 0;
5043         ofirst = old = RHS(ofunc, 0);
5044         do {
5045                 struct triple *new;
5046                 struct occurance *occurance;
5047                 int old_lhs, old_rhs;
5048                 old_lhs = TRIPLE_LHS(old->sizes);
5049                 old_rhs = TRIPLE_RHS(old->sizes);
5050                 occurance = inline_occurance(state, base_occurance, old->occurance);
5051                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
5052                         occurance);
5053                 if (!triple_stores_block(state, new)) {
5054                         memcpy(&new->u, &old->u, sizeof(new->u));
5055                 }
5056                 if (!nfirst) {
5057                         RHS(nfunc, 0) = nfirst = new;
5058                 }
5059                 else {
5060                         insert_triple(state, nfirst, new);
5061                 }
5062                 new->id |= TRIPLE_FLAG_FLATTENED;
5063                 
5064                 /* During the copy remember new as user of old */
5065                 use_triple(old, new);
5066
5067                 /* Populate the return type if present */
5068                 if (old == MISC(ofunc, 0)) {
5069                         MISC(nfunc, 0) = new;
5070                 }
5071                 old = old->next;
5072         } while(old != ofirst);
5073
5074         /* Make a second pass to fix up any unresolved references */
5075         old = ofirst;
5076         new = nfirst;
5077         do {
5078                 struct triple **oexpr, **nexpr;
5079                 int count, i;
5080                 /* Lookup where the copy is, to join pointers */
5081                 count = TRIPLE_SIZE(old->sizes);
5082                 for(i = 0; i < count; i++) {
5083                         oexpr = &old->param[i];
5084                         nexpr = &new->param[i];
5085                         if (!*nexpr && *oexpr && (*oexpr)->use) {
5086                                 *nexpr = (*oexpr)->use->member;
5087                                 if (*nexpr == old) {
5088                                         internal_error(state, 0, "new == old?");
5089                                 }
5090                                 use_triple(*nexpr, new);
5091                         }
5092                         if (!*nexpr && *oexpr) {
5093                                 internal_error(state, 0, "Could not copy %d\n", i);
5094                         }
5095                 }
5096                 old = old->next;
5097                 new = new->next;
5098         } while((old != ofirst) && (new != nfirst));
5099         
5100         /* Make a third pass to cleanup the extra useses */
5101         old = ofirst;
5102         new = nfirst;
5103         do {
5104                 unuse_triple(old, new);
5105                 old = old->next;
5106                 new = new->next;
5107         } while ((old != ofirst) && (new != nfirst));
5108         return nfunc;
5109 }
5110
5111 static struct triple *flatten_call(
5112         struct compile_state *state, struct triple *first, struct triple *ptr)
5113 {
5114         /* Inline the function call */
5115         struct type *ptype;
5116         struct triple *ofunc, *nfunc, *nfirst, *param, *result;
5117         struct triple *end, *nend;
5118         int pvals, i;
5119
5120         /* Find the triples */
5121         ofunc = MISC(ptr, 0);
5122         if (ofunc->op != OP_LIST) {
5123                 internal_error(state, 0, "improper function");
5124         }
5125         nfunc = copy_func(state, ofunc, ptr->occurance);
5126         nfirst = RHS(nfunc, 0)->next;
5127         /* Prepend the parameter reading into the new function list */
5128         ptype = nfunc->type->right;
5129         param = RHS(nfunc, 0)->next;
5130         pvals = TRIPLE_RHS(ptr->sizes);
5131         for(i = 0; i < pvals; i++) {
5132                 struct type *atype;
5133                 struct triple *arg;
5134                 atype = ptype;
5135                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
5136                         atype = ptype->left;
5137                 }
5138                 while((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
5139                         param = param->next;
5140                 }
5141                 arg = RHS(ptr, i);
5142                 flatten(state, nfirst, write_expr(state, param, arg));
5143                 ptype = ptype->right;
5144                 param = param->next;
5145         }
5146         result = 0;
5147         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
5148                 result = read_expr(state, MISC(nfunc,0));
5149         }
5150 #if 0
5151         fprintf(stdout, "\n");
5152         loc(stdout, state, 0);
5153         fprintf(stdout, "\n__________ flatten_call _________\n");
5154         print_triple(state, nfunc);
5155         fprintf(stdout, "__________ flatten_call _________ done\n\n");
5156 #endif
5157
5158         /* Get rid of the extra triples */
5159         nfirst = RHS(nfunc, 0)->next;
5160         free_triple(state, RHS(nfunc, 0));
5161         RHS(nfunc, 0) = 0;
5162         free_triple(state, nfunc);
5163
5164         /* Append the new function list onto the return list */
5165         end = first->prev;
5166         nend = nfirst->prev;
5167         end->next    = nfirst;
5168         nfirst->prev = end;
5169         nend->next   = first;
5170         first->prev  = nend;
5171
5172         return result;
5173 }
5174
5175 static struct triple *flatten(
5176         struct compile_state *state, struct triple *first, struct triple *ptr)
5177 {
5178         struct triple *orig_ptr;
5179         if (!ptr)
5180                 return 0;
5181         do {
5182                 orig_ptr = ptr;
5183                 /* Only flatten triples once */
5184                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
5185                         return ptr;
5186                 }
5187                 switch(ptr->op) {
5188                 case OP_COMMA:
5189                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5190                         ptr = RHS(ptr, 1);
5191                         break;
5192                 case OP_VAL:
5193                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5194                         return MISC(ptr, 0);
5195                         break;
5196                 case OP_LAND:
5197                         ptr = flatten_land(state, first, ptr);
5198                         break;
5199                 case OP_LOR:
5200                         ptr = flatten_lor(state, first, ptr);
5201                         break;
5202                 case OP_COND:
5203                         ptr = flatten_cond(state, first, ptr);
5204                         break;
5205                 case OP_CALL:
5206                         ptr = flatten_call(state, first, ptr);
5207                         break;
5208                 case OP_READ:
5209                 case OP_LOAD:
5210                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
5211                         use_triple(RHS(ptr, 0), ptr);
5212                         break;
5213                 case OP_BRANCH:
5214                         use_triple(TARG(ptr, 0), ptr);
5215                         if (TRIPLE_RHS(ptr->sizes)) {
5216                                 use_triple(RHS(ptr, 0), ptr);
5217                                 if (ptr->next != ptr) {
5218                                         use_triple(ptr->next, ptr);
5219                                 }
5220                         }
5221                         break;
5222                 case OP_BLOBCONST:
5223                         insert_triple(state, first, ptr);
5224                         ptr->id |= TRIPLE_FLAG_FLATTENED;
5225                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
5226                         use_triple(MISC(ptr, 0), ptr);
5227                         break;
5228                 case OP_DEREF:
5229                         /* Since OP_DEREF is just a marker delete it when I flatten it */
5230                         ptr = RHS(ptr, 0);
5231                         RHS(orig_ptr, 0) = 0;
5232                         free_triple(state, orig_ptr);
5233                         break;
5234                 case OP_DOT:
5235                 {
5236                         struct triple *base;
5237                         base = RHS(ptr, 0);
5238                         if (base->op == OP_DEREF) {
5239                                 struct triple *left;
5240                                 ulong_t offset;
5241                                 offset = field_offset(state, base->type, ptr->u.field);
5242                                 left = RHS(base, 0);
5243                                 ptr = triple(state, OP_ADD, left->type, 
5244                                         read_expr(state, left),
5245                                         int_const(state, &ulong_type, offset));
5246                                 free_triple(state, base);
5247                         }
5248                         else if (base->op == OP_VAL_VEC) {
5249                                 base = flatten(state, first, base);
5250                                 ptr = struct_field(state, base, ptr->u.field);
5251                         }
5252                         break;
5253                 }
5254                 case OP_PIECE:
5255                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5256                         use_triple(MISC(ptr, 0), ptr);
5257                         use_triple(ptr, MISC(ptr, 0));
5258                         break;
5259                 case OP_ADDRCONST:
5260                 case OP_SDECL:
5261                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
5262                         use_triple(MISC(ptr, 0), ptr);
5263                         break;
5264                 case OP_ADECL:
5265                         break;
5266                 default:
5267                         /* Flatten the easy cases we don't override */
5268                         ptr = flatten_generic(state, first, ptr);
5269                         break;
5270                 }
5271         } while(ptr && (ptr != orig_ptr));
5272         if (ptr) {
5273                 insert_triple(state, first, ptr);
5274                 ptr->id |= TRIPLE_FLAG_FLATTENED;
5275         }
5276         return ptr;
5277 }
5278
5279 static void release_expr(struct compile_state *state, struct triple *expr)
5280 {
5281         struct triple *head;
5282         head = label(state);
5283         flatten(state, head, expr);
5284         while(head->next != head) {
5285                 release_triple(state, head->next);
5286         }
5287         free_triple(state, head);
5288 }
5289
5290 static int replace_rhs_use(struct compile_state *state,
5291         struct triple *orig, struct triple *new, struct triple *use)
5292 {
5293         struct triple **expr;
5294         int found;
5295         found = 0;
5296         expr = triple_rhs(state, use, 0);
5297         for(;expr; expr = triple_rhs(state, use, expr)) {
5298                 if (*expr == orig) {
5299                         *expr = new;
5300                         found = 1;
5301                 }
5302         }
5303         if (found) {
5304                 unuse_triple(orig, use);
5305                 use_triple(new, use);
5306         }
5307         return found;
5308 }
5309
5310 static int replace_lhs_use(struct compile_state *state,
5311         struct triple *orig, struct triple *new, struct triple *use)
5312 {
5313         struct triple **expr;
5314         int found;
5315         found = 0;
5316         expr = triple_lhs(state, use, 0);
5317         for(;expr; expr = triple_lhs(state, use, expr)) {
5318                 if (*expr == orig) {
5319                         *expr = new;
5320                         found = 1;
5321                 }
5322         }
5323         if (found) {
5324                 unuse_triple(orig, use);
5325                 use_triple(new, use);
5326         }
5327         return found;
5328 }
5329
5330 static void propogate_use(struct compile_state *state,
5331         struct triple *orig, struct triple *new)
5332 {
5333         struct triple_set *user, *next;
5334         for(user = orig->use; user; user = next) {
5335                 struct triple *use;
5336                 int found;
5337                 next = user->next;
5338                 use = user->member;
5339                 found = 0;
5340                 found |= replace_rhs_use(state, orig, new, use);
5341                 found |= replace_lhs_use(state, orig, new, use);
5342                 if (!found) {
5343                         internal_error(state, use, "use without use");
5344                 }
5345         }
5346         if (orig->use) {
5347                 internal_error(state, orig, "used after propogate_use");
5348         }
5349 }
5350
5351 /*
5352  * Code generators
5353  * ===========================
5354  */
5355
5356 static struct triple *mk_add_expr(
5357         struct compile_state *state, struct triple *left, struct triple *right)
5358 {
5359         struct type *result_type;
5360         /* Put pointer operands on the left */
5361         if (is_pointer(right)) {
5362                 struct triple *tmp;
5363                 tmp = left;
5364                 left = right;
5365                 right = tmp;
5366         }
5367         left  = read_expr(state, left);
5368         right = read_expr(state, right);
5369         result_type = ptr_arithmetic_result(state, left, right);
5370         if (is_pointer(left)) {
5371                 right = triple(state, 
5372                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5373                         &ulong_type, 
5374                         right, 
5375                         int_const(state, &ulong_type, 
5376                                 size_of(state, left->type->left)));
5377         }
5378         return triple(state, OP_ADD, result_type, left, right);
5379 }
5380
5381 static struct triple *mk_sub_expr(
5382         struct compile_state *state, struct triple *left, struct triple *right)
5383 {
5384         struct type *result_type;
5385         result_type = ptr_arithmetic_result(state, left, right);
5386         left  = read_expr(state, left);
5387         right = read_expr(state, right);
5388         if (is_pointer(left)) {
5389                 right = triple(state, 
5390                         is_signed(right->type)? OP_SMUL : OP_UMUL, 
5391                         &ulong_type, 
5392                         right, 
5393                         int_const(state, &ulong_type, 
5394                                 size_of(state, left->type->left)));
5395         }
5396         return triple(state, OP_SUB, result_type, left, right);
5397 }
5398
5399 static struct triple *mk_pre_inc_expr(
5400         struct compile_state *state, struct triple *def)
5401 {
5402         struct triple *val;
5403         lvalue(state, def);
5404         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
5405         return triple(state, OP_VAL, def->type,
5406                 write_expr(state, def, val),
5407                 val);
5408 }
5409
5410 static struct triple *mk_pre_dec_expr(
5411         struct compile_state *state, struct triple *def)
5412 {
5413         struct triple *val;
5414         lvalue(state, def);
5415         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
5416         return triple(state, OP_VAL, def->type,
5417                 write_expr(state, def, val),
5418                 val);
5419 }
5420
5421 static struct triple *mk_post_inc_expr(
5422         struct compile_state *state, struct triple *def)
5423 {
5424         struct triple *val;
5425         lvalue(state, def);
5426         val = read_expr(state, def);
5427         return triple(state, OP_VAL, def->type,
5428                 write_expr(state, def,
5429                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
5430                 , val);
5431 }
5432
5433 static struct triple *mk_post_dec_expr(
5434         struct compile_state *state, struct triple *def)
5435 {
5436         struct triple *val;
5437         lvalue(state, def);
5438         val = read_expr(state, def);
5439         return triple(state, OP_VAL, def->type, 
5440                 write_expr(state, def,
5441                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
5442                 , val);
5443 }
5444
5445 static struct triple *mk_subscript_expr(
5446         struct compile_state *state, struct triple *left, struct triple *right)
5447 {
5448         left  = read_expr(state, left);
5449         right = read_expr(state, right);
5450         if (!is_pointer(left) && !is_pointer(right)) {
5451                 error(state, left, "subscripted value is not a pointer");
5452         }
5453         return mk_deref_expr(state, mk_add_expr(state, left, right));
5454 }
5455
5456 /*
5457  * Compile time evaluation
5458  * ===========================
5459  */
5460 static int is_const(struct triple *ins)
5461 {
5462         return IS_CONST_OP(ins->op);
5463 }
5464
5465 static int constants_equal(struct compile_state *state, 
5466         struct triple *left, struct triple *right)
5467 {
5468         int equal;
5469         if (!is_const(left) || !is_const(right)) {
5470                 equal = 0;
5471         }
5472         else if (left->op != right->op) {
5473                 equal = 0;
5474         }
5475         else if (!equiv_types(left->type, right->type)) {
5476                 equal = 0;
5477         }
5478         else {
5479                 equal = 0;
5480                 switch(left->op) {
5481                 case OP_INTCONST:
5482                         if (left->u.cval == right->u.cval) {
5483                                 equal = 1;
5484                         }
5485                         break;
5486                 case OP_BLOBCONST:
5487                 {
5488                         size_t lsize, rsize;
5489                         lsize = size_of(state, left->type);
5490                         rsize = size_of(state, right->type);
5491                         if (lsize != rsize) {
5492                                 break;
5493                         }
5494                         if (memcmp(left->u.blob, right->u.blob, lsize) == 0) {
5495                                 equal = 1;
5496                         }
5497                         break;
5498                 }
5499                 case OP_ADDRCONST:
5500                         if ((MISC(left, 0) == MISC(right, 0)) &&
5501                                 (left->u.cval == right->u.cval)) {
5502                                 equal = 1;
5503                         }
5504                         break;
5505                 default:
5506                         internal_error(state, left, "uknown constant type");
5507                         break;
5508                 }
5509         }
5510         return equal;
5511 }
5512
5513 static int is_zero(struct triple *ins)
5514 {
5515         return is_const(ins) && (ins->u.cval == 0);
5516 }
5517
5518 static int is_one(struct triple *ins)
5519 {
5520         return is_const(ins) && (ins->u.cval == 1);
5521 }
5522
5523 static long_t bit_count(ulong_t value)
5524 {
5525         int count;
5526         int i;
5527         count = 0;
5528         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5529                 ulong_t mask;
5530                 mask = 1;
5531                 mask <<= i;
5532                 if (value & mask) {
5533                         count++;
5534                 }
5535         }
5536         return count;
5537         
5538 }
5539 static long_t bsr(ulong_t value)
5540 {
5541         int i;
5542         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
5543                 ulong_t mask;
5544                 mask = 1;
5545                 mask <<= i;
5546                 if (value & mask) {
5547                         return i;
5548                 }
5549         }
5550         return -1;
5551 }
5552
5553 static long_t bsf(ulong_t value)
5554 {
5555         int i;
5556         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
5557                 ulong_t mask;
5558                 mask = 1;
5559                 mask <<= 1;
5560                 if (value & mask) {
5561                         return i;
5562                 }
5563         }
5564         return -1;
5565 }
5566
5567 static long_t log2(ulong_t value)
5568 {
5569         return bsr(value);
5570 }
5571
5572 static long_t tlog2(struct triple *ins)
5573 {
5574         return log2(ins->u.cval);
5575 }
5576
5577 static int is_pow2(struct triple *ins)
5578 {
5579         ulong_t value, mask;
5580         long_t log;
5581         if (!is_const(ins)) {
5582                 return 0;
5583         }
5584         value = ins->u.cval;
5585         log = log2(value);
5586         if (log == -1) {
5587                 return 0;
5588         }
5589         mask = 1;
5590         mask <<= log;
5591         return  ((value & mask) == value);
5592 }
5593
5594 static ulong_t read_const(struct compile_state *state,
5595         struct triple *ins, struct triple **expr)
5596 {
5597         struct triple *rhs;
5598         rhs = *expr;
5599         switch(rhs->type->type &TYPE_MASK) {
5600         case TYPE_CHAR:   
5601         case TYPE_SHORT:
5602         case TYPE_INT:
5603         case TYPE_LONG:
5604         case TYPE_UCHAR:   
5605         case TYPE_USHORT:  
5606         case TYPE_UINT:
5607         case TYPE_ULONG:
5608         case TYPE_POINTER:
5609                 break;
5610         default:
5611                 internal_error(state, rhs, "bad type to read_const\n");
5612                 break;
5613         }
5614         return rhs->u.cval;
5615 }
5616
5617 static long_t read_sconst(struct triple *ins, struct triple **expr)
5618 {
5619         struct triple *rhs;
5620         rhs = *expr;
5621         return (long_t)(rhs->u.cval);
5622 }
5623
5624 static void unuse_rhs(struct compile_state *state, struct triple *ins)
5625 {
5626         struct triple **expr;
5627         expr = triple_rhs(state, ins, 0);
5628         for(;expr;expr = triple_rhs(state, ins, expr)) {
5629                 if (*expr) {
5630                         unuse_triple(*expr, ins);
5631                         *expr = 0;
5632                 }
5633         }
5634 }
5635
5636 static void unuse_lhs(struct compile_state *state, struct triple *ins)
5637 {
5638         struct triple **expr;
5639         expr = triple_lhs(state, ins, 0);
5640         for(;expr;expr = triple_lhs(state, ins, expr)) {
5641                 unuse_triple(*expr, ins);
5642                 *expr = 0;
5643         }
5644 }
5645
5646 static void check_lhs(struct compile_state *state, struct triple *ins)
5647 {
5648         struct triple **expr;
5649         expr = triple_lhs(state, ins, 0);
5650         for(;expr;expr = triple_lhs(state, ins, expr)) {
5651                 internal_error(state, ins, "unexpected lhs");
5652         }
5653         
5654 }
5655 static void check_targ(struct compile_state *state, struct triple *ins)
5656 {
5657         struct triple **expr;
5658         expr = triple_targ(state, ins, 0);
5659         for(;expr;expr = triple_targ(state, ins, expr)) {
5660                 internal_error(state, ins, "unexpected targ");
5661         }
5662 }
5663
5664 static void wipe_ins(struct compile_state *state, struct triple *ins)
5665 {
5666         /* Becareful which instructions you replace the wiped
5667          * instruction with, as there are not enough slots
5668          * in all instructions to hold all others.
5669          */
5670         check_targ(state, ins);
5671         unuse_rhs(state, ins);
5672         unuse_lhs(state, ins);
5673 }
5674
5675 static void mkcopy(struct compile_state *state, 
5676         struct triple *ins, struct triple *rhs)
5677 {
5678         wipe_ins(state, ins);
5679         ins->op = OP_COPY;
5680         ins->sizes = TRIPLE_SIZES(0, 1, 0, 0);
5681         RHS(ins, 0) = rhs;
5682         use_triple(RHS(ins, 0), ins);
5683 }
5684
5685 static void mkconst(struct compile_state *state, 
5686         struct triple *ins, ulong_t value)
5687 {
5688         if (!is_integral(ins) && !is_pointer(ins)) {
5689                 internal_error(state, ins, "unknown type to make constant\n");
5690         }
5691         wipe_ins(state, ins);
5692         ins->op = OP_INTCONST;
5693         ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
5694         ins->u.cval = value;
5695 }
5696
5697 static void mkaddr_const(struct compile_state *state,
5698         struct triple *ins, struct triple *sdecl, ulong_t value)
5699 {
5700         if (sdecl->op != OP_SDECL) {
5701                 internal_error(state, ins, "bad base for addrconst");
5702         }
5703         wipe_ins(state, ins);
5704         ins->op = OP_ADDRCONST;
5705         ins->sizes = TRIPLE_SIZES(0, 0, 1, 0);
5706         MISC(ins, 0) = sdecl;
5707         ins->u.cval = value;
5708         use_triple(sdecl, ins);
5709 }
5710
5711 /* Transform multicomponent variables into simple register variables */
5712 static void flatten_structures(struct compile_state *state)
5713 {
5714         struct triple *ins, *first;
5715         first = RHS(state->main_function, 0);
5716         ins = first;
5717         /* Pass one expand structure values into valvecs.
5718          */
5719         ins = first;
5720         do {
5721                 struct triple *next;
5722                 next = ins->next;
5723                 if ((ins->type->type & TYPE_MASK) == TYPE_STRUCT) {
5724                         if (ins->op == OP_VAL_VEC) {
5725                                 /* Do nothing */
5726                         }
5727                         else if ((ins->op == OP_LOAD) || (ins->op == OP_READ)) {
5728                                 struct triple *def, **vector;
5729                                 struct type *tptr;
5730                                 int op;
5731                                 ulong_t i;
5732
5733                                 op = ins->op;
5734                                 def = RHS(ins, 0);
5735                                 get_occurance(ins->occurance);
5736                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5737                                         ins->occurance);
5738
5739                                 vector = &RHS(next, 0);
5740                                 tptr = next->type->left;
5741                                 for(i = 0; i < next->type->elements; i++) {
5742                                         struct triple *sfield;
5743                                         struct type *mtype;
5744                                         mtype = tptr;
5745                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5746                                                 mtype = mtype->left;
5747                                         }
5748                                         sfield = deref_field(state, def, mtype->field_ident);
5749                                         
5750                                         vector[i] = triple(
5751                                                 state, op, mtype, sfield, 0);
5752                                         put_occurance(vector[i]->occurance);
5753                                         get_occurance(next->occurance);
5754                                         vector[i]->occurance = next->occurance;
5755                                         tptr = tptr->right;
5756                                 }
5757                                 propogate_use(state, ins, next);
5758                                 flatten(state, ins, next);
5759                                 free_triple(state, ins);
5760                         }
5761                         else if ((ins->op == OP_STORE) || (ins->op == OP_WRITE)) {
5762                                 struct triple *src, *dst, **vector;
5763                                 struct type *tptr;
5764                                 int op;
5765                                 ulong_t i;
5766
5767                                 op = ins->op;
5768                                 src = RHS(ins, 1);
5769                                 dst = RHS(ins, 0);
5770                                 get_occurance(ins->occurance);
5771                                 next = alloc_triple(state, OP_VAL_VEC, ins->type, -1, -1,
5772                                         ins->occurance);
5773                                 
5774                                 vector = &RHS(next, 0);
5775                                 tptr = next->type->left;
5776                                 for(i = 0; i < ins->type->elements; i++) {
5777                                         struct triple *dfield, *sfield;
5778                                         struct type *mtype;
5779                                         mtype = tptr;
5780                                         if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
5781                                                 mtype = mtype->left;
5782                                         }
5783                                         sfield = deref_field(state, src, mtype->field_ident);
5784                                         dfield = deref_field(state, dst, mtype->field_ident);
5785                                         vector[i] = triple(
5786                                                 state, op, mtype, dfield, sfield);
5787                                         put_occurance(vector[i]->occurance);
5788                                         get_occurance(next->occurance);
5789                                         vector[i]->occurance = next->occurance;
5790                                         tptr = tptr->right;
5791                                 }
5792                                 propogate_use(state, ins, next);
5793                                 flatten(state, ins, next);
5794                                 free_triple(state, ins);
5795                         }
5796                 }
5797                 ins = next;
5798         } while(ins != first);
5799         /* Pass two flatten the valvecs.
5800          */
5801         ins = first;
5802         do {
5803                 struct triple *next;
5804                 next = ins->next;
5805                 if (ins->op == OP_VAL_VEC) {
5806                         release_triple(state, ins);
5807                 } 
5808                 ins = next;
5809         } while(ins != first);
5810         /* Pass three verify the state and set ->id to 0.
5811          */
5812         ins = first;
5813         do {
5814                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
5815                 if ((ins->op != OP_BLOBCONST) && (ins->op != OP_SDECL) &&
5816                         ((ins->type->type & TYPE_MASK) == TYPE_STRUCT)) {
5817                         internal_error(state, ins, "STRUCT_TYPE remains?");
5818                 }
5819                 if (ins->op == OP_DOT) {
5820                         internal_error(state, ins, "OP_DOT remains?");
5821                 }
5822                 if (ins->op == OP_VAL_VEC) {
5823                         internal_error(state, ins, "OP_VAL_VEC remains?");
5824                 }
5825                 ins = ins->next;
5826         } while(ins != first);
5827 }
5828
5829 /* For those operations that cannot be simplified */
5830 static void simplify_noop(struct compile_state *state, struct triple *ins)
5831 {
5832         return;
5833 }
5834
5835 static void simplify_smul(struct compile_state *state, struct triple *ins)
5836 {
5837         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5838                 struct triple *tmp;
5839                 tmp = RHS(ins, 0);
5840                 RHS(ins, 0) = RHS(ins, 1);
5841                 RHS(ins, 1) = tmp;
5842         }
5843         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5844                 long_t left, right;
5845                 left  = read_sconst(ins, &RHS(ins, 0));
5846                 right = read_sconst(ins, &RHS(ins, 1));
5847                 mkconst(state, ins, left * right);
5848         }
5849         else if (is_zero(RHS(ins, 1))) {
5850                 mkconst(state, ins, 0);
5851         }
5852         else if (is_one(RHS(ins, 1))) {
5853                 mkcopy(state, ins, RHS(ins, 0));
5854         }
5855         else if (is_pow2(RHS(ins, 1))) {
5856                 struct triple *val;
5857                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5858                 ins->op = OP_SL;
5859                 insert_triple(state, ins, val);
5860                 unuse_triple(RHS(ins, 1), ins);
5861                 use_triple(val, ins);
5862                 RHS(ins, 1) = val;
5863         }
5864 }
5865
5866 static void simplify_umul(struct compile_state *state, struct triple *ins)
5867 {
5868         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
5869                 struct triple *tmp;
5870                 tmp = RHS(ins, 0);
5871                 RHS(ins, 0) = RHS(ins, 1);
5872                 RHS(ins, 1) = tmp;
5873         }
5874         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5875                 ulong_t left, right;
5876                 left  = read_const(state, ins, &RHS(ins, 0));
5877                 right = read_const(state, ins, &RHS(ins, 1));
5878                 mkconst(state, ins, left * right);
5879         }
5880         else if (is_zero(RHS(ins, 1))) {
5881                 mkconst(state, ins, 0);
5882         }
5883         else if (is_one(RHS(ins, 1))) {
5884                 mkcopy(state, ins, RHS(ins, 0));
5885         }
5886         else if (is_pow2(RHS(ins, 1))) {
5887                 struct triple *val;
5888                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5889                 ins->op = OP_SL;
5890                 insert_triple(state, ins, val);
5891                 unuse_triple(RHS(ins, 1), ins);
5892                 use_triple(val, ins);
5893                 RHS(ins, 1) = val;
5894         }
5895 }
5896
5897 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
5898 {
5899         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5900                 long_t left, right;
5901                 left  = read_sconst(ins, &RHS(ins, 0));
5902                 right = read_sconst(ins, &RHS(ins, 1));
5903                 mkconst(state, ins, left / right);
5904         }
5905         else if (is_zero(RHS(ins, 0))) {
5906                 mkconst(state, ins, 0);
5907         }
5908         else if (is_zero(RHS(ins, 1))) {
5909                 error(state, ins, "division by zero");
5910         }
5911         else if (is_one(RHS(ins, 1))) {
5912                 mkcopy(state, ins, RHS(ins, 0));
5913         }
5914         else if (is_pow2(RHS(ins, 1))) {
5915                 struct triple *val;
5916                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5917                 ins->op = OP_SSR;
5918                 insert_triple(state, ins, val);
5919                 unuse_triple(RHS(ins, 1), ins);
5920                 use_triple(val, ins);
5921                 RHS(ins, 1) = val;
5922         }
5923 }
5924
5925 static void simplify_udiv(struct compile_state *state, struct triple *ins)
5926 {
5927         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5928                 ulong_t left, right;
5929                 left  = read_const(state, ins, &RHS(ins, 0));
5930                 right = read_const(state, ins, &RHS(ins, 1));
5931                 mkconst(state, ins, left / right);
5932         }
5933         else if (is_zero(RHS(ins, 0))) {
5934                 mkconst(state, ins, 0);
5935         }
5936         else if (is_zero(RHS(ins, 1))) {
5937                 error(state, ins, "division by zero");
5938         }
5939         else if (is_one(RHS(ins, 1))) {
5940                 mkcopy(state, ins, RHS(ins, 0));
5941         }
5942         else if (is_pow2(RHS(ins, 1))) {
5943                 struct triple *val;
5944                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
5945                 ins->op = OP_USR;
5946                 insert_triple(state, ins, val);
5947                 unuse_triple(RHS(ins, 1), ins);
5948                 use_triple(val, ins);
5949                 RHS(ins, 1) = val;
5950         }
5951 }
5952
5953 static void simplify_smod(struct compile_state *state, struct triple *ins)
5954 {
5955         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5956                 long_t left, right;
5957                 left  = read_const(state, ins, &RHS(ins, 0));
5958                 right = read_const(state, ins, &RHS(ins, 1));
5959                 mkconst(state, ins, left % right);
5960         }
5961         else if (is_zero(RHS(ins, 0))) {
5962                 mkconst(state, ins, 0);
5963         }
5964         else if (is_zero(RHS(ins, 1))) {
5965                 error(state, ins, "division by zero");
5966         }
5967         else if (is_one(RHS(ins, 1))) {
5968                 mkconst(state, ins, 0);
5969         }
5970         else if (is_pow2(RHS(ins, 1))) {
5971                 struct triple *val;
5972                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
5973                 ins->op = OP_AND;
5974                 insert_triple(state, ins, val);
5975                 unuse_triple(RHS(ins, 1), ins);
5976                 use_triple(val, ins);
5977                 RHS(ins, 1) = val;
5978         }
5979 }
5980 static void simplify_umod(struct compile_state *state, struct triple *ins)
5981 {
5982         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
5983                 ulong_t left, right;
5984                 left  = read_const(state, ins, &RHS(ins, 0));
5985                 right = read_const(state, ins, &RHS(ins, 1));
5986                 mkconst(state, ins, left % right);
5987         }
5988         else if (is_zero(RHS(ins, 0))) {
5989                 mkconst(state, ins, 0);
5990         }
5991         else if (is_zero(RHS(ins, 1))) {
5992                 error(state, ins, "division by zero");
5993         }
5994         else if (is_one(RHS(ins, 1))) {
5995                 mkconst(state, ins, 0);
5996         }
5997         else if (is_pow2(RHS(ins, 1))) {
5998                 struct triple *val;
5999                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
6000                 ins->op = OP_AND;
6001                 insert_triple(state, ins, val);
6002                 unuse_triple(RHS(ins, 1), ins);
6003                 use_triple(val, ins);
6004                 RHS(ins, 1) = val;
6005         }
6006 }
6007
6008 static void simplify_add(struct compile_state *state, struct triple *ins)
6009 {
6010         /* start with the pointer on the left */
6011         if (is_pointer(RHS(ins, 1))) {
6012                 struct triple *tmp;
6013                 tmp = RHS(ins, 0);
6014                 RHS(ins, 0) = RHS(ins, 1);
6015                 RHS(ins, 1) = tmp;
6016         }
6017         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6018                 if (RHS(ins, 0)->op == OP_INTCONST) {
6019                         ulong_t left, right;
6020                         left  = read_const(state, ins, &RHS(ins, 0));
6021                         right = read_const(state, ins, &RHS(ins, 1));
6022                         mkconst(state, ins, left + right);
6023                 }
6024                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6025                         struct triple *sdecl;
6026                         ulong_t left, right;
6027                         sdecl = MISC(RHS(ins, 0), 0);
6028                         left  = RHS(ins, 0)->u.cval;
6029                         right = RHS(ins, 1)->u.cval;
6030                         mkaddr_const(state, ins, sdecl, left + right);
6031                 }
6032                 else {
6033                         internal_warning(state, ins, "Optimize me!");
6034                 }
6035         }
6036         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
6037                 struct triple *tmp;
6038                 tmp = RHS(ins, 1);
6039                 RHS(ins, 1) = RHS(ins, 0);
6040                 RHS(ins, 0) = tmp;
6041         }
6042 }
6043
6044 static void simplify_sub(struct compile_state *state, struct triple *ins)
6045 {
6046         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6047                 if (RHS(ins, 0)->op == OP_INTCONST) {
6048                         ulong_t left, right;
6049                         left  = read_const(state, ins, &RHS(ins, 0));
6050                         right = read_const(state, ins, &RHS(ins, 1));
6051                         mkconst(state, ins, left - right);
6052                 }
6053                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
6054                         struct triple *sdecl;
6055                         ulong_t left, right;
6056                         sdecl = MISC(RHS(ins, 0), 0);
6057                         left  = RHS(ins, 0)->u.cval;
6058                         right = RHS(ins, 1)->u.cval;
6059                         mkaddr_const(state, ins, sdecl, left - right);
6060                 }
6061                 else {
6062                         internal_warning(state, ins, "Optimize me!");
6063                 }
6064         }
6065 }
6066
6067 static void simplify_sl(struct compile_state *state, struct triple *ins)
6068 {
6069         if (is_const(RHS(ins, 1))) {
6070                 ulong_t right;
6071                 right = read_const(state, ins, &RHS(ins, 1));
6072                 if (right >= (size_of(state, ins->type)*8)) {
6073                         warning(state, ins, "left shift count >= width of type");
6074                 }
6075         }
6076         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6077                 ulong_t left, right;
6078                 left  = read_const(state, ins, &RHS(ins, 0));
6079                 right = read_const(state, ins, &RHS(ins, 1));
6080                 mkconst(state, ins,  left << right);
6081         }
6082 }
6083
6084 static void simplify_usr(struct compile_state *state, struct triple *ins)
6085 {
6086         if (is_const(RHS(ins, 1))) {
6087                 ulong_t right;
6088                 right = read_const(state, ins, &RHS(ins, 1));
6089                 if (right >= (size_of(state, ins->type)*8)) {
6090                         warning(state, ins, "right shift count >= width of type");
6091                 }
6092         }
6093         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6094                 ulong_t left, right;
6095                 left  = read_const(state, ins, &RHS(ins, 0));
6096                 right = read_const(state, ins, &RHS(ins, 1));
6097                 mkconst(state, ins, left >> right);
6098         }
6099 }
6100
6101 static void simplify_ssr(struct compile_state *state, struct triple *ins)
6102 {
6103         if (is_const(RHS(ins, 1))) {
6104                 ulong_t right;
6105                 right = read_const(state, ins, &RHS(ins, 1));
6106                 if (right >= (size_of(state, ins->type)*8)) {
6107                         warning(state, ins, "right shift count >= width of type");
6108                 }
6109         }
6110         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6111                 long_t left, right;
6112                 left  = read_sconst(ins, &RHS(ins, 0));
6113                 right = read_sconst(ins, &RHS(ins, 1));
6114                 mkconst(state, ins, left >> right);
6115         }
6116 }
6117
6118 static void simplify_and(struct compile_state *state, struct triple *ins)
6119 {
6120         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6121                 ulong_t left, right;
6122                 left  = read_const(state, ins, &RHS(ins, 0));
6123                 right = read_const(state, ins, &RHS(ins, 1));
6124                 mkconst(state, ins, left & right);
6125         }
6126 }
6127
6128 static void simplify_or(struct compile_state *state, struct triple *ins)
6129 {
6130         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6131                 ulong_t left, right;
6132                 left  = read_const(state, ins, &RHS(ins, 0));
6133                 right = read_const(state, ins, &RHS(ins, 1));
6134                 mkconst(state, ins, left | right);
6135         }
6136 }
6137
6138 static void simplify_xor(struct compile_state *state, struct triple *ins)
6139 {
6140         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6141                 ulong_t left, right;
6142                 left  = read_const(state, ins, &RHS(ins, 0));
6143                 right = read_const(state, ins, &RHS(ins, 1));
6144                 mkconst(state, ins, left ^ right);
6145         }
6146 }
6147
6148 static void simplify_pos(struct compile_state *state, struct triple *ins)
6149 {
6150         if (is_const(RHS(ins, 0))) {
6151                 mkconst(state, ins, RHS(ins, 0)->u.cval);
6152         }
6153         else {
6154                 mkcopy(state, ins, RHS(ins, 0));
6155         }
6156 }
6157
6158 static void simplify_neg(struct compile_state *state, struct triple *ins)
6159 {
6160         if (is_const(RHS(ins, 0))) {
6161                 ulong_t left;
6162                 left = read_const(state, ins, &RHS(ins, 0));
6163                 mkconst(state, ins, -left);
6164         }
6165         else if (RHS(ins, 0)->op == OP_NEG) {
6166                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
6167         }
6168 }
6169
6170 static void simplify_invert(struct compile_state *state, struct triple *ins)
6171 {
6172         if (is_const(RHS(ins, 0))) {
6173                 ulong_t left;
6174                 left = read_const(state, ins, &RHS(ins, 0));
6175                 mkconst(state, ins, ~left);
6176         }
6177 }
6178
6179 static void simplify_eq(struct compile_state *state, struct triple *ins)
6180 {
6181         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6182                 ulong_t left, right;
6183                 left  = read_const(state, ins, &RHS(ins, 0));
6184                 right = read_const(state, ins, &RHS(ins, 1));
6185                 mkconst(state, ins, left == right);
6186         }
6187         else if (RHS(ins, 0) == RHS(ins, 1)) {
6188                 mkconst(state, ins, 1);
6189         }
6190 }
6191
6192 static void simplify_noteq(struct compile_state *state, struct triple *ins)
6193 {
6194         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6195                 ulong_t left, right;
6196                 left  = read_const(state, ins, &RHS(ins, 0));
6197                 right = read_const(state, ins, &RHS(ins, 1));
6198                 mkconst(state, ins, left != right);
6199         }
6200         else if (RHS(ins, 0) == RHS(ins, 1)) {
6201                 mkconst(state, ins, 0);
6202         }
6203 }
6204
6205 static void simplify_sless(struct compile_state *state, struct triple *ins)
6206 {
6207         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6208                 long_t left, right;
6209                 left  = read_sconst(ins, &RHS(ins, 0));
6210                 right = read_sconst(ins, &RHS(ins, 1));
6211                 mkconst(state, ins, left < right);
6212         }
6213         else if (RHS(ins, 0) == RHS(ins, 1)) {
6214                 mkconst(state, ins, 0);
6215         }
6216 }
6217
6218 static void simplify_uless(struct compile_state *state, struct triple *ins)
6219 {
6220         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6221                 ulong_t left, right;
6222                 left  = read_const(state, ins, &RHS(ins, 0));
6223                 right = read_const(state, ins, &RHS(ins, 1));
6224                 mkconst(state, ins, left < right);
6225         }
6226         else if (is_zero(RHS(ins, 0))) {
6227                 mkconst(state, ins, 1);
6228         }
6229         else if (RHS(ins, 0) == RHS(ins, 1)) {
6230                 mkconst(state, ins, 0);
6231         }
6232 }
6233
6234 static void simplify_smore(struct compile_state *state, struct triple *ins)
6235 {
6236         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6237                 long_t left, right;
6238                 left  = read_sconst(ins, &RHS(ins, 0));
6239                 right = read_sconst(ins, &RHS(ins, 1));
6240                 mkconst(state, ins, left > right);
6241         }
6242         else if (RHS(ins, 0) == RHS(ins, 1)) {
6243                 mkconst(state, ins, 0);
6244         }
6245 }
6246
6247 static void simplify_umore(struct compile_state *state, struct triple *ins)
6248 {
6249         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6250                 ulong_t left, right;
6251                 left  = read_const(state, ins, &RHS(ins, 0));
6252                 right = read_const(state, ins, &RHS(ins, 1));
6253                 mkconst(state, ins, left > right);
6254         }
6255         else if (is_zero(RHS(ins, 1))) {
6256                 mkconst(state, ins, 1);
6257         }
6258         else if (RHS(ins, 0) == RHS(ins, 1)) {
6259                 mkconst(state, ins, 0);
6260         }
6261 }
6262
6263
6264 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
6265 {
6266         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6267                 long_t left, right;
6268                 left  = read_sconst(ins, &RHS(ins, 0));
6269                 right = read_sconst(ins, &RHS(ins, 1));
6270                 mkconst(state, ins, left <= right);
6271         }
6272         else if (RHS(ins, 0) == RHS(ins, 1)) {
6273                 mkconst(state, ins, 1);
6274         }
6275 }
6276
6277 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
6278 {
6279         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6280                 ulong_t left, right;
6281                 left  = read_const(state, ins, &RHS(ins, 0));
6282                 right = read_const(state, ins, &RHS(ins, 1));
6283                 mkconst(state, ins, left <= right);
6284         }
6285         else if (is_zero(RHS(ins, 0))) {
6286                 mkconst(state, ins, 1);
6287         }
6288         else if (RHS(ins, 0) == RHS(ins, 1)) {
6289                 mkconst(state, ins, 1);
6290         }
6291 }
6292
6293 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
6294 {
6295         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 0))) {
6296                 long_t left, right;
6297                 left  = read_sconst(ins, &RHS(ins, 0));
6298                 right = read_sconst(ins, &RHS(ins, 1));
6299                 mkconst(state, ins, left >= right);
6300         }
6301         else if (RHS(ins, 0) == RHS(ins, 1)) {
6302                 mkconst(state, ins, 1);
6303         }
6304 }
6305
6306 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
6307 {
6308         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
6309                 ulong_t left, right;
6310                 left  = read_const(state, ins, &RHS(ins, 0));
6311                 right = read_const(state, ins, &RHS(ins, 1));
6312                 mkconst(state, ins, left >= right);
6313         }
6314         else if (is_zero(RHS(ins, 1))) {
6315                 mkconst(state, ins, 1);
6316         }
6317         else if (RHS(ins, 0) == RHS(ins, 1)) {
6318                 mkconst(state, ins, 1);
6319         }
6320 }
6321
6322 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
6323 {
6324         if (is_const(RHS(ins, 0))) {
6325                 ulong_t left;
6326                 left = read_const(state, ins, &RHS(ins, 0));
6327                 mkconst(state, ins, left == 0);
6328         }
6329         /* Otherwise if I am the only user... */
6330         else if ((RHS(ins, 0)->use->member == ins) && (RHS(ins, 0)->use->next == 0)) {
6331                 int need_copy = 1;
6332                 /* Invert a boolean operation */
6333                 switch(RHS(ins, 0)->op) {
6334                 case OP_LTRUE:   RHS(ins, 0)->op = OP_LFALSE;  break;
6335                 case OP_LFALSE:  RHS(ins, 0)->op = OP_LTRUE;   break;
6336                 case OP_EQ:      RHS(ins, 0)->op = OP_NOTEQ;   break;
6337                 case OP_NOTEQ:   RHS(ins, 0)->op = OP_EQ;      break;
6338                 case OP_SLESS:   RHS(ins, 0)->op = OP_SMOREEQ; break;
6339                 case OP_ULESS:   RHS(ins, 0)->op = OP_UMOREEQ; break;
6340                 case OP_SMORE:   RHS(ins, 0)->op = OP_SLESSEQ; break;
6341                 case OP_UMORE:   RHS(ins, 0)->op = OP_ULESSEQ; break;
6342                 case OP_SLESSEQ: RHS(ins, 0)->op = OP_SMORE;   break;
6343                 case OP_ULESSEQ: RHS(ins, 0)->op = OP_UMORE;   break;
6344                 case OP_SMOREEQ: RHS(ins, 0)->op = OP_SLESS;   break;
6345                 case OP_UMOREEQ: RHS(ins, 0)->op = OP_ULESS;   break;
6346                 default:
6347                         need_copy = 0;
6348                         break;
6349                 }
6350                 if (need_copy) {
6351                         mkcopy(state, ins, RHS(ins, 0));
6352                 }
6353         }
6354 }
6355
6356 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
6357 {
6358         if (is_const(RHS(ins, 0))) {
6359                 ulong_t left;
6360                 left = read_const(state, ins, &RHS(ins, 0));
6361                 mkconst(state, ins, left != 0);
6362         }
6363         else switch(RHS(ins, 0)->op) {
6364         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
6365         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
6366         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
6367                 mkcopy(state, ins, RHS(ins, 0));
6368         }
6369
6370 }
6371
6372 static void simplify_copy(struct compile_state *state, struct triple *ins)
6373 {
6374         if (is_const(RHS(ins, 0))) {
6375                 switch(RHS(ins, 0)->op) {
6376                 case OP_INTCONST:
6377                 {
6378                         ulong_t left;
6379                         left = read_const(state, ins, &RHS(ins, 0));
6380                         mkconst(state, ins, left);
6381                         break;
6382                 }
6383                 case OP_ADDRCONST:
6384                 {
6385                         struct triple *sdecl;
6386                         ulong_t offset;
6387                         sdecl  = MISC(RHS(ins, 0), 0);
6388                         offset = RHS(ins, 0)->u.cval;
6389                         mkaddr_const(state, ins, sdecl, offset);
6390                         break;
6391                 }
6392                 default:
6393                         internal_error(state, ins, "uknown constant");
6394                         break;
6395                 }
6396         }
6397 }
6398
6399 static void simplify_branch(struct compile_state *state, struct triple *ins)
6400 {
6401         struct block *block;
6402         if (ins->op != OP_BRANCH) {
6403                 internal_error(state, ins, "not branch");
6404         }
6405         if (ins->use != 0) {
6406                 internal_error(state, ins, "branch use");
6407         }
6408 #warning "FIXME implement simplify branch."
6409         /* The challenge here with simplify branch is that I need to 
6410          * make modifications to the control flow graph as well
6411          * as to the branch instruction itself.
6412          */
6413         block = ins->u.block;
6414         
6415         if (TRIPLE_RHS(ins->sizes) && is_const(RHS(ins, 0))) {
6416                 struct triple *targ;
6417                 ulong_t value;
6418                 value = read_const(state, ins, &RHS(ins, 0));
6419                 unuse_triple(RHS(ins, 0), ins);
6420                 targ = TARG(ins, 0);
6421                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 1);
6422                 if (value) {
6423                         unuse_triple(ins->next, ins);
6424                         TARG(ins, 0) = targ;
6425                 }
6426                 else {
6427                         unuse_triple(targ, ins);
6428                         TARG(ins, 0) = ins->next;
6429                 }
6430 #warning "FIXME handle the case of making a branch unconditional"
6431         }
6432         if (TARG(ins, 0) == ins->next) {
6433                 unuse_triple(ins->next, ins);
6434                 if (TRIPLE_RHS(ins->sizes)) {
6435                         unuse_triple(RHS(ins, 0), ins);
6436                         unuse_triple(ins->next, ins);
6437                 }
6438                 ins->sizes = TRIPLE_SIZES(0, 0, 0, 0);
6439                 ins->op = OP_NOOP;
6440                 if (ins->use) {
6441                         internal_error(state, ins, "noop use != 0");
6442                 }
6443 #warning "FIXME handle the case of killing a branch"
6444         }
6445 }
6446
6447 int phi_present(struct block *block)
6448 {
6449         struct triple *ptr;
6450         if (!block) {
6451                 return 0;
6452         }
6453         ptr = block->first;
6454         do {
6455                 if (ptr->op == OP_PHI) {
6456                         return 1;
6457                 }
6458                 ptr = ptr->next;
6459         } while(ptr != block->last);
6460         return 0;
6461 }
6462
6463 static void simplify_label(struct compile_state *state, struct triple *ins)
6464 {
6465 #warning "FIXME enable simplify_label"
6466         struct triple *first, *last;
6467         first = RHS(state->main_function, 0);
6468         last = first->prev;
6469         /* Ignore the first and last instructions */
6470         if ((ins == first) || (ins == last)) {
6471                 return;
6472         }
6473         if (ins->use == 0) {
6474                 ins->op = OP_NOOP;
6475         }
6476         else if (ins->prev->op == OP_LABEL) {
6477                 struct block *block;
6478                 block = ins->prev->u.block;
6479                 /* In general it is not safe to merge one label that
6480                  * imediately follows another.  The problem is that the empty
6481                  * looking block may have phi functions that depend on it.
6482                  */
6483                 if (!block || 
6484                         (!phi_present(block->left) && 
6485                         !phi_present(block->right))) 
6486                 {
6487                         struct triple_set *user, *next;
6488                         ins->op = OP_NOOP;
6489                         for(user = ins->use; user; user = next) {
6490                                 struct triple *use;
6491                                 next = user->next;
6492                                 use = user->member;
6493                                 if (TARG(use, 0) == ins) {
6494                                         TARG(use, 0) = ins->prev;
6495                                         unuse_triple(ins, use);
6496                                         use_triple(ins->prev, use);
6497                                 }
6498                         }
6499                         if (ins->use) {
6500                                 internal_error(state, ins, "noop use != 0");
6501                         }
6502                 }
6503         }
6504 }
6505
6506 static void simplify_phi(struct compile_state *state, struct triple *ins)
6507 {
6508         struct triple **expr;
6509         ulong_t value;
6510         expr = triple_rhs(state, ins, 0);
6511         if (!*expr || !is_const(*expr)) {
6512                 return;
6513         }
6514         value = read_const(state, ins, expr);
6515         for(;expr;expr = triple_rhs(state, ins, expr)) {
6516                 if (!*expr || !is_const(*expr)) {
6517                         return;
6518                 }
6519                 if (value != read_const(state, ins, expr)) {
6520                         return;
6521                 }
6522         }
6523         mkconst(state, ins, value);
6524 }
6525
6526
6527 static void simplify_bsf(struct compile_state *state, struct triple *ins)
6528 {
6529         if (is_const(RHS(ins, 0))) {
6530                 ulong_t left;
6531                 left = read_const(state, ins, &RHS(ins, 0));
6532                 mkconst(state, ins, bsf(left));
6533         }
6534 }
6535
6536 static void simplify_bsr(struct compile_state *state, struct triple *ins)
6537 {
6538         if (is_const(RHS(ins, 0))) {
6539                 ulong_t left;
6540                 left = read_const(state, ins, &RHS(ins, 0));
6541                 mkconst(state, ins, bsr(left));
6542         }
6543 }
6544
6545
6546 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
6547 static const simplify_t table_simplify[] = {
6548 #if 1
6549 #define simplify_sdivt    simplify_noop
6550 #define simplify_udivt    simplify_noop
6551 #endif
6552 #if 0
6553 #define simplify_smul     simplify_noop
6554 #define simplify_umul     simplify_noop
6555 #define simplify_sdiv     simplify_noop
6556 #define simplify_udiv     simplify_noop
6557 #define simplify_smod     simplify_noop
6558 #define simplify_umod     simplify_noop
6559 #endif
6560 #if 0
6561 #define simplify_add      simplify_noop
6562 #define simplify_sub      simplify_noop
6563 #endif
6564 #if 0
6565 #define simplify_sl       simplify_noop
6566 #define simplify_usr      simplify_noop
6567 #define simplify_ssr      simplify_noop
6568 #endif
6569 #if 0
6570 #define simplify_and      simplify_noop
6571 #define simplify_xor      simplify_noop
6572 #define simplify_or       simplify_noop
6573 #endif
6574 #if 0
6575 #define simplify_pos      simplify_noop
6576 #define simplify_neg      simplify_noop
6577 #define simplify_invert   simplify_noop
6578 #endif
6579
6580 #if 0
6581 #define simplify_eq       simplify_noop
6582 #define simplify_noteq    simplify_noop
6583 #endif
6584 #if 0
6585 #define simplify_sless    simplify_noop
6586 #define simplify_uless    simplify_noop
6587 #define simplify_smore    simplify_noop
6588 #define simplify_umore    simplify_noop
6589 #endif
6590 #if 0
6591 #define simplify_slesseq  simplify_noop
6592 #define simplify_ulesseq  simplify_noop
6593 #define simplify_smoreeq  simplify_noop
6594 #define simplify_umoreeq  simplify_noop
6595 #endif
6596 #if 0
6597 #define simplify_lfalse   simplify_noop
6598 #endif
6599 #if 0
6600 #define simplify_ltrue    simplify_noop
6601 #endif
6602
6603 #if 0
6604 #define simplify_copy     simplify_noop
6605 #endif
6606
6607 #if 0
6608 #define simplify_branch   simplify_noop
6609 #endif
6610 #if 1
6611 #define simplify_label    simplify_noop
6612 #endif
6613
6614 #if 0
6615 #define simplify_phi      simplify_noop
6616 #endif
6617
6618 #if 0
6619 #define simplify_bsf      simplify_noop
6620 #define simplify_bsr      simplify_noop
6621 #endif
6622
6623 [OP_SDIVT      ] = simplify_sdivt,
6624 [OP_UDIVT      ] = simplify_udivt,
6625 [OP_SMUL       ] = simplify_smul,
6626 [OP_UMUL       ] = simplify_umul,
6627 [OP_SDIV       ] = simplify_sdiv,
6628 [OP_UDIV       ] = simplify_udiv,
6629 [OP_SMOD       ] = simplify_smod,
6630 [OP_UMOD       ] = simplify_umod,
6631 [OP_ADD        ] = simplify_add,
6632 [OP_SUB        ] = simplify_sub,
6633 [OP_SL         ] = simplify_sl,
6634 [OP_USR        ] = simplify_usr,
6635 [OP_SSR        ] = simplify_ssr,
6636 [OP_AND        ] = simplify_and,
6637 [OP_XOR        ] = simplify_xor,
6638 [OP_OR         ] = simplify_or,
6639 [OP_POS        ] = simplify_pos,
6640 [OP_NEG        ] = simplify_neg,
6641 [OP_INVERT     ] = simplify_invert,
6642
6643 [OP_EQ         ] = simplify_eq,
6644 [OP_NOTEQ      ] = simplify_noteq,
6645 [OP_SLESS      ] = simplify_sless,
6646 [OP_ULESS      ] = simplify_uless,
6647 [OP_SMORE      ] = simplify_smore,
6648 [OP_UMORE      ] = simplify_umore,
6649 [OP_SLESSEQ    ] = simplify_slesseq,
6650 [OP_ULESSEQ    ] = simplify_ulesseq,
6651 [OP_SMOREEQ    ] = simplify_smoreeq,
6652 [OP_UMOREEQ    ] = simplify_umoreeq,
6653 [OP_LFALSE     ] = simplify_lfalse,
6654 [OP_LTRUE      ] = simplify_ltrue,
6655
6656 [OP_LOAD       ] = simplify_noop,
6657 [OP_STORE      ] = simplify_noop,
6658
6659 [OP_NOOP       ] = simplify_noop,
6660
6661 [OP_INTCONST   ] = simplify_noop,
6662 [OP_BLOBCONST  ] = simplify_noop,
6663 [OP_ADDRCONST  ] = simplify_noop,
6664
6665 [OP_WRITE      ] = simplify_noop,
6666 [OP_READ       ] = simplify_noop,
6667 [OP_COPY       ] = simplify_copy,
6668 [OP_PIECE      ] = simplify_noop,
6669 [OP_ASM        ] = simplify_noop,
6670
6671 [OP_DOT        ] = simplify_noop,
6672 [OP_VAL_VEC    ] = simplify_noop,
6673
6674 [OP_LIST       ] = simplify_noop,
6675 [OP_BRANCH     ] = simplify_branch,
6676 [OP_LABEL      ] = simplify_label,
6677 [OP_ADECL      ] = simplify_noop,
6678 [OP_SDECL      ] = simplify_noop,
6679 [OP_PHI        ] = simplify_phi,
6680
6681 [OP_INB        ] = simplify_noop,
6682 [OP_INW        ] = simplify_noop,
6683 [OP_INL        ] = simplify_noop,
6684 [OP_OUTB       ] = simplify_noop,
6685 [OP_OUTW       ] = simplify_noop,
6686 [OP_OUTL       ] = simplify_noop,
6687 [OP_BSF        ] = simplify_bsf,
6688 [OP_BSR        ] = simplify_bsr,
6689 [OP_RDMSR      ] = simplify_noop,
6690 [OP_WRMSR      ] = simplify_noop,                    
6691 [OP_HLT        ] = simplify_noop,
6692 };
6693
6694 static void simplify(struct compile_state *state, struct triple *ins)
6695 {
6696         int op;
6697         simplify_t do_simplify;
6698         do {
6699                 op = ins->op;
6700                 do_simplify = 0;
6701                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
6702                         do_simplify = 0;
6703                 }
6704                 else {
6705                         do_simplify = table_simplify[op];
6706                 }
6707                 if (!do_simplify) {
6708                         internal_error(state, ins, "cannot simplify op: %d %s\n",
6709                                 op, tops(op));
6710                         return;
6711                 }
6712                 do_simplify(state, ins);
6713         } while(ins->op != op);
6714 }
6715
6716 static void simplify_all(struct compile_state *state)
6717 {
6718         struct triple *ins, *first;
6719         first = RHS(state->main_function, 0);
6720         ins = first;
6721         do {
6722                 simplify(state, ins);
6723                 ins = ins->next;
6724         }while(ins != first);
6725 }
6726
6727 /*
6728  * Builtins....
6729  * ============================
6730  */
6731
6732 static void register_builtin_function(struct compile_state *state,
6733         const char *name, int op, struct type *rtype, ...)
6734 {
6735         struct type *ftype, *atype, *param, **next;
6736         struct triple *def, *arg, *result, *work, *last, *first;
6737         struct hash_entry *ident;
6738         struct file_state file;
6739         int parameters;
6740         int name_len;
6741         va_list args;
6742         int i;
6743
6744         /* Dummy file state to get debug handling right */
6745         memset(&file, 0, sizeof(file));
6746         file.basename = "<built-in>";
6747         file.line = 1;
6748         file.report_line = 1;
6749         file.report_name = file.basename;
6750         file.prev = state->file;
6751         state->file = &file;
6752         state->function = name;
6753
6754         /* Find the Parameter count */
6755         valid_op(state, op);
6756         parameters = table_ops[op].rhs;
6757         if (parameters < 0 ) {
6758                 internal_error(state, 0, "Invalid builtin parameter count");
6759         }
6760
6761         /* Find the function type */
6762         ftype = new_type(TYPE_FUNCTION, rtype, 0);
6763         next = &ftype->right;
6764         va_start(args, rtype);
6765         for(i = 0; i < parameters; i++) {
6766                 atype = va_arg(args, struct type *);
6767                 if (!*next) {
6768                         *next = atype;
6769                 } else {
6770                         *next = new_type(TYPE_PRODUCT, *next, atype);
6771                         next = &((*next)->right);
6772                 }
6773         }
6774         if (!*next) {
6775                 *next = &void_type;
6776         }
6777         va_end(args);
6778
6779         /* Generate the needed triples */
6780         def = triple(state, OP_LIST, ftype, 0, 0);
6781         first = label(state);
6782         RHS(def, 0) = first;
6783
6784         /* Now string them together */
6785         param = ftype->right;
6786         for(i = 0; i < parameters; i++) {
6787                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6788                         atype = param->left;
6789                 } else {
6790                         atype = param;
6791                 }
6792                 arg = flatten(state, first, variable(state, atype));
6793                 param = param->right;
6794         }
6795         result = 0;
6796         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
6797                 result = flatten(state, first, variable(state, rtype));
6798         }
6799         MISC(def, 0) = result;
6800         work = new_triple(state, op, rtype, -1, parameters);
6801         for(i = 0, arg = first->next; i < parameters; i++, arg = arg->next) {
6802                 RHS(work, i) = read_expr(state, arg);
6803         }
6804         if (result && ((rtype->type & TYPE_MASK) == TYPE_STRUCT)) {
6805                 struct triple *val;
6806                 /* Populate the LHS with the target registers */
6807                 work = flatten(state, first, work);
6808                 work->type = &void_type;
6809                 param = rtype->left;
6810                 if (rtype->elements != TRIPLE_LHS(work->sizes)) {
6811                         internal_error(state, 0, "Invalid result type");
6812                 }
6813                 val = new_triple(state, OP_VAL_VEC, rtype, -1, -1);
6814                 for(i = 0; i < rtype->elements; i++) {
6815                         struct triple *piece;
6816                         atype = param;
6817                         if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
6818                                 atype = param->left;
6819                         }
6820                         if (!TYPE_ARITHMETIC(atype->type) &&
6821                                 !TYPE_PTR(atype->type)) {
6822                                 internal_error(state, 0, "Invalid lhs type");
6823                         }
6824                         piece = triple(state, OP_PIECE, atype, work, 0);
6825                         piece->u.cval = i;
6826                         LHS(work, i) = piece;
6827                         RHS(val, i) = piece;
6828                 }
6829                 work = val;
6830         }
6831         if (result) {
6832                 work = write_expr(state, result, work);
6833         }
6834         work = flatten(state, first, work);
6835         last = flatten(state, first, label(state));
6836         name_len = strlen(name);
6837         ident = lookup(state, name, name_len);
6838         symbol(state, ident, &ident->sym_ident, def, ftype);
6839         
6840         state->file = file.prev;
6841         state->function = 0;
6842 #if 0
6843         fprintf(stdout, "\n");
6844         loc(stdout, state, 0);
6845         fprintf(stdout, "\n__________ builtin_function _________\n");
6846         print_triple(state, def);
6847         fprintf(stdout, "__________ builtin_function _________ done\n\n");
6848 #endif
6849 }
6850
6851 static struct type *partial_struct(struct compile_state *state,
6852         const char *field_name, struct type *type, struct type *rest)
6853 {
6854         struct hash_entry *field_ident;
6855         struct type *result;
6856         int field_name_len;
6857
6858         field_name_len = strlen(field_name);
6859         field_ident = lookup(state, field_name, field_name_len);
6860
6861         result = clone_type(0, type);
6862         result->field_ident = field_ident;
6863
6864         if (rest) {
6865                 result = new_type(TYPE_PRODUCT, result, rest);
6866         }
6867         return result;
6868 }
6869
6870 static struct type *register_builtin_type(struct compile_state *state,
6871         const char *name, struct type *type)
6872 {
6873         struct hash_entry *ident;
6874         int name_len;
6875
6876         name_len = strlen(name);
6877         ident = lookup(state, name, name_len);
6878         
6879         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6880                 ulong_t elements = 0;
6881                 struct type *field;
6882                 type = new_type(TYPE_STRUCT, type, 0);
6883                 field = type->left;
6884                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
6885                         elements++;
6886                         field = field->right;
6887                 }
6888                 elements++;
6889                 symbol(state, ident, &ident->sym_struct, 0, type);
6890                 type->type_ident = ident;
6891                 type->elements = elements;
6892         }
6893         symbol(state, ident, &ident->sym_ident, 0, type);
6894         ident->tok = TOK_TYPE_NAME;
6895         return type;
6896 }
6897
6898
6899 static void register_builtins(struct compile_state *state)
6900 {
6901         struct type *div_type, *ldiv_type;
6902         struct type *udiv_type, *uldiv_type;
6903         struct type *msr_type;
6904
6905         div_type = register_builtin_type(state, "__builtin_div_t",
6906                 partial_struct(state, "quot", &int_type,
6907                 partial_struct(state, "rem",  &int_type, 0)));
6908         ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
6909                 partial_struct(state, "quot", &long_type,
6910                 partial_struct(state, "rem",  &long_type, 0)));
6911         udiv_type = register_builtin_type(state, "__builtin_udiv_t",
6912                 partial_struct(state, "quot", &uint_type,
6913                 partial_struct(state, "rem",  &uint_type, 0)));
6914         uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
6915                 partial_struct(state, "quot", &ulong_type,
6916                 partial_struct(state, "rem",  &ulong_type, 0)));
6917
6918         register_builtin_function(state, "__builtin_div",   OP_SDIVT, div_type,
6919                 &int_type, &int_type);
6920         register_builtin_function(state, "__builtin_ldiv",  OP_SDIVT, ldiv_type,
6921                 &long_type, &long_type);
6922         register_builtin_function(state, "__builtin_udiv",  OP_UDIVT, udiv_type,
6923                 &uint_type, &uint_type);
6924         register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
6925                 &ulong_type, &ulong_type);
6926
6927         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
6928                 &ushort_type);
6929         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
6930                 &ushort_type);
6931         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
6932                 &ushort_type);
6933
6934         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
6935                 &uchar_type, &ushort_type);
6936         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
6937                 &ushort_type, &ushort_type);
6938         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
6939                 &uint_type, &ushort_type);
6940         
6941         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
6942                 &int_type);
6943         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
6944                 &int_type);
6945
6946         msr_type = register_builtin_type(state, "__builtin_msr_t",
6947                 partial_struct(state, "lo", &ulong_type,
6948                 partial_struct(state, "hi", &ulong_type, 0)));
6949
6950         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
6951                 &ulong_type);
6952         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
6953                 &ulong_type, &ulong_type, &ulong_type);
6954         
6955         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
6956                 &void_type);
6957 }
6958
6959 static struct type *declarator(
6960         struct compile_state *state, struct type *type, 
6961         struct hash_entry **ident, int need_ident);
6962 static void decl(struct compile_state *state, struct triple *first);
6963 static struct type *specifier_qualifier_list(struct compile_state *state);
6964 static int isdecl_specifier(int tok);
6965 static struct type *decl_specifiers(struct compile_state *state);
6966 static int istype(int tok);
6967 static struct triple *expr(struct compile_state *state);
6968 static struct triple *assignment_expr(struct compile_state *state);
6969 static struct type *type_name(struct compile_state *state);
6970 static void statement(struct compile_state *state, struct triple *fist);
6971
6972 static struct triple *call_expr(
6973         struct compile_state *state, struct triple *func)
6974 {
6975         struct triple *def;
6976         struct type *param, *type;
6977         ulong_t pvals, index;
6978
6979         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
6980                 error(state, 0, "Called object is not a function");
6981         }
6982         if (func->op != OP_LIST) {
6983                 internal_error(state, 0, "improper function");
6984         }
6985         eat(state, TOK_LPAREN);
6986         /* Find the return type without any specifiers */
6987         type = clone_type(0, func->type->left);
6988         def = new_triple(state, OP_CALL, func->type, -1, -1);
6989         def->type = type;
6990
6991         pvals = TRIPLE_RHS(def->sizes);
6992         MISC(def, 0) = func;
6993
6994         param = func->type->right;
6995         for(index = 0; index < pvals; index++) {
6996                 struct triple *val;
6997                 struct type *arg_type;
6998                 val = read_expr(state, assignment_expr(state));
6999                 arg_type = param;
7000                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
7001                         arg_type = param->left;
7002                 }
7003                 write_compatible(state, arg_type, val->type);
7004                 RHS(def, index) = val;
7005                 if (index != (pvals - 1)) {
7006                         eat(state, TOK_COMMA);
7007                         param = param->right;
7008                 }
7009         }
7010         eat(state, TOK_RPAREN);
7011         return def;
7012 }
7013
7014
7015 static struct triple *character_constant(struct compile_state *state)
7016 {
7017         struct triple *def;
7018         struct token *tk;
7019         const signed char *str, *end;
7020         int c;
7021         int str_len;
7022         eat(state, TOK_LIT_CHAR);
7023         tk = &state->token[0];
7024         str = tk->val.str + 1;
7025         str_len = tk->str_len - 2;
7026         if (str_len <= 0) {
7027                 error(state, 0, "empty character constant");
7028         }
7029         end = str + str_len;
7030         c = char_value(state, &str, end);
7031         if (str != end) {
7032                 error(state, 0, "multibyte character constant not supported");
7033         }
7034         def = int_const(state, &char_type, (ulong_t)((long_t)c));
7035         return def;
7036 }
7037
7038 static struct triple *string_constant(struct compile_state *state)
7039 {
7040         struct triple *def;
7041         struct token *tk;
7042         struct type *type;
7043         const signed char *str, *end;
7044         signed char *buf, *ptr;
7045         int str_len;
7046
7047         buf = 0;
7048         type = new_type(TYPE_ARRAY, &char_type, 0);
7049         type->elements = 0;
7050         /* The while loop handles string concatenation */
7051         do {
7052                 eat(state, TOK_LIT_STRING);
7053                 tk = &state->token[0];
7054                 str = tk->val.str + 1;
7055                 str_len = tk->str_len - 2;
7056                 if (str_len < 0) {
7057                         error(state, 0, "negative string constant length");
7058                 }
7059                 end = str + str_len;
7060                 ptr = buf;
7061                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
7062                 memcpy(buf, ptr, type->elements);
7063                 ptr = buf + type->elements;
7064                 do {
7065                         *ptr++ = char_value(state, &str, end);
7066                 } while(str < end);
7067                 type->elements = ptr - buf;
7068         } while(peek(state) == TOK_LIT_STRING);
7069         *ptr = '\0';
7070         type->elements += 1;
7071         def = triple(state, OP_BLOBCONST, type, 0, 0);
7072         def->u.blob = buf;
7073         return def;
7074 }
7075
7076
7077 static struct triple *integer_constant(struct compile_state *state)
7078 {
7079         struct triple *def;
7080         unsigned long val;
7081         struct token *tk;
7082         char *end;
7083         int u, l, decimal;
7084         struct type *type;
7085
7086         eat(state, TOK_LIT_INT);
7087         tk = &state->token[0];
7088         errno = 0;
7089         decimal = (tk->val.str[0] != '0');
7090         val = strtoul(tk->val.str, &end, 0);
7091         if ((val == ULONG_MAX) && (errno == ERANGE)) {
7092                 error(state, 0, "Integer constant to large");
7093         }
7094         u = l = 0;
7095         if ((*end == 'u') || (*end == 'U')) {
7096                 u = 1;
7097                         end++;
7098         }
7099         if ((*end == 'l') || (*end == 'L')) {
7100                 l = 1;
7101                 end++;
7102         }
7103         if ((*end == 'u') || (*end == 'U')) {
7104                 u = 1;
7105                 end++;
7106         }
7107         if (*end) {
7108                 error(state, 0, "Junk at end of integer constant");
7109         }
7110         if (u && l)  {
7111                 type = &ulong_type;
7112         }
7113         else if (l) {
7114                 type = &long_type;
7115                 if (!decimal && (val > LONG_MAX)) {
7116                         type = &ulong_type;
7117                 }
7118         }
7119         else if (u) {
7120                 type = &uint_type;
7121                 if (val > UINT_MAX) {
7122                         type = &ulong_type;
7123                 }
7124         }
7125         else {
7126                 type = &int_type;
7127                 if (!decimal && (val > INT_MAX) && (val <= UINT_MAX)) {
7128                         type = &uint_type;
7129                 }
7130                 else if (!decimal && (val > LONG_MAX)) {
7131                         type = &ulong_type;
7132                 }
7133                 else if (val > INT_MAX) {
7134                         type = &long_type;
7135                 }
7136         }
7137         def = int_const(state, type, val);
7138         return def;
7139 }
7140
7141 static struct triple *primary_expr(struct compile_state *state)
7142 {
7143         struct triple *def;
7144         int tok;
7145         tok = peek(state);
7146         switch(tok) {
7147         case TOK_IDENT:
7148         {
7149                 struct hash_entry *ident;
7150                 /* Here ident is either:
7151                  * a varable name
7152                  * a function name
7153                  * an enumeration constant.
7154                  */
7155                 eat(state, TOK_IDENT);
7156                 ident = state->token[0].ident;
7157                 if (!ident->sym_ident) {
7158                         error(state, 0, "%s undeclared", ident->name);
7159                 }
7160                 def = ident->sym_ident->def;
7161                 break;
7162         }
7163         case TOK_ENUM_CONST:
7164                 /* Here ident is an enumeration constant */
7165                 eat(state, TOK_ENUM_CONST);
7166                 def = 0;
7167                 FINISHME();
7168                 break;
7169         case TOK_LPAREN:
7170                 eat(state, TOK_LPAREN);
7171                 def = expr(state);
7172                 eat(state, TOK_RPAREN);
7173                 break;
7174         case TOK_LIT_INT:
7175                 def = integer_constant(state);
7176                 break;
7177         case TOK_LIT_FLOAT:
7178                 eat(state, TOK_LIT_FLOAT);
7179                 error(state, 0, "Floating point constants not supported");
7180                 def = 0;
7181                 FINISHME();
7182                 break;
7183         case TOK_LIT_CHAR:
7184                 def = character_constant(state);
7185                 break;
7186         case TOK_LIT_STRING:
7187                 def = string_constant(state);
7188                 break;
7189         default:
7190                 def = 0;
7191                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
7192         }
7193         return def;
7194 }
7195
7196 static struct triple *postfix_expr(struct compile_state *state)
7197 {
7198         struct triple *def;
7199         int postfix;
7200         def = primary_expr(state);
7201         do {
7202                 struct triple *left;
7203                 int tok;
7204                 postfix = 1;
7205                 left = def;
7206                 switch((tok = peek(state))) {
7207                 case TOK_LBRACKET:
7208                         eat(state, TOK_LBRACKET);
7209                         def = mk_subscript_expr(state, left, expr(state));
7210                         eat(state, TOK_RBRACKET);
7211                         break;
7212                 case TOK_LPAREN:
7213                         def = call_expr(state, def);
7214                         break;
7215                 case TOK_DOT:
7216                 {
7217                         struct hash_entry *field;
7218                         eat(state, TOK_DOT);
7219                         eat(state, TOK_IDENT);
7220                         field = state->token[0].ident;
7221                         def = deref_field(state, def, field);
7222                         break;
7223                 }
7224                 case TOK_ARROW:
7225                 {
7226                         struct hash_entry *field;
7227                         eat(state, TOK_ARROW);
7228                         eat(state, TOK_IDENT);
7229                         field = state->token[0].ident;
7230                         def = mk_deref_expr(state, read_expr(state, def));
7231                         def = deref_field(state, def, field);
7232                         break;
7233                 }
7234                 case TOK_PLUSPLUS:
7235                         eat(state, TOK_PLUSPLUS);
7236                         def = mk_post_inc_expr(state, left);
7237                         break;
7238                 case TOK_MINUSMINUS:
7239                         eat(state, TOK_MINUSMINUS);
7240                         def = mk_post_dec_expr(state, left);
7241                         break;
7242                 default:
7243                         postfix = 0;
7244                         break;
7245                 }
7246         } while(postfix);
7247         return def;
7248 }
7249
7250 static struct triple *cast_expr(struct compile_state *state);
7251
7252 static struct triple *unary_expr(struct compile_state *state)
7253 {
7254         struct triple *def, *right;
7255         int tok;
7256         switch((tok = peek(state))) {
7257         case TOK_PLUSPLUS:
7258                 eat(state, TOK_PLUSPLUS);
7259                 def = mk_pre_inc_expr(state, unary_expr(state));
7260                 break;
7261         case TOK_MINUSMINUS:
7262                 eat(state, TOK_MINUSMINUS);
7263                 def = mk_pre_dec_expr(state, unary_expr(state));
7264                 break;
7265         case TOK_AND:
7266                 eat(state, TOK_AND);
7267                 def = mk_addr_expr(state, cast_expr(state), 0);
7268                 break;
7269         case TOK_STAR:
7270                 eat(state, TOK_STAR);
7271                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
7272                 break;
7273         case TOK_PLUS:
7274                 eat(state, TOK_PLUS);
7275                 right = read_expr(state, cast_expr(state));
7276                 arithmetic(state, right);
7277                 def = integral_promotion(state, right);
7278                 break;
7279         case TOK_MINUS:
7280                 eat(state, TOK_MINUS);
7281                 right = read_expr(state, cast_expr(state));
7282                 arithmetic(state, right);
7283                 def = integral_promotion(state, right);
7284                 def = triple(state, OP_NEG, def->type, def, 0);
7285                 break;
7286         case TOK_TILDE:
7287                 eat(state, TOK_TILDE);
7288                 right = read_expr(state, cast_expr(state));
7289                 integral(state, right);
7290                 def = integral_promotion(state, right);
7291                 def = triple(state, OP_INVERT, def->type, def, 0);
7292                 break;
7293         case TOK_BANG:
7294                 eat(state, TOK_BANG);
7295                 right = read_expr(state, cast_expr(state));
7296                 bool(state, right);
7297                 def = lfalse_expr(state, right);
7298                 break;
7299         case TOK_SIZEOF:
7300         {
7301                 struct type *type;
7302                 int tok1, tok2;
7303                 eat(state, TOK_SIZEOF);
7304                 tok1 = peek(state);
7305                 tok2 = peek2(state);
7306                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7307                         eat(state, TOK_LPAREN);
7308                         type = type_name(state);
7309                         eat(state, TOK_RPAREN);
7310                 }
7311                 else {
7312                         struct triple *expr;
7313                         expr = unary_expr(state);
7314                         type = expr->type;
7315                         release_expr(state, expr);
7316                 }
7317                 def = int_const(state, &ulong_type, size_of(state, type));
7318                 break;
7319         }
7320         case TOK_ALIGNOF:
7321         {
7322                 struct type *type;
7323                 int tok1, tok2;
7324                 eat(state, TOK_ALIGNOF);
7325                 tok1 = peek(state);
7326                 tok2 = peek2(state);
7327                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7328                         eat(state, TOK_LPAREN);
7329                         type = type_name(state);
7330                         eat(state, TOK_RPAREN);
7331                 }
7332                 else {
7333                         struct triple *expr;
7334                         expr = unary_expr(state);
7335                         type = expr->type;
7336                         release_expr(state, expr);
7337                 }
7338                 def = int_const(state, &ulong_type, align_of(state, type));
7339                 break;
7340         }
7341         default:
7342                 def = postfix_expr(state);
7343                 break;
7344         }
7345         return def;
7346 }
7347
7348 static struct triple *cast_expr(struct compile_state *state)
7349 {
7350         struct triple *def;
7351         int tok1, tok2;
7352         tok1 = peek(state);
7353         tok2 = peek2(state);
7354         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
7355                 struct type *type;
7356                 eat(state, TOK_LPAREN);
7357                 type = type_name(state);
7358                 eat(state, TOK_RPAREN);
7359                 def = read_expr(state, cast_expr(state));
7360                 def = triple(state, OP_COPY, type, def, 0);
7361         }
7362         else {
7363                 def = unary_expr(state);
7364         }
7365         return def;
7366 }
7367
7368 static struct triple *mult_expr(struct compile_state *state)
7369 {
7370         struct triple *def;
7371         int done;
7372         def = cast_expr(state);
7373         do {
7374                 struct triple *left, *right;
7375                 struct type *result_type;
7376                 int tok, op, sign;
7377                 done = 0;
7378                 switch(tok = (peek(state))) {
7379                 case TOK_STAR:
7380                 case TOK_DIV:
7381                 case TOK_MOD:
7382                         left = read_expr(state, def);
7383                         arithmetic(state, left);
7384
7385                         eat(state, tok);
7386
7387                         right = read_expr(state, cast_expr(state));
7388                         arithmetic(state, right);
7389
7390                         result_type = arithmetic_result(state, left, right);
7391                         sign = is_signed(result_type);
7392                         op = -1;
7393                         switch(tok) {
7394                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
7395                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
7396                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
7397                         }
7398                         def = triple(state, op, result_type, left, right);
7399                         break;
7400                 default:
7401                         done = 1;
7402                         break;
7403                 }
7404         } while(!done);
7405         return def;
7406 }
7407
7408 static struct triple *add_expr(struct compile_state *state)
7409 {
7410         struct triple *def;
7411         int done;
7412         def = mult_expr(state);
7413         do {
7414                 done = 0;
7415                 switch( peek(state)) {
7416                 case TOK_PLUS:
7417                         eat(state, TOK_PLUS);
7418                         def = mk_add_expr(state, def, mult_expr(state));
7419                         break;
7420                 case TOK_MINUS:
7421                         eat(state, TOK_MINUS);
7422                         def = mk_sub_expr(state, def, mult_expr(state));
7423                         break;
7424                 default:
7425                         done = 1;
7426                         break;
7427                 }
7428         } while(!done);
7429         return def;
7430 }
7431
7432 static struct triple *shift_expr(struct compile_state *state)
7433 {
7434         struct triple *def;
7435         int done;
7436         def = add_expr(state);
7437         do {
7438                 struct triple *left, *right;
7439                 int tok, op;
7440                 done = 0;
7441                 switch((tok = peek(state))) {
7442                 case TOK_SL:
7443                 case TOK_SR:
7444                         left = read_expr(state, def);
7445                         integral(state, left);
7446                         left = integral_promotion(state, left);
7447
7448                         eat(state, tok);
7449
7450                         right = read_expr(state, add_expr(state));
7451                         integral(state, right);
7452                         right = integral_promotion(state, right);
7453                         
7454                         op = (tok == TOK_SL)? OP_SL : 
7455                                 is_signed(left->type)? OP_SSR: OP_USR;
7456
7457                         def = triple(state, op, left->type, left, right);
7458                         break;
7459                 default:
7460                         done = 1;
7461                         break;
7462                 }
7463         } while(!done);
7464         return def;
7465 }
7466
7467 static struct triple *relational_expr(struct compile_state *state)
7468 {
7469 #warning "Extend relational exprs to work on more than arithmetic types"
7470         struct triple *def;
7471         int done;
7472         def = shift_expr(state);
7473         do {
7474                 struct triple *left, *right;
7475                 struct type *arg_type;
7476                 int tok, op, sign;
7477                 done = 0;
7478                 switch((tok = peek(state))) {
7479                 case TOK_LESS:
7480                 case TOK_MORE:
7481                 case TOK_LESSEQ:
7482                 case TOK_MOREEQ:
7483                         left = read_expr(state, def);
7484                         arithmetic(state, left);
7485
7486                         eat(state, tok);
7487
7488                         right = read_expr(state, shift_expr(state));
7489                         arithmetic(state, right);
7490
7491                         arg_type = arithmetic_result(state, left, right);
7492                         sign = is_signed(arg_type);
7493                         op = -1;
7494                         switch(tok) {
7495                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
7496                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
7497                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
7498                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
7499                         }
7500                         def = triple(state, op, &int_type, left, right);
7501                         break;
7502                 default:
7503                         done = 1;
7504                         break;
7505                 }
7506         } while(!done);
7507         return def;
7508 }
7509
7510 static struct triple *equality_expr(struct compile_state *state)
7511 {
7512 #warning "Extend equality exprs to work on more than arithmetic types"
7513         struct triple *def;
7514         int done;
7515         def = relational_expr(state);
7516         do {
7517                 struct triple *left, *right;
7518                 int tok, op;
7519                 done = 0;
7520                 switch((tok = peek(state))) {
7521                 case TOK_EQEQ:
7522                 case TOK_NOTEQ:
7523                         left = read_expr(state, def);
7524                         arithmetic(state, left);
7525                         eat(state, tok);
7526                         right = read_expr(state, relational_expr(state));
7527                         arithmetic(state, right);
7528                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
7529                         def = triple(state, op, &int_type, left, right);
7530                         break;
7531                 default:
7532                         done = 1;
7533                         break;
7534                 }
7535         } while(!done);
7536         return def;
7537 }
7538
7539 static struct triple *and_expr(struct compile_state *state)
7540 {
7541         struct triple *def;
7542         def = equality_expr(state);
7543         while(peek(state) == TOK_AND) {
7544                 struct triple *left, *right;
7545                 struct type *result_type;
7546                 left = read_expr(state, def);
7547                 integral(state, left);
7548                 eat(state, TOK_AND);
7549                 right = read_expr(state, equality_expr(state));
7550                 integral(state, right);
7551                 result_type = arithmetic_result(state, left, right);
7552                 def = triple(state, OP_AND, result_type, left, right);
7553         }
7554         return def;
7555 }
7556
7557 static struct triple *xor_expr(struct compile_state *state)
7558 {
7559         struct triple *def;
7560         def = and_expr(state);
7561         while(peek(state) == TOK_XOR) {
7562                 struct triple *left, *right;
7563                 struct type *result_type;
7564                 left = read_expr(state, def);
7565                 integral(state, left);
7566                 eat(state, TOK_XOR);
7567                 right = read_expr(state, and_expr(state));
7568                 integral(state, right);
7569                 result_type = arithmetic_result(state, left, right);
7570                 def = triple(state, OP_XOR, result_type, left, right);
7571         }
7572         return def;
7573 }
7574
7575 static struct triple *or_expr(struct compile_state *state)
7576 {
7577         struct triple *def;
7578         def = xor_expr(state);
7579         while(peek(state) == TOK_OR) {
7580                 struct triple *left, *right;
7581                 struct type *result_type;
7582                 left = read_expr(state, def);
7583                 integral(state, left);
7584                 eat(state, TOK_OR);
7585                 right = read_expr(state, xor_expr(state));
7586                 integral(state, right);
7587                 result_type = arithmetic_result(state, left, right);
7588                 def = triple(state, OP_OR, result_type, left, right);
7589         }
7590         return def;
7591 }
7592
7593 static struct triple *land_expr(struct compile_state *state)
7594 {
7595         struct triple *def;
7596         def = or_expr(state);
7597         while(peek(state) == TOK_LOGAND) {
7598                 struct triple *left, *right;
7599                 left = read_expr(state, def);
7600                 bool(state, left);
7601                 eat(state, TOK_LOGAND);
7602                 right = read_expr(state, or_expr(state));
7603                 bool(state, right);
7604
7605                 def = triple(state, OP_LAND, &int_type,
7606                         ltrue_expr(state, left),
7607                         ltrue_expr(state, right));
7608         }
7609         return def;
7610 }
7611
7612 static struct triple *lor_expr(struct compile_state *state)
7613 {
7614         struct triple *def;
7615         def = land_expr(state);
7616         while(peek(state) == TOK_LOGOR) {
7617                 struct triple *left, *right;
7618                 left = read_expr(state, def);
7619                 bool(state, left);
7620                 eat(state, TOK_LOGOR);
7621                 right = read_expr(state, land_expr(state));
7622                 bool(state, right);
7623                 
7624                 def = triple(state, OP_LOR, &int_type,
7625                         ltrue_expr(state, left),
7626                         ltrue_expr(state, right));
7627         }
7628         return def;
7629 }
7630
7631 static struct triple *conditional_expr(struct compile_state *state)
7632 {
7633         struct triple *def;
7634         def = lor_expr(state);
7635         if (peek(state) == TOK_QUEST) {
7636                 struct triple *test, *left, *right;
7637                 bool(state, def);
7638                 test = ltrue_expr(state, read_expr(state, def));
7639                 eat(state, TOK_QUEST);
7640                 left = read_expr(state, expr(state));
7641                 eat(state, TOK_COLON);
7642                 right = read_expr(state, conditional_expr(state));
7643
7644                 def = cond_expr(state, test, left, right);
7645         }
7646         return def;
7647 }
7648
7649 static struct triple *eval_const_expr(
7650         struct compile_state *state, struct triple *expr)
7651 {
7652         struct triple *def;
7653         if (is_const(expr)) {
7654                 def = expr;
7655         } 
7656         else {
7657                 /* If we don't start out as a constant simplify into one */
7658                 struct triple *head, *ptr;
7659                 head = label(state); /* dummy initial triple */
7660                 flatten(state, head, expr);
7661                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
7662                         simplify(state, ptr);
7663                 }
7664                 /* Remove the constant value the tail of the list */
7665                 def = head->prev;
7666                 def->prev->next = def->next;
7667                 def->next->prev = def->prev;
7668                 def->next = def->prev = def;
7669                 if (!is_const(def)) {
7670                         error(state, 0, "Not a constant expression");
7671                 }
7672                 /* Free the intermediate expressions */
7673                 while(head->next != head) {
7674                         release_triple(state, head->next);
7675                 }
7676                 free_triple(state, head);
7677         }
7678         return def;
7679 }
7680
7681 static struct triple *constant_expr(struct compile_state *state)
7682 {
7683         return eval_const_expr(state, conditional_expr(state));
7684 }
7685
7686 static struct triple *assignment_expr(struct compile_state *state)
7687 {
7688         struct triple *def, *left, *right;
7689         int tok, op, sign;
7690         /* The C grammer in K&R shows assignment expressions
7691          * only taking unary expressions as input on their
7692          * left hand side.  But specifies the precedence of
7693          * assignemnt as the lowest operator except for comma.
7694          *
7695          * Allowing conditional expressions on the left hand side
7696          * of an assignement results in a grammar that accepts
7697          * a larger set of statements than standard C.   As long
7698          * as the subset of the grammar that is standard C behaves
7699          * correctly this should cause no problems.
7700          * 
7701          * For the extra token strings accepted by the grammar
7702          * none of them should produce a valid lvalue, so they
7703          * should not produce functioning programs.
7704          *
7705          * GCC has this bug as well, so surprises should be minimal.
7706          */
7707         def = conditional_expr(state);
7708         left = def;
7709         switch((tok = peek(state))) {
7710         case TOK_EQ:
7711                 lvalue(state, left);
7712                 eat(state, TOK_EQ);
7713                 def = write_expr(state, left, 
7714                         read_expr(state, assignment_expr(state)));
7715                 break;
7716         case TOK_TIMESEQ:
7717         case TOK_DIVEQ:
7718         case TOK_MODEQ:
7719                 lvalue(state, left);
7720                 arithmetic(state, left);
7721                 eat(state, tok);
7722                 right = read_expr(state, assignment_expr(state));
7723                 arithmetic(state, right);
7724
7725                 sign = is_signed(left->type);
7726                 op = -1;
7727                 switch(tok) {
7728                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
7729                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
7730                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
7731                 }
7732                 def = write_expr(state, left,
7733                         triple(state, op, left->type, 
7734                                 read_expr(state, left), right));
7735                 break;
7736         case TOK_PLUSEQ:
7737                 lvalue(state, left);
7738                 eat(state, TOK_PLUSEQ);
7739                 def = write_expr(state, left,
7740                         mk_add_expr(state, left, assignment_expr(state)));
7741                 break;
7742         case TOK_MINUSEQ:
7743                 lvalue(state, left);
7744                 eat(state, TOK_MINUSEQ);
7745                 def = write_expr(state, left,
7746                         mk_sub_expr(state, left, assignment_expr(state)));
7747                 break;
7748         case TOK_SLEQ:
7749         case TOK_SREQ:
7750         case TOK_ANDEQ:
7751         case TOK_XOREQ:
7752         case TOK_OREQ:
7753                 lvalue(state, left);
7754                 integral(state, left);
7755                 eat(state, tok);
7756                 right = read_expr(state, assignment_expr(state));
7757                 integral(state, right);
7758                 right = integral_promotion(state, right);
7759                 sign = is_signed(left->type);
7760                 op = -1;
7761                 switch(tok) {
7762                 case TOK_SLEQ:  op = OP_SL; break;
7763                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
7764                 case TOK_ANDEQ: op = OP_AND; break;
7765                 case TOK_XOREQ: op = OP_XOR; break;
7766                 case TOK_OREQ:  op = OP_OR; break;
7767                 }
7768                 def = write_expr(state, left,
7769                         triple(state, op, left->type, 
7770                                 read_expr(state, left), right));
7771                 break;
7772         }
7773         return def;
7774 }
7775
7776 static struct triple *expr(struct compile_state *state)
7777 {
7778         struct triple *def;
7779         def = assignment_expr(state);
7780         while(peek(state) == TOK_COMMA) {
7781                 struct triple *left, *right;
7782                 left = def;
7783                 eat(state, TOK_COMMA);
7784                 right = assignment_expr(state);
7785                 def = triple(state, OP_COMMA, right->type, left, right);
7786         }
7787         return def;
7788 }
7789
7790 static void expr_statement(struct compile_state *state, struct triple *first)
7791 {
7792         if (peek(state) != TOK_SEMI) {
7793                 flatten(state, first, expr(state));
7794         }
7795         eat(state, TOK_SEMI);
7796 }
7797
7798 static void if_statement(struct compile_state *state, struct triple *first)
7799 {
7800         struct triple *test, *jmp1, *jmp2, *middle, *end;
7801
7802         jmp1 = jmp2 = middle = 0;
7803         eat(state, TOK_IF);
7804         eat(state, TOK_LPAREN);
7805         test = expr(state);
7806         bool(state, test);
7807         /* Cleanup and invert the test */
7808         test = lfalse_expr(state, read_expr(state, test));
7809         eat(state, TOK_RPAREN);
7810         /* Generate the needed pieces */
7811         middle = label(state);
7812         jmp1 = branch(state, middle, test);
7813         /* Thread the pieces together */
7814         flatten(state, first, test);
7815         flatten(state, first, jmp1);
7816         flatten(state, first, label(state));
7817         statement(state, first);
7818         if (peek(state) == TOK_ELSE) {
7819                 eat(state, TOK_ELSE);
7820                 /* Generate the rest of the pieces */
7821                 end = label(state);
7822                 jmp2 = branch(state, end, 0);
7823                 /* Thread them together */
7824                 flatten(state, first, jmp2);
7825                 flatten(state, first, middle);
7826                 statement(state, first);
7827                 flatten(state, first, end);
7828         }
7829         else {
7830                 flatten(state, first, middle);
7831         }
7832 }
7833
7834 static void for_statement(struct compile_state *state, struct triple *first)
7835 {
7836         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
7837         struct triple *label1, *label2, *label3;
7838         struct hash_entry *ident;
7839
7840         eat(state, TOK_FOR);
7841         eat(state, TOK_LPAREN);
7842         head = test = tail = jmp1 = jmp2 = 0;
7843         if (peek(state) != TOK_SEMI) {
7844                 head = expr(state);
7845         } 
7846         eat(state, TOK_SEMI);
7847         if (peek(state) != TOK_SEMI) {
7848                 test = expr(state);
7849                 bool(state, test);
7850                 test = ltrue_expr(state, read_expr(state, test));
7851         }
7852         eat(state, TOK_SEMI);
7853         if (peek(state) != TOK_RPAREN) {
7854                 tail = expr(state);
7855         }
7856         eat(state, TOK_RPAREN);
7857         /* Generate the needed pieces */
7858         label1 = label(state);
7859         label2 = label(state);
7860         label3 = label(state);
7861         if (test) {
7862                 jmp1 = branch(state, label3, 0);
7863                 jmp2 = branch(state, label1, test);
7864         }
7865         else {
7866                 jmp2 = branch(state, label1, 0);
7867         }
7868         end = label(state);
7869         /* Remember where break and continue go */
7870         start_scope(state);
7871         ident = state->i_break;
7872         symbol(state, ident, &ident->sym_ident, end, end->type);
7873         ident = state->i_continue;
7874         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7875         /* Now include the body */
7876         flatten(state, first, head);
7877         flatten(state, first, jmp1);
7878         flatten(state, first, label1);
7879         statement(state, first);
7880         flatten(state, first, label2);
7881         flatten(state, first, tail);
7882         flatten(state, first, label3);
7883         flatten(state, first, test);
7884         flatten(state, first, jmp2);
7885         flatten(state, first, end);
7886         /* Cleanup the break/continue scope */
7887         end_scope(state);
7888 }
7889
7890 static void while_statement(struct compile_state *state, struct triple *first)
7891 {
7892         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
7893         struct hash_entry *ident;
7894         eat(state, TOK_WHILE);
7895         eat(state, TOK_LPAREN);
7896         test = expr(state);
7897         bool(state, test);
7898         test = ltrue_expr(state, read_expr(state, test));
7899         eat(state, TOK_RPAREN);
7900         /* Generate the needed pieces */
7901         label1 = label(state);
7902         label2 = label(state);
7903         jmp1 = branch(state, label2, 0);
7904         jmp2 = branch(state, label1, test);
7905         end = label(state);
7906         /* Remember where break and continue go */
7907         start_scope(state);
7908         ident = state->i_break;
7909         symbol(state, ident, &ident->sym_ident, end, end->type);
7910         ident = state->i_continue;
7911         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7912         /* Thread them together */
7913         flatten(state, first, jmp1);
7914         flatten(state, first, label1);
7915         statement(state, first);
7916         flatten(state, first, label2);
7917         flatten(state, first, test);
7918         flatten(state, first, jmp2);
7919         flatten(state, first, end);
7920         /* Cleanup the break/continue scope */
7921         end_scope(state);
7922 }
7923
7924 static void do_statement(struct compile_state *state, struct triple *first)
7925 {
7926         struct triple *label1, *label2, *test, *end;
7927         struct hash_entry *ident;
7928         eat(state, TOK_DO);
7929         /* Generate the needed pieces */
7930         label1 = label(state);
7931         label2 = label(state);
7932         end = label(state);
7933         /* Remember where break and continue go */
7934         start_scope(state);
7935         ident = state->i_break;
7936         symbol(state, ident, &ident->sym_ident, end, end->type);
7937         ident = state->i_continue;
7938         symbol(state, ident, &ident->sym_ident, label2, label2->type);
7939         /* Now include the body */
7940         flatten(state, first, label1);
7941         statement(state, first);
7942         /* Cleanup the break/continue scope */
7943         end_scope(state);
7944         /* Eat the rest of the loop */
7945         eat(state, TOK_WHILE);
7946         eat(state, TOK_LPAREN);
7947         test = read_expr(state, expr(state));
7948         bool(state, test);
7949         eat(state, TOK_RPAREN);
7950         eat(state, TOK_SEMI);
7951         /* Thread the pieces together */
7952         test = ltrue_expr(state, test);
7953         flatten(state, first, label2);
7954         flatten(state, first, test);
7955         flatten(state, first, branch(state, label1, test));
7956         flatten(state, first, end);
7957 }
7958
7959
7960 static void return_statement(struct compile_state *state, struct triple *first)
7961 {
7962         struct triple *jmp, *mv, *dest, *var, *val;
7963         int last;
7964         eat(state, TOK_RETURN);
7965
7966 #warning "FIXME implement a more general excess branch elimination"
7967         val = 0;
7968         /* If we have a return value do some more work */
7969         if (peek(state) != TOK_SEMI) {
7970                 val = read_expr(state, expr(state));
7971         }
7972         eat(state, TOK_SEMI);
7973
7974         /* See if this last statement in a function */
7975         last = ((peek(state) == TOK_RBRACE) && 
7976                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
7977
7978         /* Find the return variable */
7979         var = MISC(state->main_function, 0);
7980         /* Find the return destination */
7981         dest = RHS(state->main_function, 0)->prev;
7982         mv = jmp = 0;
7983         /* If needed generate a jump instruction */
7984         if (!last) {
7985                 jmp = branch(state, dest, 0);
7986         }
7987         /* If needed generate an assignment instruction */
7988         if (val) {
7989                 mv = write_expr(state, var, val);
7990         }
7991         /* Now put the code together */
7992         if (mv) {
7993                 flatten(state, first, mv);
7994                 flatten(state, first, jmp);
7995         }
7996         else if (jmp) {
7997                 flatten(state, first, jmp);
7998         }
7999 }
8000
8001 static void break_statement(struct compile_state *state, struct triple *first)
8002 {
8003         struct triple *dest;
8004         eat(state, TOK_BREAK);
8005         eat(state, TOK_SEMI);
8006         if (!state->i_break->sym_ident) {
8007                 error(state, 0, "break statement not within loop or switch");
8008         }
8009         dest = state->i_break->sym_ident->def;
8010         flatten(state, first, branch(state, dest, 0));
8011 }
8012
8013 static void continue_statement(struct compile_state *state, struct triple *first)
8014 {
8015         struct triple *dest;
8016         eat(state, TOK_CONTINUE);
8017         eat(state, TOK_SEMI);
8018         if (!state->i_continue->sym_ident) {
8019                 error(state, 0, "continue statement outside of a loop");
8020         }
8021         dest = state->i_continue->sym_ident->def;
8022         flatten(state, first, branch(state, dest, 0));
8023 }
8024
8025 static void goto_statement(struct compile_state *state, struct triple *first)
8026 {
8027         struct hash_entry *ident;
8028         eat(state, TOK_GOTO);
8029         eat(state, TOK_IDENT);
8030         ident = state->token[0].ident;
8031         if (!ident->sym_label) {
8032                 /* If this is a forward branch allocate the label now,
8033                  * it will be flattend in the appropriate location later.
8034                  */
8035                 struct triple *ins;
8036                 ins = label(state);
8037                 label_symbol(state, ident, ins);
8038         }
8039         eat(state, TOK_SEMI);
8040
8041         flatten(state, first, branch(state, ident->sym_label->def, 0));
8042 }
8043
8044 static void labeled_statement(struct compile_state *state, struct triple *first)
8045 {
8046         struct triple *ins;
8047         struct hash_entry *ident;
8048         eat(state, TOK_IDENT);
8049
8050         ident = state->token[0].ident;
8051         if (ident->sym_label && ident->sym_label->def) {
8052                 ins = ident->sym_label->def;
8053                 put_occurance(ins->occurance);
8054                 ins->occurance = new_occurance(state);
8055         }
8056         else {
8057                 ins = label(state);
8058                 label_symbol(state, ident, ins);
8059         }
8060         if (ins->id & TRIPLE_FLAG_FLATTENED) {
8061                 error(state, 0, "label %s already defined", ident->name);
8062         }
8063         flatten(state, first, ins);
8064
8065         eat(state, TOK_COLON);
8066         statement(state, first);
8067 }
8068
8069 static void switch_statement(struct compile_state *state, struct triple *first)
8070 {
8071         FINISHME();
8072         eat(state, TOK_SWITCH);
8073         eat(state, TOK_LPAREN);
8074         expr(state);
8075         eat(state, TOK_RPAREN);
8076         statement(state, first);
8077         error(state, 0, "switch statements are not implemented");
8078         FINISHME();
8079 }
8080
8081 static void case_statement(struct compile_state *state, struct triple *first)
8082 {
8083         FINISHME();
8084         eat(state, TOK_CASE);
8085         constant_expr(state);
8086         eat(state, TOK_COLON);
8087         statement(state, first);
8088         error(state, 0, "case statements are not implemented");
8089         FINISHME();
8090 }
8091
8092 static void default_statement(struct compile_state *state, struct triple *first)
8093 {
8094         FINISHME();
8095         eat(state, TOK_DEFAULT);
8096         eat(state, TOK_COLON);
8097         statement(state, first);
8098         error(state, 0, "default statements are not implemented");
8099         FINISHME();
8100 }
8101
8102 static void asm_statement(struct compile_state *state, struct triple *first)
8103 {
8104         struct asm_info *info;
8105         struct {
8106                 struct triple *constraint;
8107                 struct triple *expr;
8108         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
8109         struct triple *def, *asm_str;
8110         int out, in, clobbers, more, colons, i;
8111
8112         eat(state, TOK_ASM);
8113         /* For now ignore the qualifiers */
8114         switch(peek(state)) {
8115         case TOK_CONST:
8116                 eat(state, TOK_CONST);
8117                 break;
8118         case TOK_VOLATILE:
8119                 eat(state, TOK_VOLATILE);
8120                 break;
8121         }
8122         eat(state, TOK_LPAREN);
8123         asm_str = string_constant(state);
8124
8125         colons = 0;
8126         out = in = clobbers = 0;
8127         /* Outputs */
8128         if ((colons == 0) && (peek(state) == TOK_COLON)) {
8129                 eat(state, TOK_COLON);
8130                 colons++;
8131                 more = (peek(state) == TOK_LIT_STRING);
8132                 while(more) {
8133                         struct triple *var;
8134                         struct triple *constraint;
8135                         char *str;
8136                         more = 0;
8137                         if (out > MAX_LHS) {
8138                                 error(state, 0, "Maximum output count exceeded.");
8139                         }
8140                         constraint = string_constant(state);
8141                         str = constraint->u.blob;
8142                         if (str[0] != '=') {
8143                                 error(state, 0, "Output constraint does not start with =");
8144                         }
8145                         constraint->u.blob = str + 1;
8146                         eat(state, TOK_LPAREN);
8147                         var = conditional_expr(state);
8148                         eat(state, TOK_RPAREN);
8149
8150                         lvalue(state, var);
8151                         out_param[out].constraint = constraint;
8152                         out_param[out].expr       = var;
8153                         if (peek(state) == TOK_COMMA) {
8154                                 eat(state, TOK_COMMA);
8155                                 more = 1;
8156                         }
8157                         out++;
8158                 }
8159         }
8160         /* Inputs */
8161         if ((colons == 1) && (peek(state) == TOK_COLON)) {
8162                 eat(state, TOK_COLON);
8163                 colons++;
8164                 more = (peek(state) == TOK_LIT_STRING);
8165                 while(more) {
8166                         struct triple *val;
8167                         struct triple *constraint;
8168                         char *str;
8169                         more = 0;
8170                         if (in > MAX_RHS) {
8171                                 error(state, 0, "Maximum input count exceeded.");
8172                         }
8173                         constraint = string_constant(state);
8174                         str = constraint->u.blob;
8175                         if (digitp(str[0] && str[1] == '\0')) {
8176                                 int val;
8177                                 val = digval(str[0]);
8178                                 if ((val < 0) || (val >= out)) {
8179                                         error(state, 0, "Invalid input constraint %d", val);
8180                                 }
8181                         }
8182                         eat(state, TOK_LPAREN);
8183                         val = conditional_expr(state);
8184                         eat(state, TOK_RPAREN);
8185
8186                         in_param[in].constraint = constraint;
8187                         in_param[in].expr       = val;
8188                         if (peek(state) == TOK_COMMA) {
8189                                 eat(state, TOK_COMMA);
8190                                 more = 1;
8191                         }
8192                         in++;
8193                 }
8194         }
8195
8196         /* Clobber */
8197         if ((colons == 2) && (peek(state) == TOK_COLON)) {
8198                 eat(state, TOK_COLON);
8199                 colons++;
8200                 more = (peek(state) == TOK_LIT_STRING);
8201                 while(more) {
8202                         struct triple *clobber;
8203                         more = 0;
8204                         if ((clobbers + out) > MAX_LHS) {
8205                                 error(state, 0, "Maximum clobber limit exceeded.");
8206                         }
8207                         clobber = string_constant(state);
8208                         eat(state, TOK_RPAREN);
8209
8210                         clob_param[clobbers].constraint = clobber;
8211                         if (peek(state) == TOK_COMMA) {
8212                                 eat(state, TOK_COMMA);
8213                                 more = 1;
8214                         }
8215                         clobbers++;
8216                 }
8217         }
8218         eat(state, TOK_RPAREN);
8219         eat(state, TOK_SEMI);
8220
8221
8222         info = xcmalloc(sizeof(*info), "asm_info");
8223         info->str = asm_str->u.blob;
8224         free_triple(state, asm_str);
8225
8226         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
8227         def->u.ainfo = info;
8228
8229         /* Find the register constraints */
8230         for(i = 0; i < out; i++) {
8231                 struct triple *constraint;
8232                 constraint = out_param[i].constraint;
8233                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
8234                         out_param[i].expr->type, constraint->u.blob);
8235                 free_triple(state, constraint);
8236         }
8237         for(; i - out < clobbers; i++) {
8238                 struct triple *constraint;
8239                 constraint = clob_param[i - out].constraint;
8240                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
8241                 free_triple(state, constraint);
8242         }
8243         for(i = 0; i < in; i++) {
8244                 struct triple *constraint;
8245                 const char *str;
8246                 constraint = in_param[i].constraint;
8247                 str = constraint->u.blob;
8248                 if (digitp(str[0]) && str[1] == '\0') {
8249                         struct reg_info cinfo;
8250                         int val;
8251                         val = digval(str[0]);
8252                         cinfo.reg = info->tmpl.lhs[val].reg;
8253                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
8254                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
8255                         if (cinfo.reg == REG_UNSET) {
8256                                 cinfo.reg = REG_VIRT0 + val;
8257                         }
8258                         if (cinfo.regcm == 0) {
8259                                 error(state, 0, "No registers for %d", val);
8260                         }
8261                         info->tmpl.lhs[val] = cinfo;
8262                         info->tmpl.rhs[i]   = cinfo;
8263                                 
8264                 } else {
8265                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
8266                                 in_param[i].expr->type, str);
8267                 }
8268                 free_triple(state, constraint);
8269         }
8270
8271         /* Now build the helper expressions */
8272         for(i = 0; i < in; i++) {
8273                 RHS(def, i) = read_expr(state,in_param[i].expr);
8274         }
8275         flatten(state, first, def);
8276         for(i = 0; i < out; i++) {
8277                 struct triple *piece;
8278                 piece = triple(state, OP_PIECE, out_param[i].expr->type, def, 0);
8279                 piece->u.cval = i;
8280                 LHS(def, i) = piece;
8281                 flatten(state, first,
8282                         write_expr(state, out_param[i].expr, piece));
8283         }
8284         for(; i - out < clobbers; i++) {
8285                 struct triple *piece;
8286                 piece = triple(state, OP_PIECE, &void_type, def, 0);
8287                 piece->u.cval = i;
8288                 LHS(def, i) = piece;
8289                 flatten(state, first, piece);
8290         }
8291 }
8292
8293
8294 static int isdecl(int tok)
8295 {
8296         switch(tok) {
8297         case TOK_AUTO:
8298         case TOK_REGISTER:
8299         case TOK_STATIC:
8300         case TOK_EXTERN:
8301         case TOK_TYPEDEF:
8302         case TOK_CONST:
8303         case TOK_RESTRICT:
8304         case TOK_VOLATILE:
8305         case TOK_VOID:
8306         case TOK_CHAR:
8307         case TOK_SHORT:
8308         case TOK_INT:
8309         case TOK_LONG:
8310         case TOK_FLOAT:
8311         case TOK_DOUBLE:
8312         case TOK_SIGNED:
8313         case TOK_UNSIGNED:
8314         case TOK_STRUCT:
8315         case TOK_UNION:
8316         case TOK_ENUM:
8317         case TOK_TYPE_NAME: /* typedef name */
8318                 return 1;
8319         default:
8320                 return 0;
8321         }
8322 }
8323
8324 static void compound_statement(struct compile_state *state, struct triple *first)
8325 {
8326         eat(state, TOK_LBRACE);
8327         start_scope(state);
8328
8329         /* statement-list opt */
8330         while (peek(state) != TOK_RBRACE) {
8331                 statement(state, first);
8332         }
8333         end_scope(state);
8334         eat(state, TOK_RBRACE);
8335 }
8336
8337 static void statement(struct compile_state *state, struct triple *first)
8338 {
8339         int tok;
8340         tok = peek(state);
8341         if (tok == TOK_LBRACE) {
8342                 compound_statement(state, first);
8343         }
8344         else if (tok == TOK_IF) {
8345                 if_statement(state, first); 
8346         }
8347         else if (tok == TOK_FOR) {
8348                 for_statement(state, first);
8349         }
8350         else if (tok == TOK_WHILE) {
8351                 while_statement(state, first);
8352         }
8353         else if (tok == TOK_DO) {
8354                 do_statement(state, first);
8355         }
8356         else if (tok == TOK_RETURN) {
8357                 return_statement(state, first);
8358         }
8359         else if (tok == TOK_BREAK) {
8360                 break_statement(state, first);
8361         }
8362         else if (tok == TOK_CONTINUE) {
8363                 continue_statement(state, first);
8364         }
8365         else if (tok == TOK_GOTO) {
8366                 goto_statement(state, first);
8367         }
8368         else if (tok == TOK_SWITCH) {
8369                 switch_statement(state, first);
8370         }
8371         else if (tok == TOK_ASM) {
8372                 asm_statement(state, first);
8373         }
8374         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
8375                 labeled_statement(state, first); 
8376         }
8377         else if (tok == TOK_CASE) {
8378                 case_statement(state, first);
8379         }
8380         else if (tok == TOK_DEFAULT) {
8381                 default_statement(state, first);
8382         }
8383         else if (isdecl(tok)) {
8384                 /* This handles C99 intermixing of statements and decls */
8385                 decl(state, first);
8386         }
8387         else {
8388                 expr_statement(state, first);
8389         }
8390 }
8391
8392 static struct type *param_decl(struct compile_state *state)
8393 {
8394         struct type *type;
8395         struct hash_entry *ident;
8396         /* Cheat so the declarator will know we are not global */
8397         start_scope(state); 
8398         ident = 0;
8399         type = decl_specifiers(state);
8400         type = declarator(state, type, &ident, 0);
8401         type->field_ident = ident;
8402         end_scope(state);
8403         return type;
8404 }
8405
8406 static struct type *param_type_list(struct compile_state *state, struct type *type)
8407 {
8408         struct type *ftype, **next;
8409         ftype = new_type(TYPE_FUNCTION, type, param_decl(state));
8410         next = &ftype->right;
8411         while(peek(state) == TOK_COMMA) {
8412                 eat(state, TOK_COMMA);
8413                 if (peek(state) == TOK_DOTS) {
8414                         eat(state, TOK_DOTS);
8415                         error(state, 0, "variadic functions not supported");
8416                 }
8417                 else {
8418                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
8419                         next = &((*next)->right);
8420                 }
8421         }
8422         return ftype;
8423 }
8424
8425
8426 static struct type *type_name(struct compile_state *state)
8427 {
8428         struct type *type;
8429         type = specifier_qualifier_list(state);
8430         /* abstract-declarator (may consume no tokens) */
8431         type = declarator(state, type, 0, 0);
8432         return type;
8433 }
8434
8435 static struct type *direct_declarator(
8436         struct compile_state *state, struct type *type, 
8437         struct hash_entry **ident, int need_ident)
8438 {
8439         struct type *outer;
8440         int op;
8441         outer = 0;
8442         arrays_complete(state, type);
8443         switch(peek(state)) {
8444         case TOK_IDENT:
8445                 eat(state, TOK_IDENT);
8446                 if (!ident) {
8447                         error(state, 0, "Unexpected identifier found");
8448                 }
8449                 /* The name of what we are declaring */
8450                 *ident = state->token[0].ident;
8451                 break;
8452         case TOK_LPAREN:
8453                 eat(state, TOK_LPAREN);
8454                 outer = declarator(state, type, ident, need_ident);
8455                 eat(state, TOK_RPAREN);
8456                 break;
8457         default:
8458                 if (need_ident) {
8459                         error(state, 0, "Identifier expected");
8460                 }
8461                 break;
8462         }
8463         do {
8464                 op = 1;
8465                 arrays_complete(state, type);
8466                 switch(peek(state)) {
8467                 case TOK_LPAREN:
8468                         eat(state, TOK_LPAREN);
8469                         type = param_type_list(state, type);
8470                         eat(state, TOK_RPAREN);
8471                         break;
8472                 case TOK_LBRACKET:
8473                 {
8474                         unsigned int qualifiers;
8475                         struct triple *value;
8476                         value = 0;
8477                         eat(state, TOK_LBRACKET);
8478                         if (peek(state) != TOK_RBRACKET) {
8479                                 value = constant_expr(state);
8480                                 integral(state, value);
8481                         }
8482                         eat(state, TOK_RBRACKET);
8483
8484                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
8485                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
8486                         if (value) {
8487                                 type->elements = value->u.cval;
8488                                 free_triple(state, value);
8489                         } else {
8490                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
8491                                 op = 0;
8492                         }
8493                 }
8494                         break;
8495                 default:
8496                         op = 0;
8497                         break;
8498                 }
8499         } while(op);
8500         if (outer) {
8501                 struct type *inner;
8502                 arrays_complete(state, type);
8503                 FINISHME();
8504                 for(inner = outer; inner->left; inner = inner->left)
8505                         ;
8506                 inner->left = type;
8507                 type = outer;
8508         }
8509         return type;
8510 }
8511
8512 static struct type *declarator(
8513         struct compile_state *state, struct type *type, 
8514         struct hash_entry **ident, int need_ident)
8515 {
8516         while(peek(state) == TOK_STAR) {
8517                 eat(state, TOK_STAR);
8518                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
8519         }
8520         type = direct_declarator(state, type, ident, need_ident);
8521         return type;
8522 }
8523
8524
8525 static struct type *typedef_name(
8526         struct compile_state *state, unsigned int specifiers)
8527 {
8528         struct hash_entry *ident;
8529         struct type *type;
8530         eat(state, TOK_TYPE_NAME);
8531         ident = state->token[0].ident;
8532         type = ident->sym_ident->type;
8533         specifiers |= type->type & QUAL_MASK;
8534         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
8535                 (type->type & (STOR_MASK | QUAL_MASK))) {
8536                 type = clone_type(specifiers, type);
8537         }
8538         return type;
8539 }
8540
8541 static struct type *enum_specifier(
8542         struct compile_state *state, unsigned int specifiers)
8543 {
8544         int tok;
8545         struct type *type;
8546         type = 0;
8547         FINISHME();
8548         eat(state, TOK_ENUM);
8549         tok = peek(state);
8550         if (tok == TOK_IDENT) {
8551                 eat(state, TOK_IDENT);
8552         }
8553         if ((tok != TOK_IDENT) || (peek(state) == TOK_LBRACE)) {
8554                 eat(state, TOK_LBRACE);
8555                 do {
8556                         eat(state, TOK_IDENT);
8557                         if (peek(state) == TOK_EQ) {
8558                                 eat(state, TOK_EQ);
8559                                 constant_expr(state);
8560                         }
8561                         if (peek(state) == TOK_COMMA) {
8562                                 eat(state, TOK_COMMA);
8563                         }
8564                 } while(peek(state) != TOK_RBRACE);
8565                 eat(state, TOK_RBRACE);
8566         }
8567         FINISHME();
8568         return type;
8569 }
8570
8571 static struct type *struct_declarator(
8572         struct compile_state *state, struct type *type, struct hash_entry **ident)
8573 {
8574         int tok;
8575         tok = peek(state);
8576         if (tok != TOK_COLON) {
8577                 type = declarator(state, type, ident, 1);
8578         }
8579         if ((tok == TOK_COLON) || (peek(state) == TOK_COLON)) {
8580                 struct triple *value;
8581                 eat(state, TOK_COLON);
8582                 value = constant_expr(state);
8583 #warning "FIXME implement bitfields to reduce register usage"
8584                 error(state, 0, "bitfields not yet implemented");
8585         }
8586         return type;
8587 }
8588
8589 static struct type *struct_or_union_specifier(
8590         struct compile_state *state, unsigned int spec)
8591 {
8592         struct type *struct_type;
8593         struct hash_entry *ident;
8594         unsigned int type_join;
8595         int tok;
8596         struct_type = 0;
8597         ident = 0;
8598         switch(peek(state)) {
8599         case TOK_STRUCT:
8600                 eat(state, TOK_STRUCT);
8601                 type_join = TYPE_PRODUCT;
8602                 break;
8603         case TOK_UNION:
8604                 eat(state, TOK_UNION);
8605                 type_join = TYPE_OVERLAP;
8606                 error(state, 0, "unions not yet supported\n");
8607                 break;
8608         default:
8609                 eat(state, TOK_STRUCT);
8610                 type_join = TYPE_PRODUCT;
8611                 break;
8612         }
8613         tok = peek(state);
8614         if ((tok == TOK_IDENT) || (tok == TOK_TYPE_NAME)) {
8615                 eat(state, tok);
8616                 ident = state->token[0].ident;
8617         }
8618         if (!ident || (peek(state) == TOK_LBRACE)) {
8619                 ulong_t elements;
8620                 struct type **next;
8621                 elements = 0;
8622                 eat(state, TOK_LBRACE);
8623                 next = &struct_type;
8624                 do {
8625                         struct type *base_type;
8626                         int done;
8627                         base_type = specifier_qualifier_list(state);
8628                         do {
8629                                 struct type *type;
8630                                 struct hash_entry *fident;
8631                                 done = 1;
8632                                 type = struct_declarator(state, base_type, &fident);
8633                                 elements++;
8634                                 if (peek(state) == TOK_COMMA) {
8635                                         done = 0;
8636                                         eat(state, TOK_COMMA);
8637                                 }
8638                                 type = clone_type(0, type);
8639                                 type->field_ident = fident;
8640                                 if (*next) {
8641                                         *next = new_type(type_join, *next, type);
8642                                         next = &((*next)->right);
8643                                 } else {
8644                                         *next = type;
8645                                 }
8646                         } while(!done);
8647                         eat(state, TOK_SEMI);
8648                 } while(peek(state) != TOK_RBRACE);
8649                 eat(state, TOK_RBRACE);
8650                 struct_type = new_type(TYPE_STRUCT | spec, struct_type, 0);
8651                 struct_type->type_ident = ident;
8652                 struct_type->elements = elements;
8653                 symbol(state, ident, &ident->sym_struct, 0, struct_type);
8654         }
8655         if (ident && ident->sym_struct) {
8656                 struct_type = clone_type(spec,  ident->sym_struct->type);
8657         }
8658         else if (ident && !ident->sym_struct) {
8659                 error(state, 0, "struct %s undeclared", ident->name);
8660         }
8661         return struct_type;
8662 }
8663
8664 static unsigned int storage_class_specifier_opt(struct compile_state *state)
8665 {
8666         unsigned int specifiers;
8667         switch(peek(state)) {
8668         case TOK_AUTO:
8669                 eat(state, TOK_AUTO);
8670                 specifiers = STOR_AUTO;
8671                 break;
8672         case TOK_REGISTER:
8673                 eat(state, TOK_REGISTER);
8674                 specifiers = STOR_REGISTER;
8675                 break;
8676         case TOK_STATIC:
8677                 eat(state, TOK_STATIC);
8678                 specifiers = STOR_STATIC;
8679                 break;
8680         case TOK_EXTERN:
8681                 eat(state, TOK_EXTERN);
8682                 specifiers = STOR_EXTERN;
8683                 break;
8684         case TOK_TYPEDEF:
8685                 eat(state, TOK_TYPEDEF);
8686                 specifiers = STOR_TYPEDEF;
8687                 break;
8688         default:
8689                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
8690                         specifiers = STOR_STATIC;
8691                 }
8692                 else {
8693                         specifiers = STOR_AUTO;
8694                 }
8695         }
8696         return specifiers;
8697 }
8698
8699 static unsigned int function_specifier_opt(struct compile_state *state)
8700 {
8701         /* Ignore the inline keyword */
8702         unsigned int specifiers;
8703         specifiers = 0;
8704         switch(peek(state)) {
8705         case TOK_INLINE:
8706                 eat(state, TOK_INLINE);
8707                 specifiers = STOR_INLINE;
8708         }
8709         return specifiers;
8710 }
8711
8712 static unsigned int type_qualifiers(struct compile_state *state)
8713 {
8714         unsigned int specifiers;
8715         int done;
8716         done = 0;
8717         specifiers = QUAL_NONE;
8718         do {
8719                 switch(peek(state)) {
8720                 case TOK_CONST:
8721                         eat(state, TOK_CONST);
8722                         specifiers = QUAL_CONST;
8723                         break;
8724                 case TOK_VOLATILE:
8725                         eat(state, TOK_VOLATILE);
8726                         specifiers = QUAL_VOLATILE;
8727                         break;
8728                 case TOK_RESTRICT:
8729                         eat(state, TOK_RESTRICT);
8730                         specifiers = QUAL_RESTRICT;
8731                         break;
8732                 default:
8733                         done = 1;
8734                         break;
8735                 }
8736         } while(!done);
8737         return specifiers;
8738 }
8739
8740 static struct type *type_specifier(
8741         struct compile_state *state, unsigned int spec)
8742 {
8743         struct type *type;
8744         type = 0;
8745         switch(peek(state)) {
8746         case TOK_VOID:
8747                 eat(state, TOK_VOID);
8748                 type = new_type(TYPE_VOID | spec, 0, 0);
8749                 break;
8750         case TOK_CHAR:
8751                 eat(state, TOK_CHAR);
8752                 type = new_type(TYPE_CHAR | spec, 0, 0);
8753                 break;
8754         case TOK_SHORT:
8755                 eat(state, TOK_SHORT);
8756                 if (peek(state) == TOK_INT) {
8757                         eat(state, TOK_INT);
8758                 }
8759                 type = new_type(TYPE_SHORT | spec, 0, 0);
8760                 break;
8761         case TOK_INT:
8762                 eat(state, TOK_INT);
8763                 type = new_type(TYPE_INT | spec, 0, 0);
8764                 break;
8765         case TOK_LONG:
8766                 eat(state, TOK_LONG);
8767                 switch(peek(state)) {
8768                 case TOK_LONG:
8769                         eat(state, TOK_LONG);
8770                         error(state, 0, "long long not supported");
8771                         break;
8772                 case TOK_DOUBLE:
8773                         eat(state, TOK_DOUBLE);
8774                         error(state, 0, "long double not supported");
8775                         break;
8776                 case TOK_INT:
8777                         eat(state, TOK_INT);
8778                         type = new_type(TYPE_LONG | spec, 0, 0);
8779                         break;
8780                 default:
8781                         type = new_type(TYPE_LONG | spec, 0, 0);
8782                         break;
8783                 }
8784                 break;
8785         case TOK_FLOAT:
8786                 eat(state, TOK_FLOAT);
8787                 error(state, 0, "type float not supported");
8788                 break;
8789         case TOK_DOUBLE:
8790                 eat(state, TOK_DOUBLE);
8791                 error(state, 0, "type double not supported");
8792                 break;
8793         case TOK_SIGNED:
8794                 eat(state, TOK_SIGNED);
8795                 switch(peek(state)) {
8796                 case TOK_LONG:
8797                         eat(state, TOK_LONG);
8798                         switch(peek(state)) {
8799                         case TOK_LONG:
8800                                 eat(state, TOK_LONG);
8801                                 error(state, 0, "type long long not supported");
8802                                 break;
8803                         case TOK_INT:
8804                                 eat(state, TOK_INT);
8805                                 type = new_type(TYPE_LONG | spec, 0, 0);
8806                                 break;
8807                         default:
8808                                 type = new_type(TYPE_LONG | spec, 0, 0);
8809                                 break;
8810                         }
8811                         break;
8812                 case TOK_INT:
8813                         eat(state, TOK_INT);
8814                         type = new_type(TYPE_INT | spec, 0, 0);
8815                         break;
8816                 case TOK_SHORT:
8817                         eat(state, TOK_SHORT);
8818                         type = new_type(TYPE_SHORT | spec, 0, 0);
8819                         break;
8820                 case TOK_CHAR:
8821                         eat(state, TOK_CHAR);
8822                         type = new_type(TYPE_CHAR | spec, 0, 0);
8823                         break;
8824                 default:
8825                         type = new_type(TYPE_INT | spec, 0, 0);
8826                         break;
8827                 }
8828                 break;
8829         case TOK_UNSIGNED:
8830                 eat(state, TOK_UNSIGNED);
8831                 switch(peek(state)) {
8832                 case TOK_LONG:
8833                         eat(state, TOK_LONG);
8834                         switch(peek(state)) {
8835                         case TOK_LONG:
8836                                 eat(state, TOK_LONG);
8837                                 error(state, 0, "unsigned long long not supported");
8838                                 break;
8839                         case TOK_INT:
8840                                 eat(state, TOK_INT);
8841                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8842                                 break;
8843                         default:
8844                                 type = new_type(TYPE_ULONG | spec, 0, 0);
8845                                 break;
8846                         }
8847                         break;
8848                 case TOK_INT:
8849                         eat(state, TOK_INT);
8850                         type = new_type(TYPE_UINT | spec, 0, 0);
8851                         break;
8852                 case TOK_SHORT:
8853                         eat(state, TOK_SHORT);
8854                         type = new_type(TYPE_USHORT | spec, 0, 0);
8855                         break;
8856                 case TOK_CHAR:
8857                         eat(state, TOK_CHAR);
8858                         type = new_type(TYPE_UCHAR | spec, 0, 0);
8859                         break;
8860                 default:
8861                         type = new_type(TYPE_UINT | spec, 0, 0);
8862                         break;
8863                 }
8864                 break;
8865                 /* struct or union specifier */
8866         case TOK_STRUCT:
8867         case TOK_UNION:
8868                 type = struct_or_union_specifier(state, spec);
8869                 break;
8870                 /* enum-spefifier */
8871         case TOK_ENUM:
8872                 type = enum_specifier(state, spec);
8873                 break;
8874                 /* typedef name */
8875         case TOK_TYPE_NAME:
8876                 type = typedef_name(state, spec);
8877                 break;
8878         default:
8879                 error(state, 0, "bad type specifier %s", 
8880                         tokens[peek(state)]);
8881                 break;
8882         }
8883         return type;
8884 }
8885
8886 static int istype(int tok)
8887 {
8888         switch(tok) {
8889         case TOK_CONST:
8890         case TOK_RESTRICT:
8891         case TOK_VOLATILE:
8892         case TOK_VOID:
8893         case TOK_CHAR:
8894         case TOK_SHORT:
8895         case TOK_INT:
8896         case TOK_LONG:
8897         case TOK_FLOAT:
8898         case TOK_DOUBLE:
8899         case TOK_SIGNED:
8900         case TOK_UNSIGNED:
8901         case TOK_STRUCT:
8902         case TOK_UNION:
8903         case TOK_ENUM:
8904         case TOK_TYPE_NAME:
8905                 return 1;
8906         default:
8907                 return 0;
8908         }
8909 }
8910
8911
8912 static struct type *specifier_qualifier_list(struct compile_state *state)
8913 {
8914         struct type *type;
8915         unsigned int specifiers = 0;
8916
8917         /* type qualifiers */
8918         specifiers |= type_qualifiers(state);
8919
8920         /* type specifier */
8921         type = type_specifier(state, specifiers);
8922
8923         return type;
8924 }
8925
8926 static int isdecl_specifier(int tok)
8927 {
8928         switch(tok) {
8929                 /* storage class specifier */
8930         case TOK_AUTO:
8931         case TOK_REGISTER:
8932         case TOK_STATIC:
8933         case TOK_EXTERN:
8934         case TOK_TYPEDEF:
8935                 /* type qualifier */
8936         case TOK_CONST:
8937         case TOK_RESTRICT:
8938         case TOK_VOLATILE:
8939                 /* type specifiers */
8940         case TOK_VOID:
8941         case TOK_CHAR:
8942         case TOK_SHORT:
8943         case TOK_INT:
8944         case TOK_LONG:
8945         case TOK_FLOAT:
8946         case TOK_DOUBLE:
8947         case TOK_SIGNED:
8948         case TOK_UNSIGNED:
8949                 /* struct or union specifier */
8950         case TOK_STRUCT:
8951         case TOK_UNION:
8952                 /* enum-spefifier */
8953         case TOK_ENUM:
8954                 /* typedef name */
8955         case TOK_TYPE_NAME:
8956                 /* function specifiers */
8957         case TOK_INLINE:
8958                 return 1;
8959         default:
8960                 return 0;
8961         }
8962 }
8963
8964 static struct type *decl_specifiers(struct compile_state *state)
8965 {
8966         struct type *type;
8967         unsigned int specifiers;
8968         /* I am overly restrictive in the arragement of specifiers supported.
8969          * C is overly flexible in this department it makes interpreting
8970          * the parse tree difficult.
8971          */
8972         specifiers = 0;
8973
8974         /* storage class specifier */
8975         specifiers |= storage_class_specifier_opt(state);
8976
8977         /* function-specifier */
8978         specifiers |= function_specifier_opt(state);
8979
8980         /* type qualifier */
8981         specifiers |= type_qualifiers(state);
8982
8983         /* type specifier */
8984         type = type_specifier(state, specifiers);
8985         return type;
8986 }
8987
8988 struct field_info {
8989         struct type *type;
8990         size_t offset;
8991 };
8992
8993 static struct field_info designator(struct compile_state *state, struct type *type)
8994 {
8995         int tok;
8996         struct field_info info;
8997         info.offset = ~0U;
8998         info.type = 0;
8999         do {
9000                 switch(peek(state)) {
9001                 case TOK_LBRACKET:
9002                 {
9003                         struct triple *value;
9004                         if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
9005                                 error(state, 0, "Array designator not in array initializer");
9006                         }
9007                         eat(state, TOK_LBRACKET);
9008                         value = constant_expr(state);
9009                         eat(state, TOK_RBRACKET);
9010
9011                         info.type = type->left;
9012                         info.offset = value->u.cval * size_of(state, info.type);
9013                         break;
9014                 }
9015                 case TOK_DOT:
9016                 {
9017                         struct hash_entry *field;
9018                         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
9019                                 error(state, 0, "Struct designator not in struct initializer");
9020                         }
9021                         eat(state, TOK_DOT);
9022                         eat(state, TOK_IDENT);
9023                         field = state->token[0].ident;
9024                         info.offset = field_offset(state, type, field);
9025                         info.type   = field_type(state, type, field);
9026                         break;
9027                 }
9028                 default:
9029                         error(state, 0, "Invalid designator");
9030                 }
9031                 tok = peek(state);
9032         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
9033         eat(state, TOK_EQ);
9034         return info;
9035 }
9036
9037 static struct triple *initializer(
9038         struct compile_state *state, struct type *type)
9039 {
9040         struct triple *result;
9041         if (peek(state) != TOK_LBRACE) {
9042                 result = assignment_expr(state);
9043         }
9044         else {
9045                 int comma;
9046                 size_t max_offset;
9047                 struct field_info info;
9048                 void *buf;
9049                 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
9050                         ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
9051                         internal_error(state, 0, "unknown initializer type");
9052                 }
9053                 info.offset = 0;
9054                 info.type = type->left;
9055                 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9056                         info.type = next_field(state, type, 0);
9057                 }
9058                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
9059                         max_offset = 0;
9060                 } else {
9061                         max_offset = size_of(state, type);
9062                 }
9063                 buf = xcmalloc(max_offset, "initializer");
9064                 eat(state, TOK_LBRACE);
9065                 do {
9066                         struct triple *value;
9067                         struct type *value_type;
9068                         size_t value_size;
9069                         void *dest;
9070                         int tok;
9071                         comma = 0;
9072                         tok = peek(state);
9073                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
9074                                 info = designator(state, type);
9075                         }
9076                         if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
9077                                 (info.offset >= max_offset)) {
9078                                 error(state, 0, "element beyond bounds");
9079                         }
9080                         value_type = info.type;
9081                         value = eval_const_expr(state, initializer(state, value_type));
9082                         value_size = size_of(state, value_type);
9083                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
9084                                 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9085                                 (max_offset <= info.offset)) {
9086                                 void *old_buf;
9087                                 size_t old_size;
9088                                 old_buf = buf;
9089                                 old_size = max_offset;
9090                                 max_offset = info.offset + value_size;
9091                                 buf = xmalloc(max_offset, "initializer");
9092                                 memcpy(buf, old_buf, old_size);
9093                                 xfree(old_buf);
9094                         }
9095                         dest = ((char *)buf) + info.offset;
9096                         if (value->op == OP_BLOBCONST) {
9097                                 memcpy(dest, value->u.blob, value_size);
9098                         }
9099                         else if ((value->op == OP_INTCONST) && (value_size == 1)) {
9100                                 *((uint8_t *)dest) = value->u.cval & 0xff;
9101                         }
9102                         else if ((value->op == OP_INTCONST) && (value_size == 2)) {
9103                                 *((uint16_t *)dest) = value->u.cval & 0xffff;
9104                         }
9105                         else if ((value->op == OP_INTCONST) && (value_size == 4)) {
9106                                 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
9107                         }
9108                         else {
9109                                 internal_error(state, 0, "unhandled constant initializer");
9110                         }
9111                         free_triple(state, value);
9112                         if (peek(state) == TOK_COMMA) {
9113                                 eat(state, TOK_COMMA);
9114                                 comma = 1;
9115                         }
9116                         info.offset += value_size;
9117                         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
9118                                 info.type = next_field(state, type, info.type);
9119                                 info.offset = field_offset(state, type, 
9120                                         info.type->field_ident);
9121                         }
9122                 } while(comma && (peek(state) != TOK_RBRACE));
9123                 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
9124                         ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
9125                         type->elements = max_offset / size_of(state, type->left);
9126                 }
9127                 eat(state, TOK_RBRACE);
9128                 result = triple(state, OP_BLOBCONST, type, 0, 0);
9129                 result->u.blob = buf;
9130         }
9131         return result;
9132 }
9133
9134 static void resolve_branches(struct compile_state *state)
9135 {
9136         /* Make a second pass and finish anything outstanding
9137          * with respect to branches.  The only outstanding item
9138          * is to see if there are goto to labels that have not
9139          * been defined and to error about them.
9140          */
9141         int i;
9142         for(i = 0; i < HASH_TABLE_SIZE; i++) {
9143                 struct hash_entry *entry;
9144                 for(entry = state->hash_table[i]; entry; entry = entry->next) {
9145                         struct triple *ins;
9146                         if (!entry->sym_label) {
9147                                 continue;
9148                         }
9149                         ins = entry->sym_label->def;
9150                         if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
9151                                 error(state, ins, "label `%s' used but not defined",
9152                                         entry->name);
9153                         }
9154                 }
9155         }
9156 }
9157
9158 static struct triple *function_definition(
9159         struct compile_state *state, struct type *type)
9160 {
9161         struct triple *def, *tmp, *first, *end;
9162         struct hash_entry *ident;
9163         struct type *param;
9164         int i;
9165         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
9166                 error(state, 0, "Invalid function header");
9167         }
9168
9169         /* Verify the function type */
9170         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
9171                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
9172                 (type->right->field_ident == 0)) {
9173                 error(state, 0, "Invalid function parameters");
9174         }
9175         param = type->right;
9176         i = 0;
9177         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9178                 i++;
9179                 if (!param->left->field_ident) {
9180                         error(state, 0, "No identifier for parameter %d\n", i);
9181                 }
9182                 param = param->right;
9183         }
9184         i++;
9185         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
9186                 error(state, 0, "No identifier for paramter %d\n", i);
9187         }
9188         
9189         /* Get a list of statements for this function. */
9190         def = triple(state, OP_LIST, type, 0, 0);
9191
9192         /* Start a new scope for the passed parameters */
9193         start_scope(state);
9194
9195         /* Put a label at the very start of a function */
9196         first = label(state);
9197         RHS(def, 0) = first;
9198
9199         /* Put a label at the very end of a function */
9200         end = label(state);
9201         flatten(state, first, end);
9202
9203         /* Walk through the parameters and create symbol table entries
9204          * for them.
9205          */
9206         param = type->right;
9207         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
9208                 ident = param->left->field_ident;
9209                 tmp = variable(state, param->left);
9210                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9211                 flatten(state, end, tmp);
9212                 param = param->right;
9213         }
9214         if ((param->type & TYPE_MASK) != TYPE_VOID) {
9215                 /* And don't forget the last parameter */
9216                 ident = param->field_ident;
9217                 tmp = variable(state, param);
9218                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
9219                 flatten(state, end, tmp);
9220         }
9221         /* Add a variable for the return value */
9222         MISC(def, 0) = 0;
9223         if ((type->left->type & TYPE_MASK) != TYPE_VOID) {
9224                 /* Remove all type qualifiers from the return type */
9225                 tmp = variable(state, clone_type(0, type->left));
9226                 flatten(state, end, tmp);
9227                 /* Remember where the return value is */
9228                 MISC(def, 0) = tmp;
9229         }
9230
9231         /* Remember which function I am compiling.
9232          * Also assume the last defined function is the main function.
9233          */
9234         state->main_function = def;
9235
9236         /* Now get the actual function definition */
9237         compound_statement(state, end);
9238
9239         /* Finish anything unfinished with branches */
9240         resolve_branches(state);
9241
9242         /* Remove the parameter scope */
9243         end_scope(state);
9244
9245 #if 0
9246         fprintf(stdout, "\n");
9247         loc(stdout, state, 0);
9248         fprintf(stdout, "\n__________ function_definition _________\n");
9249         print_triple(state, def);
9250         fprintf(stdout, "__________ function_definition _________ done\n\n");
9251 #endif
9252
9253         return def;
9254 }
9255
9256 static struct triple *do_decl(struct compile_state *state, 
9257         struct type *type, struct hash_entry *ident)
9258 {
9259         struct triple *def;
9260         def = 0;
9261         /* Clean up the storage types used */
9262         switch (type->type & STOR_MASK) {
9263         case STOR_AUTO:
9264         case STOR_STATIC:
9265                 /* These are the good types I am aiming for */
9266                 break;
9267         case STOR_REGISTER:
9268                 type->type &= ~STOR_MASK;
9269                 type->type |= STOR_AUTO;
9270                 break;
9271         case STOR_EXTERN:
9272                 type->type &= ~STOR_MASK;
9273                 type->type |= STOR_STATIC;
9274                 break;
9275         case STOR_TYPEDEF:
9276                 if (!ident) {
9277                         error(state, 0, "typedef without name");
9278                 }
9279                 symbol(state, ident, &ident->sym_ident, 0, type);
9280                 ident->tok = TOK_TYPE_NAME;
9281                 return 0;
9282                 break;
9283         default:
9284                 internal_error(state, 0, "Undefined storage class");
9285         }
9286         if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
9287                 error(state, 0, "Function prototypes not supported");
9288         }
9289         if (ident && 
9290                 ((type->type & STOR_MASK) == STOR_STATIC) &&
9291                 ((type->type & QUAL_CONST) == 0)) {
9292                 error(state, 0, "non const static variables not supported");
9293         }
9294         if (ident) {
9295                 def = variable(state, type);
9296                 symbol(state, ident, &ident->sym_ident, def, type);
9297         }
9298         return def;
9299 }
9300
9301 static void decl(struct compile_state *state, struct triple *first)
9302 {
9303         struct type *base_type, *type;
9304         struct hash_entry *ident;
9305         struct triple *def;
9306         int global;
9307         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
9308         base_type = decl_specifiers(state);
9309         ident = 0;
9310         type = declarator(state, base_type, &ident, 0);
9311         if (global && ident && (peek(state) == TOK_LBRACE)) {
9312                 /* function */
9313                 state->function = ident->name;
9314                 def = function_definition(state, type);
9315                 symbol(state, ident, &ident->sym_ident, def, type);
9316                 state->function = 0;
9317         }
9318         else {
9319                 int done;
9320                 flatten(state, first, do_decl(state, type, ident));
9321                 /* type or variable definition */
9322                 do {
9323                         done = 1;
9324                         if (peek(state) == TOK_EQ) {
9325                                 if (!ident) {
9326                                         error(state, 0, "cannot assign to a type");
9327                                 }
9328                                 eat(state, TOK_EQ);
9329                                 flatten(state, first,
9330                                         init_expr(state, 
9331                                                 ident->sym_ident->def, 
9332                                                 initializer(state, type)));
9333                         }
9334                         arrays_complete(state, type);
9335                         if (peek(state) == TOK_COMMA) {
9336                                 eat(state, TOK_COMMA);
9337                                 ident = 0;
9338                                 type = declarator(state, base_type, &ident, 0);
9339                                 flatten(state, first, do_decl(state, type, ident));
9340                                 done = 0;
9341                         }
9342                 } while(!done);
9343                 eat(state, TOK_SEMI);
9344         }
9345 }
9346
9347 static void decls(struct compile_state *state)
9348 {
9349         struct triple *list;
9350         int tok;
9351         list = label(state);
9352         while(1) {
9353                 tok = peek(state);
9354                 if (tok == TOK_EOF) {
9355                         return;
9356                 }
9357                 if (tok == TOK_SPACE) {
9358                         eat(state, TOK_SPACE);
9359                 }
9360                 decl(state, list);
9361                 if (list->next != list) {
9362                         error(state, 0, "global variables not supported");
9363                 }
9364         }
9365 }
9366
9367 /*
9368  * Data structurs for optimation.
9369  */
9370
9371 static void do_use_block(
9372         struct block *used, struct block_set **head, struct block *user, 
9373         int front)
9374 {
9375         struct block_set **ptr, *new;
9376         if (!used)
9377                 return;
9378         if (!user)
9379                 return;
9380         ptr = head;
9381         while(*ptr) {
9382                 if ((*ptr)->member == user) {
9383                         return;
9384                 }
9385                 ptr = &(*ptr)->next;
9386         }
9387         new = xcmalloc(sizeof(*new), "block_set");
9388         new->member = user;
9389         if (front) {
9390                 new->next = *head;
9391                 *head = new;
9392         }
9393         else {
9394                 new->next = 0;
9395                 *ptr = new;
9396         }
9397 }
9398 static void do_unuse_block(
9399         struct block *used, struct block_set **head, struct block *unuser)
9400 {
9401         struct block_set *use, **ptr;
9402         ptr = head;
9403         while(*ptr) {
9404                 use = *ptr;
9405                 if (use->member == unuser) {
9406                         *ptr = use->next;
9407                         memset(use, -1, sizeof(*use));
9408                         xfree(use);
9409                 }
9410                 else {
9411                         ptr = &use->next;
9412                 }
9413         }
9414 }
9415
9416 static void use_block(struct block *used, struct block *user)
9417 {
9418         /* Append new to the head of the list, print_block
9419          * depends on this.
9420          */
9421         do_use_block(used, &used->use, user, 1); 
9422         used->users++;
9423 }
9424 static void unuse_block(struct block *used, struct block *unuser)
9425 {
9426         do_unuse_block(used, &used->use, unuser); 
9427         used->users--;
9428 }
9429
9430 static void idom_block(struct block *idom, struct block *user)
9431 {
9432         do_use_block(idom, &idom->idominates, user, 0);
9433 }
9434
9435 static void unidom_block(struct block *idom, struct block *unuser)
9436 {
9437         do_unuse_block(idom, &idom->idominates, unuser);
9438 }
9439
9440 static void domf_block(struct block *block, struct block *domf)
9441 {
9442         do_use_block(block, &block->domfrontier, domf, 0);
9443 }
9444
9445 static void undomf_block(struct block *block, struct block *undomf)
9446 {
9447         do_unuse_block(block, &block->domfrontier, undomf);
9448 }
9449
9450 static void ipdom_block(struct block *ipdom, struct block *user)
9451 {
9452         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
9453 }
9454
9455 static void unipdom_block(struct block *ipdom, struct block *unuser)
9456 {
9457         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
9458 }
9459
9460 static void ipdomf_block(struct block *block, struct block *ipdomf)
9461 {
9462         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
9463 }
9464
9465 static void unipdomf_block(struct block *block, struct block *unipdomf)
9466 {
9467         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
9468 }
9469
9470
9471
9472 static int do_walk_triple(struct compile_state *state,
9473         struct triple *ptr, int depth,
9474         int (*cb)(struct compile_state *state, struct triple *ptr, int depth)) 
9475 {
9476         int result;
9477         result = cb(state, ptr, depth);
9478         if ((result == 0) && (ptr->op == OP_LIST)) {
9479                 struct triple *list;
9480                 list = ptr;
9481                 ptr = RHS(list, 0);
9482                 do {
9483                         result = do_walk_triple(state, ptr, depth + 1, cb);
9484                         if (ptr->next->prev != ptr) {
9485                                 internal_error(state, ptr->next, "bad prev");
9486                         }
9487                         ptr = ptr->next;
9488                         
9489                 } while((result == 0) && (ptr != RHS(list, 0)));
9490         }
9491         return result;
9492 }
9493
9494 static int walk_triple(
9495         struct compile_state *state, 
9496         struct triple *ptr, 
9497         int (*cb)(struct compile_state *state, struct triple *ptr, int depth))
9498 {
9499         return do_walk_triple(state, ptr, 0, cb);
9500 }
9501
9502 static void do_print_prefix(int depth)
9503 {
9504         int i;
9505         for(i = 0; i < depth; i++) {
9506                 printf("  ");
9507         }
9508 }
9509
9510 #define PRINT_LIST 1
9511 static int do_print_triple(struct compile_state *state, struct triple *ins, int depth)
9512 {
9513         int op;
9514         op = ins->op;
9515         if (op == OP_LIST) {
9516 #if !PRINT_LIST
9517                 return 0;
9518 #endif
9519         }
9520         if ((op == OP_LABEL) && (ins->use)) {
9521                 printf("\n%p:\n", ins);
9522         }
9523         do_print_prefix(depth);
9524         display_triple(stdout, ins);
9525
9526         if ((ins->op == OP_BRANCH) && ins->use) {
9527                 internal_error(state, ins, "branch used?");
9528         }
9529         if (triple_is_branch(state, ins)) {
9530                 printf("\n");
9531         }
9532         return 0;
9533 }
9534
9535 static void print_triple(struct compile_state *state, struct triple *ins)
9536 {
9537         walk_triple(state, ins, do_print_triple);
9538 }
9539
9540 static void print_triples(struct compile_state *state)
9541 {
9542         print_triple(state, state->main_function);
9543 }
9544
9545 struct cf_block {
9546         struct block *block;
9547 };
9548 static void find_cf_blocks(struct cf_block *cf, struct block *block)
9549 {
9550         if (!block || (cf[block->vertex].block == block)) {
9551                 return;
9552         }
9553         cf[block->vertex].block = block;
9554         find_cf_blocks(cf, block->left);
9555         find_cf_blocks(cf, block->right);
9556 }
9557
9558 static void print_control_flow(struct compile_state *state)
9559 {
9560         struct cf_block *cf;
9561         int i;
9562         printf("\ncontrol flow\n");
9563         cf = xcmalloc(sizeof(*cf) * (state->last_vertex + 1), "cf_block");
9564         find_cf_blocks(cf, state->first_block);
9565
9566         for(i = 1; i <= state->last_vertex; i++) {
9567                 struct block *block;
9568                 block = cf[i].block;
9569                 if (!block)
9570                         continue;
9571                 printf("(%p) %d:", block, block->vertex);
9572                 if (block->left) {
9573                         printf(" %d", block->left->vertex);
9574                 }
9575                 if (block->right && (block->right != block->left)) {
9576                         printf(" %d", block->right->vertex);
9577                 }
9578                 printf("\n");
9579         }
9580
9581         xfree(cf);
9582 }
9583
9584
9585 static struct block *basic_block(struct compile_state *state,
9586         struct triple *first)
9587 {
9588         struct block *block;
9589         struct triple *ptr;
9590         int op;
9591         if (first->op != OP_LABEL) {
9592                 internal_error(state, 0, "block does not start with a label");
9593         }
9594         /* See if this basic block has already been setup */
9595         if (first->u.block != 0) {
9596                 return first->u.block;
9597         }
9598         /* Allocate another basic block structure */
9599         state->last_vertex += 1;
9600         block = xcmalloc(sizeof(*block), "block");
9601         block->first = block->last = first;
9602         block->vertex = state->last_vertex;
9603         ptr = first;
9604         do {
9605                 if ((ptr != first) && (ptr->op == OP_LABEL) && ptr->use) {
9606                         break;
9607                 }
9608                 block->last = ptr;
9609                 /* If ptr->u is not used remember where the baic block is */
9610                 if (triple_stores_block(state, ptr)) {
9611                         ptr->u.block = block;
9612                 }
9613                 if (ptr->op == OP_BRANCH) {
9614                         break;
9615                 }
9616                 ptr = ptr->next;
9617         } while (ptr != RHS(state->main_function, 0));
9618         if (ptr == RHS(state->main_function, 0))
9619                 return block;
9620         op = ptr->op;
9621         if (op == OP_LABEL) {
9622                 block->left = basic_block(state, ptr);
9623                 block->right = 0;
9624                 use_block(block->left, block);
9625         }
9626         else if (op == OP_BRANCH) {
9627                 block->left = 0;
9628                 /* Trace the branch target */
9629                 block->right = basic_block(state, TARG(ptr, 0));
9630                 use_block(block->right, block);
9631                 /* If there is a test trace the branch as well */
9632                 if (TRIPLE_RHS(ptr->sizes)) {
9633                         block->left = basic_block(state, ptr->next);
9634                         use_block(block->left, block);
9635                 }
9636         }
9637         else {
9638                 internal_error(state, 0, "Bad basic block split");
9639         }
9640         return block;
9641 }
9642
9643
9644 static void walk_blocks(struct compile_state *state,
9645         void (*cb)(struct compile_state *state, struct block *block, void *arg),
9646         void *arg)
9647 {
9648         struct triple *ptr, *first;
9649         struct block *last_block;
9650         last_block = 0;
9651         first = RHS(state->main_function, 0);
9652         ptr = first;
9653         do {
9654                 struct block *block;
9655                 if (triple_stores_block(state, ptr)) {
9656                         block = ptr->u.block;
9657                         if (block && (block != last_block)) {
9658                                 cb(state, block, arg);
9659                         }
9660                         last_block = block;
9661                 }
9662                 if (block && (block->last == ptr)) {
9663                         block = 0;
9664                 }
9665                 ptr = ptr->next;
9666         } while(ptr != first);
9667 }
9668
9669 static void print_block(
9670         struct compile_state *state, struct block *block, void *arg)
9671 {
9672         struct block_set *user;
9673         struct triple *ptr;
9674         FILE *fp = arg;
9675
9676         fprintf(fp, "\nblock: %p (%d)  %p<-%p %p<-%p\n", 
9677                 block, 
9678                 block->vertex,
9679                 block->left, 
9680                 block->left && block->left->use?block->left->use->member : 0,
9681                 block->right, 
9682                 block->right && block->right->use?block->right->use->member : 0);
9683         if (block->first->op == OP_LABEL) {
9684                 fprintf(fp, "%p:\n", block->first);
9685         }
9686         for(ptr = block->first; ; ptr = ptr->next) {
9687                 display_triple(fp, ptr);
9688                 if (ptr == block->last)
9689                         break;
9690         }
9691         fprintf(fp, "users %d: ", block->users);
9692         for(user = block->use; user; user = user->next) {
9693                 fprintf(fp, "%p (%d) ", 
9694                         user->member,
9695                         user->member->vertex);
9696         }
9697         fprintf(fp,"\n\n");
9698 }
9699
9700
9701 static void print_blocks(struct compile_state *state, FILE *fp)
9702 {
9703         fprintf(fp, "--------------- blocks ---------------\n");
9704         walk_blocks(state, print_block, fp);
9705 }
9706
9707 static void prune_nonblock_triples(struct compile_state *state)
9708 {
9709         struct block *block;
9710         struct triple *first, *ins, *next;
9711         /* Delete the triples not in a basic block */
9712         first = RHS(state->main_function, 0);
9713         block = 0;
9714         ins = first;
9715         do {
9716                 next = ins->next;
9717                 if (ins->op == OP_LABEL) {
9718                         block = ins->u.block;
9719                 }
9720                 if (!block) {
9721                         release_triple(state, ins);
9722                 }
9723                 if (block && block->last == ins) {
9724                         block = 0;
9725                 }
9726                 ins = next;
9727         } while(ins != first);
9728 }
9729
9730 static void setup_basic_blocks(struct compile_state *state)
9731 {
9732         if (!triple_stores_block(state, RHS(state->main_function, 0)) ||
9733                 !triple_stores_block(state, RHS(state->main_function,0)->prev)) {
9734                 internal_error(state, 0, "ins will not store block?");
9735         }
9736         /* Find the basic blocks */
9737         state->last_vertex = 0;
9738         state->first_block = basic_block(state, RHS(state->main_function,0));
9739         /* Delete the triples not in a basic block */
9740         prune_nonblock_triples(state);
9741         /* Find the last basic block */
9742         state->last_block = RHS(state->main_function, 0)->prev->u.block;
9743         if (!state->last_block) {
9744                 internal_error(state, 0, "end not used?");
9745         }
9746         /* If we are debugging print what I have just done */
9747         if (state->debug & DEBUG_BASIC_BLOCKS) {
9748                 print_blocks(state, stdout);
9749                 print_control_flow(state);
9750         }
9751 }
9752
9753 static void free_basic_block(struct compile_state *state, struct block *block)
9754 {
9755         struct block_set *entry, *next;
9756         struct block *child;
9757         if (!block) {
9758                 return;
9759         }
9760         if (block->vertex == -1) {
9761                 return;
9762         }
9763         block->vertex = -1;
9764         if (block->left) {
9765                 unuse_block(block->left, block);
9766         }
9767         if (block->right) {
9768                 unuse_block(block->right, block);
9769         }
9770         if (block->idom) {
9771                 unidom_block(block->idom, block);
9772         }
9773         block->idom = 0;
9774         if (block->ipdom) {
9775                 unipdom_block(block->ipdom, block);
9776         }
9777         block->ipdom = 0;
9778         for(entry = block->use; entry; entry = next) {
9779                 next = entry->next;
9780                 child = entry->member;
9781                 unuse_block(block, child);
9782                 if (child->left == block) {
9783                         child->left = 0;
9784                 }
9785                 if (child->right == block) {
9786                         child->right = 0;
9787                 }
9788         }
9789         for(entry = block->idominates; entry; entry = next) {
9790                 next = entry->next;
9791                 child = entry->member;
9792                 unidom_block(block, child);
9793                 child->idom = 0;
9794         }
9795         for(entry = block->domfrontier; entry; entry = next) {
9796                 next = entry->next;
9797                 child = entry->member;
9798                 undomf_block(block, child);
9799         }
9800         for(entry = block->ipdominates; entry; entry = next) {
9801                 next = entry->next;
9802                 child = entry->member;
9803                 unipdom_block(block, child);
9804                 child->ipdom = 0;
9805         }
9806         for(entry = block->ipdomfrontier; entry; entry = next) {
9807                 next = entry->next;
9808                 child = entry->member;
9809                 unipdomf_block(block, child);
9810         }
9811         if (block->users != 0) {
9812                 internal_error(state, 0, "block still has users");
9813         }
9814         free_basic_block(state, block->left);
9815         block->left = 0;
9816         free_basic_block(state, block->right);
9817         block->right = 0;
9818         memset(block, -1, sizeof(*block));
9819         xfree(block);
9820 }
9821
9822 static void free_basic_blocks(struct compile_state *state)
9823 {
9824         struct triple *first, *ins;
9825         free_basic_block(state, state->first_block);
9826         state->last_vertex = 0;
9827         state->first_block = state->last_block = 0;
9828         first = RHS(state->main_function, 0);
9829         ins = first;
9830         do {
9831                 if (triple_stores_block(state, ins)) {
9832                         ins->u.block = 0;
9833                 }
9834                 ins = ins->next;
9835         } while(ins != first);
9836         
9837 }
9838
9839 struct sdom_block {
9840         struct block *block;
9841         struct sdom_block *sdominates;
9842         struct sdom_block *sdom_next;
9843         struct sdom_block *sdom;
9844         struct sdom_block *label;
9845         struct sdom_block *parent;
9846         struct sdom_block *ancestor;
9847         int vertex;
9848 };
9849
9850
9851 static void unsdom_block(struct sdom_block *block)
9852 {
9853         struct sdom_block **ptr;
9854         if (!block->sdom_next) {
9855                 return;
9856         }
9857         ptr = &block->sdom->sdominates;
9858         while(*ptr) {
9859                 if ((*ptr) == block) {
9860                         *ptr = block->sdom_next;
9861                         return;
9862                 }
9863                 ptr = &(*ptr)->sdom_next;
9864         }
9865 }
9866
9867 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
9868 {
9869         unsdom_block(block);
9870         block->sdom = sdom;
9871         block->sdom_next = sdom->sdominates;
9872         sdom->sdominates = block;
9873 }
9874
9875
9876
9877 static int initialize_sdblock(struct sdom_block *sd,
9878         struct block *parent, struct block *block, int vertex)
9879 {
9880         if (!block || (sd[block->vertex].block == block)) {
9881                 return vertex;
9882         }
9883         vertex += 1;
9884         /* Renumber the blocks in a convinient fashion */
9885         block->vertex = vertex;
9886         sd[vertex].block    = block;
9887         sd[vertex].sdom     = &sd[vertex];
9888         sd[vertex].label    = &sd[vertex];
9889         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9890         sd[vertex].ancestor = 0;
9891         sd[vertex].vertex   = vertex;
9892         vertex = initialize_sdblock(sd, block, block->left, vertex);
9893         vertex = initialize_sdblock(sd, block, block->right, vertex);
9894         return vertex;
9895 }
9896
9897 static int initialize_sdpblock(
9898         struct compile_state *state, struct sdom_block *sd,
9899         struct block *parent, struct block *block, int vertex)
9900 {
9901         struct block_set *user;
9902         if (!block || (sd[block->vertex].block == block)) {
9903                 return vertex;
9904         }
9905         vertex += 1;
9906         /* Renumber the blocks in a convinient fashion */
9907         block->vertex = vertex;
9908         sd[vertex].block    = block;
9909         sd[vertex].sdom     = &sd[vertex];
9910         sd[vertex].label    = &sd[vertex];
9911         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
9912         sd[vertex].ancestor = 0;
9913         sd[vertex].vertex   = vertex;
9914         for(user = block->use; user; user = user->next) {
9915                 vertex = initialize_sdpblock(state, sd, block, user->member, vertex);
9916         }
9917         return vertex;
9918 }
9919
9920 static int setup_sdpblocks(struct compile_state *state, struct sdom_block *sd)
9921 {
9922         struct block *block;
9923         int vertex;
9924         /* Setup as many sdpblocks as possible without using fake edges */
9925         vertex = initialize_sdpblock(state, sd, 0, state->last_block, 0);
9926
9927         /* Walk through the graph and find unconnected blocks.  If 
9928          * we can, add a fake edge from the unconnected blocks to the
9929          * end of the graph.
9930          */
9931         block = state->first_block->last->next->u.block;
9932         for(; block && block != state->first_block; block =  block->last->next->u.block) {
9933                 if (sd[block->vertex].block == block) {
9934                         continue;
9935                 }
9936                 if (block->left != 0) {
9937                         continue;
9938                 }
9939
9940 #if DEBUG_SDP_BLOCKS
9941                 fprintf(stderr, "Adding %d\n", vertex +1);
9942 #endif
9943
9944                 block->left = state->last_block;
9945                 use_block(block->left, block);
9946                 vertex = initialize_sdpblock(state, sd, state->last_block, block, vertex);
9947         }
9948         return vertex;
9949 }
9950
9951 static void compress_ancestors(struct sdom_block *v)
9952 {
9953         /* This procedure assumes ancestor(v) != 0 */
9954         /* if (ancestor(ancestor(v)) != 0) {
9955          *      compress(ancestor(ancestor(v)));
9956          *      if (semi(label(ancestor(v))) < semi(label(v))) {
9957          *              label(v) = label(ancestor(v));
9958          *      }
9959          *      ancestor(v) = ancestor(ancestor(v));
9960          * }
9961          */
9962         if (!v->ancestor) {
9963                 return;
9964         }
9965         if (v->ancestor->ancestor) {
9966                 compress_ancestors(v->ancestor->ancestor);
9967                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
9968                         v->label = v->ancestor->label;
9969                 }
9970                 v->ancestor = v->ancestor->ancestor;
9971         }
9972 }
9973
9974 static void compute_sdom(struct compile_state *state, struct sdom_block *sd)
9975 {
9976         int i;
9977         /* // step 2 
9978          *  for each v <= pred(w) {
9979          *      u = EVAL(v);
9980          *      if (semi[u] < semi[w] { 
9981          *              semi[w] = semi[u]; 
9982          *      } 
9983          * }
9984          * add w to bucket(vertex(semi[w]));
9985          * LINK(parent(w), w);
9986          *
9987          * // step 3
9988          * for each v <= bucket(parent(w)) {
9989          *      delete v from bucket(parent(w));
9990          *      u = EVAL(v);
9991          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
9992          * }
9993          */
9994         for(i = state->last_vertex; i >= 2; i--) {
9995                 struct sdom_block *v, *parent, *next;
9996                 struct block_set *user;
9997                 struct block *block;
9998                 block = sd[i].block;
9999                 parent = sd[i].parent;
10000                 /* Step 2 */
10001                 for(user = block->use; user; user = user->next) {
10002                         struct sdom_block *v, *u;
10003                         v = &sd[user->member->vertex];
10004                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10005                         if (u->sdom->vertex < sd[i].sdom->vertex) {
10006                                 sd[i].sdom = u->sdom;
10007                         }
10008                 }
10009                 sdom_block(sd[i].sdom, &sd[i]);
10010                 sd[i].ancestor = parent;
10011                 /* Step 3 */
10012                 for(v = parent->sdominates; v; v = next) {
10013                         struct sdom_block *u;
10014                         next = v->sdom_next;
10015                         unsdom_block(v);
10016                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10017                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
10018                                 u->block : parent->block;
10019                 }
10020         }
10021 }
10022
10023 static void compute_spdom(struct compile_state *state, struct sdom_block *sd)
10024 {
10025         int i;
10026         /* // step 2 
10027          *  for each v <= pred(w) {
10028          *      u = EVAL(v);
10029          *      if (semi[u] < semi[w] { 
10030          *              semi[w] = semi[u]; 
10031          *      } 
10032          * }
10033          * add w to bucket(vertex(semi[w]));
10034          * LINK(parent(w), w);
10035          *
10036          * // step 3
10037          * for each v <= bucket(parent(w)) {
10038          *      delete v from bucket(parent(w));
10039          *      u = EVAL(v);
10040          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
10041          * }
10042          */
10043         for(i = state->last_vertex; i >= 2; i--) {
10044                 struct sdom_block *u, *v, *parent, *next;
10045                 struct block *block;
10046                 block = sd[i].block;
10047                 parent = sd[i].parent;
10048                 /* Step 2 */
10049                 if (block->left) {
10050                         v = &sd[block->left->vertex];
10051                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10052                         if (u->sdom->vertex < sd[i].sdom->vertex) {
10053                                 sd[i].sdom = u->sdom;
10054                         }
10055                 }
10056                 if (block->right && (block->right != block->left)) {
10057                         v = &sd[block->right->vertex];
10058                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
10059                         if (u->sdom->vertex < sd[i].sdom->vertex) {
10060                                 sd[i].sdom = u->sdom;
10061                         }
10062                 }
10063                 sdom_block(sd[i].sdom, &sd[i]);
10064                 sd[i].ancestor = parent;
10065                 /* Step 3 */
10066                 for(v = parent->sdominates; v; v = next) {
10067                         struct sdom_block *u;
10068                         next = v->sdom_next;
10069                         unsdom_block(v);
10070                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
10071                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
10072                                 u->block : parent->block;
10073                 }
10074         }
10075 }
10076
10077 static void compute_idom(struct compile_state *state, struct sdom_block *sd)
10078 {
10079         int i;
10080         for(i = 2; i <= state->last_vertex; i++) {
10081                 struct block *block;
10082                 block = sd[i].block;
10083                 if (block->idom->vertex != sd[i].sdom->vertex) {
10084                         block->idom = block->idom->idom;
10085                 }
10086                 idom_block(block->idom, block);
10087         }
10088         sd[1].block->idom = 0;
10089 }
10090
10091 static void compute_ipdom(struct compile_state *state, struct sdom_block *sd)
10092 {
10093         int i;
10094         for(i = 2; i <= state->last_vertex; i++) {
10095                 struct block *block;
10096                 block = sd[i].block;
10097                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
10098                         block->ipdom = block->ipdom->ipdom;
10099                 }
10100                 ipdom_block(block->ipdom, block);
10101         }
10102         sd[1].block->ipdom = 0;
10103 }
10104
10105         /* Theorem 1:
10106          *   Every vertex of a flowgraph G = (V, E, r) except r has
10107          *   a unique immediate dominator.  
10108          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
10109          *   rooted at r, called the dominator tree of G, such that 
10110          *   v dominates w if and only if v is a proper ancestor of w in
10111          *   the dominator tree.
10112          */
10113         /* Lemma 1:  
10114          *   If v and w are vertices of G such that v <= w,
10115          *   than any path from v to w must contain a common ancestor
10116          *   of v and w in T.
10117          */
10118         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
10119         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
10120         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
10121         /* Theorem 2:
10122          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
10123          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
10124          */
10125         /* Theorem 3:
10126          *   Let w != r and let u be a vertex for which sdom(u) is 
10127          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
10128          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
10129          */
10130         /* Lemma 5:  Let vertices v,w satisfy v -> w.
10131          *           Then v -> idom(w) or idom(w) -> idom(v)
10132          */
10133
10134 static void find_immediate_dominators(struct compile_state *state)
10135 {
10136         struct sdom_block *sd;
10137         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
10138          *           vi > w for (1 <= i <= k - 1}
10139          */
10140         /* Theorem 4:
10141          *   For any vertex w != r.
10142          *   sdom(w) = min(
10143          *                 {v|(v,w) <= E  and v < w } U 
10144          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
10145          */
10146         /* Corollary 1:
10147          *   Let w != r and let u be a vertex for which sdom(u) is 
10148          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
10149          *   Then:
10150          *                   { sdom(w) if sdom(w) = sdom(u),
10151          *        idom(w) = {
10152          *                   { idom(u) otherwise
10153          */
10154         /* The algorithm consists of the following 4 steps.
10155          * Step 1.  Carry out a depth-first search of the problem graph.  
10156          *    Number the vertices from 1 to N as they are reached during
10157          *    the search.  Initialize the variables used in succeeding steps.
10158          * Step 2.  Compute the semidominators of all vertices by applying
10159          *    theorem 4.   Carry out the computation vertex by vertex in
10160          *    decreasing order by number.
10161          * Step 3.  Implicitly define the immediate dominator of each vertex
10162          *    by applying Corollary 1.
10163          * Step 4.  Explicitly define the immediate dominator of each vertex,
10164          *    carrying out the computation vertex by vertex in increasing order
10165          *    by number.
10166          */
10167         /* Step 1 initialize the basic block information */
10168         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10169         initialize_sdblock(sd, 0, state->first_block, 0);
10170 #if 0
10171         sd[1].size  = 0;
10172         sd[1].label = 0;
10173         sd[1].sdom  = 0;
10174 #endif
10175         /* Step 2 compute the semidominators */
10176         /* Step 3 implicitly define the immediate dominator of each vertex */
10177         compute_sdom(state, sd);
10178         /* Step 4 explicitly define the immediate dominator of each vertex */
10179         compute_idom(state, sd);
10180         xfree(sd);
10181 }
10182
10183 static void find_post_dominators(struct compile_state *state)
10184 {
10185         struct sdom_block *sd;
10186         int vertex;
10187         /* Step 1 initialize the basic block information */
10188         sd = xcmalloc(sizeof(*sd) * (state->last_vertex + 1), "sdom_state");
10189
10190         vertex = setup_sdpblocks(state, sd);
10191         if (vertex != state->last_vertex) {
10192                 internal_error(state, 0, "missing %d blocks\n",
10193                         state->last_vertex - vertex);
10194         }
10195
10196         /* Step 2 compute the semidominators */
10197         /* Step 3 implicitly define the immediate dominator of each vertex */
10198         compute_spdom(state, sd);
10199         /* Step 4 explicitly define the immediate dominator of each vertex */
10200         compute_ipdom(state, sd);
10201         xfree(sd);
10202 }
10203
10204
10205
10206 static void find_block_domf(struct compile_state *state, struct block *block)
10207 {
10208         struct block *child;
10209         struct block_set *user;
10210         if (block->domfrontier != 0) {
10211                 internal_error(state, block->first, "domfrontier present?");
10212         }
10213         for(user = block->idominates; user; user = user->next) {
10214                 child = user->member;
10215                 if (child->idom != block) {
10216                         internal_error(state, block->first, "bad idom");
10217                 }
10218                 find_block_domf(state, child);
10219         }
10220         if (block->left && block->left->idom != block) {
10221                 domf_block(block, block->left);
10222         }
10223         if (block->right && block->right->idom != block) {
10224                 domf_block(block, block->right);
10225         }
10226         for(user = block->idominates; user; user = user->next) {
10227                 struct block_set *frontier;
10228                 child = user->member;
10229                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
10230                         if (frontier->member->idom != block) {
10231                                 domf_block(block, frontier->member);
10232                         }
10233                 }
10234         }
10235 }
10236
10237 static void find_block_ipdomf(struct compile_state *state, struct block *block)
10238 {
10239         struct block *child;
10240         struct block_set *user;
10241         if (block->ipdomfrontier != 0) {
10242                 internal_error(state, block->first, "ipdomfrontier present?");
10243         }
10244         for(user = block->ipdominates; user; user = user->next) {
10245                 child = user->member;
10246                 if (child->ipdom != block) {
10247                         internal_error(state, block->first, "bad ipdom");
10248                 }
10249                 find_block_ipdomf(state, child);
10250         }
10251         if (block->left && block->left->ipdom != block) {
10252                 ipdomf_block(block, block->left);
10253         }
10254         if (block->right && block->right->ipdom != block) {
10255                 ipdomf_block(block, block->right);
10256         }
10257         for(user = block->idominates; user; user = user->next) {
10258                 struct block_set *frontier;
10259                 child = user->member;
10260                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
10261                         if (frontier->member->ipdom != block) {
10262                                 ipdomf_block(block, frontier->member);
10263                         }
10264                 }
10265         }
10266 }
10267
10268 static void print_dominated(
10269         struct compile_state *state, struct block *block, void *arg)
10270 {
10271         struct block_set *user;
10272         FILE *fp = arg;
10273
10274         fprintf(fp, "%d:", block->vertex);
10275         for(user = block->idominates; user; user = user->next) {
10276                 fprintf(fp, " %d", user->member->vertex);
10277                 if (user->member->idom != block) {
10278                         internal_error(state, user->member->first, "bad idom");
10279                 }
10280         }
10281         fprintf(fp,"\n");
10282 }
10283
10284 static void print_dominators(struct compile_state *state, FILE *fp)
10285 {
10286         fprintf(fp, "\ndominates\n");
10287         walk_blocks(state, print_dominated, fp);
10288 }
10289
10290
10291 static int print_frontiers(
10292         struct compile_state *state, struct block *block, int vertex)
10293 {
10294         struct block_set *user;
10295
10296         if (!block || (block->vertex != vertex + 1)) {
10297                 return vertex;
10298         }
10299         vertex += 1;
10300
10301         printf("%d:", block->vertex);
10302         for(user = block->domfrontier; user; user = user->next) {
10303                 printf(" %d", user->member->vertex);
10304         }
10305         printf("\n");
10306
10307         vertex = print_frontiers(state, block->left, vertex);
10308         vertex = print_frontiers(state, block->right, vertex);
10309         return vertex;
10310 }
10311 static void print_dominance_frontiers(struct compile_state *state)
10312 {
10313         printf("\ndominance frontiers\n");
10314         print_frontiers(state, state->first_block, 0);
10315         
10316 }
10317
10318 static void analyze_idominators(struct compile_state *state)
10319 {
10320         /* Find the immediate dominators */
10321         find_immediate_dominators(state);
10322         /* Find the dominance frontiers */
10323         find_block_domf(state, state->first_block);
10324         /* If debuging print the print what I have just found */
10325         if (state->debug & DEBUG_FDOMINATORS) {
10326                 print_dominators(state, stdout);
10327                 print_dominance_frontiers(state);
10328                 print_control_flow(state);
10329         }
10330 }
10331
10332
10333
10334 static void print_ipdominated(
10335         struct compile_state *state, struct block *block, void *arg)
10336 {
10337         struct block_set *user;
10338         FILE *fp = arg;
10339
10340         fprintf(fp, "%d:", block->vertex);
10341         for(user = block->ipdominates; user; user = user->next) {
10342                 fprintf(fp, " %d", user->member->vertex);
10343                 if (user->member->ipdom != block) {
10344                         internal_error(state, user->member->first, "bad ipdom");
10345                 }
10346         }
10347         fprintf(fp, "\n");
10348 }
10349
10350 static void print_ipdominators(struct compile_state *state, FILE *fp)
10351 {
10352         fprintf(fp, "\nipdominates\n");
10353         walk_blocks(state, print_ipdominated, fp);
10354 }
10355
10356 static int print_pfrontiers(
10357         struct compile_state *state, struct block *block, int vertex)
10358 {
10359         struct block_set *user;
10360
10361         if (!block || (block->vertex != vertex + 1)) {
10362                 return vertex;
10363         }
10364         vertex += 1;
10365
10366         printf("%d:", block->vertex);
10367         for(user = block->ipdomfrontier; user; user = user->next) {
10368                 printf(" %d", user->member->vertex);
10369         }
10370         printf("\n");
10371         for(user = block->use; user; user = user->next) {
10372                 vertex = print_pfrontiers(state, user->member, vertex);
10373         }
10374         return vertex;
10375 }
10376 static void print_ipdominance_frontiers(struct compile_state *state)
10377 {
10378         printf("\nipdominance frontiers\n");
10379         print_pfrontiers(state, state->last_block, 0);
10380         
10381 }
10382
10383 static void analyze_ipdominators(struct compile_state *state)
10384 {
10385         /* Find the post dominators */
10386         find_post_dominators(state);
10387         /* Find the control dependencies (post dominance frontiers) */
10388         find_block_ipdomf(state, state->last_block);
10389         /* If debuging print the print what I have just found */
10390         if (state->debug & DEBUG_RDOMINATORS) {
10391                 print_ipdominators(state, stdout);
10392                 print_ipdominance_frontiers(state);
10393                 print_control_flow(state);
10394         }
10395 }
10396
10397 static int bdominates(struct compile_state *state,
10398         struct block *dom, struct block *sub)
10399 {
10400         while(sub && (sub != dom)) {
10401                 sub = sub->idom;
10402         }
10403         return sub == dom;
10404 }
10405
10406 static int tdominates(struct compile_state *state,
10407         struct triple *dom, struct triple *sub)
10408 {
10409         struct block *bdom, *bsub;
10410         int result;
10411         bdom = block_of_triple(state, dom);
10412         bsub = block_of_triple(state, sub);
10413         if (bdom != bsub) {
10414                 result = bdominates(state, bdom, bsub);
10415         } 
10416         else {
10417                 struct triple *ins;
10418                 ins = sub;
10419                 while((ins != bsub->first) && (ins != dom)) {
10420                         ins = ins->prev;
10421                 }
10422                 result = (ins == dom);
10423         }
10424         return result;
10425 }
10426
10427 static void insert_phi_operations(struct compile_state *state)
10428 {
10429         size_t size;
10430         struct triple *first;
10431         int *has_already, *work;
10432         struct block *work_list, **work_list_tail;
10433         int iter;
10434         struct triple *var, *vnext;
10435
10436         size = sizeof(int) * (state->last_vertex + 1);
10437         has_already = xcmalloc(size, "has_already");
10438         work =        xcmalloc(size, "work");
10439         iter = 0;
10440
10441         first = RHS(state->main_function, 0);
10442         for(var = first->next; var != first ; var = vnext) {
10443                 struct block *block;
10444                 struct triple_set *user, *unext;
10445                 vnext = var->next;
10446                 if ((var->op != OP_ADECL) || !var->use) {
10447                         continue;
10448                 }
10449                 iter += 1;
10450                 work_list = 0;
10451                 work_list_tail = &work_list;
10452                 for(user = var->use; user; user = unext) {
10453                         unext = user->next;
10454                         if (user->member->op == OP_READ) {
10455                                 continue;
10456                         }
10457                         if (user->member->op != OP_WRITE) {
10458                                 internal_error(state, user->member, 
10459                                         "bad variable access");
10460                         }
10461                         block = user->member->u.block;
10462                         if (!block) {
10463                                 warning(state, user->member, "dead code");
10464                                 release_triple(state, user->member);
10465                                 continue;
10466                         }
10467                         if (work[block->vertex] >= iter) {
10468                                 continue;
10469                         }
10470                         work[block->vertex] = iter;
10471                         *work_list_tail = block;
10472                         block->work_next = 0;
10473                         work_list_tail = &block->work_next;
10474                 }
10475                 for(block = work_list; block; block = block->work_next) {
10476                         struct block_set *df;
10477                         for(df = block->domfrontier; df; df = df->next) {
10478                                 struct triple *phi;
10479                                 struct block *front;
10480                                 int in_edges;
10481                                 front = df->member;
10482
10483                                 if (has_already[front->vertex] >= iter) {
10484                                         continue;
10485                                 }
10486                                 /* Count how many edges flow into this block */
10487                                 in_edges = front->users;
10488                                 /* Insert a phi function for this variable */
10489                                 get_occurance(front->first->occurance);
10490                                 phi = alloc_triple(
10491                                         state, OP_PHI, var->type, -1, in_edges, 
10492                                         front->first->occurance);
10493                                 phi->u.block = front;
10494                                 MISC(phi, 0) = var;
10495                                 use_triple(var, phi);
10496                                 /* Insert the phi functions immediately after the label */
10497                                 insert_triple(state, front->first->next, phi);
10498                                 if (front->first == front->last) {
10499                                         front->last = front->first->next;
10500                                 }
10501                                 has_already[front->vertex] = iter;
10502
10503                                 /* If necessary plan to visit the basic block */
10504                                 if (work[front->vertex] >= iter) {
10505                                         continue;
10506                                 }
10507                                 work[front->vertex] = iter;
10508                                 *work_list_tail = front;
10509                                 front->work_next = 0;
10510                                 work_list_tail = &front->work_next;
10511                         }
10512                 }
10513         }
10514         xfree(has_already);
10515         xfree(work);
10516 }
10517
10518 /*
10519  * C(V)
10520  * S(V)
10521  */
10522 static void fixup_block_phi_variables(
10523         struct compile_state *state, struct block *parent, struct block *block)
10524 {
10525         struct block_set *set;
10526         struct triple *ptr;
10527         int edge;
10528         if (!parent || !block)
10529                 return;
10530         /* Find the edge I am coming in on */
10531         edge = 0;
10532         for(set = block->use; set; set = set->next, edge++) {
10533                 if (set->member == parent) {
10534                         break;
10535                 }
10536         }
10537         if (!set) {
10538                 internal_error(state, 0, "phi input is not on a control predecessor");
10539         }
10540         for(ptr = block->first; ; ptr = ptr->next) {
10541                 if (ptr->op == OP_PHI) {
10542                         struct triple *var, *val, **slot;
10543                         var = MISC(ptr, 0);
10544                         if (!var) {
10545                                 internal_error(state, ptr, "no var???");
10546                         }
10547                         /* Find the current value of the variable */
10548                         val = var->use->member;
10549                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10550                                 internal_error(state, val, "bad value in phi");
10551                         }
10552                         if (edge >= TRIPLE_RHS(ptr->sizes)) {
10553                                 internal_error(state, ptr, "edges > phi rhs");
10554                         }
10555                         slot = &RHS(ptr, edge);
10556                         if ((*slot != 0) && (*slot != val)) {
10557                                 internal_error(state, ptr, "phi already bound on this edge");
10558                         }
10559                         *slot = val;
10560                         use_triple(val, ptr);
10561                 }
10562                 if (ptr == block->last) {
10563                         break;
10564                 }
10565         }
10566 }
10567
10568
10569 static void rename_block_variables(
10570         struct compile_state *state, struct block *block)
10571 {
10572         struct block_set *user;
10573         struct triple *ptr, *next, *last;
10574         int done;
10575         if (!block)
10576                 return;
10577         last = block->first;
10578         done = 0;
10579         for(ptr = block->first; !done; ptr = next) {
10580                 next = ptr->next;
10581                 if (ptr == block->last) {
10582                         done = 1;
10583                 }
10584                 /* RHS(A) */
10585                 if (ptr->op == OP_READ) {
10586                         struct triple *var, *val;
10587                         var = RHS(ptr, 0);
10588                         unuse_triple(var, ptr);
10589                         if (!var->use) {
10590                                 error(state, ptr, "variable used without being set");
10591                         }
10592                         /* Find the current value of the variable */
10593                         val = var->use->member;
10594                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10595                                 internal_error(state, val, "bad value in read");
10596                         }
10597                         propogate_use(state, ptr, val);
10598                         release_triple(state, ptr);
10599                         continue;
10600                 }
10601                 /* LHS(A) */
10602                 if (ptr->op == OP_WRITE) {
10603                         struct triple *var, *val, *tval;
10604                         var = RHS(ptr, 0);
10605                         tval = val = RHS(ptr, 1);
10606                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
10607                                 internal_error(state, ptr, "bad value in write");
10608                         }
10609                         /* Insert a copy if the types differ */
10610                         if (!equiv_types(ptr->type, val->type)) {
10611                                 if (val->op == OP_INTCONST) {
10612                                         tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
10613                                         tval->u.cval = val->u.cval;
10614                                 }
10615                                 else {
10616                                         tval = pre_triple(state, ptr, OP_COPY, ptr->type, val, 0);
10617                                         use_triple(val, tval);
10618                                 }
10619                                 unuse_triple(val, ptr);
10620                                 RHS(ptr, 1) = tval;
10621                                 use_triple(tval, ptr);
10622                         }
10623                         propogate_use(state, ptr, tval);
10624                         unuse_triple(var, ptr);
10625                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
10626                         push_triple(var, tval);
10627                 }
10628                 if (ptr->op == OP_PHI) {
10629                         struct triple *var;
10630                         var = MISC(ptr, 0);
10631                         /* Push OP_PHI onto a stack of variable uses */
10632                         push_triple(var, ptr);
10633                 }
10634                 last = ptr;
10635         }
10636         block->last = last;
10637
10638         /* Fixup PHI functions in the cf successors */
10639         fixup_block_phi_variables(state, block, block->left);
10640         fixup_block_phi_variables(state, block, block->right);
10641         /* rename variables in the dominated nodes */
10642         for(user = block->idominates; user; user = user->next) {
10643                 rename_block_variables(state, user->member);
10644         }
10645         /* pop the renamed variable stack */
10646         last = block->first;
10647         done = 0;
10648         for(ptr = block->first; !done ; ptr = next) {
10649                 next = ptr->next;
10650                 if (ptr == block->last) {
10651                         done = 1;
10652                 }
10653                 if (ptr->op == OP_WRITE) {
10654                         struct triple *var;
10655                         var = RHS(ptr, 0);
10656                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10657                         pop_triple(var, RHS(ptr, 1));
10658                         release_triple(state, ptr);
10659                         continue;
10660                 }
10661                 if (ptr->op == OP_PHI) {
10662                         struct triple *var;
10663                         var = MISC(ptr, 0);
10664                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
10665                         pop_triple(var, ptr);
10666                 }
10667                 last = ptr;
10668         }
10669         block->last = last;
10670 }
10671
10672 static void prune_block_variables(struct compile_state *state,
10673         struct block *block)
10674 {
10675         struct block_set *user;
10676         struct triple *next, *last, *ptr;
10677         int done;
10678         last = block->first;
10679         done = 0;
10680         for(ptr = block->first; !done; ptr = next) {
10681                 next = ptr->next;
10682                 if (ptr == block->last) {
10683                         done = 1;
10684                 }
10685                 if (ptr->op == OP_ADECL) {
10686                         struct triple_set *user, *next;
10687                         for(user = ptr->use; user; user = next) {
10688                                 struct triple *use;
10689                                 next = user->next;
10690                                 use = user->member;
10691                                 if (use->op != OP_PHI) {
10692                                         internal_error(state, use, "decl still used");
10693                                 }
10694                                 if (MISC(use, 0) != ptr) {
10695                                         internal_error(state, use, "bad phi use of decl");
10696                                 }
10697                                 unuse_triple(ptr, use);
10698                                 MISC(use, 0) = 0;
10699                         }
10700                         release_triple(state, ptr);
10701                         continue;
10702                 }
10703                 last = ptr;
10704         }
10705         block->last = last;
10706         for(user = block->idominates; user; user = user->next) {
10707                 prune_block_variables(state, user->member);
10708         }
10709 }
10710
10711 static void transform_to_ssa_form(struct compile_state *state)
10712 {
10713         insert_phi_operations(state);
10714 #if 0
10715         printf("@%s:%d\n", __FILE__, __LINE__);
10716         print_blocks(state, stdout);
10717 #endif
10718         rename_block_variables(state, state->first_block);
10719         prune_block_variables(state, state->first_block);
10720 }
10721
10722
10723 static void clear_vertex(
10724         struct compile_state *state, struct block *block, void *arg)
10725 {
10726         block->vertex = 0;
10727 }
10728
10729 static void mark_live_block(
10730         struct compile_state *state, struct block *block, int *next_vertex)
10731 {
10732         /* See if this is a block that has not been marked */
10733         if (block->vertex != 0) {
10734                 return;
10735         }
10736         block->vertex = *next_vertex;
10737         *next_vertex += 1;
10738         if (triple_is_branch(state, block->last)) {
10739                 struct triple **targ;
10740                 targ = triple_targ(state, block->last, 0);
10741                 for(; targ; targ = triple_targ(state, block->last, targ)) {
10742                         if (!*targ) {
10743                                 continue;
10744                         }
10745                         if (!triple_stores_block(state, *targ)) {
10746                                 internal_error(state, 0, "bad targ");
10747                         }
10748                         mark_live_block(state, (*targ)->u.block, next_vertex);
10749                 }
10750         }
10751         else if (block->last->next != RHS(state->main_function, 0)) {
10752                 struct triple *ins;
10753                 ins = block->last->next;
10754                 if (!triple_stores_block(state, ins)) {
10755                         internal_error(state, 0, "bad block start");
10756                 }
10757                 mark_live_block(state, ins->u.block, next_vertex);
10758         }
10759 }
10760
10761 static void transform_from_ssa_form(struct compile_state *state)
10762 {
10763         /* To get out of ssa form we insert moves on the incoming
10764          * edges to blocks containting phi functions.
10765          */
10766         struct triple *first;
10767         struct triple *phi, *next;
10768         int next_vertex;
10769
10770         /* Walk the control flow to see which blocks remain alive */
10771         walk_blocks(state, clear_vertex, 0);
10772         next_vertex = 1;
10773         mark_live_block(state, state->first_block, &next_vertex);
10774
10775         /* Walk all of the operations to find the phi functions */
10776         first = RHS(state->main_function, 0);
10777         for(phi = first->next; phi != first ; phi = next) {
10778                 struct block_set *set;
10779                 struct block *block;
10780                 struct triple **slot;
10781                 struct triple *var, *read;
10782                 struct triple_set *use, *use_next;
10783                 int edge, used;
10784                 next = phi->next;
10785                 if (phi->op != OP_PHI) {
10786                         continue;
10787                 }
10788                 block = phi->u.block;
10789                 slot  = &RHS(phi, 0);
10790
10791                 /* Forget uses from code in dead blocks */
10792                 for(use = phi->use; use; use = use_next) {
10793                         struct block *ublock;
10794                         struct triple **expr;
10795                         use_next = use->next;
10796                         ublock = block_of_triple(state, use->member);
10797                         if ((use->member == phi) || (ublock->vertex != 0)) {
10798                                 continue;
10799                         }
10800                         expr = triple_rhs(state, use->member, 0);
10801                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
10802                                 if (*expr == phi) {
10803                                         *expr = 0;
10804                                 }
10805                         }
10806                         unuse_triple(phi, use->member);
10807                 }
10808
10809 #warning "CHECK_ME does the OP_ADECL need to be placed somewhere that dominates all of the incoming phi edges?"
10810                 /* A variable to replace the phi function */
10811                 var = post_triple(state, phi, OP_ADECL, phi->type, 0,0);
10812                 /* A read of the single value that is set into the variable */
10813                 read = post_triple(state, var, OP_READ, phi->type, var, 0);
10814                 use_triple(var, read);
10815
10816                 /* Replaces uses of the phi with variable reads */
10817                 propogate_use(state, phi, read);
10818
10819                 /* Walk all of the incoming edges/blocks and insert moves.
10820                  */
10821                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
10822                         struct block *eblock;
10823                         struct triple *move;
10824                         struct triple *val, *base;
10825                         eblock = set->member;
10826                         val = slot[edge];
10827                         slot[edge] = 0;
10828                         unuse_triple(val, phi);
10829
10830                         if (!val || (val == &zero_triple) ||
10831                                 (block->vertex == 0) || (eblock->vertex == 0) ||
10832                                 (val == phi) || (val == read)) {
10833                                 continue;
10834                         }
10835                         
10836                         /* Make certain the write is placed in the edge block... */
10837                         base = eblock->first;
10838                         if (block_of_triple(state, val) == eblock) {
10839                                 base = val;
10840                         }
10841                         move = post_triple(state, base, OP_WRITE, phi->type, var, val);
10842                         use_triple(val, move);
10843                         use_triple(var, move);
10844                 }               
10845                 /* See if there are any writers of var */
10846                 used = 0;
10847                 for(use = var->use; use; use = use->next) {
10848                         if ((use->member->op == OP_WRITE) &&
10849                                 (RHS(use->member, 0) == var)) {
10850                                 used = 1;
10851                         }
10852                 }
10853                 /* If var is not used free it */
10854                 if (!used) {
10855                         unuse_triple(var, read);
10856                         free_triple(state, read);
10857                         free_triple(state, var);
10858                 }
10859
10860                 /* Release the phi function */
10861                 release_triple(state, phi);
10862         }
10863         
10864 }
10865
10866
10867 /* 
10868  * Register conflict resolution
10869  * =========================================================
10870  */
10871
10872 static struct reg_info find_def_color(
10873         struct compile_state *state, struct triple *def)
10874 {
10875         struct triple_set *set;
10876         struct reg_info info;
10877         info.reg = REG_UNSET;
10878         info.regcm = 0;
10879         if (!triple_is_def(state, def)) {
10880                 return info;
10881         }
10882         info = arch_reg_lhs(state, def, 0);
10883         if (info.reg >= MAX_REGISTERS) {
10884                 info.reg = REG_UNSET;
10885         }
10886         for(set = def->use; set; set = set->next) {
10887                 struct reg_info tinfo;
10888                 int i;
10889                 i = find_rhs_use(state, set->member, def);
10890                 if (i < 0) {
10891                         continue;
10892                 }
10893                 tinfo = arch_reg_rhs(state, set->member, i);
10894                 if (tinfo.reg >= MAX_REGISTERS) {
10895                         tinfo.reg = REG_UNSET;
10896                 }
10897                 if ((tinfo.reg != REG_UNSET) && 
10898                         (info.reg != REG_UNSET) &&
10899                         (tinfo.reg != info.reg)) {
10900                         internal_error(state, def, "register conflict");
10901                 }
10902                 if ((info.regcm & tinfo.regcm) == 0) {
10903                         internal_error(state, def, "regcm conflict %x & %x == 0",
10904                                 info.regcm, tinfo.regcm);
10905                 }
10906                 if (info.reg == REG_UNSET) {
10907                         info.reg = tinfo.reg;
10908                 }
10909                 info.regcm &= tinfo.regcm;
10910         }
10911         if (info.reg >= MAX_REGISTERS) {
10912                 internal_error(state, def, "register out of range");
10913         }
10914         return info;
10915 }
10916
10917 static struct reg_info find_lhs_pre_color(
10918         struct compile_state *state, struct triple *ins, int index)
10919 {
10920         struct reg_info info;
10921         int zlhs, zrhs, i;
10922         zrhs = TRIPLE_RHS(ins->sizes);
10923         zlhs = TRIPLE_LHS(ins->sizes);
10924         if (!zlhs && triple_is_def(state, ins)) {
10925                 zlhs = 1;
10926         }
10927         if (index >= zlhs) {
10928                 internal_error(state, ins, "Bad lhs %d", index);
10929         }
10930         info = arch_reg_lhs(state, ins, index);
10931         for(i = 0; i < zrhs; i++) {
10932                 struct reg_info rinfo;
10933                 rinfo = arch_reg_rhs(state, ins, i);
10934                 if ((info.reg == rinfo.reg) &&
10935                         (rinfo.reg >= MAX_REGISTERS)) {
10936                         struct reg_info tinfo;
10937                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
10938                         info.reg = tinfo.reg;
10939                         info.regcm &= tinfo.regcm;
10940                         break;
10941                 }
10942         }
10943         if (info.reg >= MAX_REGISTERS) {
10944                 info.reg = REG_UNSET;
10945         }
10946         return info;
10947 }
10948
10949 static struct reg_info find_rhs_post_color(
10950         struct compile_state *state, struct triple *ins, int index);
10951
10952 static struct reg_info find_lhs_post_color(
10953         struct compile_state *state, struct triple *ins, int index)
10954 {
10955         struct triple_set *set;
10956         struct reg_info info;
10957         struct triple *lhs;
10958 #if DEBUG_TRIPLE_COLOR
10959         fprintf(stderr, "find_lhs_post_color(%p, %d)\n",
10960                 ins, index);
10961 #endif
10962         if ((index == 0) && triple_is_def(state, ins)) {
10963                 lhs = ins;
10964         }
10965         else if (index < TRIPLE_LHS(ins->sizes)) {
10966                 lhs = LHS(ins, index);
10967         }
10968         else {
10969                 internal_error(state, ins, "Bad lhs %d", index);
10970                 lhs = 0;
10971         }
10972         info = arch_reg_lhs(state, ins, index);
10973         if (info.reg >= MAX_REGISTERS) {
10974                 info.reg = REG_UNSET;
10975         }
10976         for(set = lhs->use; set; set = set->next) {
10977                 struct reg_info rinfo;
10978                 struct triple *user;
10979                 int zrhs, i;
10980                 user = set->member;
10981                 zrhs = TRIPLE_RHS(user->sizes);
10982                 for(i = 0; i < zrhs; i++) {
10983                         if (RHS(user, i) != lhs) {
10984                                 continue;
10985                         }
10986                         rinfo = find_rhs_post_color(state, user, i);
10987                         if ((info.reg != REG_UNSET) &&
10988                                 (rinfo.reg != REG_UNSET) &&
10989                                 (info.reg != rinfo.reg)) {
10990                                 internal_error(state, ins, "register conflict");
10991                         }
10992                         if ((info.regcm & rinfo.regcm) == 0) {
10993                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
10994                                         info.regcm, rinfo.regcm);
10995                         }
10996                         if (info.reg == REG_UNSET) {
10997                                 info.reg = rinfo.reg;
10998                         }
10999                         info.regcm &= rinfo.regcm;
11000                 }
11001         }
11002 #if DEBUG_TRIPLE_COLOR
11003         fprintf(stderr, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
11004                 ins, index, info.reg, info.regcm);
11005 #endif
11006         return info;
11007 }
11008
11009 static struct reg_info find_rhs_post_color(
11010         struct compile_state *state, struct triple *ins, int index)
11011 {
11012         struct reg_info info, rinfo;
11013         int zlhs, i;
11014 #if DEBUG_TRIPLE_COLOR
11015         fprintf(stderr, "find_rhs_post_color(%p, %d)\n",
11016                 ins, index);
11017 #endif
11018         rinfo = arch_reg_rhs(state, ins, index);
11019         zlhs = TRIPLE_LHS(ins->sizes);
11020         if (!zlhs && triple_is_def(state, ins)) {
11021                 zlhs = 1;
11022         }
11023         info = rinfo;
11024         if (info.reg >= MAX_REGISTERS) {
11025                 info.reg = REG_UNSET;
11026         }
11027         for(i = 0; i < zlhs; i++) {
11028                 struct reg_info linfo;
11029                 linfo = arch_reg_lhs(state, ins, i);
11030                 if ((linfo.reg == rinfo.reg) &&
11031                         (linfo.reg >= MAX_REGISTERS)) {
11032                         struct reg_info tinfo;
11033                         tinfo = find_lhs_post_color(state, ins, i);
11034                         if (tinfo.reg >= MAX_REGISTERS) {
11035                                 tinfo.reg = REG_UNSET;
11036                         }
11037                         info.regcm &= linfo.regcm;
11038                         info.regcm &= tinfo.regcm;
11039                         if (info.reg != REG_UNSET) {
11040                                 internal_error(state, ins, "register conflict");
11041                         }
11042                         if (info.regcm == 0) {
11043                                 internal_error(state, ins, "regcm conflict");
11044                         }
11045                         info.reg = tinfo.reg;
11046                 }
11047         }
11048 #if DEBUG_TRIPLE_COLOR
11049         fprintf(stderr, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
11050                 ins, index, info.reg, info.regcm);
11051 #endif
11052         return info;
11053 }
11054
11055 static struct reg_info find_lhs_color(
11056         struct compile_state *state, struct triple *ins, int index)
11057 {
11058         struct reg_info pre, post, info;
11059 #if DEBUG_TRIPLE_COLOR
11060         fprintf(stderr, "find_lhs_color(%p, %d)\n",
11061                 ins, index);
11062 #endif
11063         pre = find_lhs_pre_color(state, ins, index);
11064         post = find_lhs_post_color(state, ins, index);
11065         if ((pre.reg != post.reg) &&
11066                 (pre.reg != REG_UNSET) &&
11067                 (post.reg != REG_UNSET)) {
11068                 internal_error(state, ins, "register conflict");
11069         }
11070         info.regcm = pre.regcm & post.regcm;
11071         info.reg = pre.reg;
11072         if (info.reg == REG_UNSET) {
11073                 info.reg = post.reg;
11074         }
11075 #if DEBUG_TRIPLE_COLOR
11076         fprintf(stderr, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
11077                 ins, index, info.reg, info.regcm,
11078                 pre.reg, pre.regcm, post.reg, post.regcm);
11079 #endif
11080         return info;
11081 }
11082
11083 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
11084 {
11085         struct triple_set *entry, *next;
11086         struct triple *out;
11087         struct reg_info info, rinfo;
11088
11089         info = arch_reg_lhs(state, ins, 0);
11090         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
11091         use_triple(RHS(out, 0), out);
11092         /* Get the users of ins to use out instead */
11093         for(entry = ins->use; entry; entry = next) {
11094                 int i;
11095                 next = entry->next;
11096                 if (entry->member == out) {
11097                         continue;
11098                 }
11099                 i = find_rhs_use(state, entry->member, ins);
11100                 if (i < 0) {
11101                         continue;
11102                 }
11103                 rinfo = arch_reg_rhs(state, entry->member, i);
11104                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
11105                         continue;
11106                 }
11107                 replace_rhs_use(state, ins, out, entry->member);
11108         }
11109         transform_to_arch_instruction(state, out);
11110         return out;
11111 }
11112
11113 static struct triple *typed_pre_copy(
11114         struct compile_state *state, struct type *type, struct triple *ins, int index)
11115 {
11116         /* Carefully insert enough operations so that I can
11117          * enter any operation with a GPR32.
11118          */
11119         struct triple *in;
11120         struct triple **expr;
11121         unsigned classes;
11122         struct reg_info info;
11123         if (ins->op == OP_PHI) {
11124                 internal_error(state, ins, "pre_copy on a phi?");
11125         }
11126         classes = arch_type_to_regcm(state, type);
11127         info = arch_reg_rhs(state, ins, index);
11128         expr = &RHS(ins, index);
11129         if ((info.regcm & classes) == 0) {
11130                 internal_error(state, ins, "pre_copy with no register classes");
11131         }
11132         in = pre_triple(state, ins, OP_COPY, type, *expr, 0);
11133         unuse_triple(*expr, ins);
11134         *expr = in;
11135         use_triple(RHS(in, 0), in);
11136         use_triple(in, ins);
11137         transform_to_arch_instruction(state, in);
11138         return in;
11139         
11140 }
11141 static struct triple *pre_copy(
11142         struct compile_state *state, struct triple *ins, int index)
11143 {
11144         return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
11145 }
11146
11147
11148 static void insert_copies_to_phi(struct compile_state *state)
11149 {
11150         /* To get out of ssa form we insert moves on the incoming
11151          * edges to blocks containting phi functions.
11152          */
11153         struct triple *first;
11154         struct triple *phi;
11155
11156         /* Walk all of the operations to find the phi functions */
11157         first = RHS(state->main_function, 0);
11158         for(phi = first->next; phi != first ; phi = phi->next) {
11159                 struct block_set *set;
11160                 struct block *block;
11161                 struct triple **slot, *copy;
11162                 int edge;
11163                 if (phi->op != OP_PHI) {
11164                         continue;
11165                 }
11166                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
11167                 block = phi->u.block;
11168                 slot  = &RHS(phi, 0);
11169                 /* Phi's that feed into mandatory live range joins
11170                  * cause nasty complications.  Insert a copy of
11171                  * the phi value so I never have to deal with
11172                  * that in the rest of the code.
11173                  */
11174                 copy = post_copy(state, phi);
11175                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
11176                 /* Walk all of the incoming edges/blocks and insert moves.
11177                  */
11178                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
11179                         struct block *eblock;
11180                         struct triple *move;
11181                         struct triple *val;
11182                         struct triple *ptr;
11183                         eblock = set->member;
11184                         val = slot[edge];
11185
11186                         if (val == phi) {
11187                                 continue;
11188                         }
11189
11190                         get_occurance(val->occurance);
11191                         move = build_triple(state, OP_COPY, phi->type, val, 0,
11192                                 val->occurance);
11193                         move->u.block = eblock;
11194                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
11195                         use_triple(val, move);
11196                         
11197                         slot[edge] = move;
11198                         unuse_triple(val, phi);
11199                         use_triple(move, phi);
11200
11201                         /* Walk through the block backwards to find
11202                          * an appropriate location for the OP_COPY.
11203                          */
11204                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
11205                                 struct triple **expr;
11206                                 if ((ptr == phi) || (ptr == val)) {
11207                                         goto out;
11208                                 }
11209                                 expr = triple_rhs(state, ptr, 0);
11210                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11211                                         if ((*expr) == phi) {
11212                                                 goto out;
11213                                         }
11214                                 }
11215                         }
11216                 out:
11217                         if (triple_is_branch(state, ptr)) {
11218                                 internal_error(state, ptr,
11219                                         "Could not insert write to phi");
11220                         }
11221                         insert_triple(state, ptr->next, move);
11222                         if (eblock->last == ptr) {
11223                                 eblock->last = move;
11224                         }
11225                         transform_to_arch_instruction(state, move);
11226                 }
11227         }
11228 }
11229
11230 struct triple_reg_set {
11231         struct triple_reg_set *next;
11232         struct triple *member;
11233         struct triple *new;
11234 };
11235
11236 struct reg_block {
11237         struct block *block;
11238         struct triple_reg_set *in;
11239         struct triple_reg_set *out;
11240         int vertex;
11241 };
11242
11243 static int do_triple_set(struct triple_reg_set **head, 
11244         struct triple *member, struct triple *new_member)
11245 {
11246         struct triple_reg_set **ptr, *new;
11247         if (!member)
11248                 return 0;
11249         ptr = head;
11250         while(*ptr) {
11251                 if ((*ptr)->member == member) {
11252                         return 0;
11253                 }
11254                 ptr = &(*ptr)->next;
11255         }
11256         new = xcmalloc(sizeof(*new), "triple_set");
11257         new->member = member;
11258         new->new    = new_member;
11259         new->next   = *head;
11260         *head       = new;
11261         return 1;
11262 }
11263
11264 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
11265 {
11266         struct triple_reg_set *entry, **ptr;
11267         ptr = head;
11268         while(*ptr) {
11269                 entry = *ptr;
11270                 if (entry->member == member) {
11271                         *ptr = entry->next;
11272                         xfree(entry);
11273                         return;
11274                 }
11275                 else {
11276                         ptr = &entry->next;
11277                 }
11278         }
11279 }
11280
11281 static int in_triple(struct reg_block *rb, struct triple *in)
11282 {
11283         return do_triple_set(&rb->in, in, 0);
11284 }
11285 static void unin_triple(struct reg_block *rb, struct triple *unin)
11286 {
11287         do_triple_unset(&rb->in, unin);
11288 }
11289
11290 static int out_triple(struct reg_block *rb, struct triple *out)
11291 {
11292         return do_triple_set(&rb->out, out, 0);
11293 }
11294 static void unout_triple(struct reg_block *rb, struct triple *unout)
11295 {
11296         do_triple_unset(&rb->out, unout);
11297 }
11298
11299 static int initialize_regblock(struct reg_block *blocks,
11300         struct block *block, int vertex)
11301 {
11302         struct block_set *user;
11303         if (!block || (blocks[block->vertex].block == block)) {
11304                 return vertex;
11305         }
11306         vertex += 1;
11307         /* Renumber the blocks in a convinient fashion */
11308         block->vertex = vertex;
11309         blocks[vertex].block    = block;
11310         blocks[vertex].vertex   = vertex;
11311         for(user = block->use; user; user = user->next) {
11312                 vertex = initialize_regblock(blocks, user->member, vertex);
11313         }
11314         return vertex;
11315 }
11316
11317 static int phi_in(struct compile_state *state, struct reg_block *blocks,
11318         struct reg_block *rb, struct block *suc)
11319 {
11320         /* Read the conditional input set of a successor block
11321          * (i.e. the input to the phi nodes) and place it in the
11322          * current blocks output set.
11323          */
11324         struct block_set *set;
11325         struct triple *ptr;
11326         int edge;
11327         int done, change;
11328         change = 0;
11329         /* Find the edge I am coming in on */
11330         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
11331                 if (set->member == rb->block) {
11332                         break;
11333                 }
11334         }
11335         if (!set) {
11336                 internal_error(state, 0, "Not coming on a control edge?");
11337         }
11338         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
11339                 struct triple **slot, *expr, *ptr2;
11340                 int out_change, done2;
11341                 done = (ptr == suc->last);
11342                 if (ptr->op != OP_PHI) {
11343                         continue;
11344                 }
11345                 slot = &RHS(ptr, 0);
11346                 expr = slot[edge];
11347                 out_change = out_triple(rb, expr);
11348                 if (!out_change) {
11349                         continue;
11350                 }
11351                 /* If we don't define the variable also plast it
11352                  * in the current blocks input set.
11353                  */
11354                 ptr2 = rb->block->first;
11355                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
11356                         if (ptr2 == expr) {
11357                                 break;
11358                         }
11359                         done2 = (ptr2 == rb->block->last);
11360                 }
11361                 if (!done2) {
11362                         continue;
11363                 }
11364                 change |= in_triple(rb, expr);
11365         }
11366         return change;
11367 }
11368
11369 static int reg_in(struct compile_state *state, struct reg_block *blocks,
11370         struct reg_block *rb, struct block *suc)
11371 {
11372         struct triple_reg_set *in_set;
11373         int change;
11374         change = 0;
11375         /* Read the input set of a successor block
11376          * and place it in the current blocks output set.
11377          */
11378         in_set = blocks[suc->vertex].in;
11379         for(; in_set; in_set = in_set->next) {
11380                 int out_change, done;
11381                 struct triple *first, *last, *ptr;
11382                 out_change = out_triple(rb, in_set->member);
11383                 if (!out_change) {
11384                         continue;
11385                 }
11386                 /* If we don't define the variable also place it
11387                  * in the current blocks input set.
11388                  */
11389                 first = rb->block->first;
11390                 last = rb->block->last;
11391                 done = 0;
11392                 for(ptr = first; !done; ptr = ptr->next) {
11393                         if (ptr == in_set->member) {
11394                                 break;
11395                         }
11396                         done = (ptr == last);
11397                 }
11398                 if (!done) {
11399                         continue;
11400                 }
11401                 change |= in_triple(rb, in_set->member);
11402         }
11403         change |= phi_in(state, blocks, rb, suc);
11404         return change;
11405 }
11406
11407
11408 static int use_in(struct compile_state *state, struct reg_block *rb)
11409 {
11410         /* Find the variables we use but don't define and add
11411          * it to the current blocks input set.
11412          */
11413 #warning "FIXME is this O(N^2) algorithm bad?"
11414         struct block *block;
11415         struct triple *ptr;
11416         int done;
11417         int change;
11418         block = rb->block;
11419         change = 0;
11420         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
11421                 struct triple **expr;
11422                 done = (ptr == block->first);
11423                 /* The variable a phi function uses depends on the
11424                  * control flow, and is handled in phi_in, not
11425                  * here.
11426                  */
11427                 if (ptr->op == OP_PHI) {
11428                         continue;
11429                 }
11430                 expr = triple_rhs(state, ptr, 0);
11431                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
11432                         struct triple *rhs, *test;
11433                         int tdone;
11434                         rhs = *expr;
11435                         if (!rhs) {
11436                                 continue;
11437                         }
11438                         /* See if rhs is defined in this block */
11439                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
11440                                 tdone = (test == block->first);
11441                                 if (test == rhs) {
11442                                         rhs = 0;
11443                                         break;
11444                                 }
11445                         }
11446                         /* If I still have a valid rhs add it to in */
11447                         change |= in_triple(rb, rhs);
11448                 }
11449         }
11450         return change;
11451 }
11452
11453 static struct reg_block *compute_variable_lifetimes(
11454         struct compile_state *state)
11455 {
11456         struct reg_block *blocks;
11457         int change;
11458         blocks = xcmalloc(
11459                 sizeof(*blocks)*(state->last_vertex + 1), "reg_block");
11460         initialize_regblock(blocks, state->last_block, 0);
11461         do {
11462                 int i;
11463                 change = 0;
11464                 for(i = 1; i <= state->last_vertex; i++) {
11465                         struct reg_block *rb;
11466                         rb = &blocks[i];
11467                         /* Add the left successor's input set to in */
11468                         if (rb->block->left) {
11469                                 change |= reg_in(state, blocks, rb, rb->block->left);
11470                         }
11471                         /* Add the right successor's input set to in */
11472                         if ((rb->block->right) && 
11473                                 (rb->block->right != rb->block->left)) {
11474                                 change |= reg_in(state, blocks, rb, rb->block->right);
11475                         }
11476                         /* Add use to in... */
11477                         change |= use_in(state, rb);
11478                 }
11479         } while(change);
11480         return blocks;
11481 }
11482
11483 static void free_variable_lifetimes(
11484         struct compile_state *state, struct reg_block *blocks)
11485 {
11486         int i;
11487         /* free in_set && out_set on each block */
11488         for(i = 1; i <= state->last_vertex; i++) {
11489                 struct triple_reg_set *entry, *next;
11490                 struct reg_block *rb;
11491                 rb = &blocks[i];
11492                 for(entry = rb->in; entry ; entry = next) {
11493                         next = entry->next;
11494                         do_triple_unset(&rb->in, entry->member);
11495                 }
11496                 for(entry = rb->out; entry; entry = next) {
11497                         next = entry->next;
11498                         do_triple_unset(&rb->out, entry->member);
11499                 }
11500         }
11501         xfree(blocks);
11502
11503 }
11504
11505 typedef void (*wvl_cb_t)(
11506         struct compile_state *state, 
11507         struct reg_block *blocks, struct triple_reg_set *live, 
11508         struct reg_block *rb, struct triple *ins, void *arg);
11509
11510 static void walk_variable_lifetimes(struct compile_state *state,
11511         struct reg_block *blocks, wvl_cb_t cb, void *arg)
11512 {
11513         int i;
11514         
11515         for(i = 1; i <= state->last_vertex; i++) {
11516                 struct triple_reg_set *live;
11517                 struct triple_reg_set *entry, *next;
11518                 struct triple *ptr, *prev;
11519                 struct reg_block *rb;
11520                 struct block *block;
11521                 int done;
11522
11523                 /* Get the blocks */
11524                 rb = &blocks[i];
11525                 block = rb->block;
11526
11527                 /* Copy out into live */
11528                 live = 0;
11529                 for(entry = rb->out; entry; entry = next) {
11530                         next = entry->next;
11531                         do_triple_set(&live, entry->member, entry->new);
11532                 }
11533                 /* Walk through the basic block calculating live */
11534                 for(done = 0, ptr = block->last; !done; ptr = prev) {
11535                         struct triple **expr;
11536
11537                         prev = ptr->prev;
11538                         done = (ptr == block->first);
11539
11540                         /* Ensure the current definition is in live */
11541                         if (triple_is_def(state, ptr)) {
11542                                 do_triple_set(&live, ptr, 0);
11543                         }
11544
11545                         /* Inform the callback function of what is
11546                          * going on.
11547                          */
11548                          cb(state, blocks, live, rb, ptr, arg);
11549                         
11550                         /* Remove the current definition from live */
11551                         do_triple_unset(&live, ptr);
11552
11553                         /* Add the current uses to live.
11554                          *
11555                          * It is safe to skip phi functions because they do
11556                          * not have any block local uses, and the block
11557                          * output sets already properly account for what
11558                          * control flow depedent uses phi functions do have.
11559                          */
11560                         if (ptr->op == OP_PHI) {
11561                                 continue;
11562                         }
11563                         expr = triple_rhs(state, ptr, 0);
11564                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
11565                                 /* If the triple is not a definition skip it. */
11566                                 if (!*expr || !triple_is_def(state, *expr)) {
11567                                         continue;
11568                                 }
11569                                 do_triple_set(&live, *expr, 0);
11570                         }
11571                 }
11572                 /* Free live */
11573                 for(entry = live; entry; entry = next) {
11574                         next = entry->next;
11575                         do_triple_unset(&live, entry->member);
11576                 }
11577         }
11578 }
11579
11580 static int count_triples(struct compile_state *state)
11581 {
11582         struct triple *first, *ins;
11583         int triples = 0;
11584         first = RHS(state->main_function, 0);
11585         ins = first;
11586         do {
11587                 triples++;
11588                 ins = ins->next;
11589         } while (ins != first);
11590         return triples;
11591 }
11592 struct dead_triple {
11593         struct triple *triple;
11594         struct dead_triple *work_next;
11595         struct block *block;
11596         int color;
11597         int flags;
11598 #define TRIPLE_FLAG_ALIVE 1
11599 };
11600
11601
11602 static void awaken(
11603         struct compile_state *state,
11604         struct dead_triple *dtriple, struct triple **expr,
11605         struct dead_triple ***work_list_tail)
11606 {
11607         struct triple *triple;
11608         struct dead_triple *dt;
11609         if (!expr) {
11610                 return;
11611         }
11612         triple = *expr;
11613         if (!triple) {
11614                 return;
11615         }
11616         if (triple->id <= 0)  {
11617                 internal_error(state, triple, "bad triple id: %d",
11618                         triple->id);
11619         }
11620         if (triple->op == OP_NOOP) {
11621                 internal_warning(state, triple, "awakening noop?");
11622                 return;
11623         }
11624         dt = &dtriple[triple->id];
11625         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11626                 dt->flags |= TRIPLE_FLAG_ALIVE;
11627                 if (!dt->work_next) {
11628                         **work_list_tail = dt;
11629                         *work_list_tail = &dt->work_next;
11630                 }
11631         }
11632 }
11633
11634 static void eliminate_inefectual_code(struct compile_state *state)
11635 {
11636         struct block *block;
11637         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
11638         int triples, i;
11639         struct triple *first, *ins;
11640
11641         /* Setup the work list */
11642         work_list = 0;
11643         work_list_tail = &work_list;
11644
11645         first = RHS(state->main_function, 0);
11646
11647         /* Count how many triples I have */
11648         triples = count_triples(state);
11649
11650         /* Now put then in an array and mark all of the triples dead */
11651         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
11652         
11653         ins = first;
11654         i = 1;
11655         block = 0;
11656         do {
11657                 if (ins->op == OP_LABEL) {
11658                         block = ins->u.block;
11659                 }
11660                 dtriple[i].triple = ins;
11661                 dtriple[i].block  = block;
11662                 dtriple[i].flags  = 0;
11663                 dtriple[i].color  = ins->id;
11664                 ins->id = i;
11665                 /* See if it is an operation we always keep */
11666 #warning "FIXME handle the case of killing a branch instruction"
11667                 if (!triple_is_pure(state, ins) || triple_is_branch(state, ins)) {
11668                         awaken(state, dtriple, &ins, &work_list_tail);
11669                 }
11670 #if 1
11671                 /* Unconditionally keep the very last instruction */
11672                 else if (ins->next == first) {
11673                         awaken(state, dtriple, &ins, &work_list_tail);
11674                 }
11675 #endif
11676                 i++;
11677                 ins = ins->next;
11678         } while(ins != first);
11679         while(work_list) {
11680                 struct dead_triple *dt;
11681                 struct block_set *user;
11682                 struct triple **expr;
11683                 dt = work_list;
11684                 work_list = dt->work_next;
11685                 if (!work_list) {
11686                         work_list_tail = &work_list;
11687                 }
11688                 /* Wake up the data depencencies of this triple */
11689                 expr = 0;
11690                 do {
11691                         expr = triple_rhs(state, dt->triple, expr);
11692                         awaken(state, dtriple, expr, &work_list_tail);
11693                 } while(expr);
11694                 do {
11695                         expr = triple_lhs(state, dt->triple, expr);
11696                         awaken(state, dtriple, expr, &work_list_tail);
11697                 } while(expr);
11698                 do {
11699                         expr = triple_misc(state, dt->triple, expr);
11700                         awaken(state, dtriple, expr, &work_list_tail);
11701                 } while(expr);
11702                 /* Wake up the forward control dependencies */
11703                 do {
11704                         expr = triple_targ(state, dt->triple, expr);
11705                         awaken(state, dtriple, expr, &work_list_tail);
11706                 } while(expr);
11707                 /* Wake up the reverse control dependencies of this triple */
11708                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
11709                         awaken(state, dtriple, &user->member->last, &work_list_tail);
11710                 }
11711         }
11712         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
11713                 if ((dt->triple->op == OP_NOOP) && 
11714                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
11715                         internal_error(state, dt->triple, "noop effective?");
11716                 }
11717                 dt->triple->id = dt->color;     /* Restore the color */
11718                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
11719 #warning "FIXME handle the case of killing a basic block"
11720                         if (dt->block->first == dt->triple) {
11721                                 continue;
11722                         }
11723                         if (dt->block->last == dt->triple) {
11724                                 dt->block->last = dt->triple->prev;
11725                         }
11726                         release_triple(state, dt->triple);
11727                 }
11728         }
11729         xfree(dtriple);
11730 }
11731
11732
11733 static void insert_mandatory_copies(struct compile_state *state)
11734 {
11735         struct triple *ins, *first;
11736
11737         /* The object is with a minimum of inserted copies,
11738          * to resolve in fundamental register conflicts between
11739          * register value producers and consumers.
11740          * Theoretically we may be greater than minimal when we
11741          * are inserting copies before instructions but that
11742          * case should be rare.
11743          */
11744         first = RHS(state->main_function, 0);
11745         ins = first;
11746         do {
11747                 struct triple_set *entry, *next;
11748                 struct triple *tmp;
11749                 struct reg_info info;
11750                 unsigned reg, regcm;
11751                 int do_post_copy, do_pre_copy;
11752                 tmp = 0;
11753                 if (!triple_is_def(state, ins)) {
11754                         goto next;
11755                 }
11756                 /* Find the architecture specific color information */
11757                 info = arch_reg_lhs(state, ins, 0);
11758                 if (info.reg >= MAX_REGISTERS) {
11759                         info.reg = REG_UNSET;
11760                 }
11761                 
11762                 reg = REG_UNSET;
11763                 regcm = arch_type_to_regcm(state, ins->type);
11764                 do_post_copy = do_pre_copy = 0;
11765
11766                 /* Walk through the uses of ins and check for conflicts */
11767                 for(entry = ins->use; entry; entry = next) {
11768                         struct reg_info rinfo;
11769                         int i;
11770                         next = entry->next;
11771                         i = find_rhs_use(state, entry->member, ins);
11772                         if (i < 0) {
11773                                 continue;
11774                         }
11775                         
11776                         /* Find the users color requirements */
11777                         rinfo = arch_reg_rhs(state, entry->member, i);
11778                         if (rinfo.reg >= MAX_REGISTERS) {
11779                                 rinfo.reg = REG_UNSET;
11780                         }
11781                         
11782                         /* See if I need a pre_copy */
11783                         if (rinfo.reg != REG_UNSET) {
11784                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
11785                                         do_pre_copy = 1;
11786                                 }
11787                                 reg = rinfo.reg;
11788                         }
11789                         regcm &= rinfo.regcm;
11790                         regcm = arch_regcm_normalize(state, regcm);
11791                         if (regcm == 0) {
11792                                 do_pre_copy = 1;
11793                         }
11794                         /* Always use pre_copies for constants.
11795                          * They do not take up any registers until a
11796                          * copy places them in one.
11797                          */
11798                         if ((info.reg == REG_UNNEEDED) && 
11799                                 (rinfo.reg != REG_UNNEEDED)) {
11800                                 do_pre_copy = 1;
11801                         }
11802                 }
11803                 do_post_copy =
11804                         !do_pre_copy &&
11805                         (((info.reg != REG_UNSET) && 
11806                                 (reg != REG_UNSET) &&
11807                                 (info.reg != reg)) ||
11808                         ((info.regcm & regcm) == 0));
11809
11810                 reg = info.reg;
11811                 regcm = info.regcm;
11812                 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
11813                 for(entry = ins->use; entry; entry = next) {
11814                         struct reg_info rinfo;
11815                         int i;
11816                         next = entry->next;
11817                         i = find_rhs_use(state, entry->member, ins);
11818                         if (i < 0) {
11819                                 continue;
11820                         }
11821                         
11822                         /* Find the users color requirements */
11823                         rinfo = arch_reg_rhs(state, entry->member, i);
11824                         if (rinfo.reg >= MAX_REGISTERS) {
11825                                 rinfo.reg = REG_UNSET;
11826                         }
11827
11828                         /* Now see if it is time to do the pre_copy */
11829                         if (rinfo.reg != REG_UNSET) {
11830                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
11831                                         ((regcm & rinfo.regcm) == 0) ||
11832                                         /* Don't let a mandatory coalesce sneak
11833                                          * into a operation that is marked to prevent
11834                                          * coalescing.
11835                                          */
11836                                         ((reg != REG_UNNEEDED) &&
11837                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
11838                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
11839                                         ) {
11840                                         if (do_pre_copy) {
11841                                                 struct triple *user;
11842                                                 user = entry->member;
11843                                                 if (RHS(user, i) != ins) {
11844                                                         internal_error(state, user, "bad rhs");
11845                                                 }
11846                                                 tmp = pre_copy(state, user, i);
11847                                                 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11848                                                 continue;
11849                                         } else {
11850                                                 do_post_copy = 1;
11851                                         }
11852                                 }
11853                                 reg = rinfo.reg;
11854                         }
11855                         if ((regcm & rinfo.regcm) == 0) {
11856                                 if (do_pre_copy) {
11857                                         struct triple *user;
11858                                         user = entry->member;
11859                                         if (RHS(user, i) != ins) {
11860                                                 internal_error(state, user, "bad rhs");
11861                                         }
11862                                         tmp = pre_copy(state, user, i);
11863                                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11864                                         continue;
11865                                 } else {
11866                                         do_post_copy = 1;
11867                                 }
11868                         }
11869                         regcm &= rinfo.regcm;
11870                         
11871                 }
11872                 if (do_post_copy) {
11873                         struct reg_info pre, post;
11874                         tmp = post_copy(state, ins);
11875                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
11876                         pre = arch_reg_lhs(state, ins, 0);
11877                         post = arch_reg_lhs(state, tmp, 0);
11878                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
11879                                 internal_error(state, tmp, "useless copy");
11880                         }
11881                 }
11882         next:
11883                 ins = ins->next;
11884         } while(ins != first);
11885 }
11886
11887
11888 struct live_range_edge;
11889 struct live_range_def;
11890 struct live_range {
11891         struct live_range_edge *edges;
11892         struct live_range_def *defs;
11893 /* Note. The list pointed to by defs is kept in order.
11894  * That is baring splits in the flow control
11895  * defs dominates defs->next wich dominates defs->next->next
11896  * etc.
11897  */
11898         unsigned color;
11899         unsigned classes;
11900         unsigned degree;
11901         unsigned length;
11902         struct live_range *group_next, **group_prev;
11903 };
11904
11905 struct live_range_edge {
11906         struct live_range_edge *next;
11907         struct live_range *node;
11908 };
11909
11910 struct live_range_def {
11911         struct live_range_def *next;
11912         struct live_range_def *prev;
11913         struct live_range *lr;
11914         struct triple *def;
11915         unsigned orig_id;
11916 };
11917
11918 #define LRE_HASH_SIZE 2048
11919 struct lre_hash {
11920         struct lre_hash *next;
11921         struct live_range *left;
11922         struct live_range *right;
11923 };
11924
11925
11926 struct reg_state {
11927         struct lre_hash *hash[LRE_HASH_SIZE];
11928         struct reg_block *blocks;
11929         struct live_range_def *lrd;
11930         struct live_range *lr;
11931         struct live_range *low, **low_tail;
11932         struct live_range *high, **high_tail;
11933         unsigned defs;
11934         unsigned ranges;
11935         int passes, max_passes;
11936 #define MAX_ALLOCATION_PASSES 100
11937 };
11938
11939
11940
11941 struct print_interference_block_info {
11942         struct reg_state *rstate;
11943         FILE *fp;
11944         int need_edges;
11945 };
11946 static void print_interference_block(
11947         struct compile_state *state, struct block *block, void *arg)
11948
11949 {
11950         struct print_interference_block_info *info = arg;
11951         struct reg_state *rstate = info->rstate;
11952         FILE *fp = info->fp;
11953         struct reg_block *rb;
11954         struct triple *ptr;
11955         int phi_present;
11956         int done;
11957         rb = &rstate->blocks[block->vertex];
11958
11959         fprintf(fp, "\nblock: %p (%d), %p<-%p %p<-%p\n", 
11960                 block, 
11961                 block->vertex,
11962                 block->left, 
11963                 block->left && block->left->use?block->left->use->member : 0,
11964                 block->right, 
11965                 block->right && block->right->use?block->right->use->member : 0);
11966         if (rb->in) {
11967                 struct triple_reg_set *in_set;
11968                 fprintf(fp, "        in:");
11969                 for(in_set = rb->in; in_set; in_set = in_set->next) {
11970                         fprintf(fp, " %-10p", in_set->member);
11971                 }
11972                 fprintf(fp, "\n");
11973         }
11974         phi_present = 0;
11975         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11976                 done = (ptr == block->last);
11977                 if (ptr->op == OP_PHI) {
11978                         phi_present = 1;
11979                         break;
11980                 }
11981         }
11982         if (phi_present) {
11983                 int edge;
11984                 for(edge = 0; edge < block->users; edge++) {
11985                         fprintf(fp, "     in(%d):", edge);
11986                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
11987                                 struct triple **slot;
11988                                 done = (ptr == block->last);
11989                                 if (ptr->op != OP_PHI) {
11990                                         continue;
11991                                 }
11992                                 slot = &RHS(ptr, 0);
11993                                 fprintf(fp, " %-10p", slot[edge]);
11994                         }
11995                         fprintf(fp, "\n");
11996                 }
11997         }
11998         if (block->first->op == OP_LABEL) {
11999                 fprintf(fp, "%p:\n", block->first);
12000         }
12001         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
12002                 struct live_range *lr;
12003                 unsigned id;
12004                 int op;
12005                 op = ptr->op;
12006                 done = (ptr == block->last);
12007                 lr = rstate->lrd[ptr->id].lr;
12008                 
12009                 id = ptr->id;
12010                 ptr->id = rstate->lrd[id].orig_id;
12011                 SET_REG(ptr->id, lr->color);
12012                 display_triple(fp, ptr);
12013                 ptr->id = id;
12014
12015                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
12016                         internal_error(state, ptr, "lr has no defs!");
12017                 }
12018                 if (info->need_edges) {
12019                         if (lr->defs) {
12020                                 struct live_range_def *lrd;
12021                                 fprintf(fp, "       range:");
12022                                 lrd = lr->defs;
12023                                 do {
12024                                         fprintf(fp, " %-10p", lrd->def);
12025                                         lrd = lrd->next;
12026                                 } while(lrd != lr->defs);
12027                                 fprintf(fp, "\n");
12028                         }
12029                         if (lr->edges > 0) {
12030                                 struct live_range_edge *edge;
12031                                 fprintf(fp, "       edges:");
12032                                 for(edge = lr->edges; edge; edge = edge->next) {
12033                                         struct live_range_def *lrd;
12034                                         lrd = edge->node->defs;
12035                                         do {
12036                                                 fprintf(fp, " %-10p", lrd->def);
12037                                                 lrd = lrd->next;
12038                                         } while(lrd != edge->node->defs);
12039                                         fprintf(fp, "|");
12040                                 }
12041                                 fprintf(fp, "\n");
12042                         }
12043                 }
12044                 /* Do a bunch of sanity checks */
12045                 valid_ins(state, ptr);
12046                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
12047                         internal_error(state, ptr, "Invalid triple id: %d",
12048                                 ptr->id);
12049                 }
12050         }
12051         if (rb->out) {
12052                 struct triple_reg_set *out_set;
12053                 fprintf(fp, "       out:");
12054                 for(out_set = rb->out; out_set; out_set = out_set->next) {
12055                         fprintf(fp, " %-10p", out_set->member);
12056                 }
12057                 fprintf(fp, "\n");
12058         }
12059         fprintf(fp, "\n");
12060 }
12061
12062 static void print_interference_blocks(
12063         struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
12064 {
12065         struct print_interference_block_info info;
12066         info.rstate = rstate;
12067         info.fp = fp;
12068         info.need_edges = need_edges;
12069         fprintf(fp, "\nlive variables by block\n");
12070         walk_blocks(state, print_interference_block, &info);
12071
12072 }
12073
12074 static unsigned regc_max_size(struct compile_state *state, int classes)
12075 {
12076         unsigned max_size;
12077         int i;
12078         max_size = 0;
12079         for(i = 0; i < MAX_REGC; i++) {
12080                 if (classes & (1 << i)) {
12081                         unsigned size;
12082                         size = arch_regc_size(state, i);
12083                         if (size > max_size) {
12084                                 max_size = size;
12085                         }
12086                 }
12087         }
12088         return max_size;
12089 }
12090
12091 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
12092 {
12093         unsigned equivs[MAX_REG_EQUIVS];
12094         int i;
12095         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
12096                 internal_error(state, 0, "invalid register");
12097         }
12098         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
12099                 internal_error(state, 0, "invalid register");
12100         }
12101         arch_reg_equivs(state, equivs, reg1);
12102         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12103                 if (equivs[i] == reg2) {
12104                         return 1;
12105                 }
12106         }
12107         return 0;
12108 }
12109
12110 static void reg_fill_used(struct compile_state *state, char *used, int reg)
12111 {
12112         unsigned equivs[MAX_REG_EQUIVS];
12113         int i;
12114         if (reg == REG_UNNEEDED) {
12115                 return;
12116         }
12117         arch_reg_equivs(state, equivs, reg);
12118         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12119                 used[equivs[i]] = 1;
12120         }
12121         return;
12122 }
12123
12124 static void reg_inc_used(struct compile_state *state, char *used, int reg)
12125 {
12126         unsigned equivs[MAX_REG_EQUIVS];
12127         int i;
12128         if (reg == REG_UNNEEDED) {
12129                 return;
12130         }
12131         arch_reg_equivs(state, equivs, reg);
12132         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
12133                 used[equivs[i]] += 1;
12134         }
12135         return;
12136 }
12137
12138 static unsigned int hash_live_edge(
12139         struct live_range *left, struct live_range *right)
12140 {
12141         unsigned int hash, val;
12142         unsigned long lval, rval;
12143         lval = ((unsigned long)left)/sizeof(struct live_range);
12144         rval = ((unsigned long)right)/sizeof(struct live_range);
12145         hash = 0;
12146         while(lval) {
12147                 val = lval & 0xff;
12148                 lval >>= 8;
12149                 hash = (hash *263) + val;
12150         }
12151         while(rval) {
12152                 val = rval & 0xff;
12153                 rval >>= 8;
12154                 hash = (hash *263) + val;
12155         }
12156         hash = hash & (LRE_HASH_SIZE - 1);
12157         return hash;
12158 }
12159
12160 static struct lre_hash **lre_probe(struct reg_state *rstate,
12161         struct live_range *left, struct live_range *right)
12162 {
12163         struct lre_hash **ptr;
12164         unsigned int index;
12165         /* Ensure left <= right */
12166         if (left > right) {
12167                 struct live_range *tmp;
12168                 tmp = left;
12169                 left = right;
12170                 right = tmp;
12171         }
12172         index = hash_live_edge(left, right);
12173         
12174         ptr = &rstate->hash[index];
12175         while(*ptr) {
12176                 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
12177                         break;
12178                 }
12179                 ptr = &(*ptr)->next;
12180         }
12181         return ptr;
12182 }
12183
12184 static int interfere(struct reg_state *rstate,
12185         struct live_range *left, struct live_range *right)
12186 {
12187         struct lre_hash **ptr;
12188         ptr = lre_probe(rstate, left, right);
12189         return ptr && *ptr;
12190 }
12191
12192 static void add_live_edge(struct reg_state *rstate, 
12193         struct live_range *left, struct live_range *right)
12194 {
12195         /* FIXME the memory allocation overhead is noticeable here... */
12196         struct lre_hash **ptr, *new_hash;
12197         struct live_range_edge *edge;
12198
12199         if (left == right) {
12200                 return;
12201         }
12202         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
12203                 return;
12204         }
12205         /* Ensure left <= right */
12206         if (left > right) {
12207                 struct live_range *tmp;
12208                 tmp = left;
12209                 left = right;
12210                 right = tmp;
12211         }
12212         ptr = lre_probe(rstate, left, right);
12213         if (*ptr) {
12214                 return;
12215         }
12216 #if 0
12217         fprintf(stderr, "new_live_edge(%p, %p)\n",
12218                 left, right);
12219 #endif
12220         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
12221         new_hash->next  = *ptr;
12222         new_hash->left  = left;
12223         new_hash->right = right;
12224         *ptr = new_hash;
12225
12226         edge = xmalloc(sizeof(*edge), "live_range_edge");
12227         edge->next   = left->edges;
12228         edge->node   = right;
12229         left->edges  = edge;
12230         left->degree += 1;
12231         
12232         edge = xmalloc(sizeof(*edge), "live_range_edge");
12233         edge->next    = right->edges;
12234         edge->node    = left;
12235         right->edges  = edge;
12236         right->degree += 1;
12237 }
12238
12239 static void remove_live_edge(struct reg_state *rstate,
12240         struct live_range *left, struct live_range *right)
12241 {
12242         struct live_range_edge *edge, **ptr;
12243         struct lre_hash **hptr, *entry;
12244         hptr = lre_probe(rstate, left, right);
12245         if (!hptr || !*hptr) {
12246                 return;
12247         }
12248         entry = *hptr;
12249         *hptr = entry->next;
12250         xfree(entry);
12251
12252         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
12253                 edge = *ptr;
12254                 if (edge->node == right) {
12255                         *ptr = edge->next;
12256                         memset(edge, 0, sizeof(*edge));
12257                         xfree(edge);
12258                         right->degree--;
12259                         break;
12260                 }
12261         }
12262         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
12263                 edge = *ptr;
12264                 if (edge->node == left) {
12265                         *ptr = edge->next;
12266                         memset(edge, 0, sizeof(*edge));
12267                         xfree(edge);
12268                         left->degree--;
12269                         break;
12270                 }
12271         }
12272 }
12273
12274 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
12275 {
12276         struct live_range_edge *edge, *next;
12277         for(edge = range->edges; edge; edge = next) {
12278                 next = edge->next;
12279                 remove_live_edge(rstate, range, edge->node);
12280         }
12281 }
12282
12283 static void transfer_live_edges(struct reg_state *rstate, 
12284         struct live_range *dest, struct live_range *src)
12285 {
12286         struct live_range_edge *edge, *next;
12287         for(edge = src->edges; edge; edge = next) {
12288                 struct live_range *other;
12289                 next = edge->next;
12290                 other = edge->node;
12291                 remove_live_edge(rstate, src, other);
12292                 add_live_edge(rstate, dest, other);
12293         }
12294 }
12295
12296
12297 /* Interference graph...
12298  * 
12299  * new(n) --- Return a graph with n nodes but no edges.
12300  * add(g,x,y) --- Return a graph including g with an between x and y
12301  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
12302  *                x and y in the graph g
12303  * degree(g, x) --- Return the degree of the node x in the graph g
12304  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
12305  *
12306  * Implement with a hash table && a set of adjcency vectors.
12307  * The hash table supports constant time implementations of add and interfere.
12308  * The adjacency vectors support an efficient implementation of neighbors.
12309  */
12310
12311 /* 
12312  *     +---------------------------------------------------+
12313  *     |         +--------------+                          |
12314  *     v         v              |                          |
12315  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
12316  *
12317  * -- In simplify implment optimistic coloring... (No backtracking)
12318  * -- Implement Rematerialization it is the only form of spilling we can perform
12319  *    Essentially this means dropping a constant from a register because
12320  *    we can regenerate it later.
12321  *
12322  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
12323  *     coalesce at phi points...
12324  * --- Bias coloring if at all possible do the coalesing a compile time.
12325  *
12326  *
12327  */
12328
12329 static void different_colored(
12330         struct compile_state *state, struct reg_state *rstate, 
12331         struct triple *parent, struct triple *ins)
12332 {
12333         struct live_range *lr;
12334         struct triple **expr;
12335         lr = rstate->lrd[ins->id].lr;
12336         expr = triple_rhs(state, ins, 0);
12337         for(;expr; expr = triple_rhs(state, ins, expr)) {
12338                 struct live_range *lr2;
12339                 if (!*expr || (*expr == parent) || (*expr == ins)) {
12340                         continue;
12341                 }
12342                 lr2 = rstate->lrd[(*expr)->id].lr;
12343                 if (lr->color == lr2->color) {
12344                         internal_error(state, ins, "live range too big");
12345                 }
12346         }
12347 }
12348
12349
12350 static struct live_range *coalesce_ranges(
12351         struct compile_state *state, struct reg_state *rstate,
12352         struct live_range *lr1, struct live_range *lr2)
12353 {
12354         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
12355         unsigned color;
12356         unsigned classes;
12357         if (lr1 == lr2) {
12358                 return lr1;
12359         }
12360         if (!lr1->defs || !lr2->defs) {
12361                 internal_error(state, 0,
12362                         "cannot coalese dead live ranges");
12363         }
12364         if ((lr1->color == REG_UNNEEDED) ||
12365                 (lr2->color == REG_UNNEEDED)) {
12366                 internal_error(state, 0, 
12367                         "cannot coalesce live ranges without a possible color");
12368         }
12369         if ((lr1->color != lr2->color) &&
12370                 (lr1->color != REG_UNSET) &&
12371                 (lr2->color != REG_UNSET)) {
12372                 internal_error(state, lr1->defs->def, 
12373                         "cannot coalesce live ranges of different colors");
12374         }
12375         color = lr1->color;
12376         if (color == REG_UNSET) {
12377                 color = lr2->color;
12378         }
12379         classes = lr1->classes & lr2->classes;
12380         if (!classes) {
12381                 internal_error(state, lr1->defs->def,
12382                         "cannot coalesce live ranges with dissimilar register classes");
12383         }
12384 #if DEBUG_COALESCING
12385         fprintf(stderr, "coalescing:");
12386         lrd = lr1->defs;
12387         do {
12388                 fprintf(stderr, " %p", lrd->def);
12389                 lrd = lrd->next;
12390         } while(lrd != lr1->defs);
12391         fprintf(stderr, " |");
12392         lrd = lr2->defs;
12393         do {
12394                 fprintf(stderr, " %p", lrd->def);
12395                 lrd = lrd->next;
12396         } while(lrd != lr2->defs);
12397         fprintf(stderr, "\n");
12398 #endif
12399         /* If there is a clear dominate live range put it in lr1,
12400          * For purposes of this test phi functions are
12401          * considered dominated by the definitions that feed into
12402          * them. 
12403          */
12404         if ((lr1->defs->prev->def->op == OP_PHI) ||
12405                 ((lr2->defs->prev->def->op != OP_PHI) &&
12406                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
12407                 struct live_range *tmp;
12408                 tmp = lr1;
12409                 lr1 = lr2;
12410                 lr2 = tmp;
12411         }
12412 #if 0
12413         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12414                 fprintf(stderr, "lr1 post\n");
12415         }
12416         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12417                 fprintf(stderr, "lr1 pre\n");
12418         }
12419         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
12420                 fprintf(stderr, "lr2 post\n");
12421         }
12422         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12423                 fprintf(stderr, "lr2 pre\n");
12424         }
12425 #endif
12426 #if 0
12427         fprintf(stderr, "coalesce color1(%p): %3d color2(%p) %3d\n",
12428                 lr1->defs->def,
12429                 lr1->color,
12430                 lr2->defs->def,
12431                 lr2->color);
12432 #endif
12433         
12434         /* Append lr2 onto lr1 */
12435 #warning "FIXME should this be a merge instead of a splice?"
12436         /* This FIXME item applies to the correctness of live_range_end 
12437          * and to the necessity of making multiple passes of coalesce_live_ranges.
12438          * A failure to find some coalesce opportunities in coaleace_live_ranges
12439          * does not impact the correct of the compiler just the efficiency with
12440          * which registers are allocated.
12441          */
12442         head = lr1->defs;
12443         mid1 = lr1->defs->prev;
12444         mid2 = lr2->defs;
12445         end  = lr2->defs->prev;
12446         
12447         head->prev = end;
12448         end->next  = head;
12449
12450         mid1->next = mid2;
12451         mid2->prev = mid1;
12452
12453         /* Fixup the live range in the added live range defs */
12454         lrd = head;
12455         do {
12456                 lrd->lr = lr1;
12457                 lrd = lrd->next;
12458         } while(lrd != head);
12459
12460         /* Mark lr2 as free. */
12461         lr2->defs = 0;
12462         lr2->color = REG_UNNEEDED;
12463         lr2->classes = 0;
12464
12465         if (!lr1->defs) {
12466                 internal_error(state, 0, "lr1->defs == 0 ?");
12467         }
12468
12469         lr1->color   = color;
12470         lr1->classes = classes;
12471
12472         /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
12473         transfer_live_edges(rstate, lr1, lr2);
12474
12475         return lr1;
12476 }
12477
12478 static struct live_range_def *live_range_head(
12479         struct compile_state *state, struct live_range *lr,
12480         struct live_range_def *last)
12481 {
12482         struct live_range_def *result;
12483         result = 0;
12484         if (last == 0) {
12485                 result = lr->defs;
12486         }
12487         else if (!tdominates(state, lr->defs->def, last->next->def)) {
12488                 result = last->next;
12489         }
12490         return result;
12491 }
12492
12493 static struct live_range_def *live_range_end(
12494         struct compile_state *state, struct live_range *lr,
12495         struct live_range_def *last)
12496 {
12497         struct live_range_def *result;
12498         result = 0;
12499         if (last == 0) {
12500                 result = lr->defs->prev;
12501         }
12502         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
12503                 result = last->prev;
12504         }
12505         return result;
12506 }
12507
12508
12509 static void initialize_live_ranges(
12510         struct compile_state *state, struct reg_state *rstate)
12511 {
12512         struct triple *ins, *first;
12513         size_t count, size;
12514         int i, j;
12515
12516         first = RHS(state->main_function, 0);
12517         /* First count how many instructions I have.
12518          */
12519         count = count_triples(state);
12520         /* Potentially I need one live range definitions for each
12521          * instruction.
12522          */
12523         rstate->defs = count;
12524         /* Potentially I need one live range for each instruction
12525          * plus an extra for the dummy live range.
12526          */
12527         rstate->ranges = count + 1;
12528         size = sizeof(rstate->lrd[0]) * rstate->defs;
12529         rstate->lrd = xcmalloc(size, "live_range_def");
12530         size = sizeof(rstate->lr[0]) * rstate->ranges;
12531         rstate->lr  = xcmalloc(size, "live_range");
12532
12533         /* Setup the dummy live range */
12534         rstate->lr[0].classes = 0;
12535         rstate->lr[0].color = REG_UNSET;
12536         rstate->lr[0].defs = 0;
12537         i = j = 0;
12538         ins = first;
12539         do {
12540                 /* If the triple is a variable give it a live range */
12541                 if (triple_is_def(state, ins)) {
12542                         struct reg_info info;
12543                         /* Find the architecture specific color information */
12544                         info = find_def_color(state, ins);
12545                         i++;
12546                         rstate->lr[i].defs    = &rstate->lrd[j];
12547                         rstate->lr[i].color   = info.reg;
12548                         rstate->lr[i].classes = info.regcm;
12549                         rstate->lr[i].degree  = 0;
12550                         rstate->lrd[j].lr = &rstate->lr[i];
12551                 } 
12552                 /* Otherwise give the triple the dummy live range. */
12553                 else {
12554                         rstate->lrd[j].lr = &rstate->lr[0];
12555                 }
12556
12557                 /* Initalize the live_range_def */
12558                 rstate->lrd[j].next    = &rstate->lrd[j];
12559                 rstate->lrd[j].prev    = &rstate->lrd[j];
12560                 rstate->lrd[j].def     = ins;
12561                 rstate->lrd[j].orig_id = ins->id;
12562                 ins->id = j;
12563
12564                 j++;
12565                 ins = ins->next;
12566         } while(ins != first);
12567         rstate->ranges = i;
12568
12569         /* Make a second pass to handle achitecture specific register
12570          * constraints.
12571          */
12572         ins = first;
12573         do {
12574                 int zlhs, zrhs, i, j;
12575                 if (ins->id > rstate->defs) {
12576                         internal_error(state, ins, "bad id");
12577                 }
12578                 
12579                 /* Walk through the template of ins and coalesce live ranges */
12580                 zlhs = TRIPLE_LHS(ins->sizes);
12581                 if ((zlhs == 0) && triple_is_def(state, ins)) {
12582                         zlhs = 1;
12583                 }
12584                 zrhs = TRIPLE_RHS(ins->sizes);
12585
12586 #if DEBUG_COALESCING > 1
12587                 fprintf(stderr, "mandatory coalesce: %p %d %d\n",
12588                         ins, zlhs, zrhs);
12589 #endif          
12590                 for(i = 0; i < zlhs; i++) {
12591                         struct reg_info linfo;
12592                         struct live_range_def *lhs;
12593                         linfo = arch_reg_lhs(state, ins, i);
12594                         if (linfo.reg < MAX_REGISTERS) {
12595                                 continue;
12596                         }
12597                         if (triple_is_def(state, ins)) {
12598                                 lhs = &rstate->lrd[ins->id];
12599                         } else {
12600                                 lhs = &rstate->lrd[LHS(ins, i)->id];
12601                         }
12602 #if DEBUG_COALESCING > 1
12603                         fprintf(stderr, "coalesce lhs(%d): %p %d\n",
12604                                 i, lhs, linfo.reg);
12605                 
12606 #endif          
12607                         for(j = 0; j < zrhs; j++) {
12608                                 struct reg_info rinfo;
12609                                 struct live_range_def *rhs;
12610                                 rinfo = arch_reg_rhs(state, ins, j);
12611                                 if (rinfo.reg < MAX_REGISTERS) {
12612                                         continue;
12613                                 }
12614                                 rhs = &rstate->lrd[RHS(ins, j)->id];
12615 #if DEBUG_COALESCING > 1
12616                                 fprintf(stderr, "coalesce rhs(%d): %p %d\n",
12617                                         j, rhs, rinfo.reg);
12618                 
12619 #endif          
12620                                 if (rinfo.reg == linfo.reg) {
12621                                         coalesce_ranges(state, rstate, 
12622                                                 lhs->lr, rhs->lr);
12623                                 }
12624                         }
12625                 }
12626                 ins = ins->next;
12627         } while(ins != first);
12628 }
12629
12630 static void graph_ins(
12631         struct compile_state *state, 
12632         struct reg_block *blocks, struct triple_reg_set *live, 
12633         struct reg_block *rb, struct triple *ins, void *arg)
12634 {
12635         struct reg_state *rstate = arg;
12636         struct live_range *def;
12637         struct triple_reg_set *entry;
12638
12639         /* If the triple is not a definition
12640          * we do not have a definition to add to
12641          * the interference graph.
12642          */
12643         if (!triple_is_def(state, ins)) {
12644                 return;
12645         }
12646         def = rstate->lrd[ins->id].lr;
12647         
12648         /* Create an edge between ins and everything that is
12649          * alive, unless the live_range cannot share
12650          * a physical register with ins.
12651          */
12652         for(entry = live; entry; entry = entry->next) {
12653                 struct live_range *lr;
12654                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
12655                         internal_error(state, 0, "bad entry?");
12656                 }
12657                 lr = rstate->lrd[entry->member->id].lr;
12658                 if (def == lr) {
12659                         continue;
12660                 }
12661                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
12662                         continue;
12663                 }
12664                 add_live_edge(rstate, def, lr);
12665         }
12666         return;
12667 }
12668
12669 static struct live_range *get_verify_live_range(
12670         struct compile_state *state, struct reg_state *rstate, struct triple *ins)
12671 {
12672         struct live_range *lr;
12673         struct live_range_def *lrd;
12674         int ins_found;
12675         if ((ins->id < 0) || (ins->id > rstate->defs)) {
12676                 internal_error(state, ins, "bad ins?");
12677         }
12678         lr = rstate->lrd[ins->id].lr;
12679         ins_found = 0;
12680         lrd = lr->defs;
12681         do {
12682                 if (lrd->def == ins) {
12683                         ins_found = 1;
12684                 }
12685                 lrd = lrd->next;
12686         } while(lrd != lr->defs);
12687         if (!ins_found) {
12688                 internal_error(state, ins, "ins not in live range");
12689         }
12690         return lr;
12691 }
12692
12693 static void verify_graph_ins(
12694         struct compile_state *state, 
12695         struct reg_block *blocks, struct triple_reg_set *live, 
12696         struct reg_block *rb, struct triple *ins, void *arg)
12697 {
12698         struct reg_state *rstate = arg;
12699         struct triple_reg_set *entry1, *entry2;
12700
12701
12702         /* Compare live against edges and make certain the code is working */
12703         for(entry1 = live; entry1; entry1 = entry1->next) {
12704                 struct live_range *lr1;
12705                 lr1 = get_verify_live_range(state, rstate, entry1->member);
12706                 for(entry2 = live; entry2; entry2 = entry2->next) {
12707                         struct live_range *lr2;
12708                         struct live_range_edge *edge2;
12709                         int lr1_found;
12710                         int lr2_degree;
12711                         if (entry2 == entry1) {
12712                                 continue;
12713                         }
12714                         lr2 = get_verify_live_range(state, rstate, entry2->member);
12715                         if (lr1 == lr2) {
12716                                 internal_error(state, entry2->member, 
12717                                         "live range with 2 values simultaneously alive");
12718                         }
12719                         if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
12720                                 continue;
12721                         }
12722                         if (!interfere(rstate, lr1, lr2)) {
12723                                 internal_error(state, entry2->member, 
12724                                         "edges don't interfere?");
12725                         }
12726                                 
12727                         lr1_found = 0;
12728                         lr2_degree = 0;
12729                         for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
12730                                 lr2_degree++;
12731                                 if (edge2->node == lr1) {
12732                                         lr1_found = 1;
12733                                 }
12734                         }
12735                         if (lr2_degree != lr2->degree) {
12736                                 internal_error(state, entry2->member,
12737                                         "computed degree: %d does not match reported degree: %d\n",
12738                                         lr2_degree, lr2->degree);
12739                         }
12740                         if (!lr1_found) {
12741                                 internal_error(state, entry2->member, "missing edge");
12742                         }
12743                 }
12744         }
12745         return;
12746 }
12747
12748
12749 static void print_interference_ins(
12750         struct compile_state *state, 
12751         struct reg_block *blocks, struct triple_reg_set *live, 
12752         struct reg_block *rb, struct triple *ins, void *arg)
12753 {
12754         struct reg_state *rstate = arg;
12755         struct live_range *lr;
12756         unsigned id;
12757
12758         lr = rstate->lrd[ins->id].lr;
12759         id = ins->id;
12760         ins->id = rstate->lrd[id].orig_id;
12761         SET_REG(ins->id, lr->color);
12762         display_triple(stdout, ins);
12763         ins->id = id;
12764
12765         if (lr->defs) {
12766                 struct live_range_def *lrd;
12767                 printf("       range:");
12768                 lrd = lr->defs;
12769                 do {
12770                         printf(" %-10p", lrd->def);
12771                         lrd = lrd->next;
12772                 } while(lrd != lr->defs);
12773                 printf("\n");
12774         }
12775         if (live) {
12776                 struct triple_reg_set *entry;
12777                 printf("        live:");
12778                 for(entry = live; entry; entry = entry->next) {
12779                         printf(" %-10p", entry->member);
12780                 }
12781                 printf("\n");
12782         }
12783         if (lr->edges) {
12784                 struct live_range_edge *entry;
12785                 printf("       edges:");
12786                 for(entry = lr->edges; entry; entry = entry->next) {
12787                         struct live_range_def *lrd;
12788                         lrd = entry->node->defs;
12789                         do {
12790                                 printf(" %-10p", lrd->def);
12791                                 lrd = lrd->next;
12792                         } while(lrd != entry->node->defs);
12793                         printf("|");
12794                 }
12795                 printf("\n");
12796         }
12797         if (triple_is_branch(state, ins)) {
12798                 printf("\n");
12799         }
12800         return;
12801 }
12802
12803 static int coalesce_live_ranges(
12804         struct compile_state *state, struct reg_state *rstate)
12805 {
12806         /* At the point where a value is moved from one
12807          * register to another that value requires two
12808          * registers, thus increasing register pressure.
12809          * Live range coaleescing reduces the register
12810          * pressure by keeping a value in one register
12811          * longer.
12812          *
12813          * In the case of a phi function all paths leading
12814          * into it must be allocated to the same register
12815          * otherwise the phi function may not be removed.
12816          *
12817          * Forcing a value to stay in a single register
12818          * for an extended period of time does have
12819          * limitations when applied to non homogenous
12820          * register pool.  
12821          *
12822          * The two cases I have identified are:
12823          * 1) Two forced register assignments may
12824          *    collide.
12825          * 2) Registers may go unused because they
12826          *    are only good for storing the value
12827          *    and not manipulating it.
12828          *
12829          * Because of this I need to split live ranges,
12830          * even outside of the context of coalesced live
12831          * ranges.  The need to split live ranges does
12832          * impose some constraints on live range coalescing.
12833          *
12834          * - Live ranges may not be coalesced across phi
12835          *   functions.  This creates a 2 headed live
12836          *   range that cannot be sanely split.
12837          *
12838          * - phi functions (coalesced in initialize_live_ranges) 
12839          *   are handled as pre split live ranges so we will
12840          *   never attempt to split them.
12841          */
12842         int coalesced;
12843         int i;
12844
12845         coalesced = 0;
12846         for(i = 0; i <= rstate->ranges; i++) {
12847                 struct live_range *lr1;
12848                 struct live_range_def *lrd1;
12849                 lr1 = &rstate->lr[i];
12850                 if (!lr1->defs) {
12851                         continue;
12852                 }
12853                 lrd1 = live_range_end(state, lr1, 0);
12854                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
12855                         struct triple_set *set;
12856                         if (lrd1->def->op != OP_COPY) {
12857                                 continue;
12858                         }
12859                         /* Skip copies that are the result of a live range split. */
12860                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
12861                                 continue;
12862                         }
12863                         for(set = lrd1->def->use; set; set = set->next) {
12864                                 struct live_range_def *lrd2;
12865                                 struct live_range *lr2, *res;
12866
12867                                 lrd2 = &rstate->lrd[set->member->id];
12868
12869                                 /* Don't coalesce with instructions
12870                                  * that are the result of a live range
12871                                  * split.
12872                                  */
12873                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
12874                                         continue;
12875                                 }
12876                                 lr2 = rstate->lrd[set->member->id].lr;
12877                                 if (lr1 == lr2) {
12878                                         continue;
12879                                 }
12880                                 if ((lr1->color != lr2->color) &&
12881                                         (lr1->color != REG_UNSET) &&
12882                                         (lr2->color != REG_UNSET)) {
12883                                         continue;
12884                                 }
12885                                 if ((lr1->classes & lr2->classes) == 0) {
12886                                         continue;
12887                                 }
12888                                 
12889                                 if (interfere(rstate, lr1, lr2)) {
12890                                         continue;
12891                                 }
12892
12893                                 res = coalesce_ranges(state, rstate, lr1, lr2);
12894                                 coalesced += 1;
12895                                 if (res != lr1) {
12896                                         goto next;
12897                                 }
12898                         }
12899                 }
12900         next:
12901                 ;
12902         }
12903         return coalesced;
12904 }
12905
12906
12907 static void fix_coalesce_conflicts(struct compile_state *state,
12908         struct reg_block *blocks, struct triple_reg_set *live,
12909         struct reg_block *rb, struct triple *ins, void *arg)
12910 {
12911         int *conflicts = arg;
12912         int zlhs, zrhs, i, j;
12913
12914         /* See if we have a mandatory coalesce operation between
12915          * a lhs and a rhs value.  If so and the rhs value is also
12916          * alive then this triple needs to be pre copied.  Otherwise
12917          * we would have two definitions in the same live range simultaneously
12918          * alive.
12919          */
12920         zlhs = TRIPLE_LHS(ins->sizes);
12921         if ((zlhs == 0) && triple_is_def(state, ins)) {
12922                 zlhs = 1;
12923         }
12924         zrhs = TRIPLE_RHS(ins->sizes);
12925         for(i = 0; i < zlhs; i++) {
12926                 struct reg_info linfo;
12927                 linfo = arch_reg_lhs(state, ins, i);
12928                 if (linfo.reg < MAX_REGISTERS) {
12929                         continue;
12930                 }
12931                 for(j = 0; j < zrhs; j++) {
12932                         struct reg_info rinfo;
12933                         struct triple *rhs;
12934                         struct triple_reg_set *set;
12935                         int found;
12936                         found = 0;
12937                         rinfo = arch_reg_rhs(state, ins, j);
12938                         if (rinfo.reg != linfo.reg) {
12939                                 continue;
12940                         }
12941                         rhs = RHS(ins, j);
12942                         for(set = live; set && !found; set = set->next) {
12943                                 if (set->member == rhs) {
12944                                         found = 1;
12945                                 }
12946                         }
12947                         if (found) {
12948                                 struct triple *copy;
12949                                 copy = pre_copy(state, ins, j);
12950                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
12951                                 (*conflicts)++;
12952                         }
12953                 }
12954         }
12955         return;
12956 }
12957
12958 static int correct_coalesce_conflicts(
12959         struct compile_state *state, struct reg_block *blocks)
12960 {
12961         int conflicts;
12962         conflicts = 0;
12963         walk_variable_lifetimes(state, blocks, fix_coalesce_conflicts, &conflicts);
12964         return conflicts;
12965 }
12966
12967 static void replace_set_use(struct compile_state *state,
12968         struct triple_reg_set *head, struct triple *orig, struct triple *new)
12969 {
12970         struct triple_reg_set *set;
12971         for(set = head; set; set = set->next) {
12972                 if (set->member == orig) {
12973                         set->member = new;
12974                 }
12975         }
12976 }
12977
12978 static void replace_block_use(struct compile_state *state, 
12979         struct reg_block *blocks, struct triple *orig, struct triple *new)
12980 {
12981         int i;
12982 #warning "WISHLIST visit just those blocks that need it *"
12983         for(i = 1; i <= state->last_vertex; i++) {
12984                 struct reg_block *rb;
12985                 rb = &blocks[i];
12986                 replace_set_use(state, rb->in, orig, new);
12987                 replace_set_use(state, rb->out, orig, new);
12988         }
12989 }
12990
12991 static void color_instructions(struct compile_state *state)
12992 {
12993         struct triple *ins, *first;
12994         first = RHS(state->main_function, 0);
12995         ins = first;
12996         do {
12997                 if (triple_is_def(state, ins)) {
12998                         struct reg_info info;
12999                         info = find_lhs_color(state, ins, 0);
13000                         if (info.reg >= MAX_REGISTERS) {
13001                                 info.reg = REG_UNSET;
13002                         }
13003                         SET_INFO(ins->id, info);
13004                 }
13005                 ins = ins->next;
13006         } while(ins != first);
13007 }
13008
13009 static struct reg_info read_lhs_color(
13010         struct compile_state *state, struct triple *ins, int index)
13011 {
13012         struct reg_info info;
13013         if ((index == 0) && triple_is_def(state, ins)) {
13014                 info.reg   = ID_REG(ins->id);
13015                 info.regcm = ID_REGCM(ins->id);
13016         }
13017         else if (index < TRIPLE_LHS(ins->sizes)) {
13018                 info = read_lhs_color(state, LHS(ins, index), 0);
13019         }
13020         else {
13021                 internal_error(state, ins, "Bad lhs %d", index);
13022                 info.reg = REG_UNSET;
13023                 info.regcm = 0;
13024         }
13025         return info;
13026 }
13027
13028 static struct triple *resolve_tangle(
13029         struct compile_state *state, struct triple *tangle)
13030 {
13031         struct reg_info info, uinfo;
13032         struct triple_set *set, *next;
13033         struct triple *copy;
13034
13035 #warning "WISHLIST recalculate all affected instructions colors"
13036         info = find_lhs_color(state, tangle, 0);
13037         for(set = tangle->use; set; set = next) {
13038                 struct triple *user;
13039                 int i, zrhs;
13040                 next = set->next;
13041                 user = set->member;
13042                 zrhs = TRIPLE_RHS(user->sizes);
13043                 for(i = 0; i < zrhs; i++) {
13044                         if (RHS(user, i) != tangle) {
13045                                 continue;
13046                         }
13047                         uinfo = find_rhs_post_color(state, user, i);
13048                         if (uinfo.reg == info.reg) {
13049                                 copy = pre_copy(state, user, i);
13050                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13051                                 SET_INFO(copy->id, uinfo);
13052                         }
13053                 }
13054         }
13055         copy = 0;
13056         uinfo = find_lhs_pre_color(state, tangle, 0);
13057         if (uinfo.reg == info.reg) {
13058                 struct reg_info linfo;
13059                 copy = post_copy(state, tangle);
13060                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
13061                 linfo = find_lhs_color(state, copy, 0);
13062                 SET_INFO(copy->id, linfo);
13063         }
13064         info = find_lhs_color(state, tangle, 0);
13065         SET_INFO(tangle->id, info);
13066         
13067         return copy;
13068 }
13069
13070
13071 static void fix_tangles(struct compile_state *state,
13072         struct reg_block *blocks, struct triple_reg_set *live,
13073         struct reg_block *rb, struct triple *ins, void *arg)
13074 {
13075         int *tangles = arg;
13076         struct triple *tangle;
13077         do {
13078                 char used[MAX_REGISTERS];
13079                 struct triple_reg_set *set;
13080                 tangle = 0;
13081
13082                 /* Find out which registers have multiple uses at this point */
13083                 memset(used, 0, sizeof(used));
13084                 for(set = live; set; set = set->next) {
13085                         struct reg_info info;
13086                         info = read_lhs_color(state, set->member, 0);
13087                         if (info.reg == REG_UNSET) {
13088                                 continue;
13089                         }
13090                         reg_inc_used(state, used, info.reg);
13091                 }
13092                 
13093                 /* Now find the least dominated definition of a register in
13094                  * conflict I have seen so far.
13095                  */
13096                 for(set = live; set; set = set->next) {
13097                         struct reg_info info;
13098                         info = read_lhs_color(state, set->member, 0);
13099                         if (used[info.reg] < 2) {
13100                                 continue;
13101                         }
13102                         /* Changing copies that feed into phi functions
13103                          * is incorrect.
13104                          */
13105                         if (set->member->use && 
13106                                 (set->member->use->member->op == OP_PHI)) {
13107                                 continue;
13108                         }
13109                         if (!tangle || tdominates(state, set->member, tangle)) {
13110                                 tangle = set->member;
13111                         }
13112                 }
13113                 /* If I have found a tangle resolve it */
13114                 if (tangle) {
13115                         struct triple *post_copy;
13116                         (*tangles)++;
13117                         post_copy = resolve_tangle(state, tangle);
13118                         if (post_copy) {
13119                                 replace_block_use(state, blocks, tangle, post_copy);
13120                         }
13121                         if (post_copy && (tangle != ins)) {
13122                                 replace_set_use(state, live, tangle, post_copy);
13123                         }
13124                 }
13125         } while(tangle);
13126         return;
13127 }
13128
13129 static int correct_tangles(
13130         struct compile_state *state, struct reg_block *blocks)
13131 {
13132         int tangles;
13133         tangles = 0;
13134         color_instructions(state);
13135         walk_variable_lifetimes(state, blocks, fix_tangles, &tangles);
13136         return tangles;
13137 }
13138
13139
13140 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
13141 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
13142
13143 struct triple *find_constrained_def(
13144         struct compile_state *state, struct live_range *range, struct triple *constrained)
13145 {
13146         struct live_range_def *lrd;
13147         lrd = range->defs;
13148         do {
13149                 struct reg_info info;
13150                 unsigned regcm;
13151                 int is_constrained;
13152                 regcm = arch_type_to_regcm(state, lrd->def->type);
13153                 info = find_lhs_color(state, lrd->def, 0);
13154                 regcm      = arch_regcm_reg_normalize(state, regcm);
13155                 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
13156                 /* If the 2 register class masks are not equal the
13157                  * the current register class is constrained.
13158                  */
13159                 is_constrained = regcm != info.regcm;
13160                 
13161                 /* Of the constrained live ranges deal with the
13162                  * least dominated one first.
13163                  */
13164                 if (is_constrained) {
13165 #if DEBUG_RANGE_CONFLICTS
13166                         fprintf(stderr, "canidate: %p %-8s regcm: %x %x\n",
13167                                 lrd->def, tops(lrd->def->op), regcm, info.regcm);
13168 #endif
13169                         if (!constrained || 
13170                                 tdominates(state, lrd->def, constrained))
13171                         {
13172                                 constrained = lrd->def;
13173                         }
13174                 }
13175                 lrd = lrd->next;
13176         } while(lrd != range->defs);
13177         return constrained;
13178 }
13179
13180 static int split_constrained_ranges(
13181         struct compile_state *state, struct reg_state *rstate, 
13182         struct live_range *range)
13183 {
13184         /* Walk through the edges in conflict and our current live
13185          * range, and find definitions that are more severly constrained
13186          * than they type of data they contain require.
13187          * 
13188          * Then pick one of those ranges and relax the constraints.
13189          */
13190         struct live_range_edge *edge;
13191         struct triple *constrained;
13192
13193         constrained = 0;
13194         for(edge = range->edges; edge; edge = edge->next) {
13195                 constrained = find_constrained_def(state, edge->node, constrained);
13196         }
13197         if (!constrained) {
13198                 constrained = find_constrained_def(state, range, constrained);
13199         }
13200 #if DEBUG_RANGE_CONFLICTS
13201         fprintf(stderr, "constrained: %p %-8s\n",
13202                 constrained, tops(constrained->op));
13203 #endif
13204         if (constrained) {
13205                 ids_from_rstate(state, rstate);
13206                 cleanup_rstate(state, rstate);
13207                 resolve_tangle(state, constrained);
13208         }
13209         return !!constrained;
13210 }
13211         
13212 static int split_ranges(
13213         struct compile_state *state, struct reg_state *rstate,
13214         char *used, struct live_range *range)
13215 {
13216         int split;
13217 #if DEBUG_RANGE_CONFLICTS
13218         fprintf(stderr, "split_ranges %d %s %p\n", 
13219                 rstate->passes, tops(range->defs->def->op), range->defs->def);
13220 #endif
13221         if ((range->color == REG_UNNEEDED) ||
13222                 (rstate->passes >= rstate->max_passes)) {
13223                 return 0;
13224         }
13225         split = split_constrained_ranges(state, rstate, range);
13226
13227         /* Ideally I would split the live range that will not be used
13228          * for the longest period of time in hopes that this will 
13229          * (a) allow me to spill a register or
13230          * (b) allow me to place a value in another register.
13231          *
13232          * So far I don't have a test case for this, the resolving
13233          * of mandatory constraints has solved all of my
13234          * know issues.  So I have choosen not to write any
13235          * code until I cat get a better feel for cases where
13236          * it would be useful to have.
13237          *
13238          */
13239 #warning "WISHLIST implement live range splitting..."
13240         if ((DEBUG_RANGE_CONFLICTS > 1) && 
13241                 (!split || (DEBUG_RANGE_CONFLICTS > 2))) {
13242                 print_interference_blocks(state, rstate, stderr, 0);
13243                 print_dominators(state, stderr);
13244         }
13245         return split;
13246 }
13247
13248 #if DEBUG_COLOR_GRAPH > 1
13249 #define cgdebug_printf(...) fprintf(stdout, __VA_ARGS__)
13250 #define cgdebug_flush() fflush(stdout)
13251 #define cgdebug_loc(STATE, TRIPLE) loc(stdout, STATE, TRIPLE)
13252 #elif DEBUG_COLOR_GRAPH == 1
13253 #define cgdebug_printf(...) fprintf(stderr, __VA_ARGS__)
13254 #define cgdebug_flush() fflush(stderr)
13255 #define cgdebug_loc(STATE, TRIPLE) loc(stderr, STATE, TRIPLE)
13256 #else
13257 #define cgdebug_printf(...)
13258 #define cgdebug_flush()
13259 #define cgdebug_loc(STATE, TRIPLE)
13260 #endif
13261
13262         
13263 static int select_free_color(struct compile_state *state, 
13264         struct reg_state *rstate, struct live_range *range)
13265 {
13266         struct triple_set *entry;
13267         struct live_range_def *lrd;
13268         struct live_range_def *phi;
13269         struct live_range_edge *edge;
13270         char used[MAX_REGISTERS];
13271         struct triple **expr;
13272
13273         /* Instead of doing just the trivial color select here I try
13274          * a few extra things because a good color selection will help reduce
13275          * copies.
13276          */
13277
13278         /* Find the registers currently in use */
13279         memset(used, 0, sizeof(used));
13280         for(edge = range->edges; edge; edge = edge->next) {
13281                 if (edge->node->color == REG_UNSET) {
13282                         continue;
13283                 }
13284                 reg_fill_used(state, used, edge->node->color);
13285         }
13286 #if DEBUG_COLOR_GRAPH > 1
13287         {
13288                 int i;
13289                 i = 0;
13290                 for(edge = range->edges; edge; edge = edge->next) {
13291                         i++;
13292                 }
13293                 cgdebug_printf("\n%s edges: %d @%s:%d.%d\n", 
13294                         tops(range->def->op), i, 
13295                         range->def->filename, range->def->line, range->def->col);
13296                 for(i = 0; i < MAX_REGISTERS; i++) {
13297                         if (used[i]) {
13298                                 cgdebug_printf("used: %s\n",
13299                                         arch_reg_str(i));
13300                         }
13301                 }
13302         }       
13303 #endif
13304
13305         /* If a color is already assigned see if it will work */
13306         if (range->color != REG_UNSET) {
13307                 struct live_range_def *lrd;
13308                 if (!used[range->color]) {
13309                         return 1;
13310                 }
13311                 for(edge = range->edges; edge; edge = edge->next) {
13312                         if (edge->node->color != range->color) {
13313                                 continue;
13314                         }
13315                         warning(state, edge->node->defs->def, "edge: ");
13316                         lrd = edge->node->defs;
13317                         do {
13318                                 warning(state, lrd->def, " %p %s",
13319                                         lrd->def, tops(lrd->def->op));
13320                                 lrd = lrd->next;
13321                         } while(lrd != edge->node->defs);
13322                 }
13323                 lrd = range->defs;
13324                 warning(state, range->defs->def, "def: ");
13325                 do {
13326                         warning(state, lrd->def, " %p %s",
13327                                 lrd->def, tops(lrd->def->op));
13328                         lrd = lrd->next;
13329                 } while(lrd != range->defs);
13330                 internal_error(state, range->defs->def,
13331                         "live range with already used color %s",
13332                         arch_reg_str(range->color));
13333         }
13334
13335         /* If I feed into an expression reuse it's color.
13336          * This should help remove copies in the case of 2 register instructions
13337          * and phi functions.
13338          */
13339         phi = 0;
13340         lrd = live_range_end(state, range, 0);
13341         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
13342                 entry = lrd->def->use;
13343                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
13344                         struct live_range_def *insd;
13345                         unsigned regcm;
13346                         insd = &rstate->lrd[entry->member->id];
13347                         if (insd->lr->defs == 0) {
13348                                 continue;
13349                         }
13350                         if (!phi && (insd->def->op == OP_PHI) &&
13351                                 !interfere(rstate, range, insd->lr)) {
13352                                 phi = insd;
13353                         }
13354                         if (insd->lr->color == REG_UNSET) {
13355                                 continue;
13356                         }
13357                         regcm = insd->lr->classes;
13358                         if (((regcm & range->classes) == 0) ||
13359                                 (used[insd->lr->color])) {
13360                                 continue;
13361                         }
13362                         if (interfere(rstate, range, insd->lr)) {
13363                                 continue;
13364                         }
13365                         range->color = insd->lr->color;
13366                 }
13367         }
13368         /* If I feed into a phi function reuse it's color or the color
13369          * of something else that feeds into the phi function.
13370          */
13371         if (phi) {
13372                 if (phi->lr->color != REG_UNSET) {
13373                         if (used[phi->lr->color]) {
13374                                 range->color = phi->lr->color;
13375                         }
13376                 }
13377                 else {
13378                         expr = triple_rhs(state, phi->def, 0);
13379                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
13380                                 struct live_range *lr;
13381                                 unsigned regcm;
13382                                 if (!*expr) {
13383                                         continue;
13384                                 }
13385                                 lr = rstate->lrd[(*expr)->id].lr;
13386                                 if (lr->color == REG_UNSET) {
13387                                         continue;
13388                                 }
13389                                 regcm = lr->classes;
13390                                 if (((regcm & range->classes) == 0) ||
13391                                         (used[lr->color])) {
13392                                         continue;
13393                                 }
13394                                 if (interfere(rstate, range, lr)) {
13395                                         continue;
13396                                 }
13397                                 range->color = lr->color;
13398                         }
13399                 }
13400         }
13401         /* If I don't interfere with a rhs node reuse it's color */
13402         lrd = live_range_head(state, range, 0);
13403         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
13404                 expr = triple_rhs(state, lrd->def, 0);
13405                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
13406                         struct live_range *lr;
13407                         unsigned regcm;
13408                         if (!*expr) {
13409                                 continue;
13410                         }
13411                         lr = rstate->lrd[(*expr)->id].lr;
13412                         if (lr->color == REG_UNSET) {
13413                                 continue;
13414                         }
13415                         regcm = lr->classes;
13416                         if (((regcm & range->classes) == 0) ||
13417                                 (used[lr->color])) {
13418                                 continue;
13419                         }
13420                         if (interfere(rstate, range, lr)) {
13421                                 continue;
13422                         }
13423                         range->color = lr->color;
13424                         break;
13425                 }
13426         }
13427         /* If I have not opportunitically picked a useful color
13428          * pick the first color that is free.
13429          */
13430         if (range->color == REG_UNSET) {
13431                 range->color = 
13432                         arch_select_free_register(state, used, range->classes);
13433         }
13434         if (range->color == REG_UNSET) {
13435                 struct live_range_def *lrd;
13436                 int i;
13437                 if (split_ranges(state, rstate, used, range)) {
13438                         return 0;
13439                 }
13440                 for(edge = range->edges; edge; edge = edge->next) {
13441                         warning(state, edge->node->defs->def, "edge reg %s",
13442                                 arch_reg_str(edge->node->color));
13443                         lrd = edge->node->defs;
13444                         do {
13445                                 warning(state, lrd->def, " %s %p",
13446                                         tops(lrd->def->op), lrd->def);
13447                                 lrd = lrd->next;
13448                         } while(lrd != edge->node->defs);
13449                 }
13450                 warning(state, range->defs->def, "range: ");
13451                 lrd = range->defs;
13452                 do {
13453                         warning(state, lrd->def, " %s %p",
13454                                 tops(lrd->def->op), lrd->def);
13455                         lrd = lrd->next;
13456                 } while(lrd != range->defs);
13457                         
13458                 warning(state, range->defs->def, "classes: %x",
13459                         range->classes);
13460                 for(i = 0; i < MAX_REGISTERS; i++) {
13461                         if (used[i]) {
13462                                 warning(state, range->defs->def, "used: %s",
13463                                         arch_reg_str(i));
13464                         }
13465                 }
13466 #if DEBUG_COLOR_GRAPH < 2
13467                 error(state, range->defs->def, "too few registers");
13468 #else
13469                 internal_error(state, range->defs->def, "too few registers");
13470 #endif
13471         }
13472         range->classes &= arch_reg_regcm(state, range->color);
13473         if ((range->color == REG_UNSET) || (range->classes == 0)) {
13474                 internal_error(state, range->defs->def, "select_free_color did not?");
13475         }
13476         return 1;
13477 }
13478
13479 static int color_graph(struct compile_state *state, struct reg_state *rstate)
13480 {
13481         int colored;
13482         struct live_range_edge *edge;
13483         struct live_range *range;
13484         if (rstate->low) {
13485                 cgdebug_printf("Lo: ");
13486                 range = rstate->low;
13487                 if (*range->group_prev != range) {
13488                         internal_error(state, 0, "lo: *prev != range?");
13489                 }
13490                 *range->group_prev = range->group_next;
13491                 if (range->group_next) {
13492                         range->group_next->group_prev = range->group_prev;
13493                 }
13494                 if (&range->group_next == rstate->low_tail) {
13495                         rstate->low_tail = range->group_prev;
13496                 }
13497                 if (rstate->low == range) {
13498                         internal_error(state, 0, "low: next != prev?");
13499                 }
13500         }
13501         else if (rstate->high) {
13502                 cgdebug_printf("Hi: ");
13503                 range = rstate->high;
13504                 if (*range->group_prev != range) {
13505                         internal_error(state, 0, "hi: *prev != range?");
13506                 }
13507                 *range->group_prev = range->group_next;
13508                 if (range->group_next) {
13509                         range->group_next->group_prev = range->group_prev;
13510                 }
13511                 if (&range->group_next == rstate->high_tail) {
13512                         rstate->high_tail = range->group_prev;
13513                 }
13514                 if (rstate->high == range) {
13515                         internal_error(state, 0, "high: next != prev?");
13516                 }
13517         }
13518         else {
13519                 return 1;
13520         }
13521         cgdebug_printf(" %d\n", range - rstate->lr);
13522         range->group_prev = 0;
13523         for(edge = range->edges; edge; edge = edge->next) {
13524                 struct live_range *node;
13525                 node = edge->node;
13526                 /* Move nodes from the high to the low list */
13527                 if (node->group_prev && (node->color == REG_UNSET) &&
13528                         (node->degree == regc_max_size(state, node->classes))) {
13529                         if (*node->group_prev != node) {
13530                                 internal_error(state, 0, "move: *prev != node?");
13531                         }
13532                         *node->group_prev = node->group_next;
13533                         if (node->group_next) {
13534                                 node->group_next->group_prev = node->group_prev;
13535                         }
13536                         if (&node->group_next == rstate->high_tail) {
13537                                 rstate->high_tail = node->group_prev;
13538                         }
13539                         cgdebug_printf("Moving...%d to low\n", node - rstate->lr);
13540                         node->group_prev  = rstate->low_tail;
13541                         node->group_next  = 0;
13542                         *rstate->low_tail = node;
13543                         rstate->low_tail  = &node->group_next;
13544                         if (*node->group_prev != node) {
13545                                 internal_error(state, 0, "move2: *prev != node?");
13546                         }
13547                 }
13548                 node->degree -= 1;
13549         }
13550         colored = color_graph(state, rstate);
13551         if (colored) {
13552                 cgdebug_printf("Coloring %d @", range - rstate->lr);
13553                 cgdebug_loc(state, range->defs->def);
13554                 cgdebug_flush();
13555                 colored = select_free_color(state, rstate, range);
13556                 cgdebug_printf(" %s\n", arch_reg_str(range->color));
13557         }
13558         return colored;
13559 }
13560
13561 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
13562 {
13563         struct live_range *lr;
13564         struct live_range_edge *edge;
13565         struct triple *ins, *first;
13566         char used[MAX_REGISTERS];
13567         first = RHS(state->main_function, 0);
13568         ins = first;
13569         do {
13570                 if (triple_is_def(state, ins)) {
13571                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
13572                                 internal_error(state, ins, 
13573                                         "triple without a live range def");
13574                         }
13575                         lr = rstate->lrd[ins->id].lr;
13576                         if (lr->color == REG_UNSET) {
13577                                 internal_error(state, ins,
13578                                         "triple without a color");
13579                         }
13580                         /* Find the registers used by the edges */
13581                         memset(used, 0, sizeof(used));
13582                         for(edge = lr->edges; edge; edge = edge->next) {
13583                                 if (edge->node->color == REG_UNSET) {
13584                                         internal_error(state, 0,
13585                                                 "live range without a color");
13586                         }
13587                                 reg_fill_used(state, used, edge->node->color);
13588                         }
13589                         if (used[lr->color]) {
13590                                 internal_error(state, ins,
13591                                         "triple with already used color");
13592                         }
13593                 }
13594                 ins = ins->next;
13595         } while(ins != first);
13596 }
13597
13598 static void color_triples(struct compile_state *state, struct reg_state *rstate)
13599 {
13600         struct live_range *lr;
13601         struct triple *first, *ins;
13602         first = RHS(state->main_function, 0);
13603         ins = first;
13604         do {
13605                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
13606                         internal_error(state, ins, 
13607                                 "triple without a live range");
13608                 }
13609                 lr = rstate->lrd[ins->id].lr;
13610                 SET_REG(ins->id, lr->color);
13611                 ins = ins->next;
13612         } while (ins != first);
13613 }
13614
13615 static struct live_range *merge_sort_lr(
13616         struct live_range *first, struct live_range *last)
13617 {
13618         struct live_range *mid, *join, **join_tail, *pick;
13619         size_t size;
13620         size = (last - first) + 1;
13621         if (size >= 2) {
13622                 mid = first + size/2;
13623                 first = merge_sort_lr(first, mid -1);
13624                 mid   = merge_sort_lr(mid, last);
13625                 
13626                 join = 0;
13627                 join_tail = &join;
13628                 /* merge the two lists */
13629                 while(first && mid) {
13630                         if ((first->degree < mid->degree) ||
13631                                 ((first->degree == mid->degree) &&
13632                                         (first->length < mid->length))) {
13633                                 pick = first;
13634                                 first = first->group_next;
13635                                 if (first) {
13636                                         first->group_prev = 0;
13637                                 }
13638                         }
13639                         else {
13640                                 pick = mid;
13641                                 mid = mid->group_next;
13642                                 if (mid) {
13643                                         mid->group_prev = 0;
13644                                 }
13645                         }
13646                         pick->group_next = 0;
13647                         pick->group_prev = join_tail;
13648                         *join_tail = pick;
13649                         join_tail = &pick->group_next;
13650                 }
13651                 /* Splice the remaining list */
13652                 pick = (first)? first : mid;
13653                 *join_tail = pick;
13654                 if (pick) { 
13655                         pick->group_prev = join_tail;
13656                 }
13657         }
13658         else {
13659                 if (!first->defs) {
13660                         first = 0;
13661                 }
13662                 join = first;
13663         }
13664         return join;
13665 }
13666
13667 static void ids_from_rstate(struct compile_state *state, 
13668         struct reg_state *rstate)
13669 {
13670         struct triple *ins, *first;
13671         if (!rstate->defs) {
13672                 return;
13673         }
13674         /* Display the graph if desired */
13675         if (state->debug & DEBUG_INTERFERENCE) {
13676                 print_blocks(state, stdout);
13677                 print_control_flow(state);
13678         }
13679         first = RHS(state->main_function, 0);
13680         ins = first;
13681         do {
13682                 if (ins->id) {
13683                         struct live_range_def *lrd;
13684                         lrd = &rstate->lrd[ins->id];
13685                         ins->id = lrd->orig_id;
13686                 }
13687                 ins = ins->next;
13688         } while(ins != first);
13689 }
13690
13691 static void cleanup_live_edges(struct reg_state *rstate)
13692 {
13693         int i;
13694         /* Free the edges on each node */
13695         for(i = 1; i <= rstate->ranges; i++) {
13696                 remove_live_edges(rstate, &rstate->lr[i]);
13697         }
13698 }
13699
13700 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
13701 {
13702         cleanup_live_edges(rstate);
13703         xfree(rstate->lrd);
13704         xfree(rstate->lr);
13705
13706         /* Free the variable lifetime information */
13707         if (rstate->blocks) {
13708                 free_variable_lifetimes(state, rstate->blocks);
13709         }
13710         rstate->defs = 0;
13711         rstate->ranges = 0;
13712         rstate->lrd = 0;
13713         rstate->lr = 0;
13714         rstate->blocks = 0;
13715 }
13716
13717 static void verify_consistency(struct compile_state *state);
13718 static void allocate_registers(struct compile_state *state)
13719 {
13720         struct reg_state rstate;
13721         int colored;
13722
13723         /* Clear out the reg_state */
13724         memset(&rstate, 0, sizeof(rstate));
13725         rstate.max_passes = MAX_ALLOCATION_PASSES;
13726
13727         do {
13728                 struct live_range **point, **next;
13729                 int conflicts;
13730                 int tangles;
13731                 int coalesced;
13732
13733 #if DEBUG_RANGE_CONFLICTS
13734                 fprintf(stderr, "pass: %d\n", rstate.passes);
13735 #endif
13736
13737                 /* Restore ids */
13738                 ids_from_rstate(state, &rstate);
13739
13740                 /* Cleanup the temporary data structures */
13741                 cleanup_rstate(state, &rstate);
13742
13743                 /* Compute the variable lifetimes */
13744                 rstate.blocks = compute_variable_lifetimes(state);
13745
13746                 /* Fix invalid mandatory live range coalesce conflicts */
13747                 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
13748
13749                 /* Fix two simultaneous uses of the same register.
13750                  * In a few pathlogical cases a partial untangle moves
13751                  * the tangle to a part of the graph we won't revisit.
13752                  * So we keep looping until we have no more tangle fixes
13753                  * to apply.
13754                  */
13755                 do {
13756                         tangles = correct_tangles(state, rstate.blocks);
13757                 } while(tangles);
13758
13759                 if (state->debug & DEBUG_INSERTED_COPIES) {
13760                         printf("After resolve_tangles\n");
13761                         print_blocks(state, stdout);
13762                         print_control_flow(state);
13763                 }
13764                 verify_consistency(state);
13765                 
13766                 /* Allocate and initialize the live ranges */
13767                 initialize_live_ranges(state, &rstate);
13768
13769                 /* Note current doing coalescing in a loop appears to 
13770                  * buys me nothing.  The code is left this way in case
13771                  * there is some value in it.  Or if a future bugfix
13772                  *  yields some benefit.
13773                  */
13774                 do {
13775 #if DEBUG_COALESCING
13776                         fprintf(stderr, "coalescing\n");
13777 #endif                  
13778                         /* Remove any previous live edge calculations */
13779                         cleanup_live_edges(&rstate);
13780
13781                         /* Compute the interference graph */
13782                         walk_variable_lifetimes(
13783                                 state, rstate.blocks, graph_ins, &rstate);
13784                         
13785                         /* Display the interference graph if desired */
13786                         if (state->debug & DEBUG_INTERFERENCE) {
13787                                 print_interference_blocks(state, &rstate, stdout, 1);
13788                                 printf("\nlive variables by instruction\n");
13789                                 walk_variable_lifetimes(
13790                                         state, rstate.blocks, 
13791                                         print_interference_ins, &rstate);
13792                         }
13793                         
13794                         coalesced = coalesce_live_ranges(state, &rstate);
13795
13796 #if DEBUG_COALESCING
13797                         fprintf(stderr, "coalesced: %d\n", coalesced);
13798 #endif
13799                 } while(coalesced);
13800
13801 #if DEBUG_CONSISTENCY > 1
13802 # if 0
13803                 fprintf(stderr, "verify_graph_ins...\n");
13804 # endif
13805                 /* Verify the interference graph */
13806                 walk_variable_lifetimes(
13807                         state, rstate.blocks, verify_graph_ins, &rstate);
13808 # if 0
13809                 fprintf(stderr, "verify_graph_ins done\n");
13810 #endif
13811 #endif
13812                         
13813                 /* Build the groups low and high.  But with the nodes
13814                  * first sorted by degree order.
13815                  */
13816                 rstate.low_tail  = &rstate.low;
13817                 rstate.high_tail = &rstate.high;
13818                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
13819                 if (rstate.high) {
13820                         rstate.high->group_prev = &rstate.high;
13821                 }
13822                 for(point = &rstate.high; *point; point = &(*point)->group_next)
13823                         ;
13824                 rstate.high_tail = point;
13825                 /* Walk through the high list and move everything that needs
13826                  * to be onto low.
13827                  */
13828                 for(point = &rstate.high; *point; point = next) {
13829                         struct live_range *range;
13830                         next = &(*point)->group_next;
13831                         range = *point;
13832                         
13833                         /* If it has a low degree or it already has a color
13834                          * place the node in low.
13835                          */
13836                         if ((range->degree < regc_max_size(state, range->classes)) ||
13837                                 (range->color != REG_UNSET)) {
13838                                 cgdebug_printf("Lo: %5d degree %5d%s\n", 
13839                                         range - rstate.lr, range->degree,
13840                                         (range->color != REG_UNSET) ? " (colored)": "");
13841                                 *range->group_prev = range->group_next;
13842                                 if (range->group_next) {
13843                                         range->group_next->group_prev = range->group_prev;
13844                                 }
13845                                 if (&range->group_next == rstate.high_tail) {
13846                                         rstate.high_tail = range->group_prev;
13847                                 }
13848                                 range->group_prev  = rstate.low_tail;
13849                                 range->group_next  = 0;
13850                                 *rstate.low_tail   = range;
13851                                 rstate.low_tail    = &range->group_next;
13852                                 next = point;
13853                         }
13854                         else {
13855                                 cgdebug_printf("hi: %5d degree %5d%s\n", 
13856                                         range - rstate.lr, range->degree,
13857                                         (range->color != REG_UNSET) ? " (colored)": "");
13858                         }
13859                 }
13860                 /* Color the live_ranges */
13861                 colored = color_graph(state, &rstate);
13862                 rstate.passes++;
13863         } while (!colored);
13864
13865         /* Verify the graph was properly colored */
13866         verify_colors(state, &rstate);
13867
13868         /* Move the colors from the graph to the triples */
13869         color_triples(state, &rstate);
13870
13871         /* Cleanup the temporary data structures */
13872         cleanup_rstate(state, &rstate);
13873 }
13874
13875 /* Sparce Conditional Constant Propogation
13876  * =========================================
13877  */
13878 struct ssa_edge;
13879 struct flow_block;
13880 struct lattice_node {
13881         unsigned old_id;
13882         struct triple *def;
13883         struct ssa_edge *out;
13884         struct flow_block *fblock;
13885         struct triple *val;
13886         /* lattice high   val && !is_const(val) 
13887          * lattice const  is_const(val)
13888          * lattice low    val == 0
13889          */
13890 };
13891 struct ssa_edge {
13892         struct lattice_node *src;
13893         struct lattice_node *dst;
13894         struct ssa_edge *work_next;
13895         struct ssa_edge *work_prev;
13896         struct ssa_edge *out_next;
13897 };
13898 struct flow_edge {
13899         struct flow_block *src;
13900         struct flow_block *dst;
13901         struct flow_edge *work_next;
13902         struct flow_edge *work_prev;
13903         struct flow_edge *in_next;
13904         struct flow_edge *out_next;
13905         int executable;
13906 };
13907 struct flow_block {
13908         struct block *block;
13909         struct flow_edge *in;
13910         struct flow_edge *out;
13911         struct flow_edge left, right;
13912 };
13913
13914 struct scc_state {
13915         int ins_count;
13916         struct lattice_node *lattice;
13917         struct ssa_edge     *ssa_edges;
13918         struct flow_block   *flow_blocks;
13919         struct flow_edge    *flow_work_list;
13920         struct ssa_edge     *ssa_work_list;
13921 };
13922
13923
13924 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
13925         struct flow_edge *fedge)
13926 {
13927         if (!scc->flow_work_list) {
13928                 scc->flow_work_list = fedge;
13929                 fedge->work_next = fedge->work_prev = fedge;
13930         }
13931         else {
13932                 struct flow_edge *ftail;
13933                 ftail = scc->flow_work_list->work_prev;
13934                 fedge->work_next = ftail->work_next;
13935                 fedge->work_prev = ftail;
13936                 fedge->work_next->work_prev = fedge;
13937                 fedge->work_prev->work_next = fedge;
13938         }
13939 }
13940
13941 static struct flow_edge *scc_next_fedge(
13942         struct compile_state *state, struct scc_state *scc)
13943 {
13944         struct flow_edge *fedge;
13945         fedge = scc->flow_work_list;
13946         if (fedge) {
13947                 fedge->work_next->work_prev = fedge->work_prev;
13948                 fedge->work_prev->work_next = fedge->work_next;
13949                 if (fedge->work_next != fedge) {
13950                         scc->flow_work_list = fedge->work_next;
13951                 } else {
13952                         scc->flow_work_list = 0;
13953                 }
13954         }
13955         return fedge;
13956 }
13957
13958 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
13959         struct ssa_edge *sedge)
13960 {
13961         if (!scc->ssa_work_list) {
13962                 scc->ssa_work_list = sedge;
13963                 sedge->work_next = sedge->work_prev = sedge;
13964         }
13965         else {
13966                 struct ssa_edge *stail;
13967                 stail = scc->ssa_work_list->work_prev;
13968                 sedge->work_next = stail->work_next;
13969                 sedge->work_prev = stail;
13970                 sedge->work_next->work_prev = sedge;
13971                 sedge->work_prev->work_next = sedge;
13972         }
13973 }
13974
13975 static struct ssa_edge *scc_next_sedge(
13976         struct compile_state *state, struct scc_state *scc)
13977 {
13978         struct ssa_edge *sedge;
13979         sedge = scc->ssa_work_list;
13980         if (sedge) {
13981                 sedge->work_next->work_prev = sedge->work_prev;
13982                 sedge->work_prev->work_next = sedge->work_next;
13983                 if (sedge->work_next != sedge) {
13984                         scc->ssa_work_list = sedge->work_next;
13985                 } else {
13986                         scc->ssa_work_list = 0;
13987                 }
13988         }
13989         return sedge;
13990 }
13991
13992 static void initialize_scc_state(
13993         struct compile_state *state, struct scc_state *scc)
13994 {
13995         int ins_count, ssa_edge_count;
13996         int ins_index, ssa_edge_index, fblock_index;
13997         struct triple *first, *ins;
13998         struct block *block;
13999         struct flow_block *fblock;
14000
14001         memset(scc, 0, sizeof(*scc));
14002
14003         /* Inialize pass zero find out how much memory we need */
14004         first = RHS(state->main_function, 0);
14005         ins = first;
14006         ins_count = ssa_edge_count = 0;
14007         do {
14008                 struct triple_set *edge;
14009                 ins_count += 1;
14010                 for(edge = ins->use; edge; edge = edge->next) {
14011                         ssa_edge_count++;
14012                 }
14013                 ins = ins->next;
14014         } while(ins != first);
14015 #if DEBUG_SCC
14016         fprintf(stderr, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
14017                 ins_count, ssa_edge_count, state->last_vertex);
14018 #endif
14019         scc->ins_count   = ins_count;
14020         scc->lattice     = 
14021                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
14022         scc->ssa_edges   = 
14023                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
14024         scc->flow_blocks = 
14025                 xcmalloc(sizeof(*scc->flow_blocks)*(state->last_vertex + 1), 
14026                         "flow_blocks");
14027
14028         /* Initialize pass one collect up the nodes */
14029         fblock = 0;
14030         block = 0;
14031         ins_index = ssa_edge_index = fblock_index = 0;
14032         ins = first;
14033         do {
14034                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14035                         block = ins->u.block;
14036                         if (!block) {
14037                                 internal_error(state, ins, "label without block");
14038                         }
14039                         fblock_index += 1;
14040                         block->vertex = fblock_index;
14041                         fblock = &scc->flow_blocks[fblock_index];
14042                         fblock->block = block;
14043                 }
14044                 {
14045                         struct lattice_node *lnode;
14046                         ins_index += 1;
14047                         lnode = &scc->lattice[ins_index];
14048                         lnode->def = ins;
14049                         lnode->out = 0;
14050                         lnode->fblock = fblock;
14051                         lnode->val = ins; /* LATTICE HIGH */
14052                         lnode->old_id = ins->id;
14053                         ins->id = ins_index;
14054                 }
14055                 ins = ins->next;
14056         } while(ins != first);
14057         /* Initialize pass two collect up the edges */
14058         block = 0;
14059         fblock = 0;
14060         ins = first;
14061         do {
14062                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
14063                         struct flow_edge *fedge, **ftail;
14064                         struct block_set *bedge;
14065                         block = ins->u.block;
14066                         fblock = &scc->flow_blocks[block->vertex];
14067                         fblock->in = 0;
14068                         fblock->out = 0;
14069                         ftail = &fblock->out;
14070                         if (block->left) {
14071                                 fblock->left.dst = &scc->flow_blocks[block->left->vertex];
14072                                 if (fblock->left.dst->block != block->left) {
14073                                         internal_error(state, 0, "block mismatch");
14074                                 }
14075                                 fblock->left.out_next = 0;
14076                                 *ftail = &fblock->left;
14077                                 ftail = &fblock->left.out_next;
14078                         }
14079                         if (block->right) {
14080                                 fblock->right.dst = &scc->flow_blocks[block->right->vertex];
14081                                 if (fblock->right.dst->block != block->right) {
14082                                         internal_error(state, 0, "block mismatch");
14083                                 }
14084                                 fblock->right.out_next = 0;
14085                                 *ftail = &fblock->right;
14086                                 ftail = &fblock->right.out_next;
14087                         }
14088                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
14089                                 fedge->src = fblock;
14090                                 fedge->work_next = fedge->work_prev = fedge;
14091                                 fedge->executable = 0;
14092                         }
14093                         ftail = &fblock->in;
14094                         for(bedge = block->use; bedge; bedge = bedge->next) {
14095                                 struct block *src_block;
14096                                 struct flow_block *sfblock;
14097                                 struct flow_edge *sfedge;
14098                                 src_block = bedge->member;
14099                                 sfblock = &scc->flow_blocks[src_block->vertex];
14100                                 sfedge = 0;
14101                                 if (src_block->left == block) {
14102                                         sfedge = &sfblock->left;
14103                                 } else {
14104                                         sfedge = &sfblock->right;
14105                                 }
14106                                 *ftail = sfedge;
14107                                 ftail = &sfedge->in_next;
14108                                 sfedge->in_next = 0;
14109                         }
14110                 }
14111                 {
14112                         struct triple_set *edge;
14113                         struct ssa_edge **stail;
14114                         struct lattice_node *lnode;
14115                         lnode = &scc->lattice[ins->id];
14116                         lnode->out = 0;
14117                         stail = &lnode->out;
14118                         for(edge = ins->use; edge; edge = edge->next) {
14119                                 struct ssa_edge *sedge;
14120                                 ssa_edge_index += 1;
14121                                 sedge = &scc->ssa_edges[ssa_edge_index];
14122                                 *stail = sedge;
14123                                 stail = &sedge->out_next;
14124                                 sedge->src = lnode;
14125                                 sedge->dst = &scc->lattice[edge->member->id];
14126                                 sedge->work_next = sedge->work_prev = sedge;
14127                                 sedge->out_next = 0;
14128                         }
14129                 }
14130                 ins = ins->next;
14131         } while(ins != first);
14132         /* Setup a dummy block 0 as a node above the start node */
14133         {
14134                 struct flow_block *fblock, *dst;
14135                 struct flow_edge *fedge;
14136                 fblock = &scc->flow_blocks[0];
14137                 fblock->block = 0;
14138                 fblock->in = 0;
14139                 fblock->out = &fblock->left;
14140                 dst = &scc->flow_blocks[state->first_block->vertex];
14141                 fedge = &fblock->left;
14142                 fedge->src        = fblock;
14143                 fedge->dst        = dst;
14144                 fedge->work_next  = fedge;
14145                 fedge->work_prev  = fedge;
14146                 fedge->in_next    = fedge->dst->in;
14147                 fedge->out_next   = 0;
14148                 fedge->executable = 0;
14149                 fedge->dst->in = fedge;
14150                 
14151                 /* Initialize the work lists */
14152                 scc->flow_work_list = 0;
14153                 scc->ssa_work_list  = 0;
14154                 scc_add_fedge(state, scc, fedge);
14155         }
14156 #if DEBUG_SCC
14157         fprintf(stderr, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
14158                 ins_index, ssa_edge_index, fblock_index);
14159 #endif
14160 }
14161
14162         
14163 static void free_scc_state(
14164         struct compile_state *state, struct scc_state *scc)
14165 {
14166         xfree(scc->flow_blocks);
14167         xfree(scc->ssa_edges);
14168         xfree(scc->lattice);
14169         
14170 }
14171
14172 static struct lattice_node *triple_to_lattice(
14173         struct compile_state *state, struct scc_state *scc, struct triple *ins)
14174 {
14175         if (ins->id <= 0) {
14176                 internal_error(state, ins, "bad id");
14177         }
14178         return &scc->lattice[ins->id];
14179 }
14180
14181 static struct triple *preserve_lval(
14182         struct compile_state *state, struct lattice_node *lnode)
14183 {
14184         struct triple *old;
14185         /* Preserve the original value */
14186         if (lnode->val) {
14187                 old = dup_triple(state, lnode->val);
14188                 if (lnode->val != lnode->def) {
14189                         xfree(lnode->val);
14190                 }
14191                 lnode->val = 0;
14192         } else {
14193                 old = 0;
14194         }
14195         return old;
14196 }
14197
14198 static int lval_changed(struct compile_state *state, 
14199         struct triple *old, struct lattice_node *lnode)
14200 {
14201         int changed;
14202         /* See if the lattice value has changed */
14203         changed = 1;
14204         if (!old && !lnode->val) {
14205                 changed = 0;
14206         }
14207         if (changed && lnode->val && !is_const(lnode->val)) {
14208                 changed = 0;
14209         }
14210         if (changed &&
14211                 lnode->val && old &&
14212                 (memcmp(lnode->val->param, old->param,
14213                         TRIPLE_SIZE(lnode->val->sizes) * sizeof(lnode->val->param[0])) == 0) &&
14214                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
14215                 changed = 0;
14216         }
14217         if (old) {
14218                 xfree(old);
14219         }
14220         return changed;
14221
14222 }
14223
14224 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
14225         struct lattice_node *lnode)
14226 {
14227         struct lattice_node *tmp;
14228         struct triple **slot, *old;
14229         struct flow_edge *fedge;
14230         int index;
14231         if (lnode->def->op != OP_PHI) {
14232                 internal_error(state, lnode->def, "not phi");
14233         }
14234         /* Store the original value */
14235         old = preserve_lval(state, lnode);
14236
14237         /* default to lattice high */
14238         lnode->val = lnode->def;
14239         slot = &RHS(lnode->def, 0);
14240         index = 0;
14241         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
14242                 if (!fedge->executable) {
14243                         continue;
14244                 }
14245                 if (!slot[index]) {
14246                         internal_error(state, lnode->def, "no phi value");
14247                 }
14248                 tmp = triple_to_lattice(state, scc, slot[index]);
14249                 /* meet(X, lattice low) = lattice low */
14250                 if (!tmp->val) {
14251                         lnode->val = 0;
14252                 }
14253                 /* meet(X, lattice high) = X */
14254                 else if (!tmp->val) {
14255                         lnode->val = lnode->val;
14256                 }
14257                 /* meet(lattice high, X) = X */
14258                 else if (!is_const(lnode->val)) {
14259                         lnode->val = dup_triple(state, tmp->val);
14260                         lnode->val->type = lnode->def->type;
14261                 }
14262                 /* meet(const, const) = const or lattice low */
14263                 else if (!constants_equal(state, lnode->val, tmp->val)) {
14264                         lnode->val = 0;
14265                 }
14266                 if (!lnode->val) {
14267                         break;
14268                 }
14269         }
14270 #if DEBUG_SCC
14271         fprintf(stderr, "phi: %d -> %s\n",
14272                 lnode->def->id,
14273                 (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14274 #endif
14275         /* If the lattice value has changed update the work lists. */
14276         if (lval_changed(state, old, lnode)) {
14277                 struct ssa_edge *sedge;
14278                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14279                         scc_add_sedge(state, scc, sedge);
14280                 }
14281         }
14282 }
14283
14284 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
14285         struct lattice_node *lnode)
14286 {
14287         int changed;
14288         struct triple *old, *scratch;
14289         struct triple **dexpr, **vexpr;
14290         int count, i;
14291         
14292         /* Store the original value */
14293         old = preserve_lval(state, lnode);
14294
14295         /* Reinitialize the value */
14296         lnode->val = scratch = dup_triple(state, lnode->def);
14297         scratch->id = lnode->old_id;
14298         scratch->next     = scratch;
14299         scratch->prev     = scratch;
14300         scratch->use      = 0;
14301
14302         count = TRIPLE_SIZE(scratch->sizes);
14303         for(i = 0; i < count; i++) {
14304                 dexpr = &lnode->def->param[i];
14305                 vexpr = &scratch->param[i];
14306                 *vexpr = *dexpr;
14307                 if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14308                         (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14309                         *dexpr) {
14310                         struct lattice_node *tmp;
14311                         tmp = triple_to_lattice(state, scc, *dexpr);
14312                         *vexpr = (tmp->val)? tmp->val : tmp->def;
14313                 }
14314         }
14315         if (scratch->op == OP_BRANCH) {
14316                 scratch->next = lnode->def->next;
14317         }
14318         /* Recompute the value */
14319 #warning "FIXME see if simplify does anything bad"
14320         /* So far it looks like only the strength reduction
14321          * optimization are things I need to worry about.
14322          */
14323         simplify(state, scratch);
14324         /* Cleanup my value */
14325         if (scratch->use) {
14326                 internal_error(state, lnode->def, "scratch used?");
14327         }
14328         if ((scratch->prev != scratch) ||
14329                 ((scratch->next != scratch) &&
14330                         ((lnode->def->op != OP_BRANCH) ||
14331                                 (scratch->next != lnode->def->next)))) {
14332                 internal_error(state, lnode->def, "scratch in list?");
14333         }
14334         /* undo any uses... */
14335         count = TRIPLE_SIZE(scratch->sizes);
14336         for(i = 0; i < count; i++) {
14337                 vexpr = &scratch->param[i];
14338                 if (*vexpr) {
14339                         unuse_triple(*vexpr, scratch);
14340                 }
14341         }
14342         if (!is_const(scratch)) {
14343                 for(i = 0; i < count; i++) {
14344                         dexpr = &lnode->def->param[i];
14345                         if (((i < TRIPLE_MISC_OFF(scratch->sizes)) ||
14346                                 (i >= TRIPLE_TARG_OFF(scratch->sizes))) &&
14347                                 *dexpr) {
14348                                 struct lattice_node *tmp;
14349                                 tmp = triple_to_lattice(state, scc, *dexpr);
14350                                 if (!tmp->val) {
14351                                         lnode->val = 0;
14352                                 }
14353                         }
14354                 }
14355         }
14356         if (lnode->val && 
14357                 (lnode->val->op == lnode->def->op) &&
14358                 (memcmp(lnode->val->param, lnode->def->param, 
14359                         count * sizeof(lnode->val->param[0])) == 0) &&
14360                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
14361                 lnode->val = lnode->def;
14362         }
14363         /* Find the cases that are always lattice lo */
14364         if (lnode->val && 
14365                 triple_is_def(state, lnode->val) &&
14366                 !triple_is_pure(state, lnode->val)) {
14367                 lnode->val = 0;
14368         }
14369         if (lnode->val && 
14370                 (lnode->val->op == OP_SDECL) && 
14371                 (lnode->val != lnode->def)) {
14372                 internal_error(state, lnode->def, "bad sdecl");
14373         }
14374         /* See if the lattice value has changed */
14375         changed = lval_changed(state, old, lnode);
14376         if (lnode->val != scratch) {
14377                 xfree(scratch);
14378         }
14379         return changed;
14380 }
14381
14382 static void scc_visit_branch(struct compile_state *state, struct scc_state *scc,
14383         struct lattice_node *lnode)
14384 {
14385         struct lattice_node *cond;
14386 #if DEBUG_SCC
14387         {
14388                 struct flow_edge *fedge;
14389                 fprintf(stderr, "branch: %d (",
14390                         lnode->def->id);
14391                 
14392                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
14393                         fprintf(stderr, " %d", fedge->dst->block->vertex);
14394                 }
14395                 fprintf(stderr, " )");
14396                 if (TRIPLE_RHS(lnode->def->sizes) > 0) {
14397                         fprintf(stderr, " <- %d",
14398                                 RHS(lnode->def, 0)->id);
14399                 }
14400                 fprintf(stderr, "\n");
14401         }
14402 #endif
14403         if (lnode->def->op != OP_BRANCH) {
14404                 internal_error(state, lnode->def, "not branch");
14405         }
14406         /* This only applies to conditional branches */
14407         if (TRIPLE_RHS(lnode->def->sizes) == 0) {
14408                 return;
14409         }
14410         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
14411         if (cond->val && !is_const(cond->val)) {
14412 #warning "FIXME do I need to do something here?"
14413                 warning(state, cond->def, "condition not constant?");
14414                 return;
14415         }
14416         if (cond->val == 0) {
14417                 scc_add_fedge(state, scc, cond->fblock->out);
14418                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14419         }
14420         else if (cond->val->u.cval) {
14421                 scc_add_fedge(state, scc, cond->fblock->out->out_next);
14422                 
14423         } else {
14424                 scc_add_fedge(state, scc, cond->fblock->out);
14425         }
14426
14427 }
14428
14429 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
14430         struct lattice_node *lnode)
14431 {
14432         int changed;
14433
14434         changed = compute_lnode_val(state, scc, lnode);
14435 #if DEBUG_SCC
14436         {
14437                 struct triple **expr;
14438                 fprintf(stderr, "expr: %3d %10s (",
14439                         lnode->def->id, tops(lnode->def->op));
14440                 expr = triple_rhs(state, lnode->def, 0);
14441                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
14442                         if (*expr) {
14443                                 fprintf(stderr, " %d", (*expr)->id);
14444                         }
14445                 }
14446                 fprintf(stderr, " ) -> %s\n",
14447                         (!lnode->val)? "lo": is_const(lnode->val)? "const": "hi");
14448         }
14449 #endif
14450         if (lnode->def->op == OP_BRANCH) {
14451                 scc_visit_branch(state, scc, lnode);
14452
14453         }
14454         else if (changed) {
14455                 struct ssa_edge *sedge;
14456                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
14457                         scc_add_sedge(state, scc, sedge);
14458                 }
14459         }
14460 }
14461
14462 static void scc_writeback_values(
14463         struct compile_state *state, struct scc_state *scc)
14464 {
14465         struct triple *first, *ins;
14466         first = RHS(state->main_function, 0);
14467         ins = first;
14468         do {
14469                 struct lattice_node *lnode;
14470                 lnode = triple_to_lattice(state, scc, ins);
14471                 /* Restore id */
14472                 ins->id = lnode->old_id;
14473 #if DEBUG_SCC
14474                 if (lnode->val && !is_const(lnode->val)) {
14475                         warning(state, lnode->def, 
14476                                 "lattice node still high?");
14477                 }
14478 #endif
14479                 if (lnode->val && (lnode->val != ins)) {
14480                         /* See if it something I know how to write back */
14481                         switch(lnode->val->op) {
14482                         case OP_INTCONST:
14483                                 mkconst(state, ins, lnode->val->u.cval);
14484                                 break;
14485                         case OP_ADDRCONST:
14486                                 mkaddr_const(state, ins, 
14487                                         MISC(lnode->val, 0), lnode->val->u.cval);
14488                                 break;
14489                         default:
14490                                 /* By default don't copy the changes,
14491                                  * recompute them in place instead.
14492                                  */
14493                                 simplify(state, ins);
14494                                 break;
14495                         }
14496                         if (is_const(lnode->val) &&
14497                                 !constants_equal(state, lnode->val, ins)) {
14498                                 internal_error(state, 0, "constants not equal");
14499                         }
14500                         /* Free the lattice nodes */
14501                         xfree(lnode->val);
14502                         lnode->val = 0;
14503                 }
14504                 ins = ins->next;
14505         } while(ins != first);
14506 }
14507
14508 static void scc_transform(struct compile_state *state)
14509 {
14510         struct scc_state scc;
14511
14512         initialize_scc_state(state, &scc);
14513
14514         while(scc.flow_work_list || scc.ssa_work_list) {
14515                 struct flow_edge *fedge;
14516                 struct ssa_edge *sedge;
14517                 struct flow_edge *fptr;
14518                 while((fedge = scc_next_fedge(state, &scc))) {
14519                         struct block *block;
14520                         struct triple *ptr;
14521                         struct flow_block *fblock;
14522                         int time;
14523                         int done;
14524                         if (fedge->executable) {
14525                                 continue;
14526                         }
14527                         if (!fedge->dst) {
14528                                 internal_error(state, 0, "fedge without dst");
14529                         }
14530                         if (!fedge->src) {
14531                                 internal_error(state, 0, "fedge without src");
14532                         }
14533                         fedge->executable = 1;
14534                         fblock = fedge->dst;
14535                         block = fblock->block;
14536                         time = 0;
14537                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14538                                 if (fptr->executable) {
14539                                         time++;
14540                                 }
14541                         }
14542 #if DEBUG_SCC
14543                         fprintf(stderr, "vertex: %d time: %d\n", 
14544                                 block->vertex, time);
14545                         
14546 #endif
14547                         done = 0;
14548                         for(ptr = block->first; !done; ptr = ptr->next) {
14549                                 struct lattice_node *lnode;
14550                                 done = (ptr == block->last);
14551                                 lnode = &scc.lattice[ptr->id];
14552                                 if (ptr->op == OP_PHI) {
14553                                         scc_visit_phi(state, &scc, lnode);
14554                                 }
14555                                 else if (time == 1) {
14556                                         scc_visit_expr(state, &scc, lnode);
14557                                 }
14558                         }
14559                         if (fblock->out && !fblock->out->out_next) {
14560                                 scc_add_fedge(state, &scc, fblock->out);
14561                         }
14562                 }
14563                 while((sedge = scc_next_sedge(state, &scc))) {
14564                         struct lattice_node *lnode;
14565                         struct flow_block *fblock;
14566                         lnode = sedge->dst;
14567                         fblock = lnode->fblock;
14568 #if DEBUG_SCC
14569                         fprintf(stderr, "sedge: %5d (%5d -> %5d)\n",
14570                                 sedge - scc.ssa_edges,
14571                                 sedge->src->def->id,
14572                                 sedge->dst->def->id);
14573 #endif
14574                         if (lnode->def->op == OP_PHI) {
14575                                 scc_visit_phi(state, &scc, lnode);
14576                         }
14577                         else {
14578                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
14579                                         if (fptr->executable) {
14580                                                 break;
14581                                         }
14582                                 }
14583                                 if (fptr) {
14584                                         scc_visit_expr(state, &scc, lnode);
14585                                 }
14586                         }
14587                 }
14588         }
14589         
14590         scc_writeback_values(state, &scc);
14591         free_scc_state(state, &scc);
14592 }
14593
14594
14595 static void transform_to_arch_instructions(struct compile_state *state)
14596 {
14597         struct triple *ins, *first;
14598         first = RHS(state->main_function, 0);
14599         ins = first;
14600         do {
14601                 ins = transform_to_arch_instruction(state, ins);
14602         } while(ins != first);
14603 }
14604
14605 #if DEBUG_CONSISTENCY
14606 static void verify_uses(struct compile_state *state)
14607 {
14608         struct triple *first, *ins;
14609         struct triple_set *set;
14610         first = RHS(state->main_function, 0);
14611         ins = first;
14612         do {
14613                 struct triple **expr;
14614                 expr = triple_rhs(state, ins, 0);
14615                 for(; expr; expr = triple_rhs(state, ins, expr)) {
14616                         struct triple *rhs;
14617                         rhs = *expr;
14618                         for(set = rhs?rhs->use:0; set; set = set->next) {
14619                                 if (set->member == ins) {
14620                                         break;
14621                                 }
14622                         }
14623                         if (!set) {
14624                                 internal_error(state, ins, "rhs not used");
14625                         }
14626                 }
14627                 expr = triple_lhs(state, ins, 0);
14628                 for(; expr; expr = triple_lhs(state, ins, expr)) {
14629                         struct triple *lhs;
14630                         lhs = *expr;
14631                         for(set =  lhs?lhs->use:0; set; set = set->next) {
14632                                 if (set->member == ins) {
14633                                         break;
14634                                 }
14635                         }
14636                         if (!set) {
14637                                 internal_error(state, ins, "lhs not used");
14638                         }
14639                 }
14640                 ins = ins->next;
14641         } while(ins != first);
14642         
14643 }
14644 static void verify_blocks_present(struct compile_state *state)
14645 {
14646         struct triple *first, *ins;
14647         if (!state->first_block) {
14648                 return;
14649         }
14650         first = RHS(state->main_function, 0);
14651         ins = first;
14652         do {
14653                 valid_ins(state, ins);
14654                 if (triple_stores_block(state, ins)) {
14655                         if (!ins->u.block) {
14656                                 internal_error(state, ins, 
14657                                         "%p not in a block?\n", ins);
14658                         }
14659                 }
14660                 ins = ins->next;
14661         } while(ins != first);
14662         
14663         
14664 }
14665 static void verify_blocks(struct compile_state *state)
14666 {
14667         struct triple *ins;
14668         struct block *block;
14669         int blocks;
14670         block = state->first_block;
14671         if (!block) {
14672                 return;
14673         }
14674         blocks = 0;
14675         do {
14676                 int users;
14677                 struct block_set *user;
14678                 blocks++;
14679                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
14680                         if (triple_stores_block(state, ins) && (ins->u.block != block)) {
14681                                 internal_error(state, ins, "inconsitent block specified");
14682                         }
14683                         valid_ins(state, ins);
14684                 }
14685                 users = 0;
14686                 for(user = block->use; user; user = user->next) {
14687                         users++;
14688                         if ((block == state->last_block) &&
14689                                 (user->member == state->first_block)) {
14690                                 continue;
14691                         }
14692                         if ((user->member->left != block) &&
14693                                 (user->member->right != block)) {
14694                                 internal_error(state, user->member->first,
14695                                         "user does not use block");
14696                         }
14697                 }
14698                 if (triple_is_branch(state, block->last) &&
14699                         (block->right != block_of_triple(state, TARG(block->last, 0))))
14700                 {
14701                         internal_error(state, block->last, "block->right != TARG(0)");
14702                 }
14703                 if (!triple_is_uncond_branch(state, block->last) &&
14704                         (block != state->last_block) &&
14705                         (block->left != block_of_triple(state, block->last->next)))
14706                 {
14707                         internal_error(state, block->last, "block->left != block->last->next");
14708                 }
14709                 if (block->left) {
14710                         for(user = block->left->use; user; user = user->next) {
14711                                 if (user->member == block) {
14712                                         break;
14713                                 }
14714                         }
14715                         if (!user || user->member != block) {
14716                                 internal_error(state, block->first,
14717                                         "block does not use left");
14718                         }
14719                 }
14720                 if (block->right) {
14721                         for(user = block->right->use; user; user = user->next) {
14722                                 if (user->member == block) {
14723                                         break;
14724                                 }
14725                         }
14726                         if (!user || user->member != block) {
14727                                 internal_error(state, block->first,
14728                                         "block does not use right");
14729                         }
14730                 }
14731                 if (block->users != users) {
14732                         internal_error(state, block->first, 
14733                                 "computed users %d != stored users %d\n",
14734                                 users, block->users);
14735                 }
14736                 if (!triple_stores_block(state, block->last->next)) {
14737                         internal_error(state, block->last->next, 
14738                                 "cannot find next block");
14739                 }
14740                 block = block->last->next->u.block;
14741                 if (!block) {
14742                         internal_error(state, block->last->next,
14743                                 "bad next block");
14744                 }
14745         } while(block != state->first_block);
14746         if (blocks != state->last_vertex) {
14747                 internal_error(state, 0, "computed blocks != stored blocks %d\n",
14748                         blocks, state->last_vertex);
14749         }
14750 }
14751
14752 static void verify_domination(struct compile_state *state)
14753 {
14754         struct triple *first, *ins;
14755         struct triple_set *set;
14756         if (!state->first_block) {
14757                 return;
14758         }
14759         
14760         first = RHS(state->main_function, 0);
14761         ins = first;
14762         do {
14763                 for(set = ins->use; set; set = set->next) {
14764                         struct triple **expr;
14765                         if (set->member->op == OP_PHI) {
14766                                 continue;
14767                         }
14768                         /* See if the use is on the righ hand side */
14769                         expr = triple_rhs(state, set->member, 0);
14770                         for(; expr ; expr = triple_rhs(state, set->member, expr)) {
14771                                 if (*expr == ins) {
14772                                         break;
14773                                 }
14774                         }
14775                         if (expr &&
14776                                 !tdominates(state, ins, set->member)) {
14777                                 internal_error(state, set->member, 
14778                                         "non dominated rhs use?");
14779                         }
14780                 }
14781                 ins = ins->next;
14782         } while(ins != first);
14783 }
14784
14785 static void verify_piece(struct compile_state *state)
14786 {
14787         struct triple *first, *ins;
14788         first = RHS(state->main_function, 0);
14789         ins = first;
14790         do {
14791                 struct triple *ptr;
14792                 int lhs, i;
14793                 lhs = TRIPLE_LHS(ins->sizes);
14794                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
14795                         if (ptr != LHS(ins, i)) {
14796                                 internal_error(state, ins, "malformed lhs on %s",
14797                                         tops(ins->op));
14798                         }
14799                         if (ptr->op != OP_PIECE) {
14800                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
14801                                         tops(ptr->op), i, tops(ins->op));
14802                         }
14803                         if (ptr->u.cval != i) {
14804                                 internal_error(state, ins, "bad u.cval of %d %d expected",
14805                                         ptr->u.cval, i);
14806                         }
14807                 }
14808                 ins = ins->next;
14809         } while(ins != first);
14810 }
14811 static void verify_ins_colors(struct compile_state *state)
14812 {
14813         struct triple *first, *ins;
14814         
14815         first = RHS(state->main_function, 0);
14816         ins = first;
14817         do {
14818                 ins = ins->next;
14819         } while(ins != first);
14820 }
14821 static void verify_consistency(struct compile_state *state)
14822 {
14823         verify_uses(state);
14824         verify_blocks_present(state);
14825         verify_blocks(state);
14826         verify_domination(state);
14827         verify_piece(state);
14828         verify_ins_colors(state);
14829 }
14830 #else 
14831 static void verify_consistency(struct compile_state *state) {}
14832 #endif /* DEBUG_USES */
14833
14834 static void optimize(struct compile_state *state)
14835 {
14836         if (state->debug & DEBUG_TRIPLES) {
14837                 print_triples(state);
14838         }
14839         /* Replace structures with simpler data types */
14840         flatten_structures(state);
14841         if (state->debug & DEBUG_TRIPLES) {
14842                 print_triples(state);
14843         }
14844         verify_consistency(state);
14845         /* Analize the intermediate code */
14846         setup_basic_blocks(state);
14847         analyze_idominators(state);
14848         analyze_ipdominators(state);
14849
14850         /* Transform the code to ssa form. */
14851         /*
14852          * The transformation to ssa form puts a phi function
14853          * on each of edge of a dominance frontier where that
14854          * phi function might be needed.  At -O2 if we don't
14855          * eleminate the excess phi functions we can get an
14856          * exponential code size growth.  So I kill the extra
14857          * phi functions early and I kill them often.
14858          */
14859         transform_to_ssa_form(state);
14860         eliminate_inefectual_code(state);
14861
14862         verify_consistency(state);
14863         if (state->debug & DEBUG_CODE_ELIMINATION) {
14864                 fprintf(stdout, "After transform_to_ssa_form\n");
14865                 print_blocks(state, stdout);
14866         }
14867         /* Do strength reduction and simple constant optimizations */
14868         if (state->optimize >= 1) {
14869                 simplify_all(state);
14870                 transform_from_ssa_form(state);
14871                 free_basic_blocks(state);
14872                 setup_basic_blocks(state);
14873                 analyze_idominators(state);
14874                 analyze_ipdominators(state);
14875                 transform_to_ssa_form(state);
14876                 eliminate_inefectual_code(state);
14877         }
14878         if (state->debug & DEBUG_CODE_ELIMINATION) {
14879                 fprintf(stdout, "After simplify_all\n");
14880                 print_blocks(state, stdout);
14881         }
14882         verify_consistency(state);
14883         /* Propogate constants throughout the code */
14884         if (state->optimize >= 2) {
14885                 scc_transform(state);
14886                 transform_from_ssa_form(state);
14887                 free_basic_blocks(state);
14888                 setup_basic_blocks(state);
14889                 analyze_idominators(state);
14890                 analyze_ipdominators(state);
14891                 transform_to_ssa_form(state);
14892                 eliminate_inefectual_code(state);
14893         }
14894         verify_consistency(state);
14895 #warning "WISHLIST implement single use constants (least possible register pressure)"
14896 #warning "WISHLIST implement induction variable elimination"
14897         /* Select architecture instructions and an initial partial
14898          * coloring based on architecture constraints.
14899          */
14900         transform_to_arch_instructions(state);
14901         verify_consistency(state);
14902         if (state->debug & DEBUG_ARCH_CODE) {
14903                 printf("After transform_to_arch_instructions\n");
14904                 print_blocks(state, stdout);
14905                 print_control_flow(state);
14906         }
14907         eliminate_inefectual_code(state);
14908         verify_consistency(state);
14909         if (state->debug & DEBUG_CODE_ELIMINATION) {
14910                 printf("After eliminate_inefectual_code\n");
14911                 print_blocks(state, stdout);
14912                 print_control_flow(state);
14913         }
14914         verify_consistency(state);
14915         /* Color all of the variables to see if they will fit in registers */
14916         insert_copies_to_phi(state);
14917         if (state->debug & DEBUG_INSERTED_COPIES) {
14918                 printf("After insert_copies_to_phi\n");
14919                 print_blocks(state, stdout);
14920                 print_control_flow(state);
14921         }
14922         verify_consistency(state);
14923         insert_mandatory_copies(state);
14924         if (state->debug & DEBUG_INSERTED_COPIES) {
14925                 printf("After insert_mandatory_copies\n");
14926                 print_blocks(state, stdout);
14927                 print_control_flow(state);
14928         }
14929         verify_consistency(state);
14930         allocate_registers(state);
14931         verify_consistency(state);
14932         if (state->debug & DEBUG_INTERMEDIATE_CODE) {
14933                 print_blocks(state, stdout);
14934         }
14935         if (state->debug & DEBUG_CONTROL_FLOW) {
14936                 print_control_flow(state);
14937         }
14938         /* Remove the optimization information.
14939          * This is more to check for memory consistency than to free memory.
14940          */
14941         free_basic_blocks(state);
14942 }
14943
14944 static void print_op_asm(struct compile_state *state,
14945         struct triple *ins, FILE *fp)
14946 {
14947         struct asm_info *info;
14948         const char *ptr;
14949         unsigned lhs, rhs, i;
14950         info = ins->u.ainfo;
14951         lhs = TRIPLE_LHS(ins->sizes);
14952         rhs = TRIPLE_RHS(ins->sizes);
14953         /* Don't count the clobbers in lhs */
14954         for(i = 0; i < lhs; i++) {
14955                 if (LHS(ins, i)->type == &void_type) {
14956                         break;
14957                 }
14958         }
14959         lhs = i;
14960         fprintf(fp, "#ASM\n");
14961         fputc('\t', fp);
14962         for(ptr = info->str; *ptr; ptr++) {
14963                 char *next;
14964                 unsigned long param;
14965                 struct triple *piece;
14966                 if (*ptr != '%') {
14967                         fputc(*ptr, fp);
14968                         continue;
14969                 }
14970                 ptr++;
14971                 if (*ptr == '%') {
14972                         fputc('%', fp);
14973                         continue;
14974                 }
14975                 param = strtoul(ptr, &next, 10);
14976                 if (ptr == next) {
14977                         error(state, ins, "Invalid asm template");
14978                 }
14979                 if (param >= (lhs + rhs)) {
14980                         error(state, ins, "Invalid param %%%u in asm template",
14981                                 param);
14982                 }
14983                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
14984                 fprintf(fp, "%s", 
14985                         arch_reg_str(ID_REG(piece->id)));
14986                 ptr = next -1;
14987         }
14988         fprintf(fp, "\n#NOT ASM\n");
14989 }
14990
14991
14992 /* Only use the low x86 byte registers.  This allows me
14993  * allocate the entire register when a byte register is used.
14994  */
14995 #define X86_4_8BIT_GPRS 1
14996
14997 /* Recognized x86 cpu variants */
14998 #define BAD_CPU      0
14999 #define CPU_I386     1
15000 #define CPU_P3       2
15001 #define CPU_P4       3
15002 #define CPU_K7       4
15003 #define CPU_K8       5
15004
15005 #define CPU_DEFAULT  CPU_I386
15006
15007 /* The x86 register classes */
15008 #define REGC_FLAGS       0
15009 #define REGC_GPR8        1
15010 #define REGC_GPR16       2
15011 #define REGC_GPR32       3
15012 #define REGC_DIVIDEND64  4
15013 #define REGC_DIVIDEND32  5
15014 #define REGC_MMX         6
15015 #define REGC_XMM         7
15016 #define REGC_GPR32_8     8
15017 #define REGC_GPR16_8     9
15018 #define REGC_GPR8_LO    10
15019 #define REGC_IMM32      11
15020 #define REGC_IMM16      12
15021 #define REGC_IMM8       13
15022 #define LAST_REGC  REGC_IMM8
15023 #if LAST_REGC >= MAX_REGC
15024 #error "MAX_REGC is to low"
15025 #endif
15026
15027 /* Register class masks */
15028 #define REGCM_FLAGS      (1 << REGC_FLAGS)
15029 #define REGCM_GPR8       (1 << REGC_GPR8)
15030 #define REGCM_GPR16      (1 << REGC_GPR16)
15031 #define REGCM_GPR32      (1 << REGC_GPR32)
15032 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
15033 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
15034 #define REGCM_MMX        (1 << REGC_MMX)
15035 #define REGCM_XMM        (1 << REGC_XMM)
15036 #define REGCM_GPR32_8    (1 << REGC_GPR32_8)
15037 #define REGCM_GPR16_8    (1 << REGC_GPR16_8)
15038 #define REGCM_GPR8_LO    (1 << REGC_GPR8_LO)
15039 #define REGCM_IMM32      (1 << REGC_IMM32)
15040 #define REGCM_IMM16      (1 << REGC_IMM16)
15041 #define REGCM_IMM8       (1 << REGC_IMM8)
15042 #define REGCM_ALL        ((1 << (LAST_REGC + 1)) - 1)
15043
15044 /* The x86 registers */
15045 #define REG_EFLAGS  2
15046 #define REGC_FLAGS_FIRST REG_EFLAGS
15047 #define REGC_FLAGS_LAST  REG_EFLAGS
15048 #define REG_AL      3
15049 #define REG_BL      4
15050 #define REG_CL      5
15051 #define REG_DL      6
15052 #define REG_AH      7
15053 #define REG_BH      8
15054 #define REG_CH      9
15055 #define REG_DH      10
15056 #define REGC_GPR8_LO_FIRST REG_AL
15057 #define REGC_GPR8_LO_LAST  REG_DL
15058 #define REGC_GPR8_FIRST  REG_AL
15059 #define REGC_GPR8_LAST   REG_DH
15060 #define REG_AX     11
15061 #define REG_BX     12
15062 #define REG_CX     13
15063 #define REG_DX     14
15064 #define REG_SI     15
15065 #define REG_DI     16
15066 #define REG_BP     17
15067 #define REG_SP     18
15068 #define REGC_GPR16_FIRST REG_AX
15069 #define REGC_GPR16_LAST  REG_SP
15070 #define REG_EAX    19
15071 #define REG_EBX    20
15072 #define REG_ECX    21
15073 #define REG_EDX    22
15074 #define REG_ESI    23
15075 #define REG_EDI    24
15076 #define REG_EBP    25
15077 #define REG_ESP    26
15078 #define REGC_GPR32_FIRST REG_EAX
15079 #define REGC_GPR32_LAST  REG_ESP
15080 #define REG_EDXEAX 27
15081 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
15082 #define REGC_DIVIDEND64_LAST  REG_EDXEAX
15083 #define REG_DXAX   28
15084 #define REGC_DIVIDEND32_FIRST REG_DXAX
15085 #define REGC_DIVIDEND32_LAST  REG_DXAX
15086 #define REG_MMX0   29
15087 #define REG_MMX1   30
15088 #define REG_MMX2   31
15089 #define REG_MMX3   32
15090 #define REG_MMX4   33
15091 #define REG_MMX5   34
15092 #define REG_MMX6   35
15093 #define REG_MMX7   36
15094 #define REGC_MMX_FIRST REG_MMX0
15095 #define REGC_MMX_LAST  REG_MMX7
15096 #define REG_XMM0   37
15097 #define REG_XMM1   38
15098 #define REG_XMM2   39
15099 #define REG_XMM3   40
15100 #define REG_XMM4   41
15101 #define REG_XMM5   42
15102 #define REG_XMM6   43
15103 #define REG_XMM7   44
15104 #define REGC_XMM_FIRST REG_XMM0
15105 #define REGC_XMM_LAST  REG_XMM7
15106 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
15107 #define LAST_REG   REG_XMM7
15108
15109 #define REGC_GPR32_8_FIRST REG_EAX
15110 #define REGC_GPR32_8_LAST  REG_EDX
15111 #define REGC_GPR16_8_FIRST REG_AX
15112 #define REGC_GPR16_8_LAST  REG_DX
15113
15114 #define REGC_IMM8_FIRST    -1
15115 #define REGC_IMM8_LAST     -1
15116 #define REGC_IMM16_FIRST   -2
15117 #define REGC_IMM16_LAST    -1
15118 #define REGC_IMM32_FIRST   -4
15119 #define REGC_IMM32_LAST    -1
15120
15121 #if LAST_REG >= MAX_REGISTERS
15122 #error "MAX_REGISTERS to low"
15123 #endif
15124
15125
15126 static unsigned regc_size[LAST_REGC +1] = {
15127         [REGC_FLAGS]      = REGC_FLAGS_LAST      - REGC_FLAGS_FIRST + 1,
15128         [REGC_GPR8]       = REGC_GPR8_LAST       - REGC_GPR8_FIRST + 1,
15129         [REGC_GPR16]      = REGC_GPR16_LAST      - REGC_GPR16_FIRST + 1,
15130         [REGC_GPR32]      = REGC_GPR32_LAST      - REGC_GPR32_FIRST + 1,
15131         [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
15132         [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
15133         [REGC_MMX]        = REGC_MMX_LAST        - REGC_MMX_FIRST + 1,
15134         [REGC_XMM]        = REGC_XMM_LAST        - REGC_XMM_FIRST + 1,
15135         [REGC_GPR32_8]    = REGC_GPR32_8_LAST    - REGC_GPR32_8_FIRST + 1,
15136         [REGC_GPR16_8]    = REGC_GPR16_8_LAST    - REGC_GPR16_8_FIRST + 1,
15137         [REGC_GPR8_LO]    = REGC_GPR8_LO_LAST    - REGC_GPR8_LO_FIRST + 1,
15138         [REGC_IMM32]      = 0,
15139         [REGC_IMM16]      = 0,
15140         [REGC_IMM8]       = 0,
15141 };
15142
15143 static const struct {
15144         int first, last;
15145 } regcm_bound[LAST_REGC + 1] = {
15146         [REGC_FLAGS]      = { REGC_FLAGS_FIRST,      REGC_FLAGS_LAST },
15147         [REGC_GPR8]       = { REGC_GPR8_FIRST,       REGC_GPR8_LAST },
15148         [REGC_GPR16]      = { REGC_GPR16_FIRST,      REGC_GPR16_LAST },
15149         [REGC_GPR32]      = { REGC_GPR32_FIRST,      REGC_GPR32_LAST },
15150         [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
15151         [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
15152         [REGC_MMX]        = { REGC_MMX_FIRST,        REGC_MMX_LAST },
15153         [REGC_XMM]        = { REGC_XMM_FIRST,        REGC_XMM_LAST },
15154         [REGC_GPR32_8]    = { REGC_GPR32_8_FIRST,    REGC_GPR32_8_LAST },
15155         [REGC_GPR16_8]    = { REGC_GPR16_8_FIRST,    REGC_GPR16_8_LAST },
15156         [REGC_GPR8_LO]    = { REGC_GPR8_LO_FIRST,    REGC_GPR8_LO_LAST },
15157         [REGC_IMM32]      = { REGC_IMM32_FIRST,      REGC_IMM32_LAST },
15158         [REGC_IMM16]      = { REGC_IMM16_FIRST,      REGC_IMM16_LAST },
15159         [REGC_IMM8]       = { REGC_IMM8_FIRST,       REGC_IMM8_LAST },
15160 };
15161
15162 static int arch_encode_cpu(const char *cpu)
15163 {
15164         struct cpu {
15165                 const char *name;
15166                 int cpu;
15167         } cpus[] = {
15168                 { "i386", CPU_I386 },
15169                 { "p3",   CPU_P3 },
15170                 { "p4",   CPU_P4 },
15171                 { "k7",   CPU_K7 },
15172                 { "k8",   CPU_K8 },
15173                 {  0,     BAD_CPU }
15174         };
15175         struct cpu *ptr;
15176         for(ptr = cpus; ptr->name; ptr++) {
15177                 if (strcmp(ptr->name, cpu) == 0) {
15178                         break;
15179                 }
15180         }
15181         return ptr->cpu;
15182 }
15183
15184 static unsigned arch_regc_size(struct compile_state *state, int class)
15185 {
15186         if ((class < 0) || (class > LAST_REGC)) {
15187                 return 0;
15188         }
15189         return regc_size[class];
15190 }
15191
15192 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
15193 {
15194         /* See if two register classes may have overlapping registers */
15195         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
15196                 REGCM_GPR32_8 | REGCM_GPR32 | 
15197                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
15198
15199         /* Special case for the immediates */
15200         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15201                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
15202                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
15203                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
15204                 return 0;
15205         }
15206         return (regcm1 & regcm2) ||
15207                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
15208 }
15209
15210 static void arch_reg_equivs(
15211         struct compile_state *state, unsigned *equiv, int reg)
15212 {
15213         if ((reg < 0) || (reg > LAST_REG)) {
15214                 internal_error(state, 0, "invalid register");
15215         }
15216         *equiv++ = reg;
15217         switch(reg) {
15218         case REG_AL:
15219 #if X86_4_8BIT_GPRS
15220                 *equiv++ = REG_AH;
15221 #endif
15222                 *equiv++ = REG_AX;
15223                 *equiv++ = REG_EAX;
15224                 *equiv++ = REG_DXAX;
15225                 *equiv++ = REG_EDXEAX;
15226                 break;
15227         case REG_AH:
15228 #if X86_4_8BIT_GPRS
15229                 *equiv++ = REG_AL;
15230 #endif
15231                 *equiv++ = REG_AX;
15232                 *equiv++ = REG_EAX;
15233                 *equiv++ = REG_DXAX;
15234                 *equiv++ = REG_EDXEAX;
15235                 break;
15236         case REG_BL:  
15237 #if X86_4_8BIT_GPRS
15238                 *equiv++ = REG_BH;
15239 #endif
15240                 *equiv++ = REG_BX;
15241                 *equiv++ = REG_EBX;
15242                 break;
15243
15244         case REG_BH:
15245 #if X86_4_8BIT_GPRS
15246                 *equiv++ = REG_BL;
15247 #endif
15248                 *equiv++ = REG_BX;
15249                 *equiv++ = REG_EBX;
15250                 break;
15251         case REG_CL:
15252 #if X86_4_8BIT_GPRS
15253                 *equiv++ = REG_CH;
15254 #endif
15255                 *equiv++ = REG_CX;
15256                 *equiv++ = REG_ECX;
15257                 break;
15258
15259         case REG_CH:
15260 #if X86_4_8BIT_GPRS
15261                 *equiv++ = REG_CL;
15262 #endif
15263                 *equiv++ = REG_CX;
15264                 *equiv++ = REG_ECX;
15265                 break;
15266         case REG_DL:
15267 #if X86_4_8BIT_GPRS
15268                 *equiv++ = REG_DH;
15269 #endif
15270                 *equiv++ = REG_DX;
15271                 *equiv++ = REG_EDX;
15272                 *equiv++ = REG_DXAX;
15273                 *equiv++ = REG_EDXEAX;
15274                 break;
15275         case REG_DH:
15276 #if X86_4_8BIT_GPRS
15277                 *equiv++ = REG_DL;
15278 #endif
15279                 *equiv++ = REG_DX;
15280                 *equiv++ = REG_EDX;
15281                 *equiv++ = REG_DXAX;
15282                 *equiv++ = REG_EDXEAX;
15283                 break;
15284         case REG_AX:
15285                 *equiv++ = REG_AL;
15286                 *equiv++ = REG_AH;
15287                 *equiv++ = REG_EAX;
15288                 *equiv++ = REG_DXAX;
15289                 *equiv++ = REG_EDXEAX;
15290                 break;
15291         case REG_BX:
15292                 *equiv++ = REG_BL;
15293                 *equiv++ = REG_BH;
15294                 *equiv++ = REG_EBX;
15295                 break;
15296         case REG_CX:  
15297                 *equiv++ = REG_CL;
15298                 *equiv++ = REG_CH;
15299                 *equiv++ = REG_ECX;
15300                 break;
15301         case REG_DX:  
15302                 *equiv++ = REG_DL;
15303                 *equiv++ = REG_DH;
15304                 *equiv++ = REG_EDX;
15305                 *equiv++ = REG_DXAX;
15306                 *equiv++ = REG_EDXEAX;
15307                 break;
15308         case REG_SI:  
15309                 *equiv++ = REG_ESI;
15310                 break;
15311         case REG_DI:
15312                 *equiv++ = REG_EDI;
15313                 break;
15314         case REG_BP:
15315                 *equiv++ = REG_EBP;
15316                 break;
15317         case REG_SP:
15318                 *equiv++ = REG_ESP;
15319                 break;
15320         case REG_EAX:
15321                 *equiv++ = REG_AL;
15322                 *equiv++ = REG_AH;
15323                 *equiv++ = REG_AX;
15324                 *equiv++ = REG_DXAX;
15325                 *equiv++ = REG_EDXEAX;
15326                 break;
15327         case REG_EBX:
15328                 *equiv++ = REG_BL;
15329                 *equiv++ = REG_BH;
15330                 *equiv++ = REG_BX;
15331                 break;
15332         case REG_ECX:
15333                 *equiv++ = REG_CL;
15334                 *equiv++ = REG_CH;
15335                 *equiv++ = REG_CX;
15336                 break;
15337         case REG_EDX:
15338                 *equiv++ = REG_DL;
15339                 *equiv++ = REG_DH;
15340                 *equiv++ = REG_DX;
15341                 *equiv++ = REG_DXAX;
15342                 *equiv++ = REG_EDXEAX;
15343                 break;
15344         case REG_ESI: 
15345                 *equiv++ = REG_SI;
15346                 break;
15347         case REG_EDI: 
15348                 *equiv++ = REG_DI;
15349                 break;
15350         case REG_EBP: 
15351                 *equiv++ = REG_BP;
15352                 break;
15353         case REG_ESP: 
15354                 *equiv++ = REG_SP;
15355                 break;
15356         case REG_DXAX: 
15357                 *equiv++ = REG_AL;
15358                 *equiv++ = REG_AH;
15359                 *equiv++ = REG_DL;
15360                 *equiv++ = REG_DH;
15361                 *equiv++ = REG_AX;
15362                 *equiv++ = REG_DX;
15363                 *equiv++ = REG_EAX;
15364                 *equiv++ = REG_EDX;
15365                 *equiv++ = REG_EDXEAX;
15366                 break;
15367         case REG_EDXEAX: 
15368                 *equiv++ = REG_AL;
15369                 *equiv++ = REG_AH;
15370                 *equiv++ = REG_DL;
15371                 *equiv++ = REG_DH;
15372                 *equiv++ = REG_AX;
15373                 *equiv++ = REG_DX;
15374                 *equiv++ = REG_EAX;
15375                 *equiv++ = REG_EDX;
15376                 *equiv++ = REG_DXAX;
15377                 break;
15378         }
15379         *equiv++ = REG_UNSET; 
15380 }
15381
15382 static unsigned arch_avail_mask(struct compile_state *state)
15383 {
15384         unsigned avail_mask;
15385         /* REGCM_GPR8 is not available */
15386         avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 | 
15387                 REGCM_GPR32 | REGCM_GPR32_8 | 
15388                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15389                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
15390         switch(state->cpu) {
15391         case CPU_P3:
15392         case CPU_K7:
15393                 avail_mask |= REGCM_MMX;
15394                 break;
15395         case CPU_P4:
15396         case CPU_K8:
15397                 avail_mask |= REGCM_MMX | REGCM_XMM;
15398                 break;
15399         }
15400         return avail_mask;
15401 }
15402
15403 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
15404 {
15405         unsigned mask, result;
15406         int class, class2;
15407         result = regcm;
15408
15409         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
15410                 if ((result & mask) == 0) {
15411                         continue;
15412                 }
15413                 if (class > LAST_REGC) {
15414                         result &= ~mask;
15415                 }
15416                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
15417                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
15418                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
15419                                 result |= (1 << class2);
15420                         }
15421                 }
15422         }
15423         result &= arch_avail_mask(state);
15424         return result;
15425 }
15426
15427 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
15428 {
15429         /* Like arch_regcm_normalize except immediate register classes are excluded */
15430         regcm = arch_regcm_normalize(state, regcm);
15431         /* Remove the immediate register classes */
15432         regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
15433         return regcm;
15434         
15435 }
15436
15437 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
15438 {
15439         unsigned mask;
15440         int class;
15441         mask = 0;
15442         for(class = 0; class <= LAST_REGC; class++) {
15443                 if ((reg >= regcm_bound[class].first) &&
15444                         (reg <= regcm_bound[class].last)) {
15445                         mask |= (1 << class);
15446                 }
15447         }
15448         if (!mask) {
15449                 internal_error(state, 0, "reg %d not in any class", reg);
15450         }
15451         return mask;
15452 }
15453
15454 static struct reg_info arch_reg_constraint(
15455         struct compile_state *state, struct type *type, const char *constraint)
15456 {
15457         static const struct {
15458                 char class;
15459                 unsigned int mask;
15460                 unsigned int reg;
15461         } constraints[] = {
15462                 { 'r', REGCM_GPR32,   REG_UNSET },
15463                 { 'g', REGCM_GPR32,   REG_UNSET },
15464                 { 'p', REGCM_GPR32,   REG_UNSET },
15465                 { 'q', REGCM_GPR8_LO, REG_UNSET },
15466                 { 'Q', REGCM_GPR32_8, REG_UNSET },
15467                 { 'x', REGCM_XMM,     REG_UNSET },
15468                 { 'y', REGCM_MMX,     REG_UNSET },
15469                 { 'a', REGCM_GPR32,   REG_EAX },
15470                 { 'b', REGCM_GPR32,   REG_EBX },
15471                 { 'c', REGCM_GPR32,   REG_ECX },
15472                 { 'd', REGCM_GPR32,   REG_EDX },
15473                 { 'D', REGCM_GPR32,   REG_EDI },
15474                 { 'S', REGCM_GPR32,   REG_ESI },
15475                 { '\0', 0, REG_UNSET },
15476         };
15477         unsigned int regcm;
15478         unsigned int mask, reg;
15479         struct reg_info result;
15480         const char *ptr;
15481         regcm = arch_type_to_regcm(state, type);
15482         reg = REG_UNSET;
15483         mask = 0;
15484         for(ptr = constraint; *ptr; ptr++) {
15485                 int i;
15486                 if (*ptr ==  ' ') {
15487                         continue;
15488                 }
15489                 for(i = 0; constraints[i].class != '\0'; i++) {
15490                         if (constraints[i].class == *ptr) {
15491                                 break;
15492                         }
15493                 }
15494                 if (constraints[i].class == '\0') {
15495                         error(state, 0, "invalid register constraint ``%c''", *ptr);
15496                         break;
15497                 }
15498                 if ((constraints[i].mask & regcm) == 0) {
15499                         error(state, 0, "invalid register class %c specified",
15500                                 *ptr);
15501                 }
15502                 mask |= constraints[i].mask;
15503                 if (constraints[i].reg != REG_UNSET) {
15504                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
15505                                 error(state, 0, "Only one register may be specified");
15506                         }
15507                         reg = constraints[i].reg;
15508                 }
15509         }
15510         result.reg = reg;
15511         result.regcm = mask;
15512         return result;
15513 }
15514
15515 static struct reg_info arch_reg_clobber(
15516         struct compile_state *state, const char *clobber)
15517 {
15518         struct reg_info result;
15519         if (strcmp(clobber, "memory") == 0) {
15520                 result.reg = REG_UNSET;
15521                 result.regcm = 0;
15522         }
15523         else if (strcmp(clobber, "%eax") == 0) {
15524                 result.reg = REG_EAX;
15525                 result.regcm = REGCM_GPR32;
15526         }
15527         else if (strcmp(clobber, "%ebx") == 0) {
15528                 result.reg = REG_EBX;
15529                 result.regcm = REGCM_GPR32;
15530         }
15531         else if (strcmp(clobber, "%ecx") == 0) {
15532                 result.reg = REG_ECX;
15533                 result.regcm = REGCM_GPR32;
15534         }
15535         else if (strcmp(clobber, "%edx") == 0) {
15536                 result.reg = REG_EDX;
15537                 result.regcm = REGCM_GPR32;
15538         }
15539         else if (strcmp(clobber, "%esi") == 0) {
15540                 result.reg = REG_ESI;
15541                 result.regcm = REGCM_GPR32;
15542         }
15543         else if (strcmp(clobber, "%edi") == 0) {
15544                 result.reg = REG_EDI;
15545                 result.regcm = REGCM_GPR32;
15546         }
15547         else if (strcmp(clobber, "%ebp") == 0) {
15548                 result.reg = REG_EBP;
15549                 result.regcm = REGCM_GPR32;
15550         }
15551         else if (strcmp(clobber, "%esp") == 0) {
15552                 result.reg = REG_ESP;
15553                 result.regcm = REGCM_GPR32;
15554         }
15555         else if (strcmp(clobber, "cc") == 0) {
15556                 result.reg = REG_EFLAGS;
15557                 result.regcm = REGCM_FLAGS;
15558         }
15559         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
15560                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15561                 result.reg = REG_XMM0 + octdigval(clobber[3]);
15562                 result.regcm = REGCM_XMM;
15563         }
15564         else if ((strncmp(clobber, "mmx", 3) == 0) &&
15565                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
15566                 result.reg = REG_MMX0 + octdigval(clobber[3]);
15567                 result.regcm = REGCM_MMX;
15568         }
15569         else {
15570                 error(state, 0, "Invalid register clobber");
15571                 result.reg = REG_UNSET;
15572                 result.regcm = 0;
15573         }
15574         return result;
15575 }
15576
15577 static int do_select_reg(struct compile_state *state, 
15578         char *used, int reg, unsigned classes)
15579 {
15580         unsigned mask;
15581         if (used[reg]) {
15582                 return REG_UNSET;
15583         }
15584         mask = arch_reg_regcm(state, reg);
15585         return (classes & mask) ? reg : REG_UNSET;
15586 }
15587
15588 static int arch_select_free_register(
15589         struct compile_state *state, char *used, int classes)
15590 {
15591         /* Live ranges with the most neighbors are colored first.
15592          *
15593          * Generally it does not matter which colors are given
15594          * as the register allocator attempts to color live ranges
15595          * in an order where you are guaranteed not to run out of colors.
15596          *
15597          * Occasionally the register allocator cannot find an order
15598          * of register selection that will find a free color.  To
15599          * increase the odds the register allocator will work when
15600          * it guesses first give out registers from register classes
15601          * least likely to run out of registers.
15602          * 
15603          */
15604         int i, reg;
15605         reg = REG_UNSET;
15606         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
15607                 reg = do_select_reg(state, used, i, classes);
15608         }
15609         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
15610                 reg = do_select_reg(state, used, i, classes);
15611         }
15612         for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
15613                 reg = do_select_reg(state, used, i, classes);
15614         }
15615         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
15616                 reg = do_select_reg(state, used, i, classes);
15617         }
15618         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
15619                 reg = do_select_reg(state, used, i, classes);
15620         }
15621         for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
15622                 reg = do_select_reg(state, used, i, classes);
15623         }
15624         for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
15625                 reg = do_select_reg(state, used, i, classes);
15626         }
15627         for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
15628                 reg = do_select_reg(state, used, i, classes);
15629         }
15630         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
15631                 reg = do_select_reg(state, used, i, classes);
15632         }
15633         return reg;
15634 }
15635
15636
15637 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
15638 {
15639 #warning "FIXME force types smaller (if legal) before I get here"
15640         unsigned mask;
15641         mask = 0;
15642         switch(type->type & TYPE_MASK) {
15643         case TYPE_ARRAY:
15644         case TYPE_VOID: 
15645                 mask = 0; 
15646                 break;
15647         case TYPE_CHAR:
15648         case TYPE_UCHAR:
15649                 mask = REGCM_GPR8 | REGCM_GPR8_LO |
15650                         REGCM_GPR16 | REGCM_GPR16_8 | 
15651                         REGCM_GPR32 | REGCM_GPR32_8 |
15652                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15653                         REGCM_MMX | REGCM_XMM |
15654                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
15655                 break;
15656         case TYPE_SHORT:
15657         case TYPE_USHORT:
15658                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
15659                         REGCM_GPR32 | REGCM_GPR32_8 |
15660                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15661                         REGCM_MMX | REGCM_XMM |
15662                         REGCM_IMM32 | REGCM_IMM16;
15663                 break;
15664         case TYPE_INT:
15665         case TYPE_UINT:
15666         case TYPE_LONG:
15667         case TYPE_ULONG:
15668         case TYPE_POINTER:
15669                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
15670                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
15671                         REGCM_MMX | REGCM_XMM |
15672                         REGCM_IMM32;
15673                 break;
15674         default:
15675                 internal_error(state, 0, "no register class for type");
15676                 break;
15677         }
15678         mask = arch_regcm_normalize(state, mask);
15679         return mask;
15680 }
15681
15682 static int is_imm32(struct triple *imm)
15683 {
15684         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
15685                 (imm->op == OP_ADDRCONST);
15686         
15687 }
15688 static int is_imm16(struct triple *imm)
15689 {
15690         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
15691 }
15692 static int is_imm8(struct triple *imm)
15693 {
15694         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
15695 }
15696
15697 static int get_imm32(struct triple *ins, struct triple **expr)
15698 {
15699         struct triple *imm;
15700         imm = *expr;
15701         while(imm->op == OP_COPY) {
15702                 imm = RHS(imm, 0);
15703         }
15704         if (!is_imm32(imm)) {
15705                 return 0;
15706         }
15707         unuse_triple(*expr, ins);
15708         use_triple(imm, ins);
15709         *expr = imm;
15710         return 1;
15711 }
15712
15713 static int get_imm8(struct triple *ins, struct triple **expr)
15714 {
15715         struct triple *imm;
15716         imm = *expr;
15717         while(imm->op == OP_COPY) {
15718                 imm = RHS(imm, 0);
15719         }
15720         if (!is_imm8(imm)) {
15721                 return 0;
15722         }
15723         unuse_triple(*expr, ins);
15724         use_triple(imm, ins);
15725         *expr = imm;
15726         return 1;
15727 }
15728
15729 #define TEMPLATE_NOP           0
15730 #define TEMPLATE_INTCONST8     1
15731 #define TEMPLATE_INTCONST32    2
15732 #define TEMPLATE_COPY8_REG     3
15733 #define TEMPLATE_COPY16_REG    4
15734 #define TEMPLATE_COPY32_REG    5
15735 #define TEMPLATE_COPY_IMM8     6
15736 #define TEMPLATE_COPY_IMM16    7
15737 #define TEMPLATE_COPY_IMM32    8
15738 #define TEMPLATE_PHI8          9
15739 #define TEMPLATE_PHI16        10
15740 #define TEMPLATE_PHI32        11
15741 #define TEMPLATE_STORE8       12
15742 #define TEMPLATE_STORE16      13
15743 #define TEMPLATE_STORE32      14
15744 #define TEMPLATE_LOAD8        15
15745 #define TEMPLATE_LOAD16       16
15746 #define TEMPLATE_LOAD32       17
15747 #define TEMPLATE_BINARY8_REG  18
15748 #define TEMPLATE_BINARY16_REG 19
15749 #define TEMPLATE_BINARY32_REG 20
15750 #define TEMPLATE_BINARY8_IMM  21
15751 #define TEMPLATE_BINARY16_IMM 22
15752 #define TEMPLATE_BINARY32_IMM 23
15753 #define TEMPLATE_SL8_CL       24
15754 #define TEMPLATE_SL16_CL      25
15755 #define TEMPLATE_SL32_CL      26
15756 #define TEMPLATE_SL8_IMM      27
15757 #define TEMPLATE_SL16_IMM     28
15758 #define TEMPLATE_SL32_IMM     29
15759 #define TEMPLATE_UNARY8       30
15760 #define TEMPLATE_UNARY16      31
15761 #define TEMPLATE_UNARY32      32
15762 #define TEMPLATE_CMP8_REG     33
15763 #define TEMPLATE_CMP16_REG    34
15764 #define TEMPLATE_CMP32_REG    35
15765 #define TEMPLATE_CMP8_IMM     36
15766 #define TEMPLATE_CMP16_IMM    37
15767 #define TEMPLATE_CMP32_IMM    38
15768 #define TEMPLATE_TEST8        39
15769 #define TEMPLATE_TEST16       40
15770 #define TEMPLATE_TEST32       41
15771 #define TEMPLATE_SET          42
15772 #define TEMPLATE_JMP          43
15773 #define TEMPLATE_INB_DX       44
15774 #define TEMPLATE_INB_IMM      45
15775 #define TEMPLATE_INW_DX       46
15776 #define TEMPLATE_INW_IMM      47
15777 #define TEMPLATE_INL_DX       48
15778 #define TEMPLATE_INL_IMM      49
15779 #define TEMPLATE_OUTB_DX      50
15780 #define TEMPLATE_OUTB_IMM     51
15781 #define TEMPLATE_OUTW_DX      52
15782 #define TEMPLATE_OUTW_IMM     53
15783 #define TEMPLATE_OUTL_DX      54
15784 #define TEMPLATE_OUTL_IMM     55
15785 #define TEMPLATE_BSF          56
15786 #define TEMPLATE_RDMSR        57
15787 #define TEMPLATE_WRMSR        58
15788 #define TEMPLATE_UMUL8        59
15789 #define TEMPLATE_UMUL16       60
15790 #define TEMPLATE_UMUL32       61
15791 #define TEMPLATE_DIV8         62
15792 #define TEMPLATE_DIV16        63
15793 #define TEMPLATE_DIV32        64
15794 #define LAST_TEMPLATE       TEMPLATE_DIV32
15795 #if LAST_TEMPLATE >= MAX_TEMPLATES
15796 #error "MAX_TEMPLATES to low"
15797 #endif
15798
15799 #define COPY8_REGCM     (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
15800 #define COPY16_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)  
15801 #define COPY32_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
15802
15803
15804 static struct ins_template templates[] = {
15805         [TEMPLATE_NOP]      = {},
15806         [TEMPLATE_INTCONST8] = { 
15807                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15808         },
15809         [TEMPLATE_INTCONST32] = { 
15810                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
15811         },
15812         [TEMPLATE_COPY8_REG] = {
15813                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15814                 .rhs = { [0] = { REG_UNSET, COPY8_REGCM }  },
15815         },
15816         [TEMPLATE_COPY16_REG] = {
15817                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15818                 .rhs = { [0] = { REG_UNSET, COPY16_REGCM }  },
15819         },
15820         [TEMPLATE_COPY32_REG] = {
15821                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15822                 .rhs = { [0] = { REG_UNSET, COPY32_REGCM }  },
15823         },
15824         [TEMPLATE_COPY_IMM8] = {
15825                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
15826                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
15827         },
15828         [TEMPLATE_COPY_IMM16] = {
15829                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
15830                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
15831         },
15832         [TEMPLATE_COPY_IMM32] = {
15833                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
15834                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
15835         },
15836         [TEMPLATE_PHI8] = { 
15837                 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
15838                 .rhs = { 
15839                         [ 0] = { REG_VIRT0, COPY8_REGCM },
15840                         [ 1] = { REG_VIRT0, COPY8_REGCM },
15841                         [ 2] = { REG_VIRT0, COPY8_REGCM },
15842                         [ 3] = { REG_VIRT0, COPY8_REGCM },
15843                         [ 4] = { REG_VIRT0, COPY8_REGCM },
15844                         [ 5] = { REG_VIRT0, COPY8_REGCM },
15845                         [ 6] = { REG_VIRT0, COPY8_REGCM },
15846                         [ 7] = { REG_VIRT0, COPY8_REGCM },
15847                         [ 8] = { REG_VIRT0, COPY8_REGCM },
15848                         [ 9] = { REG_VIRT0, COPY8_REGCM },
15849                         [10] = { REG_VIRT0, COPY8_REGCM },
15850                         [11] = { REG_VIRT0, COPY8_REGCM },
15851                         [12] = { REG_VIRT0, COPY8_REGCM },
15852                         [13] = { REG_VIRT0, COPY8_REGCM },
15853                         [14] = { REG_VIRT0, COPY8_REGCM },
15854                         [15] = { REG_VIRT0, COPY8_REGCM },
15855                 }, },
15856         [TEMPLATE_PHI16] = { 
15857                 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
15858                 .rhs = { 
15859                         [ 0] = { REG_VIRT0, COPY16_REGCM },
15860                         [ 1] = { REG_VIRT0, COPY16_REGCM },
15861                         [ 2] = { REG_VIRT0, COPY16_REGCM },
15862                         [ 3] = { REG_VIRT0, COPY16_REGCM },
15863                         [ 4] = { REG_VIRT0, COPY16_REGCM },
15864                         [ 5] = { REG_VIRT0, COPY16_REGCM },
15865                         [ 6] = { REG_VIRT0, COPY16_REGCM },
15866                         [ 7] = { REG_VIRT0, COPY16_REGCM },
15867                         [ 8] = { REG_VIRT0, COPY16_REGCM },
15868                         [ 9] = { REG_VIRT0, COPY16_REGCM },
15869                         [10] = { REG_VIRT0, COPY16_REGCM },
15870                         [11] = { REG_VIRT0, COPY16_REGCM },
15871                         [12] = { REG_VIRT0, COPY16_REGCM },
15872                         [13] = { REG_VIRT0, COPY16_REGCM },
15873                         [14] = { REG_VIRT0, COPY16_REGCM },
15874                         [15] = { REG_VIRT0, COPY16_REGCM },
15875                 }, },
15876         [TEMPLATE_PHI32] = { 
15877                 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
15878                 .rhs = { 
15879                         [ 0] = { REG_VIRT0, COPY32_REGCM },
15880                         [ 1] = { REG_VIRT0, COPY32_REGCM },
15881                         [ 2] = { REG_VIRT0, COPY32_REGCM },
15882                         [ 3] = { REG_VIRT0, COPY32_REGCM },
15883                         [ 4] = { REG_VIRT0, COPY32_REGCM },
15884                         [ 5] = { REG_VIRT0, COPY32_REGCM },
15885                         [ 6] = { REG_VIRT0, COPY32_REGCM },
15886                         [ 7] = { REG_VIRT0, COPY32_REGCM },
15887                         [ 8] = { REG_VIRT0, COPY32_REGCM },
15888                         [ 9] = { REG_VIRT0, COPY32_REGCM },
15889                         [10] = { REG_VIRT0, COPY32_REGCM },
15890                         [11] = { REG_VIRT0, COPY32_REGCM },
15891                         [12] = { REG_VIRT0, COPY32_REGCM },
15892                         [13] = { REG_VIRT0, COPY32_REGCM },
15893                         [14] = { REG_VIRT0, COPY32_REGCM },
15894                         [15] = { REG_VIRT0, COPY32_REGCM },
15895                 }, },
15896         [TEMPLATE_STORE8] = {
15897                 .rhs = { 
15898                         [0] = { REG_UNSET, REGCM_GPR32 },
15899                         [1] = { REG_UNSET, REGCM_GPR8_LO },
15900                 },
15901         },
15902         [TEMPLATE_STORE16] = {
15903                 .rhs = { 
15904                         [0] = { REG_UNSET, REGCM_GPR32 },
15905                         [1] = { REG_UNSET, REGCM_GPR16 },
15906                 },
15907         },
15908         [TEMPLATE_STORE32] = {
15909                 .rhs = { 
15910                         [0] = { REG_UNSET, REGCM_GPR32 },
15911                         [1] = { REG_UNSET, REGCM_GPR32 },
15912                 },
15913         },
15914         [TEMPLATE_LOAD8] = {
15915                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
15916                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15917         },
15918         [TEMPLATE_LOAD16] = {
15919                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
15920                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15921         },
15922         [TEMPLATE_LOAD32] = {
15923                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15924                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
15925         },
15926         [TEMPLATE_BINARY8_REG] = {
15927                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15928                 .rhs = { 
15929                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
15930                         [1] = { REG_UNSET, REGCM_GPR8_LO },
15931                 },
15932         },
15933         [TEMPLATE_BINARY16_REG] = {
15934                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15935                 .rhs = { 
15936                         [0] = { REG_VIRT0, REGCM_GPR16 },
15937                         [1] = { REG_UNSET, REGCM_GPR16 },
15938                 },
15939         },
15940         [TEMPLATE_BINARY32_REG] = {
15941                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15942                 .rhs = { 
15943                         [0] = { REG_VIRT0, REGCM_GPR32 },
15944                         [1] = { REG_UNSET, REGCM_GPR32 },
15945                 },
15946         },
15947         [TEMPLATE_BINARY8_IMM] = {
15948                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15949                 .rhs = { 
15950                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
15951                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15952                 },
15953         },
15954         [TEMPLATE_BINARY16_IMM] = {
15955                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15956                 .rhs = { 
15957                         [0] = { REG_VIRT0,    REGCM_GPR16 },
15958                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
15959                 },
15960         },
15961         [TEMPLATE_BINARY32_IMM] = {
15962                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15963                 .rhs = { 
15964                         [0] = { REG_VIRT0,    REGCM_GPR32 },
15965                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
15966                 },
15967         },
15968         [TEMPLATE_SL8_CL] = {
15969                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15970                 .rhs = { 
15971                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
15972                         [1] = { REG_CL, REGCM_GPR8_LO },
15973                 },
15974         },
15975         [TEMPLATE_SL16_CL] = {
15976                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15977                 .rhs = { 
15978                         [0] = { REG_VIRT0, REGCM_GPR16 },
15979                         [1] = { REG_CL, REGCM_GPR8_LO },
15980                 },
15981         },
15982         [TEMPLATE_SL32_CL] = {
15983                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
15984                 .rhs = { 
15985                         [0] = { REG_VIRT0, REGCM_GPR32 },
15986                         [1] = { REG_CL, REGCM_GPR8_LO },
15987                 },
15988         },
15989         [TEMPLATE_SL8_IMM] = {
15990                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
15991                 .rhs = { 
15992                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
15993                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
15994                 },
15995         },
15996         [TEMPLATE_SL16_IMM] = {
15997                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
15998                 .rhs = { 
15999                         [0] = { REG_VIRT0,    REGCM_GPR16 },
16000                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
16001                 },
16002         },
16003         [TEMPLATE_SL32_IMM] = {
16004                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16005                 .rhs = { 
16006                         [0] = { REG_VIRT0,    REGCM_GPR32 },
16007                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
16008                 },
16009         },
16010         [TEMPLATE_UNARY8] = {
16011                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16012                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
16013         },
16014         [TEMPLATE_UNARY16] = {
16015                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16016                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
16017         },
16018         [TEMPLATE_UNARY32] = {
16019                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16020                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
16021         },
16022         [TEMPLATE_CMP8_REG] = {
16023                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16024                 .rhs = {
16025                         [0] = { REG_UNSET, REGCM_GPR8_LO },
16026                         [1] = { REG_UNSET, REGCM_GPR8_LO },
16027                 },
16028         },
16029         [TEMPLATE_CMP16_REG] = {
16030                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16031                 .rhs = {
16032                         [0] = { REG_UNSET, REGCM_GPR16 },
16033                         [1] = { REG_UNSET, REGCM_GPR16 },
16034                 },
16035         },
16036         [TEMPLATE_CMP32_REG] = {
16037                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16038                 .rhs = {
16039                         [0] = { REG_UNSET, REGCM_GPR32 },
16040                         [1] = { REG_UNSET, REGCM_GPR32 },
16041                 },
16042         },
16043         [TEMPLATE_CMP8_IMM] = {
16044                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16045                 .rhs = {
16046                         [0] = { REG_UNSET, REGCM_GPR8_LO },
16047                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
16048                 },
16049         },
16050         [TEMPLATE_CMP16_IMM] = {
16051                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16052                 .rhs = {
16053                         [0] = { REG_UNSET, REGCM_GPR16 },
16054                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
16055                 },
16056         },
16057         [TEMPLATE_CMP32_IMM] = {
16058                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16059                 .rhs = {
16060                         [0] = { REG_UNSET, REGCM_GPR32 },
16061                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
16062                 },
16063         },
16064         [TEMPLATE_TEST8] = {
16065                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16066                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16067         },
16068         [TEMPLATE_TEST16] = {
16069                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16070                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
16071         },
16072         [TEMPLATE_TEST32] = {
16073                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16074                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16075         },
16076         [TEMPLATE_SET] = {
16077                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
16078                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16079         },
16080         [TEMPLATE_JMP] = {
16081                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
16082         },
16083         [TEMPLATE_INB_DX] = {
16084                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },  
16085                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16086         },
16087         [TEMPLATE_INB_IMM] = {
16088                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },  
16089                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16090         },
16091         [TEMPLATE_INW_DX]  = { 
16092                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
16093                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16094         },
16095         [TEMPLATE_INW_IMM] = { 
16096                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
16097                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16098         },
16099         [TEMPLATE_INL_DX]  = {
16100                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16101                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
16102         },
16103         [TEMPLATE_INL_IMM] = {
16104                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
16105                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
16106         },
16107         [TEMPLATE_OUTB_DX] = { 
16108                 .rhs = {
16109                         [0] = { REG_AL,  REGCM_GPR8_LO },
16110                         [1] = { REG_DX, REGCM_GPR16 },
16111                 },
16112         },
16113         [TEMPLATE_OUTB_IMM] = { 
16114                 .rhs = {
16115                         [0] = { REG_AL,  REGCM_GPR8_LO },  
16116                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
16117                 },
16118         },
16119         [TEMPLATE_OUTW_DX] = { 
16120                 .rhs = {
16121                         [0] = { REG_AX,  REGCM_GPR16 },
16122                         [1] = { REG_DX, REGCM_GPR16 },
16123                 },
16124         },
16125         [TEMPLATE_OUTW_IMM] = {
16126                 .rhs = {
16127                         [0] = { REG_AX,  REGCM_GPR16 }, 
16128                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
16129                 },
16130         },
16131         [TEMPLATE_OUTL_DX] = { 
16132                 .rhs = {
16133                         [0] = { REG_EAX, REGCM_GPR32 },
16134                         [1] = { REG_DX, REGCM_GPR16 },
16135                 },
16136         },
16137         [TEMPLATE_OUTL_IMM] = { 
16138                 .rhs = {
16139                         [0] = { REG_EAX, REGCM_GPR32 }, 
16140                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
16141                 },
16142         },
16143         [TEMPLATE_BSF] = {
16144                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16145                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
16146         },
16147         [TEMPLATE_RDMSR] = {
16148                 .lhs = { 
16149                         [0] = { REG_EAX, REGCM_GPR32 },
16150                         [1] = { REG_EDX, REGCM_GPR32 },
16151                 },
16152                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
16153         },
16154         [TEMPLATE_WRMSR] = {
16155                 .rhs = {
16156                         [0] = { REG_ECX, REGCM_GPR32 },
16157                         [1] = { REG_EAX, REGCM_GPR32 },
16158                         [2] = { REG_EDX, REGCM_GPR32 },
16159                 },
16160         },
16161         [TEMPLATE_UMUL8] = {
16162                 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
16163                 .rhs = { 
16164                         [0] = { REG_AL, REGCM_GPR8_LO },
16165                         [1] = { REG_UNSET, REGCM_GPR8_LO },
16166                 },
16167         },
16168         [TEMPLATE_UMUL16] = {
16169                 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
16170                 .rhs = { 
16171                         [0] = { REG_AX, REGCM_GPR16 },
16172                         [1] = { REG_UNSET, REGCM_GPR16 },
16173                 },
16174         },
16175         [TEMPLATE_UMUL32] = {
16176                 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
16177                 .rhs = { 
16178                         [0] = { REG_EAX, REGCM_GPR32 },
16179                         [1] = { REG_UNSET, REGCM_GPR32 },
16180                 },
16181         },
16182         [TEMPLATE_DIV8] = {
16183                 .lhs = { 
16184                         [0] = { REG_AL, REGCM_GPR8_LO },
16185                         [1] = { REG_AH, REGCM_GPR8 },
16186                 },
16187                 .rhs = {
16188                         [0] = { REG_AX, REGCM_GPR16 },
16189                         [1] = { REG_UNSET, REGCM_GPR8_LO },
16190                 },
16191         },
16192         [TEMPLATE_DIV16] = {
16193                 .lhs = { 
16194                         [0] = { REG_AX, REGCM_GPR16 },
16195                         [1] = { REG_DX, REGCM_GPR16 },
16196                 },
16197                 .rhs = {
16198                         [0] = { REG_DXAX, REGCM_DIVIDEND32 },
16199                         [1] = { REG_UNSET, REGCM_GPR16 },
16200                 },
16201         },
16202         [TEMPLATE_DIV32] = {
16203                 .lhs = { 
16204                         [0] = { REG_EAX, REGCM_GPR32 },
16205                         [1] = { REG_EDX, REGCM_GPR32 },
16206                 },
16207                 .rhs = {
16208                         [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
16209                         [1] = { REG_UNSET, REGCM_GPR32 },
16210                 },
16211         },
16212 };
16213
16214 static void fixup_branches(struct compile_state *state,
16215         struct triple *cmp, struct triple *use, int jmp_op)
16216 {
16217         struct triple_set *entry, *next;
16218         for(entry = use->use; entry; entry = next) {
16219                 next = entry->next;
16220                 if (entry->member->op == OP_COPY) {
16221                         fixup_branches(state, cmp, entry->member, jmp_op);
16222                 }
16223                 else if (entry->member->op == OP_BRANCH) {
16224                         struct triple *branch, *test;
16225                         struct triple *left, *right;
16226                         left = right = 0;
16227                         left = RHS(cmp, 0);
16228                         if (TRIPLE_RHS(cmp->sizes) > 1) {
16229                                 right = RHS(cmp, 1);
16230                         }
16231                         branch = entry->member;
16232                         test = pre_triple(state, branch,
16233                                 cmp->op, cmp->type, left, right);
16234                         test->template_id = TEMPLATE_TEST32; 
16235                         if (cmp->op == OP_CMP) {
16236                                 test->template_id = TEMPLATE_CMP32_REG;
16237                                 if (get_imm32(test, &RHS(test, 1))) {
16238                                         test->template_id = TEMPLATE_CMP32_IMM;
16239                                 }
16240                         }
16241                         use_triple(RHS(test, 0), test);
16242                         use_triple(RHS(test, 1), test);
16243                         unuse_triple(RHS(branch, 0), branch);
16244                         RHS(branch, 0) = test;
16245                         branch->op = jmp_op;
16246                         branch->template_id = TEMPLATE_JMP;
16247                         use_triple(RHS(branch, 0), branch);
16248                 }
16249         }
16250 }
16251
16252 static void bool_cmp(struct compile_state *state, 
16253         struct triple *ins, int cmp_op, int jmp_op, int set_op)
16254 {
16255         struct triple_set *entry, *next;
16256         struct triple *set;
16257
16258         /* Put a barrier up before the cmp which preceeds the
16259          * copy instruction.  If a set actually occurs this gives
16260          * us a chance to move variables in registers out of the way.
16261          */
16262
16263         /* Modify the comparison operator */
16264         ins->op = cmp_op;
16265         ins->template_id = TEMPLATE_TEST32;
16266         if (cmp_op == OP_CMP) {
16267                 ins->template_id = TEMPLATE_CMP32_REG;
16268                 if (get_imm32(ins, &RHS(ins, 1))) {
16269                         ins->template_id =  TEMPLATE_CMP32_IMM;
16270                 }
16271         }
16272         /* Generate the instruction sequence that will transform the
16273          * result of the comparison into a logical value.
16274          */
16275         set = post_triple(state, ins, set_op, &char_type, ins, 0);
16276         use_triple(ins, set);
16277         set->template_id = TEMPLATE_SET;
16278
16279         for(entry = ins->use; entry; entry = next) {
16280                 next = entry->next;
16281                 if (entry->member == set) {
16282                         continue;
16283                 }
16284                 replace_rhs_use(state, ins, set, entry->member);
16285         }
16286         fixup_branches(state, ins, set, jmp_op);
16287 }
16288
16289 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
16290 {
16291         struct triple *next;
16292         int lhs, i;
16293         lhs = TRIPLE_LHS(ins->sizes);
16294         for(next = ins->next, i = 0; i < lhs; i++, next = next->next) {
16295                 if (next != LHS(ins, i)) {
16296                         internal_error(state, ins, "malformed lhs on %s",
16297                                 tops(ins->op));
16298                 }
16299                 if (next->op != OP_PIECE) {
16300                         internal_error(state, ins, "bad lhs op %s at %d on %s",
16301                                 tops(next->op), i, tops(ins->op));
16302                 }
16303                 if (next->u.cval != i) {
16304                         internal_error(state, ins, "bad u.cval of %d %d expected",
16305                                 next->u.cval, i);
16306                 }
16307         }
16308         return next;
16309 }
16310
16311 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
16312 {
16313         struct ins_template *template;
16314         struct reg_info result;
16315         int zlhs;
16316         if (ins->op == OP_PIECE) {
16317                 index = ins->u.cval;
16318                 ins = MISC(ins, 0);
16319         }
16320         zlhs = TRIPLE_LHS(ins->sizes);
16321         if (triple_is_def(state, ins)) {
16322                 zlhs = 1;
16323         }
16324         if (index >= zlhs) {
16325                 internal_error(state, ins, "index %d out of range for %s\n",
16326                         index, tops(ins->op));
16327         }
16328         switch(ins->op) {
16329         case OP_ASM:
16330                 template = &ins->u.ainfo->tmpl;
16331                 break;
16332         default:
16333                 if (ins->template_id > LAST_TEMPLATE) {
16334                         internal_error(state, ins, "bad template number %d", 
16335                                 ins->template_id);
16336                 }
16337                 template = &templates[ins->template_id];
16338                 break;
16339         }
16340         result = template->lhs[index];
16341         result.regcm = arch_regcm_normalize(state, result.regcm);
16342         if (result.reg != REG_UNNEEDED) {
16343                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
16344         }
16345         if (result.regcm == 0) {
16346                 internal_error(state, ins, "lhs %d regcm == 0", index);
16347         }
16348         return result;
16349 }
16350
16351 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
16352 {
16353         struct reg_info result;
16354         struct ins_template *template;
16355         if ((index > TRIPLE_RHS(ins->sizes)) ||
16356                 (ins->op == OP_PIECE)) {
16357                 internal_error(state, ins, "index %d out of range for %s\n",
16358                         index, tops(ins->op));
16359         }
16360         switch(ins->op) {
16361         case OP_ASM:
16362                 template = &ins->u.ainfo->tmpl;
16363                 break;
16364         default:
16365                 if (ins->template_id > LAST_TEMPLATE) {
16366                         internal_error(state, ins, "bad template number %d", 
16367                                 ins->template_id);
16368                 }
16369                 template = &templates[ins->template_id];
16370                 break;
16371         }
16372         result = template->rhs[index];
16373         result.regcm = arch_regcm_normalize(state, result.regcm);
16374         if (result.regcm == 0) {
16375                 internal_error(state, ins, "rhs %d regcm == 0", index);
16376         }
16377         return result;
16378 }
16379
16380 static struct triple *mod_div(struct compile_state *state,
16381         struct triple *ins, int div_op, int index)
16382 {
16383         struct triple *div, *piece0, *piece1;
16384         
16385         /* Generate a piece to hold the remainder */
16386         piece1 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16387         piece1->u.cval = 1;
16388
16389         /* Generate a piece to hold the quotient */
16390         piece0 = post_triple(state, ins, OP_PIECE, ins->type, 0, 0);
16391         piece0->u.cval = 0;
16392
16393         /* Generate the appropriate division instruction */
16394         div = post_triple(state, ins, div_op, ins->type, 0, 0);
16395         RHS(div, 0) = RHS(ins, 0);
16396         RHS(div, 1) = RHS(ins, 1);
16397         LHS(div, 0) = piece0;
16398         LHS(div, 1) = piece1;
16399         div->template_id  = TEMPLATE_DIV32;
16400         use_triple(RHS(div, 0), div);
16401         use_triple(RHS(div, 1), div);
16402         use_triple(LHS(div, 0), div);
16403         use_triple(LHS(div, 1), div);
16404
16405         /* Hook on piece0 */
16406         MISC(piece0, 0) = div;
16407         use_triple(div, piece0);
16408
16409         /* Hook on piece1 */
16410         MISC(piece1, 0) = div;
16411         use_triple(div, piece1);
16412         
16413         /* Replate uses of ins with the appropriate piece of the div */
16414         propogate_use(state, ins, LHS(div, index));
16415         release_triple(state, ins);
16416
16417         /* Return the address of the next instruction */
16418         return piece1->next;
16419 }
16420
16421 static struct triple *transform_to_arch_instruction(
16422         struct compile_state *state, struct triple *ins)
16423 {
16424         /* Transform from generic 3 address instructions
16425          * to archtecture specific instructions.
16426          * And apply architecture specific constraints to instructions.
16427          * Copies are inserted to preserve the register flexibility
16428          * of 3 address instructions.
16429          */
16430         struct triple *next;
16431         size_t size;
16432         next = ins->next;
16433         switch(ins->op) {
16434         case OP_INTCONST:
16435                 ins->template_id = TEMPLATE_INTCONST32;
16436                 if (ins->u.cval < 256) {
16437                         ins->template_id = TEMPLATE_INTCONST8;
16438                 }
16439                 break;
16440         case OP_ADDRCONST:
16441                 ins->template_id = TEMPLATE_INTCONST32;
16442                 break;
16443         case OP_NOOP:
16444         case OP_SDECL:
16445         case OP_BLOBCONST:
16446         case OP_LABEL:
16447                 ins->template_id = TEMPLATE_NOP;
16448                 break;
16449         case OP_COPY:
16450                 size = size_of(state, ins->type);
16451                 if (is_imm8(RHS(ins, 0)) && (size <= 1)) {
16452                         ins->template_id = TEMPLATE_COPY_IMM8;
16453                 }
16454                 else if (is_imm16(RHS(ins, 0)) && (size <= 2)) {
16455                         ins->template_id = TEMPLATE_COPY_IMM16;
16456                 }
16457                 else if (is_imm32(RHS(ins, 0)) && (size <= 4)) {
16458                         ins->template_id = TEMPLATE_COPY_IMM32;
16459                 }
16460                 else if (is_const(RHS(ins, 0))) {
16461                         internal_error(state, ins, "bad constant passed to copy");
16462                 }
16463                 else if (size <= 1) {
16464                         ins->template_id = TEMPLATE_COPY8_REG;
16465                 }
16466                 else if (size <= 2) {
16467                         ins->template_id = TEMPLATE_COPY16_REG;
16468                 }
16469                 else if (size <= 4) {
16470                         ins->template_id = TEMPLATE_COPY32_REG;
16471                 }
16472                 else {
16473                         internal_error(state, ins, "bad type passed to copy");
16474                 }
16475                 break;
16476         case OP_PHI:
16477                 size = size_of(state, ins->type);
16478                 if (size <= 1) {
16479                         ins->template_id = TEMPLATE_PHI8;
16480                 }
16481                 else if (size <= 2) {
16482                         ins->template_id = TEMPLATE_PHI16;
16483                 }
16484                 else if (size <= 4) {
16485                         ins->template_id = TEMPLATE_PHI32;
16486                 }
16487                 else {
16488                         internal_error(state, ins, "bad type passed to phi");
16489                 }
16490                 break;
16491         case OP_STORE:
16492                 switch(ins->type->type & TYPE_MASK) {
16493                 case TYPE_CHAR:    case TYPE_UCHAR:
16494                         ins->template_id = TEMPLATE_STORE8;
16495                         break;
16496                 case TYPE_SHORT:   case TYPE_USHORT:
16497                         ins->template_id = TEMPLATE_STORE16;
16498                         break;
16499                 case TYPE_INT:     case TYPE_UINT:
16500                 case TYPE_LONG:    case TYPE_ULONG:
16501                 case TYPE_POINTER:
16502                         ins->template_id = TEMPLATE_STORE32;
16503                         break;
16504                 default:
16505                         internal_error(state, ins, "unknown type in store");
16506                         break;
16507                 }
16508                 break;
16509         case OP_LOAD:
16510                 switch(ins->type->type & TYPE_MASK) {
16511                 case TYPE_CHAR:   case TYPE_UCHAR:
16512                         ins->template_id = TEMPLATE_LOAD8;
16513                         break;
16514                 case TYPE_SHORT:
16515                 case TYPE_USHORT:
16516                         ins->template_id = TEMPLATE_LOAD16;
16517                         break;
16518                 case TYPE_INT:
16519                 case TYPE_UINT:
16520                 case TYPE_LONG:
16521                 case TYPE_ULONG:
16522                 case TYPE_POINTER:
16523                         ins->template_id = TEMPLATE_LOAD32;
16524                         break;
16525                 default:
16526                         internal_error(state, ins, "unknown type in load");
16527                         break;
16528                 }
16529                 break;
16530         case OP_ADD:
16531         case OP_SUB:
16532         case OP_AND:
16533         case OP_XOR:
16534         case OP_OR:
16535         case OP_SMUL:
16536                 ins->template_id = TEMPLATE_BINARY32_REG;
16537                 if (get_imm32(ins, &RHS(ins, 1))) {
16538                         ins->template_id = TEMPLATE_BINARY32_IMM;
16539                 }
16540                 break;
16541         case OP_SDIVT:
16542         case OP_UDIVT:
16543                 ins->template_id = TEMPLATE_DIV32;
16544                 next = after_lhs(state, ins);
16545                 break;
16546                 /* FIXME UMUL does not work yet.. */
16547         case OP_UMUL:
16548                 ins->template_id = TEMPLATE_UMUL32;
16549                 break;
16550         case OP_UDIV:
16551                 next = mod_div(state, ins, OP_UDIVT, 0);
16552                 break;
16553         case OP_SDIV:
16554                 next = mod_div(state, ins, OP_SDIVT, 0);
16555                 break;
16556         case OP_UMOD:
16557                 next = mod_div(state, ins, OP_UDIVT, 1);
16558                 break;
16559         case OP_SMOD:
16560                 next = mod_div(state, ins, OP_SDIVT, 1);
16561                 break;
16562         case OP_SL:
16563         case OP_SSR:
16564         case OP_USR:
16565                 ins->template_id = TEMPLATE_SL32_CL;
16566                 if (get_imm8(ins, &RHS(ins, 1))) {
16567                         ins->template_id = TEMPLATE_SL32_IMM;
16568                 } else if (size_of(state, RHS(ins, 1)->type) > 1) {
16569                         typed_pre_copy(state, &char_type, ins, 1);
16570                 }
16571                 break;
16572         case OP_INVERT:
16573         case OP_NEG:
16574                 ins->template_id = TEMPLATE_UNARY32;
16575                 break;
16576         case OP_EQ: 
16577                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
16578                 break;
16579         case OP_NOTEQ:
16580                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16581                 break;
16582         case OP_SLESS:
16583                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
16584                 break;
16585         case OP_ULESS:
16586                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
16587                 break;
16588         case OP_SMORE:
16589                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
16590                 break;
16591         case OP_UMORE:
16592                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
16593                 break;
16594         case OP_SLESSEQ:
16595                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
16596                 break;
16597         case OP_ULESSEQ:
16598                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
16599                 break;
16600         case OP_SMOREEQ:
16601                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
16602                 break;
16603         case OP_UMOREEQ:
16604                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
16605                 break;
16606         case OP_LTRUE:
16607                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
16608                 break;
16609         case OP_LFALSE:
16610                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
16611                 break;
16612         case OP_BRANCH:
16613                 if (TRIPLE_RHS(ins->sizes) > 0) {
16614                         internal_error(state, ins, "bad branch test");
16615                 }
16616                 ins->op = OP_JMP;
16617                 ins->template_id = TEMPLATE_NOP;
16618                 break;
16619         case OP_INB:
16620         case OP_INW:
16621         case OP_INL:
16622                 switch(ins->op) {
16623                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
16624                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
16625                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
16626                 }
16627                 if (get_imm8(ins, &RHS(ins, 0))) {
16628                         ins->template_id += 1;
16629                 }
16630                 break;
16631         case OP_OUTB:
16632         case OP_OUTW:
16633         case OP_OUTL:
16634                 switch(ins->op) {
16635                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
16636                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
16637                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
16638                 }
16639                 if (get_imm8(ins, &RHS(ins, 1))) {
16640                         ins->template_id += 1;
16641                 }
16642                 break;
16643         case OP_BSF:
16644         case OP_BSR:
16645                 ins->template_id = TEMPLATE_BSF;
16646                 break;
16647         case OP_RDMSR:
16648                 ins->template_id = TEMPLATE_RDMSR;
16649                 next = after_lhs(state, ins);
16650                 break;
16651         case OP_WRMSR:
16652                 ins->template_id = TEMPLATE_WRMSR;
16653                 break;
16654         case OP_HLT:
16655                 ins->template_id = TEMPLATE_NOP;
16656                 break;
16657         case OP_ASM:
16658                 ins->template_id = TEMPLATE_NOP;
16659                 next = after_lhs(state, ins);
16660                 break;
16661                 /* Already transformed instructions */
16662         case OP_TEST:
16663                 ins->template_id = TEMPLATE_TEST32;
16664                 break;
16665         case OP_CMP:
16666                 ins->template_id = TEMPLATE_CMP32_REG;
16667                 if (get_imm32(ins, &RHS(ins, 1))) {
16668                         ins->template_id = TEMPLATE_CMP32_IMM;
16669                 }
16670                 break;
16671         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
16672         case OP_JMP_SLESS:   case OP_JMP_ULESS:
16673         case OP_JMP_SMORE:   case OP_JMP_UMORE:
16674         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
16675         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
16676                 ins->template_id = TEMPLATE_JMP;
16677                 break;
16678         case OP_SET_EQ:      case OP_SET_NOTEQ:
16679         case OP_SET_SLESS:   case OP_SET_ULESS:
16680         case OP_SET_SMORE:   case OP_SET_UMORE:
16681         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
16682         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
16683                 ins->template_id = TEMPLATE_SET;
16684                 break;
16685                 /* Unhandled instructions */
16686         case OP_PIECE:
16687         default:
16688                 internal_error(state, ins, "unhandled ins: %d %s\n",
16689                         ins->op, tops(ins->op));
16690                 break;
16691         }
16692         return next;
16693 }
16694
16695 static long next_label(struct compile_state *state)
16696 {
16697         static long label_counter = 0;
16698         return ++label_counter;
16699 }
16700 static void generate_local_labels(struct compile_state *state)
16701 {
16702         struct triple *first, *label;
16703         first = RHS(state->main_function, 0);
16704         label = first;
16705         do {
16706                 if ((label->op == OP_LABEL) || 
16707                         (label->op == OP_SDECL)) {
16708                         if (label->use) {
16709                                 label->u.cval = next_label(state);
16710                         } else {
16711                                 label->u.cval = 0;
16712                         }
16713                         
16714                 }
16715                 label = label->next;
16716         } while(label != first);
16717 }
16718
16719 static int check_reg(struct compile_state *state, 
16720         struct triple *triple, int classes)
16721 {
16722         unsigned mask;
16723         int reg;
16724         reg = ID_REG(triple->id);
16725         if (reg == REG_UNSET) {
16726                 internal_error(state, triple, "register not set");
16727         }
16728         mask = arch_reg_regcm(state, reg);
16729         if (!(classes & mask)) {
16730                 internal_error(state, triple, "reg %d in wrong class",
16731                         reg);
16732         }
16733         return reg;
16734 }
16735
16736 static const char *arch_reg_str(int reg)
16737 {
16738 #if REG_XMM7 != 44
16739 #error "Registers have renumberd fix arch_reg_str"
16740 #endif
16741         static const char *regs[] = {
16742                 "%unset",
16743                 "%unneeded",
16744                 "%eflags",
16745                 "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
16746                 "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
16747                 "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
16748                 "%edx:%eax",
16749                 "%dx:%ax",
16750                 "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
16751                 "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
16752                 "%xmm4", "%xmm5", "%xmm6", "%xmm7",
16753         };
16754         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
16755                 reg = 0;
16756         }
16757         return regs[reg];
16758 }
16759
16760
16761 static const char *reg(struct compile_state *state, struct triple *triple,
16762         int classes)
16763 {
16764         int reg;
16765         reg = check_reg(state, triple, classes);
16766         return arch_reg_str(reg);
16767 }
16768
16769 const char *type_suffix(struct compile_state *state, struct type *type)
16770 {
16771         const char *suffix;
16772         switch(size_of(state, type)) {
16773         case 1: suffix = "b"; break;
16774         case 2: suffix = "w"; break;
16775         case 4: suffix = "l"; break;
16776         default:
16777                 internal_error(state, 0, "unknown suffix");
16778                 suffix = 0;
16779                 break;
16780         }
16781         return suffix;
16782 }
16783
16784 static void print_const_val(
16785         struct compile_state *state, struct triple *ins, FILE *fp)
16786 {
16787         switch(ins->op) {
16788         case OP_INTCONST:
16789                 fprintf(fp, " $%ld ", 
16790                         (long_t)(ins->u.cval));
16791                 break;
16792         case OP_ADDRCONST:
16793                 if (MISC(ins, 0)->op != OP_SDECL) {
16794                         internal_error(state, ins, "bad base for addrconst");
16795                 }
16796                 if (MISC(ins, 0)->u.cval <= 0) {
16797                         internal_error(state, ins, "unlabeled constant");
16798                 }
16799                 fprintf(fp, " $L%s%lu+%lu ",
16800                         state->label_prefix, 
16801                         MISC(ins, 0)->u.cval,
16802                         ins->u.cval);
16803                 break;
16804         default:
16805                 internal_error(state, ins, "unknown constant type");
16806                 break;
16807         }
16808 }
16809
16810 static void print_const(struct compile_state *state,
16811         struct triple *ins, FILE *fp)
16812 {
16813         switch(ins->op) {
16814         case OP_INTCONST:
16815                 switch(ins->type->type & TYPE_MASK) {
16816                 case TYPE_CHAR:
16817                 case TYPE_UCHAR:
16818                         fprintf(fp, ".byte 0x%02lx\n", ins->u.cval);
16819                         break;
16820                 case TYPE_SHORT:
16821                 case TYPE_USHORT:
16822                         fprintf(fp, ".short 0x%04lx\n", ins->u.cval);
16823                         break;
16824                 case TYPE_INT:
16825                 case TYPE_UINT:
16826                 case TYPE_LONG:
16827                 case TYPE_ULONG:
16828                         fprintf(fp, ".int %lu\n", ins->u.cval);
16829                         break;
16830                 default:
16831                         internal_error(state, ins, "Unknown constant type");
16832                 }
16833                 break;
16834         case OP_ADDRCONST:
16835                 if (MISC(ins, 0)->op != OP_SDECL) {
16836                         internal_error(state, ins, "bad base for addrconst");
16837                 }
16838                 if (MISC(ins, 0)->u.cval <= 0) {
16839                         internal_error(state, ins, "unlabeled constant");
16840                 }
16841                 fprintf(fp, ".int L%s%lu+%lu\n",
16842                         state->label_prefix,
16843                         MISC(ins, 0)->u.cval,
16844                         ins->u.cval);
16845                 break;
16846         case OP_BLOBCONST:
16847         {
16848                 unsigned char *blob;
16849                 size_t size, i;
16850                 size = size_of(state, ins->type);
16851                 blob = ins->u.blob;
16852                 for(i = 0; i < size; i++) {
16853                         fprintf(fp, ".byte 0x%02x\n",
16854                                 blob[i]);
16855                 }
16856                 break;
16857         }
16858         default:
16859                 internal_error(state, ins, "Unknown constant type");
16860                 break;
16861         }
16862 }
16863
16864 #define TEXT_SECTION ".rom.text"
16865 #define DATA_SECTION ".rom.data"
16866
16867 static long get_const_pool_ref(
16868         struct compile_state *state, struct triple *ins, FILE *fp)
16869 {
16870         long ref;
16871         ref = next_label(state);
16872         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
16873         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
16874         fprintf(fp, "L%s%lu:\n", state->label_prefix, ref);
16875         print_const(state, ins, fp);
16876         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
16877         return ref;
16878 }
16879
16880 static void print_binary_op(struct compile_state *state,
16881         const char *op, struct triple *ins, FILE *fp) 
16882 {
16883         unsigned mask;
16884         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16885         if (RHS(ins, 0)->id != ins->id) {
16886                 internal_error(state, ins, "invalid register assignment");
16887         }
16888         if (is_const(RHS(ins, 1))) {
16889                 fprintf(fp, "\t%s ", op);
16890                 print_const_val(state, RHS(ins, 1), fp);
16891                 fprintf(fp, ", %s\n",
16892                         reg(state, RHS(ins, 0), mask));
16893         }
16894         else {
16895                 unsigned lmask, rmask;
16896                 int lreg, rreg;
16897                 lreg = check_reg(state, RHS(ins, 0), mask);
16898                 rreg = check_reg(state, RHS(ins, 1), mask);
16899                 lmask = arch_reg_regcm(state, lreg);
16900                 rmask = arch_reg_regcm(state, rreg);
16901                 mask = lmask & rmask;
16902                 fprintf(fp, "\t%s %s, %s\n",
16903                         op,
16904                         reg(state, RHS(ins, 1), mask),
16905                         reg(state, RHS(ins, 0), mask));
16906         }
16907 }
16908 static void print_unary_op(struct compile_state *state, 
16909         const char *op, struct triple *ins, FILE *fp)
16910 {
16911         unsigned mask;
16912         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16913         fprintf(fp, "\t%s %s\n",
16914                 op,
16915                 reg(state, RHS(ins, 0), mask));
16916 }
16917
16918 static void print_op_shift(struct compile_state *state,
16919         const char *op, struct triple *ins, FILE *fp)
16920 {
16921         unsigned mask;
16922         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
16923         if (RHS(ins, 0)->id != ins->id) {
16924                 internal_error(state, ins, "invalid register assignment");
16925         }
16926         if (is_const(RHS(ins, 1))) {
16927                 fprintf(fp, "\t%s ", op);
16928                 print_const_val(state, RHS(ins, 1), fp);
16929                 fprintf(fp, ", %s\n",
16930                         reg(state, RHS(ins, 0), mask));
16931         }
16932         else {
16933                 fprintf(fp, "\t%s %s, %s\n",
16934                         op,
16935                         reg(state, RHS(ins, 1), REGCM_GPR8_LO),
16936                         reg(state, RHS(ins, 0), mask));
16937         }
16938 }
16939
16940 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
16941 {
16942         const char *op;
16943         int mask;
16944         int dreg;
16945         mask = 0;
16946         switch(ins->op) {
16947         case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
16948         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
16949         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
16950         default:
16951                 internal_error(state, ins, "not an in operation");
16952                 op = 0;
16953                 break;
16954         }
16955         dreg = check_reg(state, ins, mask);
16956         if (!reg_is_reg(state, dreg, REG_EAX)) {
16957                 internal_error(state, ins, "dst != %%eax");
16958         }
16959         if (is_const(RHS(ins, 0))) {
16960                 fprintf(fp, "\t%s ", op);
16961                 print_const_val(state, RHS(ins, 0), fp);
16962                 fprintf(fp, ", %s\n",
16963                         reg(state, ins, mask));
16964         }
16965         else {
16966                 int addr_reg;
16967                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
16968                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
16969                         internal_error(state, ins, "src != %%dx");
16970                 }
16971                 fprintf(fp, "\t%s %s, %s\n",
16972                         op, 
16973                         reg(state, RHS(ins, 0), REGCM_GPR16),
16974                         reg(state, ins, mask));
16975         }
16976 }
16977
16978 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
16979 {
16980         const char *op;
16981         int mask;
16982         int lreg;
16983         mask = 0;
16984         switch(ins->op) {
16985         case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
16986         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
16987         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
16988         default:
16989                 internal_error(state, ins, "not an out operation");
16990                 op = 0;
16991                 break;
16992         }
16993         lreg = check_reg(state, RHS(ins, 0), mask);
16994         if (!reg_is_reg(state, lreg, REG_EAX)) {
16995                 internal_error(state, ins, "src != %%eax");
16996         }
16997         if (is_const(RHS(ins, 1))) {
16998                 fprintf(fp, "\t%s %s,", 
16999                         op, reg(state, RHS(ins, 0), mask));
17000                 print_const_val(state, RHS(ins, 1), fp);
17001                 fprintf(fp, "\n");
17002         }
17003         else {
17004                 int addr_reg;
17005                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
17006                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
17007                         internal_error(state, ins, "dst != %%dx");
17008                 }
17009                 fprintf(fp, "\t%s %s, %s\n",
17010                         op, 
17011                         reg(state, RHS(ins, 0), mask),
17012                         reg(state, RHS(ins, 1), REGCM_GPR16));
17013         }
17014 }
17015
17016 static void print_op_move(struct compile_state *state,
17017         struct triple *ins, FILE *fp)
17018 {
17019         /* op_move is complex because there are many types
17020          * of registers we can move between.
17021          * Because OP_COPY will be introduced in arbitrary locations
17022          * OP_COPY must not affect flags.
17023          */
17024         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
17025         struct triple *dst, *src;
17026         if (ins->op == OP_COPY) {
17027                 src = RHS(ins, 0);
17028                 dst = ins;
17029         }
17030         else {
17031                 internal_error(state, ins, "unknown move operation");
17032                 src = dst = 0;
17033         }
17034         if (!is_const(src)) {
17035                 int src_reg, dst_reg;
17036                 int src_regcm, dst_regcm;
17037                 src_reg   = ID_REG(src->id);
17038                 dst_reg   = ID_REG(dst->id);
17039                 src_regcm = arch_reg_regcm(state, src_reg);
17040                 dst_regcm = arch_reg_regcm(state, dst_reg);
17041                 /* If the class is the same just move the register */
17042                 if (src_regcm & dst_regcm & 
17043                         (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
17044                         if ((src_reg != dst_reg) || !omit_copy) {
17045                                 fprintf(fp, "\tmov %s, %s\n",
17046                                         reg(state, src, src_regcm),
17047                                         reg(state, dst, dst_regcm));
17048                         }
17049                 }
17050                 /* Move 32bit to 16bit */
17051                 else if ((src_regcm & REGCM_GPR32) &&
17052                         (dst_regcm & REGCM_GPR16)) {
17053                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
17054                         if ((src_reg != dst_reg) || !omit_copy) {
17055                                 fprintf(fp, "\tmovw %s, %s\n",
17056                                         arch_reg_str(src_reg), 
17057                                         arch_reg_str(dst_reg));
17058                         }
17059                 }
17060                 /* Move from 32bit gprs to 16bit gprs */
17061                 else if ((src_regcm & REGCM_GPR32) &&
17062                         (dst_regcm & REGCM_GPR16)) {
17063                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17064                         if ((src_reg != dst_reg) || !omit_copy) {
17065                                 fprintf(fp, "\tmov %s, %s\n",
17066                                         arch_reg_str(src_reg),
17067                                         arch_reg_str(dst_reg));
17068                         }
17069                 }
17070                 /* Move 32bit to 8bit */
17071                 else if ((src_regcm & REGCM_GPR32_8) &&
17072                         (dst_regcm & REGCM_GPR8_LO))
17073                 {
17074                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
17075                         if ((src_reg != dst_reg) || !omit_copy) {
17076                                 fprintf(fp, "\tmovb %s, %s\n",
17077                                         arch_reg_str(src_reg),
17078                                         arch_reg_str(dst_reg));
17079                         }
17080                 }
17081                 /* Move 16bit to 8bit */
17082                 else if ((src_regcm & REGCM_GPR16_8) &&
17083                         (dst_regcm & REGCM_GPR8_LO))
17084                 {
17085                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
17086                         if ((src_reg != dst_reg) || !omit_copy) {
17087                                 fprintf(fp, "\tmovb %s, %s\n",
17088                                         arch_reg_str(src_reg),
17089                                         arch_reg_str(dst_reg));
17090                         }
17091                 }
17092                 /* Move 8/16bit to 16/32bit */
17093                 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) && 
17094                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
17095                         const char *op;
17096                         op = is_signed(src->type)? "movsx": "movzx";
17097                         fprintf(fp, "\t%s %s, %s\n",
17098                                 op,
17099                                 reg(state, src, src_regcm),
17100                                 reg(state, dst, dst_regcm));
17101                 }
17102                 /* Move between sse registers */
17103                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
17104                         if ((src_reg != dst_reg) || !omit_copy) {
17105                                 fprintf(fp, "\tmovdqa %s, %s\n",
17106                                         reg(state, src, src_regcm),
17107                                         reg(state, dst, dst_regcm));
17108                         }
17109                 }
17110                 /* Move between mmx registers */
17111                 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
17112                         if ((src_reg != dst_reg) || !omit_copy) {
17113                                 fprintf(fp, "\tmovq %s, %s\n",
17114                                         reg(state, src, src_regcm),
17115                                         reg(state, dst, dst_regcm));
17116                         }
17117                 }
17118                 /* Move from sse to mmx registers */
17119                 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
17120                         fprintf(fp, "\tmovdq2q %s, %s\n",
17121                                 reg(state, src, src_regcm),
17122                                 reg(state, dst, dst_regcm));
17123                 }
17124                 /* Move from mmx to sse registers */
17125                 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
17126                         fprintf(fp, "\tmovq2dq %s, %s\n",
17127                                 reg(state, src, src_regcm),
17128                                 reg(state, dst, dst_regcm));
17129                 }
17130                 /* Move between 32bit gprs & mmx/sse registers */
17131                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
17132                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
17133                         fprintf(fp, "\tmovd %s, %s\n",
17134                                 reg(state, src, src_regcm),
17135                                 reg(state, dst, dst_regcm));
17136                 }
17137                 /* Move from 16bit gprs &  mmx/sse registers */
17138                 else if ((src_regcm & REGCM_GPR16) &&
17139                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17140                         const char *op;
17141                         int mid_reg;
17142                         op = is_signed(src->type)? "movsx":"movzx";
17143                         mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17144                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17145                                 op,
17146                                 arch_reg_str(src_reg),
17147                                 arch_reg_str(mid_reg),
17148                                 arch_reg_str(mid_reg),
17149                                 arch_reg_str(dst_reg));
17150                 }
17151                 /* Move from mmx/sse registers to 16bit gprs */
17152                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17153                         (dst_regcm & REGCM_GPR16)) {
17154                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
17155                         fprintf(fp, "\tmovd %s, %s\n",
17156                                 arch_reg_str(src_reg),
17157                                 arch_reg_str(dst_reg));
17158                 }
17159                 /* Move from gpr to 64bit dividend */
17160                 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))  &&
17161                         (dst_regcm & REGCM_DIVIDEND64)) {
17162                         const char *extend;
17163                         extend = is_signed(src->type)? "cltd":"movl $0, %edx";
17164                         fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
17165                                 arch_reg_str(src_reg), 
17166                                 extend);
17167                 }
17168                 /* Move from 64bit gpr to gpr */
17169                 else if ((src_regcm & REGCM_DIVIDEND64) &&
17170                         (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
17171                         if (dst_regcm & REGCM_GPR32) {
17172                                 src_reg = REG_EAX;
17173                         } 
17174                         else if (dst_regcm & REGCM_GPR16) {
17175                                 src_reg = REG_AX;
17176                         }
17177                         else if (dst_regcm & REGCM_GPR8_LO) {
17178                                 src_reg = REG_AL;
17179                         }
17180                         fprintf(fp, "\tmov %s, %s\n",
17181                                 arch_reg_str(src_reg),
17182                                 arch_reg_str(dst_reg));
17183                 }
17184                 /* Move from mmx/sse registers to 64bit gpr */
17185                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17186                         (dst_regcm & REGCM_DIVIDEND64)) {
17187                         const char *extend;
17188                         extend = is_signed(src->type)? "cltd": "movl $0, %edx";
17189                         fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
17190                                 arch_reg_str(src_reg),
17191                                 extend);
17192                 }
17193                 /* Move from 64bit gpr to mmx/sse register */
17194                 else if ((src_regcm & REGCM_DIVIDEND64) &&
17195                         (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
17196                         fprintf(fp, "\tmovd %%eax, %s\n",
17197                                 arch_reg_str(dst_reg));
17198                 }
17199 #if X86_4_8BIT_GPRS
17200                 /* Move from 8bit gprs to  mmx/sse registers */
17201                 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
17202                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
17203                         const char *op;
17204                         int mid_reg;
17205                         op = is_signed(src->type)? "movsx":"movzx";
17206                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17207                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
17208                                 op,
17209                                 reg(state, src, src_regcm),
17210                                 arch_reg_str(mid_reg),
17211                                 arch_reg_str(mid_reg),
17212                                 reg(state, dst, dst_regcm));
17213                 }
17214                 /* Move from mmx/sse registers and 8bit gprs */
17215                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
17216                         (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
17217                         int mid_reg;
17218                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17219                         fprintf(fp, "\tmovd %s, %s\n",
17220                                 reg(state, src, src_regcm),
17221                                 arch_reg_str(mid_reg));
17222                 }
17223                 /* Move from 32bit gprs to 8bit gprs */
17224                 else if ((src_regcm & REGCM_GPR32) &&
17225                         (dst_regcm & REGCM_GPR8_LO)) {
17226                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
17227                         if ((src_reg != dst_reg) || !omit_copy) {
17228                                 fprintf(fp, "\tmov %s, %s\n",
17229                                         arch_reg_str(src_reg),
17230                                         arch_reg_str(dst_reg));
17231                         }
17232                 }
17233                 /* Move from 16bit gprs to 8bit gprs */
17234                 else if ((src_regcm & REGCM_GPR16) &&
17235                         (dst_regcm & REGCM_GPR8_LO)) {
17236                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
17237                         if ((src_reg != dst_reg) || !omit_copy) {
17238                                 fprintf(fp, "\tmov %s, %s\n",
17239                                         arch_reg_str(src_reg),
17240                                         arch_reg_str(dst_reg));
17241                         }
17242                 }
17243 #endif /* X86_4_8BIT_GPRS */
17244                 else {
17245                         internal_error(state, ins, "unknown copy type");
17246                 }
17247         }
17248         else {
17249                 int dst_reg;
17250                 int dst_regcm;
17251                 dst_reg = ID_REG(dst->id);
17252                 dst_regcm = arch_reg_regcm(state, dst_reg);
17253                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
17254                         fprintf(fp, "\tmov ");
17255                         print_const_val(state, src, fp);
17256                         fprintf(fp, ", %s\n",
17257                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
17258                 }
17259                 else if (dst_regcm & REGCM_DIVIDEND64) {
17260                         if (size_of(state, dst->type) > 4) {
17261                                 internal_error(state, ins, "64bit constant...");
17262                         }
17263                         fprintf(fp, "\tmov $0, %%edx\n");
17264                         fprintf(fp, "\tmov ");
17265                         print_const_val(state, src, fp);
17266                         fprintf(fp, ", %%eax\n");
17267                 }
17268                 else if (dst_regcm & REGCM_DIVIDEND32) {
17269                         if (size_of(state, dst->type) > 2) {
17270                                 internal_error(state, ins, "32bit constant...");
17271                         }
17272                         fprintf(fp, "\tmov $0, %%dx\n");
17273                         fprintf(fp, "\tmov ");
17274                         print_const_val(state, src, fp);
17275                         fprintf(fp, ", %%ax");
17276                 }
17277                 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
17278                         long ref;
17279                         ref = get_const_pool_ref(state, src, fp);
17280                         fprintf(fp, "\tmovq L%s%lu, %s\n",
17281                                 state->label_prefix, ref,
17282                                 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
17283                 }
17284                 else {
17285                         internal_error(state, ins, "unknown copy immediate type");
17286                 }
17287         }
17288 }
17289
17290 static void print_op_load(struct compile_state *state,
17291         struct triple *ins, FILE *fp)
17292 {
17293         struct triple *dst, *src;
17294         dst = ins;
17295         src = RHS(ins, 0);
17296         if (is_const(src) || is_const(dst)) {
17297                 internal_error(state, ins, "unknown load operation");
17298         }
17299         fprintf(fp, "\tmov (%s), %s\n",
17300                 reg(state, src, REGCM_GPR32),
17301                 reg(state, dst, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32));
17302 }
17303
17304
17305 static void print_op_store(struct compile_state *state,
17306         struct triple *ins, FILE *fp)
17307 {
17308         struct triple *dst, *src;
17309         dst = RHS(ins, 0);
17310         src = RHS(ins, 1);
17311         if (is_const(src) && (src->op == OP_INTCONST)) {
17312                 long_t value;
17313                 value = (long_t)(src->u.cval);
17314                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
17315                         type_suffix(state, src->type),
17316                         value,
17317                         reg(state, dst, REGCM_GPR32));
17318         }
17319         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
17320                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
17321                         type_suffix(state, src->type),
17322                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17323                         dst->u.cval);
17324         }
17325         else {
17326                 if (is_const(src) || is_const(dst)) {
17327                         internal_error(state, ins, "unknown store operation");
17328                 }
17329                 fprintf(fp, "\tmov%s %s, (%s)\n",
17330                         type_suffix(state, src->type),
17331                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
17332                         reg(state, dst, REGCM_GPR32));
17333         }
17334         
17335         
17336 }
17337
17338 static void print_op_smul(struct compile_state *state,
17339         struct triple *ins, FILE *fp)
17340 {
17341         if (!is_const(RHS(ins, 1))) {
17342                 fprintf(fp, "\timul %s, %s\n",
17343                         reg(state, RHS(ins, 1), REGCM_GPR32),
17344                         reg(state, RHS(ins, 0), REGCM_GPR32));
17345         }
17346         else {
17347                 fprintf(fp, "\timul ");
17348                 print_const_val(state, RHS(ins, 1), fp);
17349                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
17350         }
17351 }
17352
17353 static void print_op_cmp(struct compile_state *state,
17354         struct triple *ins, FILE *fp)
17355 {
17356         unsigned mask;
17357         int dreg;
17358         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17359         dreg = check_reg(state, ins, REGCM_FLAGS);
17360         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
17361                 internal_error(state, ins, "bad dest register for cmp");
17362         }
17363         if (is_const(RHS(ins, 1))) {
17364                 fprintf(fp, "\tcmp ");
17365                 print_const_val(state, RHS(ins, 1), fp);
17366                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
17367         }
17368         else {
17369                 unsigned lmask, rmask;
17370                 int lreg, rreg;
17371                 lreg = check_reg(state, RHS(ins, 0), mask);
17372                 rreg = check_reg(state, RHS(ins, 1), mask);
17373                 lmask = arch_reg_regcm(state, lreg);
17374                 rmask = arch_reg_regcm(state, rreg);
17375                 mask = lmask & rmask;
17376                 fprintf(fp, "\tcmp %s, %s\n",
17377                         reg(state, RHS(ins, 1), mask),
17378                         reg(state, RHS(ins, 0), mask));
17379         }
17380 }
17381
17382 static void print_op_test(struct compile_state *state,
17383         struct triple *ins, FILE *fp)
17384 {
17385         unsigned mask;
17386         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
17387         fprintf(fp, "\ttest %s, %s\n",
17388                 reg(state, RHS(ins, 0), mask),
17389                 reg(state, RHS(ins, 0), mask));
17390 }
17391
17392 static void print_op_branch(struct compile_state *state,
17393         struct triple *branch, FILE *fp)
17394 {
17395         const char *bop = "j";
17396         if (branch->op == OP_JMP) {
17397                 if (TRIPLE_RHS(branch->sizes) != 0) {
17398                         internal_error(state, branch, "jmp with condition?");
17399                 }
17400                 bop = "jmp";
17401         }
17402         else {
17403                 struct triple *ptr;
17404                 if (TRIPLE_RHS(branch->sizes) != 1) {
17405                         internal_error(state, branch, "jmpcc without condition?");
17406                 }
17407                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
17408                 if ((RHS(branch, 0)->op != OP_CMP) &&
17409                         (RHS(branch, 0)->op != OP_TEST)) {
17410                         internal_error(state, branch, "bad branch test");
17411                 }
17412 #warning "FIXME I have observed instructions between the test and branch instructions"
17413                 ptr = RHS(branch, 0);
17414                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
17415                         if (ptr->op != OP_COPY) {
17416                                 internal_error(state, branch, "branch does not follow test");
17417                         }
17418                 }
17419                 switch(branch->op) {
17420                 case OP_JMP_EQ:       bop = "jz";  break;
17421                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
17422                 case OP_JMP_SLESS:    bop = "jl";  break;
17423                 case OP_JMP_ULESS:    bop = "jb";  break;
17424                 case OP_JMP_SMORE:    bop = "jg";  break;
17425                 case OP_JMP_UMORE:    bop = "ja";  break;
17426                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
17427                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
17428                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
17429                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
17430                 default:
17431                         internal_error(state, branch, "Invalid branch op");
17432                         break;
17433                 }
17434                 
17435         }
17436         fprintf(fp, "\t%s L%s%lu\n",
17437                 bop, 
17438                 state->label_prefix,
17439                 TARG(branch, 0)->u.cval);
17440 }
17441
17442 static void print_op_set(struct compile_state *state,
17443         struct triple *set, FILE *fp)
17444 {
17445         const char *sop = "set";
17446         if (TRIPLE_RHS(set->sizes) != 1) {
17447                 internal_error(state, set, "setcc without condition?");
17448         }
17449         check_reg(state, RHS(set, 0), REGCM_FLAGS);
17450         if ((RHS(set, 0)->op != OP_CMP) &&
17451                 (RHS(set, 0)->op != OP_TEST)) {
17452                 internal_error(state, set, "bad set test");
17453         }
17454         if (RHS(set, 0)->next != set) {
17455                 internal_error(state, set, "set does not follow test");
17456         }
17457         switch(set->op) {
17458         case OP_SET_EQ:       sop = "setz";  break;
17459         case OP_SET_NOTEQ:    sop = "setnz"; break;
17460         case OP_SET_SLESS:    sop = "setl";  break;
17461         case OP_SET_ULESS:    sop = "setb";  break;
17462         case OP_SET_SMORE:    sop = "setg";  break;
17463         case OP_SET_UMORE:    sop = "seta";  break;
17464         case OP_SET_SLESSEQ:  sop = "setle"; break;
17465         case OP_SET_ULESSEQ:  sop = "setbe"; break;
17466         case OP_SET_SMOREEQ:  sop = "setge"; break;
17467         case OP_SET_UMOREEQ:  sop = "setae"; break;
17468         default:
17469                 internal_error(state, set, "Invalid set op");
17470                 break;
17471         }
17472         fprintf(fp, "\t%s %s\n",
17473                 sop, reg(state, set, REGCM_GPR8_LO));
17474 }
17475
17476 static void print_op_bit_scan(struct compile_state *state, 
17477         struct triple *ins, FILE *fp) 
17478 {
17479         const char *op;
17480         switch(ins->op) {
17481         case OP_BSF: op = "bsf"; break;
17482         case OP_BSR: op = "bsr"; break;
17483         default: 
17484                 internal_error(state, ins, "unknown bit scan");
17485                 op = 0;
17486                 break;
17487         }
17488         fprintf(fp, 
17489                 "\t%s %s, %s\n"
17490                 "\tjnz 1f\n"
17491                 "\tmovl $-1, %s\n"
17492                 "1:\n",
17493                 op,
17494                 reg(state, RHS(ins, 0), REGCM_GPR32),
17495                 reg(state, ins, REGCM_GPR32),
17496                 reg(state, ins, REGCM_GPR32));
17497 }
17498
17499
17500 static void print_sdecl(struct compile_state *state,
17501         struct triple *ins, FILE *fp)
17502 {
17503         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
17504         fprintf(fp, ".balign %d\n", align_of(state, ins->type));
17505         fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17506         print_const(state, MISC(ins, 0), fp);
17507         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17508                 
17509 }
17510
17511 static void print_instruction(struct compile_state *state,
17512         struct triple *ins, FILE *fp)
17513 {
17514         /* Assumption: after I have exted the register allocator
17515          * everything is in a valid register. 
17516          */
17517         switch(ins->op) {
17518         case OP_ASM:
17519                 print_op_asm(state, ins, fp);
17520                 break;
17521         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
17522         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
17523         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
17524         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
17525         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
17526         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
17527         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
17528         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
17529         case OP_POS:    break;
17530         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
17531         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
17532         case OP_INTCONST:
17533         case OP_ADDRCONST:
17534         case OP_BLOBCONST:
17535                 /* Don't generate anything here for constants */
17536         case OP_PHI:
17537                 /* Don't generate anything for variable declarations. */
17538                 break;
17539         case OP_SDECL:
17540                 print_sdecl(state, ins, fp);
17541                 break;
17542         case OP_COPY:   
17543                 print_op_move(state, ins, fp);
17544                 break;
17545         case OP_LOAD:
17546                 print_op_load(state, ins, fp);
17547                 break;
17548         case OP_STORE:
17549                 print_op_store(state, ins, fp);
17550                 break;
17551         case OP_SMUL:
17552                 print_op_smul(state, ins, fp);
17553                 break;
17554         case OP_CMP:    print_op_cmp(state, ins, fp); break;
17555         case OP_TEST:   print_op_test(state, ins, fp); break;
17556         case OP_JMP:
17557         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
17558         case OP_JMP_SLESS:   case OP_JMP_ULESS:
17559         case OP_JMP_SMORE:   case OP_JMP_UMORE:
17560         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
17561         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
17562                 print_op_branch(state, ins, fp);
17563                 break;
17564         case OP_SET_EQ:      case OP_SET_NOTEQ:
17565         case OP_SET_SLESS:   case OP_SET_ULESS:
17566         case OP_SET_SMORE:   case OP_SET_UMORE:
17567         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
17568         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
17569                 print_op_set(state, ins, fp);
17570                 break;
17571         case OP_INB:  case OP_INW:  case OP_INL:
17572                 print_op_in(state, ins, fp); 
17573                 break;
17574         case OP_OUTB: case OP_OUTW: case OP_OUTL:
17575                 print_op_out(state, ins, fp); 
17576                 break;
17577         case OP_BSF:
17578         case OP_BSR:
17579                 print_op_bit_scan(state, ins, fp);
17580                 break;
17581         case OP_RDMSR:
17582                 after_lhs(state, ins);
17583                 fprintf(fp, "\trdmsr\n");
17584                 break;
17585         case OP_WRMSR:
17586                 fprintf(fp, "\twrmsr\n");
17587                 break;
17588         case OP_HLT:
17589                 fprintf(fp, "\thlt\n");
17590                 break;
17591         case OP_SDIVT:
17592                 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17593                 break;
17594         case OP_UDIVT:
17595                 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17596                 break;
17597         case OP_UMUL:
17598                 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
17599                 break;
17600         case OP_LABEL:
17601                 if (!ins->use) {
17602                         return;
17603                 }
17604                 fprintf(fp, "L%s%lu:\n", state->label_prefix, ins->u.cval);
17605                 break;
17606                 /* Ignore OP_PIECE */
17607         case OP_PIECE:
17608                 break;
17609                 /* Operations that should never get here */
17610         case OP_SDIV: case OP_UDIV:
17611         case OP_SMOD: case OP_UMOD:
17612         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
17613         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
17614         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
17615         default:
17616                 internal_error(state, ins, "unknown op: %d %s",
17617                         ins->op, tops(ins->op));
17618                 break;
17619         }
17620 }
17621
17622 static void print_instructions(struct compile_state *state)
17623 {
17624         struct triple *first, *ins;
17625         int print_location;
17626         struct occurance *last_occurance;
17627         FILE *fp;
17628         int max_inline_depth;
17629         max_inline_depth = 0;
17630         print_location = 1;
17631         last_occurance = 0;
17632         fp = state->output;
17633         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
17634         first = RHS(state->main_function, 0);
17635         ins = first;
17636         do {
17637                 if (print_location && 
17638                         last_occurance != ins->occurance) {
17639                         if (!ins->occurance->parent) {
17640                                 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
17641                                         ins->occurance->function,
17642                                         ins->occurance->filename,
17643                                         ins->occurance->line,
17644                                         ins->occurance->col);
17645                         }
17646                         else {
17647                                 struct occurance *ptr;
17648                                 int inline_depth;
17649                                 fprintf(fp, "\t/*\n");
17650                                 inline_depth = 0;
17651                                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
17652                                         inline_depth++;
17653                                         fprintf(fp, "\t * %s,%s:%d.%d\n",
17654                                                 ptr->function,
17655                                                 ptr->filename,
17656                                                 ptr->line,
17657                                                 ptr->col);
17658                                 }
17659                                 fprintf(fp, "\t */\n");
17660                                 if (inline_depth > max_inline_depth) {
17661                                         max_inline_depth = inline_depth;
17662                                 }
17663                         }
17664                         if (last_occurance) {
17665                                 put_occurance(last_occurance);
17666                         }
17667                         get_occurance(ins->occurance);
17668                         last_occurance = ins->occurance;
17669                 }
17670
17671                 print_instruction(state, ins, fp);
17672                 ins = ins->next;
17673         } while(ins != first);
17674         if (print_location) {
17675                 fprintf(fp, "/* max inline depth %d */\n",
17676                         max_inline_depth);
17677         }
17678 }
17679
17680 static void generate_code(struct compile_state *state)
17681 {
17682         generate_local_labels(state);
17683         print_instructions(state);
17684         
17685 }
17686
17687 static void print_tokens(struct compile_state *state)
17688 {
17689         struct token *tk;
17690         tk = &state->token[0];
17691         do {
17692 #if 1
17693                 token(state, 0);
17694 #else
17695                 next_token(state, 0);
17696 #endif
17697                 loc(stdout, state, 0);
17698                 printf("%s <- `%s'\n",
17699                         tokens[tk->tok],
17700                         tk->ident ? tk->ident->name :
17701                         tk->str_len ? tk->val.str : "");
17702                 
17703         } while(tk->tok != TOK_EOF);
17704 }
17705
17706 static void compile(const char *filename, const char *ofilename, 
17707         int cpu, int debug, int opt, const char *label_prefix)
17708 {
17709         int i;
17710         struct compile_state state;
17711         memset(&state, 0, sizeof(state));
17712         state.file = 0;
17713         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
17714                 memset(&state.token[i], 0, sizeof(state.token[i]));
17715                 state.token[i].tok = -1;
17716         }
17717         /* Remember the debug settings */
17718         state.cpu      = cpu;
17719         state.debug    = debug;
17720         state.optimize = opt;
17721         /* Remember the output filename */
17722         state.ofilename = ofilename;
17723         state.output    = fopen(state.ofilename, "w");
17724         if (!state.output) {
17725                 error(&state, 0, "Cannot open output file %s\n",
17726                         ofilename);
17727         }
17728         /* Remember the label prefix */
17729         state.label_prefix = label_prefix;
17730         /* Prep the preprocessor */
17731         state.if_depth = 0;
17732         state.if_value = 0;
17733         /* register the C keywords */
17734         register_keywords(&state);
17735         /* register the keywords the macro preprocessor knows */
17736         register_macro_keywords(&state);
17737         /* Memorize where some special keywords are. */
17738         state.i_continue = lookup(&state, "continue", 8);
17739         state.i_break    = lookup(&state, "break", 5);
17740         /* Enter the globl definition scope */
17741         start_scope(&state);
17742         register_builtins(&state);
17743         compile_file(&state, filename, 1);
17744 #if 0
17745         print_tokens(&state);
17746 #endif  
17747         decls(&state);
17748         /* Exit the global definition scope */
17749         end_scope(&state);
17750
17751         /* Now that basic compilation has happened 
17752          * optimize the intermediate code 
17753          */
17754         optimize(&state);
17755
17756         generate_code(&state);
17757         if (state.debug) {
17758                 fprintf(stderr, "done\n");
17759         }
17760 }
17761
17762 static void version(void)
17763 {
17764         printf("romcc " VERSION " released " RELEASE_DATE "\n");
17765 }
17766
17767 static void usage(void)
17768 {
17769         version();
17770         printf(
17771                 "Usage: romcc <source>.c\n"
17772                 "Compile a C source file without using ram\n"
17773         );
17774 }
17775
17776 static void arg_error(char *fmt, ...)
17777 {
17778         va_list args;
17779         va_start(args, fmt);
17780         vfprintf(stderr, fmt, args);
17781         va_end(args);
17782         usage();
17783         exit(1);
17784 }
17785
17786 int main(int argc, char **argv)
17787 {
17788         const char *filename;
17789         const char *ofilename;
17790         const char *label_prefix;
17791         int cpu;
17792         int last_argc;
17793         int debug;
17794         int optimize;
17795         cpu = CPU_DEFAULT;
17796         label_prefix = "";
17797         ofilename = "auto.inc";
17798         optimize = 0;
17799         debug = 0;
17800         last_argc = -1;
17801         while((argc > 1) && (argc != last_argc)) {
17802                 last_argc = argc;
17803                 if (strncmp(argv[1], "--debug=", 8) == 0) {
17804                         debug = atoi(argv[1] + 8);
17805                         argv++;
17806                         argc--;
17807                 }
17808                 else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
17809                         label_prefix= argv[1] + 15;
17810                         argv++;
17811                         argc--;
17812                 }
17813                 else if ((strcmp(argv[1],"-O") == 0) ||
17814                         (strcmp(argv[1], "-O1") == 0)) {
17815                         optimize = 1;
17816                         argv++;
17817                         argc--;
17818                 }
17819                 else if (strcmp(argv[1],"-O2") == 0) {
17820                         optimize = 2;
17821                         argv++;
17822                         argc--;
17823                 }
17824                 else if ((strcmp(argv[1], "-o") == 0) && (argc > 2)) {
17825                         ofilename = argv[2];
17826                         argv += 2;
17827                         argc -= 2;
17828                 }
17829                 else if (strncmp(argv[1], "-mcpu=", 6) == 0) {
17830                         cpu = arch_encode_cpu(argv[1] + 6);
17831                         if (cpu == BAD_CPU) {
17832                                 arg_error("Invalid cpu specified: %s\n",
17833                                         argv[1] + 6);
17834                         }
17835                         argv++;
17836                         argc--;
17837                 }
17838         }
17839         if (argc != 2) {
17840                 arg_error("Wrong argument count %d\n", argc);
17841         }
17842         filename = argv[1];
17843         compile(filename, ofilename, cpu, debug, optimize, label_prefix);
17844
17845         return 0;
17846 }