romcc:
[coreboot.git] / util / romcc / romcc.c
1 #undef VERSION_MAJOR
2 #undef VERSION_MINOR
3 #undef RELEASE_DATE
4 #undef VERSION
5 #define VERSION_MAJOR "0"
6 #define VERSION_MINOR "71"
7 #define RELEASE_DATE "03 April 2009"
8 #define VERSION VERSION_MAJOR "." VERSION_MINOR
9
10 #include <stdarg.h>
11 #include <errno.h>
12 #include <stdint.h>
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <limits.h>
22 #include <locale.h>
23 #include <time.h>
24
25 #define MAX_CWD_SIZE 4096
26 #define MAX_ALLOCATION_PASSES 100
27
28 /* NOTE: Before you even start thinking to touch anything 
29  * in this code, set DEBUG_ROMCC_WARNINGS to 1 to get an
30  * insight on the original author's thoughts. We introduced 
31  * this switch as romcc was about the only thing producing
32  * massive warnings in our code..
33  */
34 #define DEBUG_ROMCC_WARNINGS 0
35
36 #define DEBUG_CONSISTENCY 1
37 #define DEBUG_SDP_BLOCKS 0
38 #define DEBUG_TRIPLE_COLOR 0
39
40 #define DEBUG_DISPLAY_USES 1
41 #define DEBUG_DISPLAY_TYPES 1
42 #define DEBUG_REPLACE_CLOSURE_TYPE_HIRES 0
43 #define DEBUG_DECOMPOSE_PRINT_TUPLES 0
44 #define DEBUG_DECOMPOSE_HIRES  0
45 #define DEBUG_INITIALIZER 0
46 #define DEBUG_UPDATE_CLOSURE_TYPE 0
47 #define DEBUG_LOCAL_TRIPLE 0
48 #define DEBUG_BASIC_BLOCKS_VERBOSE 0
49 #define DEBUG_CPS_RENAME_VARIABLES_HIRES 0
50 #define DEBUG_SIMPLIFY_HIRES 0
51 #define DEBUG_SHRINKING 0
52 #define DEBUG_COALESCE_HITCHES 0
53 #define DEBUG_CODE_ELIMINATION 0
54
55 #define DEBUG_EXPLICIT_CLOSURES 0
56
57 #if DEBUG_ROMCC_WARNINGS
58 #warning "FIXME give clear error messages about unused variables"
59 #warning "FIXME properly handle multi dimensional arrays"
60 #warning "FIXME handle multiple register sizes"
61 #endif
62
63 /*  Control flow graph of a loop without goto.
64  * 
65  *        AAA
66  *   +---/
67  *  /
68  * / +--->CCC
69  * | |    / \
70  * | |  DDD EEE    break;
71  * | |    \    \
72  * | |    FFF   \
73  *  \|    / \    \
74  *   |\ GGG HHH   |   continue;
75  *   | \  \   |   |
76  *   |  \ III |  /
77  *   |   \ | /  / 
78  *   |    vvv  /  
79  *   +----BBB /   
80  *         | /
81  *         vv
82  *        JJJ
83  *
84  * 
85  *             AAA
86  *     +-----+  |  +----+
87  *     |      \ | /     |
88  *     |       BBB  +-+ |
89  *     |       / \ /  | |
90  *     |     CCC JJJ / /
91  *     |     / \    / / 
92  *     |   DDD EEE / /  
93  *     |    |   +-/ /
94  *     |   FFF     /    
95  *     |   / \    /     
96  *     | GGG HHH /      
97  *     |  |   +-/
98  *     | III
99  *     +--+ 
100  *
101  * 
102  * DFlocal(X) = { Y <- Succ(X) | idom(Y) != X }
103  * DFup(Z)    = { Y <- DF(Z) | idom(Y) != X }
104  *
105  *
106  * [] == DFlocal(X) U DF(X)
107  * () == DFup(X)
108  *
109  * Dominator graph of the same nodes.
110  *
111  *           AAA     AAA: [ ] ()
112  *          /   \
113  *        BBB    JJJ BBB: [ JJJ ] ( JJJ )  JJJ: [ ] ()
114  *         |
115  *        CCC        CCC: [ ] ( BBB, JJJ )
116  *        / \
117  *     DDD   EEE     DDD: [ ] ( BBB ) EEE: [ JJJ ] ()
118  *      |
119  *     FFF           FFF: [ ] ( BBB )
120  *     / \         
121  *  GGG   HHH        GGG: [ ] ( BBB ) HHH: [ BBB ] ()
122  *   |
123  *  III              III: [ BBB ] ()
124  *
125  *
126  * BBB and JJJ are definitely the dominance frontier.
127  * Where do I place phi functions and how do I make that decision.
128  *   
129  */
130 static void die(char *fmt, ...)
131 {
132         va_list args;
133
134         va_start(args, fmt);
135         vfprintf(stderr, fmt, args);
136         va_end(args);
137         fflush(stdout);
138         fflush(stderr);
139         exit(1);
140 }
141
142 static void *xmalloc(size_t size, const char *name)
143 {
144         void *buf;
145         buf = malloc(size);
146         if (!buf) {
147                 die("Cannot malloc %ld bytes to hold %s: %s\n",
148                         size + 0UL, name, strerror(errno));
149         }
150         return buf;
151 }
152
153 static void *xcmalloc(size_t size, const char *name)
154 {
155         void *buf;
156         buf = xmalloc(size, name);
157         memset(buf, 0, size);
158         return buf;
159 }
160
161 static void *xrealloc(void *ptr, size_t size, const char *name)
162 {
163         void *buf;
164         buf = realloc(ptr, size);
165         if (!buf) {
166                 die("Cannot realloc %ld bytes to hold %s: %s\n",
167                         size + 0UL, name, strerror(errno));
168         }
169         return buf;
170 }
171
172 static void xfree(const void *ptr)
173 {
174         free((void *)ptr);
175 }
176
177 static char *xstrdup(const char *str)
178 {
179         char *new;
180         int len;
181         len = strlen(str);
182         new = xmalloc(len + 1, "xstrdup string");
183         memcpy(new, str, len);
184         new[len] = '\0';
185         return new;
186 }
187
188 static void xchdir(const char *path)
189 {
190         if (chdir(path) != 0) {
191                 die("chdir to `%s' failed: %s\n",
192                         path, strerror(errno));
193         }
194 }
195
196 static int exists(const char *dirname, const char *filename)
197 {
198         char cwd[MAX_CWD_SIZE];
199         int does_exist;
200
201         if (getcwd(cwd, sizeof(cwd)) == 0) {
202                 die("cwd buffer to small");
203         }
204
205         does_exist = 1;
206         if (chdir(dirname) != 0) {
207                 does_exist = 0;
208         }
209         if (does_exist && (access(filename, O_RDONLY) < 0)) {
210                 if ((errno != EACCES) && (errno != EROFS)) {
211                         does_exist = 0;
212                 }
213         }
214         xchdir(cwd);
215         return does_exist;
216 }
217
218
219 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
220 {
221         char cwd[MAX_CWD_SIZE];
222         char *buf;
223         off_t size, progress;
224         ssize_t result;
225         FILE* file;
226         
227         if (!filename) {
228                 *r_size = 0;
229                 return 0;
230         }
231         if (getcwd(cwd, sizeof(cwd)) == 0) {
232                 die("cwd buffer to small");
233         }
234         xchdir(dirname);
235         file = fopen(filename, "rb");
236         xchdir(cwd);
237         if (file == NULL) {
238                 die("Cannot open '%s' : %s\n",
239                         filename, strerror(errno));
240         }
241         fseek(file, 0, SEEK_END);
242         size = ftell(file);
243         fseek(file, 0, SEEK_SET);
244         *r_size = size +1;
245         buf = xmalloc(size +2, filename);
246         buf[size] = '\n'; /* Make certain the file is newline terminated */
247         buf[size+1] = '\0'; /* Null terminate the file for good measure */
248         progress = 0;
249         while(progress < size) {
250                 result = fread(buf + progress, 1, size - progress, file);
251                 if (result < 0) {
252                         if ((errno == EINTR) || (errno == EAGAIN))
253                                 continue;
254                         die("read on %s of %ld bytes failed: %s\n",
255                                 filename, (size - progress)+ 0UL, strerror(errno));
256                 }
257                 progress += result;
258         }
259         fclose(file);
260         return buf;
261 }
262
263 /* Types on the destination platform */
264 #if DEBUG_ROMCC_WARNINGS
265 #warning "FIXME this assumes 32bit x86 is the destination"
266 #endif
267 typedef int8_t   schar_t;
268 typedef uint8_t  uchar_t;
269 typedef int8_t   char_t;
270 typedef int16_t  short_t;
271 typedef uint16_t ushort_t;
272 typedef int32_t  int_t;
273 typedef uint32_t uint_t;
274 typedef int32_t  long_t;
275 #define ulong_t uint32_t
276
277 #define SCHAR_T_MIN (-128)
278 #define SCHAR_T_MAX 127
279 #define UCHAR_T_MAX 255
280 #define CHAR_T_MIN  SCHAR_T_MIN
281 #define CHAR_T_MAX  SCHAR_T_MAX
282 #define SHRT_T_MIN  (-32768)
283 #define SHRT_T_MAX  32767
284 #define USHRT_T_MAX 65535
285 #define INT_T_MIN   (-LONG_T_MAX - 1)
286 #define INT_T_MAX   2147483647
287 #define UINT_T_MAX  4294967295U
288 #define LONG_T_MIN  (-LONG_T_MAX - 1)
289 #define LONG_T_MAX  2147483647
290 #define ULONG_T_MAX 4294967295U
291
292 #define SIZEOF_I8    8
293 #define SIZEOF_I16   16
294 #define SIZEOF_I32   32
295 #define SIZEOF_I64   64
296
297 #define SIZEOF_CHAR    8
298 #define SIZEOF_SHORT   16
299 #define SIZEOF_INT     32
300 #define SIZEOF_LONG    (sizeof(long_t)*SIZEOF_CHAR)
301
302
303 #define ALIGNOF_CHAR    8
304 #define ALIGNOF_SHORT   16
305 #define ALIGNOF_INT     32
306 #define ALIGNOF_LONG    (sizeof(long_t)*SIZEOF_CHAR)
307
308 #define REG_SIZEOF_REG     32
309 #define REG_SIZEOF_CHAR    REG_SIZEOF_REG
310 #define REG_SIZEOF_SHORT   REG_SIZEOF_REG
311 #define REG_SIZEOF_INT     REG_SIZEOF_REG
312 #define REG_SIZEOF_LONG    REG_SIZEOF_REG
313
314 #define REG_ALIGNOF_REG     REG_SIZEOF_REG
315 #define REG_ALIGNOF_CHAR    REG_SIZEOF_REG
316 #define REG_ALIGNOF_SHORT   REG_SIZEOF_REG
317 #define REG_ALIGNOF_INT     REG_SIZEOF_REG
318 #define REG_ALIGNOF_LONG    REG_SIZEOF_REG
319
320 /* Additional definitions for clarity.
321  * I currently assume a long is the largest native
322  * machine word and that a pointer fits into it.
323  */
324 #define SIZEOF_WORD     SIZEOF_LONG
325 #define SIZEOF_POINTER  SIZEOF_LONG
326 #define ALIGNOF_WORD    ALIGNOF_LONG
327 #define ALIGNOF_POINTER ALIGNOF_LONG
328 #define REG_SIZEOF_POINTER  REG_SIZEOF_LONG
329 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
330
331 struct file_state {
332         struct file_state *prev;
333         const char *basename;
334         char *dirname;
335         const char *buf;
336         off_t size;
337         const char *pos;
338         int line;
339         const char *line_start;
340         int report_line;
341         const char *report_name;
342         const char *report_dir;
343         int macro      : 1;
344         int trigraphs  : 1;
345         int join_lines : 1;
346 };
347 struct hash_entry;
348 struct token {
349         int tok;
350         struct hash_entry *ident;
351         const char *pos;
352         int str_len;
353         union {
354                 ulong_t integer;
355                 const char *str;
356                 int notmacro;
357         } val;
358 };
359
360 /* I have two classes of types:
361  * Operational types.
362  * Logical types.  (The type the C standard says the operation is of)
363  *
364  * The operational types are:
365  * chars
366  * shorts
367  * ints
368  * longs
369  *
370  * floats
371  * doubles
372  * long doubles
373  *
374  * pointer
375  */
376
377
378 /* Machine model.
379  * No memory is useable by the compiler.
380  * There is no floating point support.
381  * All operations take place in general purpose registers.
382  * There is one type of general purpose register.
383  * Unsigned longs are stored in that general purpose register.
384  */
385
386 /* Operations on general purpose registers.
387  */
388
389 #define OP_SDIVT      0
390 #define OP_UDIVT      1
391 #define OP_SMUL       2
392 #define OP_UMUL       3
393 #define OP_SDIV       4
394 #define OP_UDIV       5
395 #define OP_SMOD       6
396 #define OP_UMOD       7
397 #define OP_ADD        8
398 #define OP_SUB        9
399 #define OP_SL        10
400 #define OP_USR       11
401 #define OP_SSR       12 
402 #define OP_AND       13 
403 #define OP_XOR       14
404 #define OP_OR        15
405 #define OP_POS       16 /* Dummy positive operator don't use it */
406 #define OP_NEG       17
407 #define OP_INVERT    18
408                      
409 #define OP_EQ        20
410 #define OP_NOTEQ     21
411 #define OP_SLESS     22
412 #define OP_ULESS     23
413 #define OP_SMORE     24
414 #define OP_UMORE     25
415 #define OP_SLESSEQ   26
416 #define OP_ULESSEQ   27
417 #define OP_SMOREEQ   28
418 #define OP_UMOREEQ   29
419                      
420 #define OP_LFALSE    30  /* Test if the expression is logically false */
421 #define OP_LTRUE     31  /* Test if the expression is logcially true */
422
423 #define OP_LOAD      32
424 #define OP_STORE     33
425 /* For OP_STORE ->type holds the type
426  * RHS(0) holds the destination address
427  * RHS(1) holds the value to store.
428  */
429
430 #define OP_UEXTRACT  34
431 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
432  * RHS(0) holds the psuedo register to extract from
433  * ->type holds the size of the bitfield.
434  * ->u.bitfield.size holds the size of the bitfield.
435  * ->u.bitfield.offset holds the offset to extract from
436  */
437 #define OP_SEXTRACT  35
438 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
439  * RHS(0) holds the psuedo register to extract from
440  * ->type holds the size of the bitfield.
441  * ->u.bitfield.size holds the size of the bitfield.
442  * ->u.bitfield.offset holds the offset to extract from
443  */
444 #define OP_DEPOSIT   36
445 /* OP_DEPOSIT replaces a bitfield with a new value.
446  * RHS(0) holds the value to replace a bitifield in.
447  * RHS(1) holds the replacement value
448  * ->u.bitfield.size holds the size of the bitfield.
449  * ->u.bitfield.offset holds the deposit into
450  */
451
452 #define OP_NOOP      37
453
454 #define OP_MIN_CONST 50
455 #define OP_MAX_CONST 58
456 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
457 #define OP_INTCONST  50
458 /* For OP_INTCONST ->type holds the type.
459  * ->u.cval holds the constant value.
460  */
461 #define OP_BLOBCONST 51
462 /* For OP_BLOBCONST ->type holds the layout and size
463  * information.  u.blob holds a pointer to the raw binary
464  * data for the constant initializer.
465  */
466 #define OP_ADDRCONST 52
467 /* For OP_ADDRCONST ->type holds the type.
468  * MISC(0) holds the reference to the static variable.
469  * ->u.cval holds an offset from that value.
470  */
471 #define OP_UNKNOWNVAL 59
472 /* For OP_UNKNOWNAL ->type holds the type.
473  * For some reason we don't know what value this type has.
474  * This allows for variables that have don't have values
475  * assigned yet, or variables whose value we simply do not know.
476  */
477
478 #define OP_WRITE     60 
479 /* OP_WRITE moves one pseudo register to another.
480  * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
481  * RHS(0) holds the psuedo to move.
482  */
483
484 #define OP_READ      61
485 /* OP_READ reads the value of a variable and makes
486  * it available for the pseudo operation.
487  * Useful for things like def-use chains.
488  * RHS(0) holds points to the triple to read from.
489  */
490 #define OP_COPY      62
491 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
492  */
493 #define OP_CONVERT   63
494 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
495  * And then the type is converted appropriately.
496  */
497 #define OP_PIECE     64
498 /* OP_PIECE returns one piece of a instruction that returns a structure.
499  * MISC(0) is the instruction
500  * u.cval is the LHS piece of the instruction to return.
501  */
502 #define OP_ASM       65
503 /* OP_ASM holds a sequence of assembly instructions, the result
504  * of a C asm directive.
505  * RHS(x) holds input value x to the assembly sequence.
506  * LHS(x) holds the output value x from the assembly sequence.
507  * u.blob holds the string of assembly instructions.
508  */
509
510 #define OP_DEREF     66
511 /* OP_DEREF generates an lvalue from a pointer.
512  * RHS(0) holds the pointer value.
513  * OP_DEREF serves as a place holder to indicate all necessary
514  * checks have been done to indicate a value is an lvalue.
515  */
516 #define OP_DOT       67
517 /* OP_DOT references a submember of a structure lvalue.
518  * MISC(0) holds the lvalue.
519  * ->u.field holds the name of the field we want.
520  *
521  * Not seen after structures are flattened.
522  */
523 #define OP_INDEX     68
524 /* OP_INDEX references a submember of a tuple or array lvalue.
525  * MISC(0) holds the lvalue.
526  * ->u.cval holds the index into the lvalue.
527  *
528  * Not seen after structures are flattened.
529  */
530 #define OP_VAL       69
531 /* OP_VAL returns the value of a subexpression of the current expression.
532  * Useful for operators that have side effects.
533  * RHS(0) holds the expression.
534  * MISC(0) holds the subexpression of RHS(0) that is the
535  * value of the expression.
536  *
537  * Not seen outside of expressions.
538  */
539
540 #define OP_TUPLE     70
541 /* OP_TUPLE is an array of triples that are either variable
542  * or values for a structure or an array.  It is used as
543  * a place holder when flattening compound types.
544  * The value represented by an OP_TUPLE is held in N registers.
545  * LHS(0..N-1) refer to those registers.
546  * ->use is a list of statements that use the value.
547  * 
548  * Although OP_TUPLE always has register sized pieces they are not
549  * used until structures are flattened/decomposed into their register
550  * components. 
551  * ???? registers ????
552  */
553
554 #define OP_BITREF    71
555 /* OP_BITREF describes a bitfield as an lvalue.
556  * RHS(0) holds the register value.
557  * ->type holds the type of the bitfield.
558  * ->u.bitfield.size holds the size of the bitfield.
559  * ->u.bitfield.offset holds the offset of the bitfield in the register
560  */
561
562
563 #define OP_FCALL     72
564 /* OP_FCALL performs a procedure call. 
565  * MISC(0) holds a pointer to the OP_LIST of a function
566  * RHS(x) holds argument x of a function
567  * 
568  * Currently not seen outside of expressions.
569  */
570 #define OP_PROG      73
571 /* OP_PROG is an expression that holds a list of statements, or
572  * expressions.  The final expression is the value of the expression.
573  * RHS(0) holds the start of the list.
574  */
575
576 /* statements */
577 #define OP_LIST      80
578 /* OP_LIST Holds a list of statements that compose a function, and a result value.
579  * RHS(0) holds the list of statements.
580  * A list of all functions is maintained.
581  */
582
583 #define OP_BRANCH    81 /* an unconditional branch */
584 /* For branch instructions
585  * TARG(0) holds the branch target.
586  * ->next holds where to branch to if the branch is not taken.
587  * The branch target can only be a label
588  */
589
590 #define OP_CBRANCH   82 /* a conditional branch */
591 /* For conditional branch instructions
592  * RHS(0) holds the branch condition.
593  * TARG(0) holds the branch target.
594  * ->next holds where to branch to if the branch is not taken.
595  * The branch target can only be a label
596  */
597
598 #define OP_CALL      83 /* an uncontional branch that will return */
599 /* For call instructions
600  * MISC(0) holds the OP_RET that returns from the branch
601  * TARG(0) holds the branch target.
602  * ->next holds where to branch to if the branch is not taken.
603  * The branch target can only be a label
604  */
605
606 #define OP_RET       84 /* an uncontinonal branch through a variable back to an OP_CALL */
607 /* For call instructions
608  * RHS(0) holds the variable with the return address
609  * The branch target can only be a label
610  */
611
612 #define OP_LABEL     86
613 /* OP_LABEL is a triple that establishes an target for branches.
614  * ->use is the list of all branches that use this label.
615  */
616
617 #define OP_ADECL     87 
618 /* OP_ADECL is a triple that establishes an lvalue for assignments.
619  * A variable takes N registers to contain.
620  * LHS(0..N-1) refer to an OP_PIECE triple that represents
621  * the Xth register that the variable is stored in.
622  * ->use is a list of statements that use the variable.
623  * 
624  * Although OP_ADECL always has register sized pieces they are not
625  * used until structures are flattened/decomposed into their register
626  * components. 
627  */
628
629 #define OP_SDECL     88
630 /* OP_SDECL is a triple that establishes a variable of static
631  * storage duration.
632  * ->use is a list of statements that use the variable.
633  * MISC(0) holds the initializer expression.
634  */
635
636
637 #define OP_PHI       89
638 /* OP_PHI is a triple used in SSA form code.  
639  * It is used when multiple code paths merge and a variable needs
640  * a single assignment from any of those code paths.
641  * The operation is a cross between OP_DECL and OP_WRITE, which
642  * is what OP_PHI is generated from.
643  * 
644  * RHS(x) points to the value from code path x
645  * The number of RHS entries is the number of control paths into the block
646  * in which OP_PHI resides.  The elements of the array point to point
647  * to the variables OP_PHI is derived from.
648  *
649  * MISC(0) holds a pointer to the orginal OP_DECL node.
650  */
651
652 #if 0
653 /* continuation helpers
654  */
655 #define OP_CPS_BRANCH    90 /* an unconditional branch */
656 /* OP_CPS_BRANCH calls a continuation 
657  * RHS(x) holds argument x of the function
658  * TARG(0) holds OP_CPS_START target
659  */
660 #define OP_CPS_CBRANCH   91  /* a conditional branch */
661 /* OP_CPS_CBRANCH conditionally calls one of two continuations 
662  * RHS(0) holds the branch condition
663  * RHS(x + 1) holds argument x of the function
664  * TARG(0) holds the OP_CPS_START to jump to when true
665  * ->next holds the OP_CPS_START to jump to when false
666  */
667 #define OP_CPS_CALL      92  /* an uncontional branch that will return */
668 /* For OP_CPS_CALL instructions
669  * RHS(x) holds argument x of the function
670  * MISC(0) holds the OP_CPS_RET that returns from the branch
671  * TARG(0) holds the branch target.
672  * ->next holds where the OP_CPS_RET will return to.
673  */
674 #define OP_CPS_RET       93
675 /* OP_CPS_RET conditionally calls one of two continuations 
676  * RHS(0) holds the variable with the return function address
677  * RHS(x + 1) holds argument x of the function
678  * The branch target may be any OP_CPS_START
679  */
680 #define OP_CPS_END       94
681 /* OP_CPS_END is the triple at the end of the program.
682  * For most practical purposes it is a branch.
683  */
684 #define OP_CPS_START     95
685 /* OP_CPS_START is a triple at the start of a continuation
686  * The arguments variables takes N registers to contain.
687  * LHS(0..N-1) refer to an OP_PIECE triple that represents
688  * the Xth register that the arguments are stored in.
689  */
690 #endif
691
692 /* Architecture specific instructions */
693 #define OP_CMP         100
694 #define OP_TEST        101
695 #define OP_SET_EQ      102
696 #define OP_SET_NOTEQ   103
697 #define OP_SET_SLESS   104
698 #define OP_SET_ULESS   105
699 #define OP_SET_SMORE   106
700 #define OP_SET_UMORE   107
701 #define OP_SET_SLESSEQ 108
702 #define OP_SET_ULESSEQ 109
703 #define OP_SET_SMOREEQ 110
704 #define OP_SET_UMOREEQ 111
705
706 #define OP_JMP         112
707 #define OP_JMP_EQ      113
708 #define OP_JMP_NOTEQ   114
709 #define OP_JMP_SLESS   115
710 #define OP_JMP_ULESS   116
711 #define OP_JMP_SMORE   117
712 #define OP_JMP_UMORE   118
713 #define OP_JMP_SLESSEQ 119
714 #define OP_JMP_ULESSEQ 120
715 #define OP_JMP_SMOREEQ 121
716 #define OP_JMP_UMOREEQ 122
717
718 /* Builtin operators that it is just simpler to use the compiler for */
719 #define OP_INB         130
720 #define OP_INW         131
721 #define OP_INL         132
722 #define OP_OUTB        133
723 #define OP_OUTW        134
724 #define OP_OUTL        135
725 #define OP_BSF         136
726 #define OP_BSR         137
727 #define OP_RDMSR       138
728 #define OP_WRMSR       139
729 #define OP_HLT         140
730
731 struct op_info {
732         const char *name;
733         unsigned flags;
734 #define PURE       0x001 /* Triple has no side effects */
735 #define IMPURE     0x002 /* Triple has side effects */
736 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
737 #define DEF        0x004 /* Triple is a variable definition */
738 #define BLOCK      0x008 /* Triple stores the current block */
739 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
740 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
741 #define UBRANCH    0x020 /* Triple is an unconditional branch instruction */
742 #define CBRANCH    0x040 /* Triple is a conditional branch instruction */
743 #define RETBRANCH  0x060 /* Triple is a return instruction */
744 #define CALLBRANCH 0x080 /* Triple is a call instruction */
745 #define ENDBRANCH  0x0a0 /* Triple is an end instruction */
746 #define PART       0x100 /* Triple is really part of another triple */
747 #define BITFIELD   0x200 /* Triple manipulates a bitfield */
748         signed char lhs, rhs, misc, targ;
749 };
750
751 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
752         .name = (NAME), \
753         .flags = (FLAGS), \
754         .lhs = (LHS), \
755         .rhs = (RHS), \
756         .misc = (MISC), \
757         .targ = (TARG), \
758          }
759 static const struct op_info table_ops[] = {
760 [OP_SDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "sdivt"),
761 [OP_UDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "udivt"),
762 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
763 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
764 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
765 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
766 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
767 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
768 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
769 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
770 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
771 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
772 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
773 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
774 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
775 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
776 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
777 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
778 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
779
780 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
781 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
782 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
783 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
784 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
785 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
786 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
787 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
788 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
789 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
790 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
791 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
792
793 [OP_LOAD       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "load"),
794 [OP_STORE      ] = OP( 0,  2, 0, 0, PURE | BLOCK , "store"),
795
796 [OP_UEXTRACT   ] = OP( 0,  1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
797 [OP_SEXTRACT   ] = OP( 0,  1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
798 [OP_DEPOSIT    ] = OP( 0,  2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
799
800 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
801
802 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
803 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE , "blobconst"),
804 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
805 [OP_UNKNOWNVAL ] = OP( 0,  0, 0, 0, PURE | DEF, "unknown"),
806
807 #if DEBUG_ROMCC_WARNINGS
808 #warning "FIXME is it correct for OP_WRITE to be a def?  I currently use it as one..."
809 #endif
810 [OP_WRITE      ] = OP( 0,  1, 1, 0, PURE | DEF | BLOCK, "write"),
811 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
812 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
813 [OP_CONVERT    ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "convert"),
814 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
815 [OP_ASM        ] = OP(-1, -1, 0, 0, PURE, "asm"),
816 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"), 
817 [OP_DOT        ] = OP( 0,  0, 1, 0, PURE | DEF | PART, "dot"),
818 [OP_INDEX      ] = OP( 0,  0, 1, 0, PURE | DEF | PART, "index"),
819
820 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
821 [OP_TUPLE      ] = OP(-1,  0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
822 [OP_BITREF     ] = OP( 0,  1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
823 /* Call is special most it can stand in for anything so it depends on context */
824 [OP_FCALL      ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
825 [OP_PROG       ] = OP( 0,  1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
826 /* The sizes of OP_FCALL depends upon context */
827
828 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
829 [OP_BRANCH     ] = OP( 0,  0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
830 [OP_CBRANCH    ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
831 [OP_CALL       ] = OP( 0,  0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
832 [OP_RET        ] = OP( 0,  1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
833 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
834 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
835 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
836 /* The number of RHS elements of OP_PHI depend upon context */
837 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
838
839 #if 0
840 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH,     "cps_branch"),
841 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH,     "cps_cbranch"),
842 [OP_CPS_CALL   ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH,  "cps_call"),
843 [OP_CPS_RET    ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH,   "cps_ret"),
844 [OP_CPS_END    ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
845 [OP_CPS_START  ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL,  "cps_start"),
846 #endif
847
848 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
849 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
850 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
851 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
852 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
853 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
854 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
855 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
856 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
857 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
858 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
859 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
860 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
861 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
862 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
863 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
864 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
865 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
866 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
867 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
868 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
869 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
870 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
871
872 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
873 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
874 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
875 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
876 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
877 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
878 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
879 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
880 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
881 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
882 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
883 };
884 #undef OP
885 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
886
887 static const char *tops(int index) 
888 {
889         static const char unknown[] = "unknown op";
890         if (index < 0) {
891                 return unknown;
892         }
893         if (index > OP_MAX) {
894                 return unknown;
895         }
896         return table_ops[index].name;
897 }
898
899 struct asm_info;
900 struct triple;
901 struct block;
902 struct triple_set {
903         struct triple_set *next;
904         struct triple *member;
905 };
906
907 #define MAX_LHS  63
908 #define MAX_RHS  127
909 #define MAX_MISC 3
910 #define MAX_TARG 1
911
912 struct occurance {
913         int count;
914         const char *filename;
915         const char *function;
916         int line;
917         int col;
918         struct occurance *parent;
919 };
920 struct bitfield {
921         ulong_t size : 8;
922         ulong_t offset : 24;
923 };
924 struct triple {
925         struct triple *next, *prev;
926         struct triple_set *use;
927         struct type *type;
928         unsigned int op : 8;
929         unsigned int template_id : 7;
930         unsigned int lhs  : 6;
931         unsigned int rhs  : 7;
932         unsigned int misc : 2;
933         unsigned int targ : 1;
934 #define TRIPLE_SIZE(TRIPLE) \
935         ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
936 #define TRIPLE_LHS_OFF(PTR)  (0)
937 #define TRIPLE_RHS_OFF(PTR)  (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
938 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
939 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
940 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
941 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
942 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
943 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
944         unsigned id; /* A scratch value and finally the register */
945 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
946 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
947 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
948 #define TRIPLE_FLAG_VOLATILE    (1 << 28)
949 #define TRIPLE_FLAG_INLINE      (1 << 27) /* ???? */
950 #define TRIPLE_FLAG_LOCAL       (1 << 26)
951
952 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
953         struct occurance *occurance;
954         union {
955                 ulong_t cval;
956                 struct bitfield bitfield;
957                 struct block  *block;
958                 void *blob;
959                 struct hash_entry *field;
960                 struct asm_info *ainfo;
961                 struct triple *func;
962                 struct symbol *symbol;
963         } u;
964         struct triple *param[2];
965 };
966
967 struct reg_info {
968         unsigned reg;
969         unsigned regcm;
970 };
971 struct ins_template {
972         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
973 };
974
975 struct asm_info {
976         struct ins_template tmpl;
977         char *str;
978 };
979
980 struct block_set {
981         struct block_set *next;
982         struct block *member;
983 };
984 struct block {
985         struct block *work_next;
986         struct triple *first, *last;
987         int edge_count;
988         struct block_set *edges;
989         int users;
990         struct block_set *use;
991         struct block_set *idominates;
992         struct block_set *domfrontier;
993         struct block *idom;
994         struct block_set *ipdominates;
995         struct block_set *ipdomfrontier;
996         struct block *ipdom;
997         int vertex;
998         
999 };
1000
1001 struct symbol {
1002         struct symbol *next;
1003         struct hash_entry *ident;
1004         struct triple *def;
1005         struct type *type;
1006         int scope_depth;
1007 };
1008
1009 struct macro_arg {
1010         struct macro_arg *next;
1011         struct hash_entry *ident;
1012 };
1013 struct macro {
1014         struct hash_entry *ident;
1015         const char *buf;
1016         int buf_len;
1017         struct macro_arg *args;
1018         int argc;
1019 };
1020
1021 struct hash_entry {
1022         struct hash_entry *next;
1023         const char *name;
1024         int name_len;
1025         int tok;
1026         struct macro *sym_define;
1027         struct symbol *sym_label;
1028         struct symbol *sym_tag;
1029         struct symbol *sym_ident;
1030 };
1031
1032 #define HASH_TABLE_SIZE 2048
1033
1034 struct compiler_state {
1035         const char *label_prefix;
1036         const char *ofilename;
1037         unsigned long flags;
1038         unsigned long debug;
1039         unsigned long max_allocation_passes;
1040
1041         size_t include_path_count;
1042         const char **include_paths;
1043
1044         size_t define_count;
1045         const char **defines;
1046
1047         size_t undef_count;
1048         const char **undefs;
1049 };
1050 struct arch_state {
1051         unsigned long features;
1052 };
1053 struct basic_blocks {
1054         struct triple *func;
1055         struct triple *first;
1056         struct block *first_block, *last_block;
1057         int last_vertex;
1058 };
1059 #define MAX_PP_IF_DEPTH 63
1060 struct compile_state {
1061         struct compiler_state *compiler;
1062         struct arch_state *arch;
1063         FILE *output;
1064         FILE *errout;
1065         FILE *dbgout;
1066         struct file_state *file;
1067         struct occurance *last_occurance;
1068         const char *function;
1069         int    token_base;
1070         struct token token[6];
1071         struct hash_entry *hash_table[HASH_TABLE_SIZE];
1072         struct hash_entry *i_switch;
1073         struct hash_entry *i_case;
1074         struct hash_entry *i_continue;
1075         struct hash_entry *i_break;
1076         struct hash_entry *i_default;
1077         struct hash_entry *i_return;
1078         /* Additional hash entries for predefined macros */
1079         struct hash_entry *i_defined;
1080         struct hash_entry *i___VA_ARGS__;
1081         struct hash_entry *i___FILE__;
1082         struct hash_entry *i___LINE__;
1083         /* Additional hash entries for predefined identifiers */
1084         struct hash_entry *i___func__;
1085         /* Additional hash entries for attributes */
1086         struct hash_entry *i_noinline;
1087         struct hash_entry *i_always_inline;
1088         int scope_depth;
1089         unsigned char if_bytes[(MAX_PP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1090         int if_depth;
1091         int eat_depth, eat_targ;
1092         struct file_state *macro_file;
1093         struct triple *functions;
1094         struct triple *main_function;
1095         struct triple *first;
1096         struct triple *global_pool;
1097         struct basic_blocks bb;
1098         int functions_joined;
1099 };
1100
1101 /* visibility global/local */
1102 /* static/auto duration */
1103 /* typedef, register, inline */
1104 #define STOR_SHIFT         0
1105 #define STOR_MASK     0x001f
1106 /* Visibility */
1107 #define STOR_GLOBAL   0x0001
1108 /* Duration */
1109 #define STOR_PERM     0x0002
1110 /* Definition locality */
1111 #define STOR_NONLOCAL 0x0004  /* The definition is not in this translation unit */
1112 /* Storage specifiers */
1113 #define STOR_AUTO     0x0000
1114 #define STOR_STATIC   0x0002
1115 #define STOR_LOCAL    0x0003
1116 #define STOR_EXTERN   0x0007
1117 #define STOR_INLINE   0x0008
1118 #define STOR_REGISTER 0x0010
1119 #define STOR_TYPEDEF  0x0018
1120
1121 #define QUAL_SHIFT         5
1122 #define QUAL_MASK     0x00e0
1123 #define QUAL_NONE     0x0000
1124 #define QUAL_CONST    0x0020
1125 #define QUAL_VOLATILE 0x0040
1126 #define QUAL_RESTRICT 0x0080
1127
1128 #define TYPE_SHIFT         8
1129 #define TYPE_MASK     0x1f00
1130 #define TYPE_INTEGER(TYPE)    ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1131 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1132 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
1133 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
1134 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1135 #define TYPE_RANK(TYPE)       ((TYPE) & ~0xF1FF)
1136 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1137 #define TYPE_DEFAULT  0x0000
1138 #define TYPE_VOID     0x0100
1139 #define TYPE_CHAR     0x0200
1140 #define TYPE_UCHAR    0x0300
1141 #define TYPE_SHORT    0x0400
1142 #define TYPE_USHORT   0x0500
1143 #define TYPE_INT      0x0600
1144 #define TYPE_UINT     0x0700
1145 #define TYPE_LONG     0x0800
1146 #define TYPE_ULONG    0x0900
1147 #define TYPE_LLONG    0x0a00 /* long long */
1148 #define TYPE_ULLONG   0x0b00
1149 #define TYPE_FLOAT    0x0c00
1150 #define TYPE_DOUBLE   0x0d00
1151 #define TYPE_LDOUBLE  0x0e00 /* long double */
1152
1153 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1154 #define TYPE_ENUM     0x1600
1155 #define TYPE_LIST     0x1700
1156 /* TYPE_LIST is a basic building block when defining enumerations
1157  * type->field_ident holds the name of this enumeration entry.
1158  * type->right holds the entry in the list.
1159  */
1160
1161 #define TYPE_STRUCT   0x1000
1162 /* For TYPE_STRUCT
1163  * type->left holds the link list of TYPE_PRODUCT entries that
1164  * make up the structure.
1165  * type->elements hold the length of the linked list
1166  */
1167 #define TYPE_UNION    0x1100
1168 /* For TYPE_UNION
1169  * type->left holds the link list of TYPE_OVERLAP entries that
1170  * make up the union.
1171  * type->elements hold the length of the linked list
1172  */
1173 #define TYPE_POINTER  0x1200 
1174 /* For TYPE_POINTER:
1175  * type->left holds the type pointed to.
1176  */
1177 #define TYPE_FUNCTION 0x1300 
1178 /* For TYPE_FUNCTION:
1179  * type->left holds the return type.
1180  * type->right holds the type of the arguments
1181  * type->elements holds the count of the arguments
1182  */
1183 #define TYPE_PRODUCT  0x1400
1184 /* TYPE_PRODUCT is a basic building block when defining structures
1185  * type->left holds the type that appears first in memory.
1186  * type->right holds the type that appears next in memory.
1187  */
1188 #define TYPE_OVERLAP  0x1500
1189 /* TYPE_OVERLAP is a basic building block when defining unions
1190  * type->left and type->right holds to types that overlap
1191  * each other in memory.
1192  */
1193 #define TYPE_ARRAY    0x1800
1194 /* TYPE_ARRAY is a basic building block when definitng arrays.
1195  * type->left holds the type we are an array of.
1196  * type->elements holds the number of elements.
1197  */
1198 #define TYPE_TUPLE    0x1900
1199 /* TYPE_TUPLE is a basic building block when defining 
1200  * positionally reference type conglomerations. (i.e. closures)
1201  * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1202  * except it has no field names.
1203  * type->left holds the liked list of TYPE_PRODUCT entries that
1204  * make up the closure type.
1205  * type->elements hold the number of elements in the closure.
1206  */
1207 #define TYPE_JOIN     0x1a00
1208 /* TYPE_JOIN is a basic building block when defining 
1209  * positionally reference type conglomerations. (i.e. closures)
1210  * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1211  * except it has no field names.
1212  * type->left holds the liked list of TYPE_OVERLAP entries that
1213  * make up the closure type.
1214  * type->elements hold the number of elements in the closure.
1215  */
1216 #define TYPE_BITFIELD 0x1b00
1217 /* TYPE_BITFIED is the type of a bitfield.
1218  * type->left holds the type basic type TYPE_BITFIELD is derived from.
1219  * type->elements holds the number of bits in the bitfield.
1220  */
1221 #define TYPE_UNKNOWN  0x1c00
1222 /* TYPE_UNKNOWN is the type of an unknown value.
1223  * Used on unknown consts and other places where I don't know the type.
1224  */
1225
1226 #define ATTRIB_SHIFT                 16
1227 #define ATTRIB_MASK          0xffff0000
1228 #define ATTRIB_NOINLINE      0x00010000
1229 #define ATTRIB_ALWAYS_INLINE 0x00020000
1230
1231 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1232
1233 struct type {
1234         unsigned int type;
1235         struct type *left, *right;
1236         ulong_t elements;
1237         struct hash_entry *field_ident;
1238         struct hash_entry *type_ident;
1239 };
1240
1241 #define TEMPLATE_BITS      7
1242 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
1243 #define MAX_REG_EQUIVS     16
1244 #define MAX_REGC           14
1245 #define MAX_REGISTERS      75
1246 #define REGISTER_BITS      7
1247 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1248 #define REG_ERROR          0
1249 #define REG_UNSET          1
1250 #define REG_UNNEEDED       2
1251 #define REG_VIRT0          (MAX_REGISTERS + 0)
1252 #define REG_VIRT1          (MAX_REGISTERS + 1)
1253 #define REG_VIRT2          (MAX_REGISTERS + 2)
1254 #define REG_VIRT3          (MAX_REGISTERS + 3)
1255 #define REG_VIRT4          (MAX_REGISTERS + 4)
1256 #define REG_VIRT5          (MAX_REGISTERS + 5)
1257 #define REG_VIRT6          (MAX_REGISTERS + 6)
1258 #define REG_VIRT7          (MAX_REGISTERS + 7)
1259 #define REG_VIRT8          (MAX_REGISTERS + 8)
1260 #define REG_VIRT9          (MAX_REGISTERS + 9)
1261
1262 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1263 #error "MAX_VIRT_REGISTERS to small"
1264 #endif
1265 #if (MAX_REGC + REGISTER_BITS) >= 26
1266 #error "Too many id bits used"
1267 #endif
1268
1269 /* Provision for 8 register classes */
1270 #define REG_SHIFT  0
1271 #define REGC_SHIFT REGISTER_BITS
1272 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1273 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1274 #define ID_REG(ID)              ((ID) & REG_MASK)
1275 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1276 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
1277 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1278 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1279                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1280
1281 #define ARCH_INPUT_REGS 4
1282 #define ARCH_OUTPUT_REGS 4
1283
1284 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1285 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1286 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1287 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1288 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1289 static void arch_reg_equivs(
1290         struct compile_state *state, unsigned *equiv, int reg);
1291 static int arch_select_free_register(
1292         struct compile_state *state, char *used, int classes);
1293 static unsigned arch_regc_size(struct compile_state *state, int class);
1294 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1295 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1296 static const char *arch_reg_str(int reg);
1297 static struct reg_info arch_reg_constraint(
1298         struct compile_state *state, struct type *type, const char *constraint);
1299 static struct reg_info arch_reg_clobber(
1300         struct compile_state *state, const char *clobber);
1301 static struct reg_info arch_reg_lhs(struct compile_state *state, 
1302         struct triple *ins, int index);
1303 static struct reg_info arch_reg_rhs(struct compile_state *state, 
1304         struct triple *ins, int index);
1305 static int arch_reg_size(int reg);
1306 static struct triple *transform_to_arch_instruction(
1307         struct compile_state *state, struct triple *ins);
1308 static struct triple *flatten(
1309         struct compile_state *state, struct triple *first, struct triple *ptr);
1310 static void print_dominators(struct compile_state *state,
1311         FILE *fp, struct basic_blocks *bb);
1312 static void print_dominance_frontiers(struct compile_state *state,
1313         FILE *fp, struct basic_blocks *bb);
1314
1315
1316
1317 #define DEBUG_ABORT_ON_ERROR    0x00000001
1318 #define DEBUG_BASIC_BLOCKS      0x00000002
1319 #define DEBUG_FDOMINATORS       0x00000004
1320 #define DEBUG_RDOMINATORS       0x00000008
1321 #define DEBUG_TRIPLES           0x00000010
1322 #define DEBUG_INTERFERENCE      0x00000020
1323 #define DEBUG_SCC_TRANSFORM     0x00000040
1324 #define DEBUG_SCC_TRANSFORM2    0x00000080
1325 #define DEBUG_REBUILD_SSA_FORM  0x00000100
1326 #define DEBUG_INLINE            0x00000200
1327 #define DEBUG_RANGE_CONFLICTS   0x00000400
1328 #define DEBUG_RANGE_CONFLICTS2  0x00000800
1329 #define DEBUG_COLOR_GRAPH       0x00001000
1330 #define DEBUG_COLOR_GRAPH2      0x00002000
1331 #define DEBUG_COALESCING        0x00004000
1332 #define DEBUG_COALESCING2       0x00008000
1333 #define DEBUG_VERIFICATION      0x00010000
1334 #define DEBUG_CALLS             0x00020000
1335 #define DEBUG_CALLS2            0x00040000
1336 #define DEBUG_TOKENS            0x80000000
1337
1338 #define DEBUG_DEFAULT ( \
1339         DEBUG_ABORT_ON_ERROR | \
1340         DEBUG_BASIC_BLOCKS | \
1341         DEBUG_FDOMINATORS | \
1342         DEBUG_RDOMINATORS | \
1343         DEBUG_TRIPLES | \
1344         0 )
1345
1346 #define DEBUG_ALL ( \
1347         DEBUG_ABORT_ON_ERROR   | \
1348         DEBUG_BASIC_BLOCKS     | \
1349         DEBUG_FDOMINATORS      | \
1350         DEBUG_RDOMINATORS      | \
1351         DEBUG_TRIPLES          | \
1352         DEBUG_INTERFERENCE     | \
1353         DEBUG_SCC_TRANSFORM    | \
1354         DEBUG_SCC_TRANSFORM2   | \
1355         DEBUG_REBUILD_SSA_FORM | \
1356         DEBUG_INLINE           | \
1357         DEBUG_RANGE_CONFLICTS  | \
1358         DEBUG_RANGE_CONFLICTS2 | \
1359         DEBUG_COLOR_GRAPH      | \
1360         DEBUG_COLOR_GRAPH2     | \
1361         DEBUG_COALESCING       | \
1362         DEBUG_COALESCING2      | \
1363         DEBUG_VERIFICATION     | \
1364         DEBUG_CALLS            | \
1365         DEBUG_CALLS2           | \
1366         DEBUG_TOKENS           | \
1367         0 )
1368
1369 #define COMPILER_INLINE_MASK               0x00000007
1370 #define COMPILER_INLINE_ALWAYS             0x00000000
1371 #define COMPILER_INLINE_NEVER              0x00000001
1372 #define COMPILER_INLINE_DEFAULTON          0x00000002
1373 #define COMPILER_INLINE_DEFAULTOFF         0x00000003
1374 #define COMPILER_INLINE_NOPENALTY          0x00000004
1375 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1376 #define COMPILER_SIMPLIFY                  0x00000010
1377 #define COMPILER_SCC_TRANSFORM             0x00000020
1378 #define COMPILER_SIMPLIFY_OP               0x00000040
1379 #define COMPILER_SIMPLIFY_PHI              0x00000080
1380 #define COMPILER_SIMPLIFY_LABEL            0x00000100
1381 #define COMPILER_SIMPLIFY_BRANCH           0x00000200
1382 #define COMPILER_SIMPLIFY_COPY             0x00000400
1383 #define COMPILER_SIMPLIFY_ARITH            0x00000800
1384 #define COMPILER_SIMPLIFY_SHIFT            0x00001000
1385 #define COMPILER_SIMPLIFY_BITWISE          0x00002000
1386 #define COMPILER_SIMPLIFY_LOGICAL          0x00004000
1387 #define COMPILER_SIMPLIFY_BITFIELD         0x00008000
1388
1389 #define COMPILER_TRIGRAPHS                 0x40000000
1390 #define COMPILER_PP_ONLY                   0x80000000
1391
1392 #define COMPILER_DEFAULT_FLAGS ( \
1393         COMPILER_TRIGRAPHS | \
1394         COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1395         COMPILER_INLINE_DEFAULTON | \
1396         COMPILER_SIMPLIFY_OP | \
1397         COMPILER_SIMPLIFY_PHI | \
1398         COMPILER_SIMPLIFY_LABEL | \
1399         COMPILER_SIMPLIFY_BRANCH | \
1400         COMPILER_SIMPLIFY_COPY | \
1401         COMPILER_SIMPLIFY_ARITH | \
1402         COMPILER_SIMPLIFY_SHIFT | \
1403         COMPILER_SIMPLIFY_BITWISE | \
1404         COMPILER_SIMPLIFY_LOGICAL | \
1405         COMPILER_SIMPLIFY_BITFIELD | \
1406         0 )
1407
1408 #define GLOBAL_SCOPE_DEPTH   1
1409 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1410
1411 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1412
1413
1414
1415 static void init_compiler_state(struct compiler_state *compiler)
1416 {
1417         memset(compiler, 0, sizeof(*compiler));
1418         compiler->label_prefix = "";
1419         compiler->ofilename = "auto.inc";
1420         compiler->flags = COMPILER_DEFAULT_FLAGS;
1421         compiler->debug = 0;
1422         compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1423         compiler->include_path_count = 1;
1424         compiler->include_paths      = xcmalloc(sizeof(char *), "include_paths");
1425         compiler->define_count       = 1;
1426         compiler->defines            = xcmalloc(sizeof(char *), "defines");
1427         compiler->undef_count        = 1;
1428         compiler->undefs             = xcmalloc(sizeof(char *), "undefs");
1429 }
1430
1431 struct compiler_flag {
1432         const char *name;
1433         unsigned long flag;
1434 };
1435
1436 struct compiler_arg {
1437         const char *name;
1438         unsigned long mask;
1439         struct compiler_flag flags[16];
1440 };
1441
1442 static int set_flag(
1443         const struct compiler_flag *ptr, unsigned long *flags,
1444         int act, const char *flag)
1445 {
1446         int result = -1;
1447         for(; ptr->name; ptr++) {
1448                 if (strcmp(ptr->name, flag) == 0) {
1449                         break;
1450                 }
1451         }
1452         if (ptr->name) {
1453                 result = 0;
1454                 *flags &= ~(ptr->flag);
1455                 if (act) {
1456                         *flags |= ptr->flag;
1457                 }
1458         }
1459         return result;
1460 }
1461
1462 static int set_arg(
1463         const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1464 {
1465         const char *val;
1466         int result = -1;
1467         int len;
1468         val = strchr(arg, '=');
1469         if (val) {
1470                 len = val - arg;
1471                 val++;
1472                 for(; ptr->name; ptr++) {
1473                         if (strncmp(ptr->name, arg, len) == 0) {
1474                                 break;
1475                         }
1476                 }
1477                 if (ptr->name) {
1478                         *flags &= ~ptr->mask;
1479                         result = set_flag(&ptr->flags[0], flags, 1, val);
1480                 }
1481         }
1482         return result;
1483 }
1484         
1485
1486 static void flag_usage(FILE *fp, const struct compiler_flag *ptr, 
1487         const char *prefix, const char *invert_prefix)
1488 {
1489         for(;ptr->name; ptr++) {
1490                 fprintf(fp, "%s%s\n", prefix, ptr->name);
1491                 if (invert_prefix) {
1492                         fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1493                 }
1494         }
1495 }
1496
1497 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1498         const char *prefix)
1499 {
1500         for(;ptr->name; ptr++) {
1501                 const struct compiler_flag *flag;
1502                 for(flag = &ptr->flags[0]; flag->name; flag++) {
1503                         fprintf(fp, "%s%s=%s\n", 
1504                                 prefix, ptr->name, flag->name);
1505                 }
1506         }
1507 }
1508
1509 static int append_string(size_t *max, const char ***vec, const char *str,
1510         const char *name)
1511 {
1512         size_t count;
1513         count = ++(*max);
1514         *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1515         (*vec)[count -1] = 0;
1516         (*vec)[count -2] = str; 
1517         return 0;
1518 }
1519
1520 static void arg_error(char *fmt, ...);
1521 static const char *identifier(const char *str, const char *end);
1522
1523 static int append_include_path(struct compiler_state *compiler, const char *str)
1524 {
1525         int result;
1526         if (!exists(str, ".")) {
1527                 arg_error("Nonexistent include path: `%s'\n",
1528                         str);
1529         }
1530         result = append_string(&compiler->include_path_count,
1531                 &compiler->include_paths, str, "include_paths");
1532         return result;
1533 }
1534
1535 static int append_define(struct compiler_state *compiler, const char *str)
1536 {
1537         const char *end, *rest;
1538         int result;
1539
1540         end = strchr(str, '=');
1541         if (!end) {
1542                 end = str + strlen(str);
1543         }
1544         rest = identifier(str, end);
1545         if (rest != end) {
1546                 int len = end - str - 1;
1547                 arg_error("Invalid name cannot define macro: `%*.*s'\n", 
1548                         len, len, str);
1549         }
1550         result = append_string(&compiler->define_count,
1551                 &compiler->defines, str, "defines");
1552         return result;
1553 }
1554
1555 static int append_undef(struct compiler_state *compiler, const char *str)
1556 {
1557         const char *end, *rest;
1558         int result;
1559
1560         end = str + strlen(str);
1561         rest = identifier(str, end);
1562         if (rest != end) {
1563                 int len = end - str - 1;
1564                 arg_error("Invalid name cannot undefine macro: `%*.*s'\n", 
1565                         len, len, str);
1566         }
1567         result = append_string(&compiler->undef_count,
1568                 &compiler->undefs, str, "undefs");
1569         return result;
1570 }
1571
1572 static const struct compiler_flag romcc_flags[] = {
1573         { "trigraphs",                 COMPILER_TRIGRAPHS },
1574         { "pp-only",                   COMPILER_PP_ONLY },
1575         { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1576         { "simplify",                  COMPILER_SIMPLIFY },
1577         { "scc-transform",             COMPILER_SCC_TRANSFORM },
1578         { "simplify-op",               COMPILER_SIMPLIFY_OP },
1579         { "simplify-phi",              COMPILER_SIMPLIFY_PHI },
1580         { "simplify-label",            COMPILER_SIMPLIFY_LABEL },
1581         { "simplify-branch",           COMPILER_SIMPLIFY_BRANCH },
1582         { "simplify-copy",             COMPILER_SIMPLIFY_COPY },
1583         { "simplify-arith",            COMPILER_SIMPLIFY_ARITH },
1584         { "simplify-shift",            COMPILER_SIMPLIFY_SHIFT },
1585         { "simplify-bitwise",          COMPILER_SIMPLIFY_BITWISE },
1586         { "simplify-logical",          COMPILER_SIMPLIFY_LOGICAL },
1587         { "simplify-bitfield",         COMPILER_SIMPLIFY_BITFIELD },
1588         { 0, 0 },
1589 };
1590 static const struct compiler_arg romcc_args[] = {
1591         { "inline-policy",             COMPILER_INLINE_MASK,
1592                 {
1593                         { "always",      COMPILER_INLINE_ALWAYS, },
1594                         { "never",       COMPILER_INLINE_NEVER, },
1595                         { "defaulton",   COMPILER_INLINE_DEFAULTON, },
1596                         { "defaultoff",  COMPILER_INLINE_DEFAULTOFF, },
1597                         { "nopenalty",   COMPILER_INLINE_NOPENALTY, },
1598                         { 0, 0 },
1599                 },
1600         },
1601         { 0, 0 },
1602 };
1603 static const struct compiler_flag romcc_opt_flags[] = {
1604         { "-O",  COMPILER_SIMPLIFY },
1605         { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1606         { "-E",  COMPILER_PP_ONLY },
1607         { 0, 0, },
1608 };
1609 static const struct compiler_flag romcc_debug_flags[] = {
1610         { "all",                   DEBUG_ALL },
1611         { "abort-on-error",        DEBUG_ABORT_ON_ERROR },
1612         { "basic-blocks",          DEBUG_BASIC_BLOCKS },
1613         { "fdominators",           DEBUG_FDOMINATORS },
1614         { "rdominators",           DEBUG_RDOMINATORS },
1615         { "triples",               DEBUG_TRIPLES },
1616         { "interference",          DEBUG_INTERFERENCE },
1617         { "scc-transform",         DEBUG_SCC_TRANSFORM },
1618         { "scc-transform2",        DEBUG_SCC_TRANSFORM2 },
1619         { "rebuild-ssa-form",      DEBUG_REBUILD_SSA_FORM },
1620         { "inline",                DEBUG_INLINE },
1621         { "live-range-conflicts",  DEBUG_RANGE_CONFLICTS },
1622         { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1623         { "color-graph",           DEBUG_COLOR_GRAPH },
1624         { "color-graph2",          DEBUG_COLOR_GRAPH2 },
1625         { "coalescing",            DEBUG_COALESCING },
1626         { "coalescing2",           DEBUG_COALESCING2 },
1627         { "verification",          DEBUG_VERIFICATION },
1628         { "calls",                 DEBUG_CALLS },
1629         { "calls2",                DEBUG_CALLS2 },
1630         { "tokens",                DEBUG_TOKENS },
1631         { 0, 0 },
1632 };
1633
1634 static int compiler_encode_flag(
1635         struct compiler_state *compiler, const char *flag)
1636 {
1637         int act;
1638         int result;
1639
1640         act = 1;
1641         result = -1;
1642         if (strncmp(flag, "no-", 3) == 0) {
1643                 flag += 3;
1644                 act = 0;
1645         }
1646         if (strncmp(flag, "-O", 2) == 0) {
1647                 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1648         }
1649         else if (strncmp(flag, "-E", 2) == 0) {
1650                 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1651         }
1652         else if (strncmp(flag, "-I", 2) == 0) {
1653                 result = append_include_path(compiler, flag + 2);
1654         }
1655         else if (strncmp(flag, "-D", 2) == 0) {
1656                 result = append_define(compiler, flag + 2);
1657         }
1658         else if (strncmp(flag, "-U", 2) == 0) {
1659                 result = append_undef(compiler, flag + 2);
1660         }
1661         else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1662                 result = 0;
1663                 compiler->label_prefix = flag + 13;
1664         }
1665         else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1666                 unsigned long max_passes;
1667                 char *end;
1668                 max_passes = strtoul(flag + 22, &end, 10);
1669                 if (end[0] == '\0') {
1670                         result = 0;
1671                         compiler->max_allocation_passes = max_passes;
1672                 }
1673         }
1674         else if (act && strcmp(flag, "debug") == 0) {
1675                 result = 0;
1676                 compiler->debug |= DEBUG_DEFAULT;
1677         }
1678         else if (strncmp(flag, "debug-", 6) == 0) {
1679                 flag += 6;
1680                 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1681         }
1682         else {
1683                 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1684                 if (result < 0) {
1685                         result = set_arg(romcc_args, &compiler->flags, flag);
1686                 }
1687         }
1688         return result;
1689 }
1690
1691 static void compiler_usage(FILE *fp)
1692 {
1693         flag_usage(fp, romcc_opt_flags, "", 0);
1694         flag_usage(fp, romcc_flags, "-f", "-fno-");
1695         arg_usage(fp,  romcc_args, "-f");
1696         flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1697         fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1698         fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1699         fprintf(fp, "-I<include path>\n");
1700         fprintf(fp, "-D<macro>[=defn]\n");
1701         fprintf(fp, "-U<macro>\n");
1702 }
1703
1704 static void do_cleanup(struct compile_state *state)
1705 {
1706         if (state->output) {
1707                 fclose(state->output);
1708                 unlink(state->compiler->ofilename);
1709                 state->output = 0;
1710         }
1711         if (state->dbgout) {
1712                 fflush(state->dbgout);
1713         }
1714         if (state->errout) {
1715                 fflush(state->errout);
1716         }
1717 }
1718
1719 static struct compile_state *exit_state;
1720 static void exit_cleanup(void)
1721 {
1722         if (exit_state) {
1723                 do_cleanup(exit_state);
1724         }
1725 }
1726
1727 static int get_col(struct file_state *file)
1728 {
1729         int col;
1730         const char *ptr, *end;
1731         ptr = file->line_start;
1732         end = file->pos;
1733         for(col = 0; ptr < end; ptr++) {
1734                 if (*ptr != '\t') {
1735                         col++;
1736                 } 
1737                 else {
1738                         col = (col & ~7) + 8;
1739                 }
1740         }
1741         return col;
1742 }
1743
1744 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1745 {
1746         int col;
1747         if (triple && triple->occurance) {
1748                 struct occurance *spot;
1749                 for(spot = triple->occurance; spot; spot = spot->parent) {
1750                         fprintf(fp, "%s:%d.%d: ", 
1751                                 spot->filename, spot->line, spot->col);
1752                 }
1753                 return;
1754         }
1755         if (!state->file) {
1756                 return;
1757         }
1758         col = get_col(state->file);
1759         fprintf(fp, "%s:%d.%d: ", 
1760                 state->file->report_name, state->file->report_line, col);
1761 }
1762
1763 static void __attribute__ ((noreturn)) internal_error(struct compile_state *state, struct triple *ptr, 
1764         const char *fmt, ...)
1765 {
1766         FILE *fp = state->errout;
1767         va_list args;
1768         va_start(args, fmt);
1769         loc(fp, state, ptr);
1770         fputc('\n', fp);
1771         if (ptr) {
1772                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1773         }
1774         fprintf(fp, "Internal compiler error: ");
1775         vfprintf(fp, fmt, args);
1776         fprintf(fp, "\n");
1777         va_end(args);
1778         do_cleanup(state);
1779         abort();
1780 }
1781
1782
1783 static void internal_warning(struct compile_state *state, struct triple *ptr, 
1784         const char *fmt, ...)
1785 {
1786         FILE *fp = state->errout;
1787         va_list args;
1788         va_start(args, fmt);
1789         loc(fp, state, ptr);
1790         if (ptr) {
1791                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1792         }
1793         fprintf(fp, "Internal compiler warning: ");
1794         vfprintf(fp, fmt, args);
1795         fprintf(fp, "\n");
1796         va_end(args);
1797 }
1798
1799
1800
1801 static void __attribute__ ((noreturn)) error(struct compile_state *state, struct triple *ptr, 
1802         const char *fmt, ...)
1803 {
1804         FILE *fp = state->errout;
1805         va_list args;
1806         va_start(args, fmt);
1807         loc(fp, state, ptr);
1808         fputc('\n', fp);
1809         if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1810                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1811         }
1812         vfprintf(fp, fmt, args);
1813         va_end(args);
1814         fprintf(fp, "\n");
1815         do_cleanup(state);
1816         if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1817                 abort();
1818         }
1819         exit(1);
1820 }
1821
1822 static void warning(struct compile_state *state, struct triple *ptr, 
1823         const char *fmt, ...)
1824 {
1825         FILE *fp = state->errout;
1826         va_list args;
1827         va_start(args, fmt);
1828         loc(fp, state, ptr);
1829         fprintf(fp, "warning: "); 
1830         if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1831                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1832         }
1833         vfprintf(fp, fmt, args);
1834         fprintf(fp, "\n");
1835         va_end(args);
1836 }
1837
1838 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1839
1840 static void valid_op(struct compile_state *state, int op)
1841 {
1842         char *fmt = "invalid op: %d";
1843         if (op >= OP_MAX) {
1844                 internal_error(state, 0, fmt, op);
1845         }
1846         if (op < 0) {
1847                 internal_error(state, 0, fmt, op);
1848         }
1849 }
1850
1851 static void valid_ins(struct compile_state *state, struct triple *ptr)
1852 {
1853         valid_op(state, ptr->op);
1854 }
1855
1856 #if DEBUG_ROMCC_WARNING
1857 static void valid_param_count(struct compile_state *state, struct triple *ins)
1858 {
1859         int lhs, rhs, misc, targ;
1860         valid_ins(state, ins);
1861         lhs  = table_ops[ins->op].lhs;
1862         rhs  = table_ops[ins->op].rhs;
1863         misc = table_ops[ins->op].misc;
1864         targ = table_ops[ins->op].targ;
1865
1866         if ((lhs >= 0) && (ins->lhs != lhs)) {
1867                 internal_error(state, ins, "Bad lhs count");
1868         }
1869         if ((rhs >= 0) && (ins->rhs != rhs)) {
1870                 internal_error(state, ins, "Bad rhs count");
1871         }
1872         if ((misc >= 0) && (ins->misc != misc)) {
1873                 internal_error(state, ins, "Bad misc count");
1874         }
1875         if ((targ >= 0) && (ins->targ != targ)) {
1876                 internal_error(state, ins, "Bad targ count");
1877         }
1878 }
1879 #endif
1880
1881 static struct type void_type;
1882 static struct type unknown_type;
1883 static void use_triple(struct triple *used, struct triple *user)
1884 {
1885         struct triple_set **ptr, *new;
1886         if (!used)
1887                 return;
1888         if (!user)
1889                 return;
1890         ptr = &used->use;
1891         while(*ptr) {
1892                 if ((*ptr)->member == user) {
1893                         return;
1894                 }
1895                 ptr = &(*ptr)->next;
1896         }
1897         /* Append new to the head of the list, 
1898          * copy_func and rename_block_variables
1899          * depends on this.
1900          */
1901         new = xcmalloc(sizeof(*new), "triple_set");
1902         new->member = user;
1903         new->next   = used->use;
1904         used->use   = new;
1905 }
1906
1907 static void unuse_triple(struct triple *used, struct triple *unuser)
1908 {
1909         struct triple_set *use, **ptr;
1910         if (!used) {
1911                 return;
1912         }
1913         ptr = &used->use;
1914         while(*ptr) {
1915                 use = *ptr;
1916                 if (use->member == unuser) {
1917                         *ptr = use->next;
1918                         xfree(use);
1919                 }
1920                 else {
1921                         ptr = &use->next;
1922                 }
1923         }
1924 }
1925
1926 static void put_occurance(struct occurance *occurance)
1927 {
1928         if (occurance) {
1929                 occurance->count -= 1;
1930                 if (occurance->count <= 0) {
1931                         if (occurance->parent) {
1932                                 put_occurance(occurance->parent);
1933                         }
1934                         xfree(occurance);
1935                 }
1936         }
1937 }
1938
1939 static void get_occurance(struct occurance *occurance)
1940 {
1941         if (occurance) {
1942                 occurance->count += 1;
1943         }
1944 }
1945
1946
1947 static struct occurance *new_occurance(struct compile_state *state)
1948 {
1949         struct occurance *result, *last;
1950         const char *filename;
1951         const char *function;
1952         int line, col;
1953
1954         function = "";
1955         filename = 0;
1956         line = 0;
1957         col  = 0;
1958         if (state->file) {
1959                 filename = state->file->report_name;
1960                 line     = state->file->report_line;
1961                 col      = get_col(state->file);
1962         }
1963         if (state->function) {
1964                 function = state->function;
1965         }
1966         last = state->last_occurance;
1967         if (last &&
1968                 (last->col == col) &&
1969                 (last->line == line) &&
1970                 (last->function == function) &&
1971                 ((last->filename == filename) ||
1972                         (strcmp(last->filename, filename) == 0))) 
1973         {
1974                 get_occurance(last);
1975                 return last;
1976         }
1977         if (last) {
1978                 state->last_occurance = 0;
1979                 put_occurance(last);
1980         }
1981         result = xmalloc(sizeof(*result), "occurance");
1982         result->count    = 2;
1983         result->filename = filename;
1984         result->function = function;
1985         result->line     = line;
1986         result->col      = col;
1987         result->parent   = 0;
1988         state->last_occurance = result;
1989         return result;
1990 }
1991
1992 static struct occurance *inline_occurance(struct compile_state *state,
1993         struct occurance *base, struct occurance *top)
1994 {
1995         struct occurance *result, *last;
1996         if (top->parent) {
1997                 internal_error(state, 0, "inlining an already inlined function?");
1998         }
1999         /* If I have a null base treat it that way */
2000         if ((base->parent == 0) &&
2001                 (base->col == 0) &&
2002                 (base->line == 0) &&
2003                 (base->function[0] == '\0') &&
2004                 (base->filename[0] == '\0')) {
2005                 base = 0;
2006         }
2007         /* See if I can reuse the last occurance I had */
2008         last = state->last_occurance;
2009         if (last &&
2010                 (last->parent   == base) &&
2011                 (last->col      == top->col) &&
2012                 (last->line     == top->line) &&
2013                 (last->function == top->function) &&
2014                 (last->filename == top->filename)) {
2015                 get_occurance(last);
2016                 return last;
2017         }
2018         /* I can't reuse the last occurance so free it */
2019         if (last) {
2020                 state->last_occurance = 0;
2021                 put_occurance(last);
2022         }
2023         /* Generate a new occurance structure */
2024         get_occurance(base);
2025         result = xmalloc(sizeof(*result), "occurance");
2026         result->count    = 2;
2027         result->filename = top->filename;
2028         result->function = top->function;
2029         result->line     = top->line;
2030         result->col      = top->col;
2031         result->parent   = base;
2032         state->last_occurance = result;
2033         return result;
2034 }
2035
2036 static struct occurance dummy_occurance = {
2037         .count    = 2,
2038         .filename = __FILE__,
2039         .function = "",
2040         .line     = __LINE__,
2041         .col      = 0,
2042         .parent   = 0,
2043 };
2044
2045 /* The undef triple is used as a place holder when we are removing pointers
2046  * from a triple.  Having allows certain sanity checks to pass even
2047  * when the original triple that was pointed to is gone.
2048  */
2049 static struct triple unknown_triple = {
2050         .next      = &unknown_triple,
2051         .prev      = &unknown_triple,
2052         .use       = 0,
2053         .op        = OP_UNKNOWNVAL,
2054         .lhs       = 0,
2055         .rhs       = 0,
2056         .misc      = 0,
2057         .targ      = 0,
2058         .type      = &unknown_type,
2059         .id        = -1, /* An invalid id */
2060         .u = { .cval = 0, },
2061         .occurance = &dummy_occurance,
2062         .param = { [0] = 0, [1] = 0, },
2063 };
2064
2065
2066 static size_t registers_of(struct compile_state *state, struct type *type);
2067
2068 static struct triple *alloc_triple(struct compile_state *state, 
2069         int op, struct type *type, int lhs_wanted, int rhs_wanted,
2070         struct occurance *occurance)
2071 {
2072         size_t size, extra_count, min_count;
2073         int lhs, rhs, misc, targ;
2074         struct triple *ret, dummy;
2075         dummy.op = op;
2076         dummy.occurance = occurance;
2077         valid_op(state, op);
2078         lhs = table_ops[op].lhs;
2079         rhs = table_ops[op].rhs;
2080         misc = table_ops[op].misc;
2081         targ = table_ops[op].targ;
2082
2083         switch(op) {
2084         case OP_FCALL:
2085                 rhs = rhs_wanted;
2086                 break;
2087         case OP_PHI:
2088                 rhs = rhs_wanted;
2089                 break;
2090         case OP_ADECL:
2091                 lhs = registers_of(state, type);
2092                 break;
2093         case OP_TUPLE:
2094                 lhs = registers_of(state, type);
2095                 break;
2096         case OP_ASM:
2097                 rhs = rhs_wanted;
2098                 lhs = lhs_wanted;
2099                 break;
2100         }
2101         if ((rhs < 0) || (rhs > MAX_RHS)) {
2102                 internal_error(state, &dummy, "bad rhs count %d", rhs);
2103         }
2104         if ((lhs < 0) || (lhs > MAX_LHS)) {
2105                 internal_error(state, &dummy, "bad lhs count %d", lhs);
2106         }
2107         if ((misc < 0) || (misc > MAX_MISC)) {
2108                 internal_error(state, &dummy, "bad misc count %d", misc);
2109         }
2110         if ((targ < 0) || (targ > MAX_TARG)) {
2111                 internal_error(state, &dummy, "bad targs count %d", targ);
2112         }
2113
2114         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2115         extra_count = lhs + rhs + misc + targ;
2116         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2117
2118         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2119         ret = xcmalloc(size, "tripple");
2120         ret->op        = op;
2121         ret->lhs       = lhs;
2122         ret->rhs       = rhs;
2123         ret->misc      = misc;
2124         ret->targ      = targ;
2125         ret->type      = type;
2126         ret->next      = ret;
2127         ret->prev      = ret;
2128         ret->occurance = occurance;
2129         /* A simple sanity check */
2130         if ((ret->op != op) ||
2131                 (ret->lhs != lhs) ||
2132                 (ret->rhs != rhs) ||
2133                 (ret->misc != misc) ||
2134                 (ret->targ != targ) ||
2135                 (ret->type != type) ||
2136                 (ret->next != ret) ||
2137                 (ret->prev != ret) ||
2138                 (ret->occurance != occurance)) {
2139                 internal_error(state, ret, "huh?");
2140         }
2141         return ret;
2142 }
2143
2144 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2145 {
2146         struct triple *dup;
2147         int src_lhs, src_rhs, src_size;
2148         src_lhs = src->lhs;
2149         src_rhs = src->rhs;
2150         src_size = TRIPLE_SIZE(src);
2151         get_occurance(src->occurance);
2152         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2153                 src->occurance);
2154         memcpy(dup, src, sizeof(*src));
2155         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2156         return dup;
2157 }
2158
2159 static struct triple *copy_triple(struct compile_state *state, struct triple *src)
2160 {
2161         struct triple *copy;
2162         copy = dup_triple(state, src);
2163         copy->use = 0;
2164         copy->next = copy->prev = copy;
2165         return copy;
2166 }
2167
2168 static struct triple *new_triple(struct compile_state *state, 
2169         int op, struct type *type, int lhs, int rhs)
2170 {
2171         struct triple *ret;
2172         struct occurance *occurance;
2173         occurance = new_occurance(state);
2174         ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2175         return ret;
2176 }
2177
2178 static struct triple *build_triple(struct compile_state *state, 
2179         int op, struct type *type, struct triple *left, struct triple *right,
2180         struct occurance *occurance)
2181 {
2182         struct triple *ret;
2183         size_t count;
2184         ret = alloc_triple(state, op, type, -1, -1, occurance);
2185         count = TRIPLE_SIZE(ret);
2186         if (count > 0) {
2187                 ret->param[0] = left;
2188         }
2189         if (count > 1) {
2190                 ret->param[1] = right;
2191         }
2192         return ret;
2193 }
2194
2195 static struct triple *triple(struct compile_state *state, 
2196         int op, struct type *type, struct triple *left, struct triple *right)
2197 {
2198         struct triple *ret;
2199         size_t count;
2200         ret = new_triple(state, op, type, -1, -1);
2201         count = TRIPLE_SIZE(ret);
2202         if (count >= 1) {
2203                 ret->param[0] = left;
2204         }
2205         if (count >= 2) {
2206                 ret->param[1] = right;
2207         }
2208         return ret;
2209 }
2210
2211 static struct triple *branch(struct compile_state *state, 
2212         struct triple *targ, struct triple *test)
2213 {
2214         struct triple *ret;
2215         if (test) {
2216                 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2217                 RHS(ret, 0) = test;
2218         } else {
2219                 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2220         }
2221         TARG(ret, 0) = targ;
2222         /* record the branch target was used */
2223         if (!targ || (targ->op != OP_LABEL)) {
2224                 internal_error(state, 0, "branch not to label");
2225         }
2226         return ret;
2227 }
2228
2229 static int triple_is_label(struct compile_state *state, struct triple *ins);
2230 static int triple_is_call(struct compile_state *state, struct triple *ins);
2231 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2232 static void insert_triple(struct compile_state *state,
2233         struct triple *first, struct triple *ptr)
2234 {
2235         if (ptr) {
2236                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2237                         internal_error(state, ptr, "expression already used");
2238                 }
2239                 ptr->next       = first;
2240                 ptr->prev       = first->prev;
2241                 ptr->prev->next = ptr;
2242                 ptr->next->prev = ptr;
2243
2244                 if (triple_is_cbranch(state, ptr->prev) ||
2245                         triple_is_call(state, ptr->prev)) {
2246                         unuse_triple(first, ptr->prev);
2247                         use_triple(ptr, ptr->prev);
2248                 }
2249         }
2250 }
2251
2252 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2253 {
2254         /* This function is used to determine if u.block 
2255          * is utilized to store the current block number.
2256          */
2257         int stores_block;
2258         valid_ins(state, ins);
2259         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2260         return stores_block;
2261 }
2262
2263 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2264 static struct block *block_of_triple(struct compile_state *state, 
2265         struct triple *ins)
2266 {
2267         struct triple *first;
2268         if (!ins || ins == &unknown_triple) {
2269                 return 0;
2270         }
2271         first = state->first;
2272         while(ins != first && !triple_is_branch(state, ins->prev) &&
2273                 !triple_stores_block(state, ins)) 
2274         { 
2275                 if (ins == ins->prev) {
2276                         internal_error(state, ins, "ins == ins->prev?");
2277                 }
2278                 ins = ins->prev;
2279         }
2280         return triple_stores_block(state, ins)? ins->u.block: 0;
2281 }
2282
2283 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2284 static struct triple *pre_triple(struct compile_state *state,
2285         struct triple *base,
2286         int op, struct type *type, struct triple *left, struct triple *right)
2287 {
2288         struct block *block;
2289         struct triple *ret;
2290         int i;
2291         /* If I am an OP_PIECE jump to the real instruction */
2292         if (base->op == OP_PIECE) {
2293                 base = MISC(base, 0);
2294         }
2295         block = block_of_triple(state, base);
2296         get_occurance(base->occurance);
2297         ret = build_triple(state, op, type, left, right, base->occurance);
2298         generate_lhs_pieces(state, ret);
2299         if (triple_stores_block(state, ret)) {
2300                 ret->u.block = block;
2301         }
2302         insert_triple(state, base, ret);
2303         for(i = 0; i < ret->lhs; i++) {
2304                 struct triple *piece;
2305                 piece = LHS(ret, i);
2306                 insert_triple(state, base, piece);
2307                 use_triple(ret, piece);
2308                 use_triple(piece, ret);
2309         }
2310         if (block && (block->first == base)) {
2311                 block->first = ret;
2312         }
2313         return ret;
2314 }
2315
2316 static struct triple *post_triple(struct compile_state *state,
2317         struct triple *base,
2318         int op, struct type *type, struct triple *left, struct triple *right)
2319 {
2320         struct block *block;
2321         struct triple *ret, *next;
2322         int zlhs, i;
2323         /* If I am an OP_PIECE jump to the real instruction */
2324         if (base->op == OP_PIECE) {
2325                 base = MISC(base, 0);
2326         }
2327         /* If I have a left hand side skip over it */
2328         zlhs = base->lhs;
2329         if (zlhs) {
2330                 base = LHS(base, zlhs - 1);
2331         }
2332
2333         block = block_of_triple(state, base);
2334         get_occurance(base->occurance);
2335         ret = build_triple(state, op, type, left, right, base->occurance);
2336         generate_lhs_pieces(state, ret);
2337         if (triple_stores_block(state, ret)) {
2338                 ret->u.block = block;
2339         }
2340         next = base->next;
2341         insert_triple(state, next, ret);
2342         zlhs = ret->lhs;
2343         for(i = 0; i < zlhs; i++) {
2344                 struct triple *piece;
2345                 piece = LHS(ret, i);
2346                 insert_triple(state, next, piece);
2347                 use_triple(ret, piece);
2348                 use_triple(piece, ret);
2349         }
2350         if (block && (block->last == base)) {
2351                 block->last = ret;
2352                 if (zlhs) {
2353                         block->last = LHS(ret, zlhs - 1);
2354                 }
2355         }
2356         return ret;
2357 }
2358
2359 static struct type *reg_type(
2360         struct compile_state *state, struct type *type, int reg);
2361
2362 static void generate_lhs_piece(
2363         struct compile_state *state, struct triple *ins, int index)
2364 {
2365         struct type *piece_type;
2366         struct triple *piece;
2367         get_occurance(ins->occurance);
2368         piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2369
2370         if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2371                 piece_type = piece_type->left;
2372         }
2373 #if 0
2374 {
2375         static void name_of(FILE *fp, struct type *type);
2376         FILE * fp = state->errout;
2377         fprintf(fp, "piece_type(%d): ", index);
2378         name_of(fp, piece_type);
2379         fprintf(fp, "\n");
2380 }
2381 #endif
2382         piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2383         piece->u.cval  = index;
2384         LHS(ins, piece->u.cval) = piece;
2385         MISC(piece, 0) = ins;
2386 }
2387
2388 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2389 {
2390         int i, zlhs;
2391         zlhs = ins->lhs;
2392         for(i = 0; i < zlhs; i++) {
2393                 generate_lhs_piece(state, ins, i);
2394         }
2395 }
2396
2397 static struct triple *label(struct compile_state *state)
2398 {
2399         /* Labels don't get a type */
2400         struct triple *result;
2401         result = triple(state, OP_LABEL, &void_type, 0, 0);
2402         return result;
2403 }
2404
2405 static struct triple *mkprog(struct compile_state *state, ...)
2406 {
2407         struct triple *prog, *head, *arg;
2408         va_list args;
2409         int i;
2410
2411         head = label(state);
2412         prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2413         RHS(prog, 0) = head;
2414         va_start(args, state);
2415         i = 0;
2416         while((arg = va_arg(args, struct triple *)) != 0) {
2417                 if (++i >= 100) {
2418                         internal_error(state, 0, "too many arguments to mkprog");
2419                 }
2420                 flatten(state, head, arg);
2421         }
2422         va_end(args);
2423         prog->type = head->prev->type;
2424         return prog;
2425 }
2426 static void name_of(FILE *fp, struct type *type);
2427 static void display_triple(FILE *fp, struct triple *ins)
2428 {
2429         struct occurance *ptr;
2430         const char *reg;
2431         char pre, post, vol;
2432         pre = post = vol = ' ';
2433         if (ins) {
2434                 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2435                         pre = '^';
2436                 }
2437                 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2438                         post = ',';
2439                 }
2440                 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2441                         vol = 'v';
2442                 }
2443                 reg = arch_reg_str(ID_REG(ins->id));
2444         }
2445         if (ins == 0) {
2446                 fprintf(fp, "(%p) <nothing> ", ins);
2447         }
2448         else if (ins->op == OP_INTCONST) {
2449                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx>         ",
2450                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2451                         (unsigned long)(ins->u.cval));
2452         }
2453         else if (ins->op == OP_ADDRCONST) {
2454                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2455                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2456                         MISC(ins, 0), (unsigned long)(ins->u.cval));
2457         }
2458         else if (ins->op == OP_INDEX) {
2459                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2460                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2461                         RHS(ins, 0), (unsigned long)(ins->u.cval));
2462         }
2463         else if (ins->op == OP_PIECE) {
2464                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2465                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op), 
2466                         MISC(ins, 0), (unsigned long)(ins->u.cval));
2467         }
2468         else {
2469                 int i, count;
2470                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s", 
2471                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2472                 if (table_ops[ins->op].flags & BITFIELD) {
2473                         fprintf(fp, " <%2d-%2d:%2d>", 
2474                                 ins->u.bitfield.offset,
2475                                 ins->u.bitfield.offset + ins->u.bitfield.size,
2476                                 ins->u.bitfield.size);
2477                 }
2478                 count = TRIPLE_SIZE(ins);
2479                 for(i = 0; i < count; i++) {
2480                         fprintf(fp, " %-10p", ins->param[i]);
2481                 }
2482                 for(; i < 2; i++) {
2483                         fprintf(fp, "           ");
2484                 }
2485         }
2486         if (ins) {
2487                 struct triple_set *user;
2488 #if DEBUG_DISPLAY_TYPES
2489                 fprintf(fp, " <");
2490                 name_of(fp, ins->type);
2491                 fprintf(fp, "> ");
2492 #endif
2493 #if DEBUG_DISPLAY_USES
2494                 fprintf(fp, " [");
2495                 for(user = ins->use; user; user = user->next) {
2496                         fprintf(fp, " %-10p", user->member);
2497                 }
2498                 fprintf(fp, " ]");
2499 #endif
2500                 fprintf(fp, " @");
2501                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2502                         fprintf(fp, " %s,%s:%d.%d",
2503                                 ptr->function, 
2504                                 ptr->filename,
2505                                 ptr->line, 
2506                                 ptr->col);
2507                 }
2508                 if (ins->op == OP_ASM) {
2509                         fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2510                 }
2511         }
2512         fprintf(fp, "\n");
2513         fflush(fp);
2514 }
2515
2516 static int equiv_types(struct type *left, struct type *right);
2517 static void display_triple_changes(
2518         FILE *fp, const struct triple *new, const struct triple *orig)
2519 {
2520
2521         int new_count, orig_count;
2522         new_count = TRIPLE_SIZE(new);
2523         orig_count = TRIPLE_SIZE(orig);
2524         if ((new->op != orig->op) ||
2525                 (new_count != orig_count) ||
2526                 (memcmp(orig->param, new->param,        
2527                         orig_count * sizeof(orig->param[0])) != 0) ||
2528                 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0)) 
2529         {
2530                 struct occurance *ptr;
2531                 int i, min_count, indent;
2532                 fprintf(fp, "(%p %p)", new, orig);
2533                 if (orig->op == new->op) {
2534                         fprintf(fp, " %-11s", tops(orig->op));
2535                 } else {
2536                         fprintf(fp, " [%-10s %-10s]", 
2537                                 tops(new->op), tops(orig->op));
2538                 }
2539                 min_count = new_count;
2540                 if (min_count > orig_count) {
2541                         min_count = orig_count;
2542                 }
2543                 for(indent = i = 0; i < min_count; i++) {
2544                         if (orig->param[i] == new->param[i]) {
2545                                 fprintf(fp, " %-11p", 
2546                                         orig->param[i]);
2547                                 indent += 12;
2548                         } else {
2549                                 fprintf(fp, " [%-10p %-10p]",
2550                                         new->param[i], 
2551                                         orig->param[i]);
2552                                 indent += 24;
2553                         }
2554                 }
2555                 for(; i < orig_count; i++) {
2556                         fprintf(fp, " [%-9p]", orig->param[i]);
2557                         indent += 12;
2558                 }
2559                 for(; i < new_count; i++) {
2560                         fprintf(fp, " [%-9p]", new->param[i]);
2561                         indent += 12;
2562                 }
2563                 if ((new->op == OP_INTCONST)||
2564                         (new->op == OP_ADDRCONST)) {
2565                         fprintf(fp, " <0x%08lx>", 
2566                                 (unsigned long)(new->u.cval));
2567                         indent += 13;
2568                 }
2569                 for(;indent < 36; indent++) {
2570                         putc(' ', fp);
2571                 }
2572
2573 #if DEBUG_DISPLAY_TYPES
2574                 fprintf(fp, " <");
2575                 name_of(fp, new->type);
2576                 if (!equiv_types(new->type, orig->type)) {
2577                         fprintf(fp, " -- ");
2578                         name_of(fp, orig->type);
2579                 }
2580                 fprintf(fp, "> ");
2581 #endif
2582
2583                 fprintf(fp, " @");
2584                 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2585                         fprintf(fp, " %s,%s:%d.%d",
2586                                 ptr->function, 
2587                                 ptr->filename,
2588                                 ptr->line, 
2589                                 ptr->col);
2590                         
2591                 }
2592                 fprintf(fp, "\n");
2593                 fflush(fp);
2594         }
2595 }
2596
2597 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2598 {
2599         /* Does the triple have no side effects.
2600          * I.e. Rexecuting the triple with the same arguments 
2601          * gives the same value.
2602          */
2603         unsigned pure;
2604         valid_ins(state, ins);
2605         pure = PURE_BITS(table_ops[ins->op].flags);
2606         if ((pure != PURE) && (pure != IMPURE)) {
2607                 internal_error(state, 0, "Purity of %s not known",
2608                         tops(ins->op));
2609         }
2610         return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2611 }
2612
2613 static int triple_is_branch_type(struct compile_state *state, 
2614         struct triple *ins, unsigned type)
2615 {
2616         /* Is this one of the passed branch types? */
2617         valid_ins(state, ins);
2618         return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2619 }
2620
2621 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2622 {
2623         /* Is this triple a branch instruction? */
2624         valid_ins(state, ins);
2625         return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2626 }
2627
2628 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2629 {
2630         /* Is this triple a conditional branch instruction? */
2631         return triple_is_branch_type(state, ins, CBRANCH);
2632 }
2633
2634 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2635 {
2636         /* Is this triple a unconditional branch instruction? */
2637         unsigned type;
2638         valid_ins(state, ins);
2639         type = BRANCH_BITS(table_ops[ins->op].flags);
2640         return (type != 0) && (type != CBRANCH);
2641 }
2642
2643 static int triple_is_call(struct compile_state *state, struct triple *ins)
2644 {
2645         /* Is this triple a call instruction? */
2646         return triple_is_branch_type(state, ins, CALLBRANCH);
2647 }
2648
2649 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2650 {
2651         /* Is this triple a return instruction? */
2652         return triple_is_branch_type(state, ins, RETBRANCH);
2653 }
2654  
2655 #if DEBUG_ROMCC_WARNING
2656 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2657 {
2658         /* Is this triple an unconditional branch and not a call or a
2659          * return? */
2660         return triple_is_branch_type(state, ins, UBRANCH);
2661 }
2662 #endif
2663
2664 static int triple_is_end(struct compile_state *state, struct triple *ins)
2665 {
2666         return triple_is_branch_type(state, ins, ENDBRANCH);
2667 }
2668
2669 static int triple_is_label(struct compile_state *state, struct triple *ins)
2670 {
2671         valid_ins(state, ins);
2672         return (ins->op == OP_LABEL);
2673 }
2674
2675 static struct triple *triple_to_block_start(
2676         struct compile_state *state, struct triple *start)
2677 {
2678         while(!triple_is_branch(state, start->prev) &&
2679                 (!triple_is_label(state, start) || !start->use)) {
2680                 start = start->prev;
2681         }
2682         return start;
2683 }
2684
2685 static int triple_is_def(struct compile_state *state, struct triple *ins)
2686 {
2687         /* This function is used to determine which triples need
2688          * a register.
2689          */
2690         int is_def;
2691         valid_ins(state, ins);
2692         is_def = (table_ops[ins->op].flags & DEF) == DEF;
2693         if (ins->lhs >= 1) {
2694                 is_def = 0;
2695         }
2696         return is_def;
2697 }
2698
2699 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2700 {
2701         int is_structural;
2702         valid_ins(state, ins);
2703         is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2704         return is_structural;
2705 }
2706
2707 static int triple_is_part(struct compile_state *state, struct triple *ins)
2708 {
2709         int is_part;
2710         valid_ins(state, ins);
2711         is_part = (table_ops[ins->op].flags & PART) == PART;
2712         return is_part;
2713 }
2714
2715 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2716 {
2717         return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2718 }
2719
2720 static struct triple **triple_iter(struct compile_state *state,
2721         size_t count, struct triple **vector,
2722         struct triple *ins, struct triple **last)
2723 {
2724         struct triple **ret;
2725         ret = 0;
2726         if (count) {
2727                 if (!last) {
2728                         ret = vector;
2729                 }
2730                 else if ((last >= vector) && (last < (vector + count - 1))) {
2731                         ret = last + 1;
2732                 }
2733         }
2734         return ret;
2735         
2736 }
2737
2738 static struct triple **triple_lhs(struct compile_state *state,
2739         struct triple *ins, struct triple **last)
2740 {
2741         return triple_iter(state, ins->lhs, &LHS(ins,0), 
2742                 ins, last);
2743 }
2744
2745 static struct triple **triple_rhs(struct compile_state *state,
2746         struct triple *ins, struct triple **last)
2747 {
2748         return triple_iter(state, ins->rhs, &RHS(ins,0), 
2749                 ins, last);
2750 }
2751
2752 static struct triple **triple_misc(struct compile_state *state,
2753         struct triple *ins, struct triple **last)
2754 {
2755         return triple_iter(state, ins->misc, &MISC(ins,0), 
2756                 ins, last);
2757 }
2758
2759 static struct triple **do_triple_targ(struct compile_state *state,
2760         struct triple *ins, struct triple **last, int call_edges, int next_edges)
2761 {
2762         size_t count;
2763         struct triple **ret, **vector;
2764         int next_is_targ;
2765         ret = 0;
2766         count = ins->targ;
2767         next_is_targ = 0;
2768         if (triple_is_cbranch(state, ins)) {
2769                 next_is_targ = 1;
2770         }
2771         if (!call_edges && triple_is_call(state, ins)) {
2772                 count = 0;
2773         }
2774         if (next_edges && triple_is_call(state, ins)) {
2775                 next_is_targ = 1;
2776         }
2777         vector = &TARG(ins, 0);
2778         if (!ret && next_is_targ) {
2779                 if (!last) {
2780                         ret = &ins->next;
2781                 } else if (last == &ins->next) {
2782                         last = 0;
2783                 }
2784         }
2785         if (!ret && count) {
2786                 if (!last) {
2787                         ret = vector;
2788                 }
2789                 else if ((last >= vector) && (last < (vector + count - 1))) {
2790                         ret = last + 1;
2791                 }
2792                 else if (last == vector + count - 1) {
2793                         last = 0;
2794                 }
2795         }
2796         if (!ret && triple_is_ret(state, ins) && call_edges) {
2797                 struct triple_set *use;
2798                 for(use = ins->use; use; use = use->next) {
2799                         if (!triple_is_call(state, use->member)) {
2800                                 continue;
2801                         }
2802                         if (!last) {
2803                                 ret = &use->member->next;
2804                                 break;
2805                         }
2806                         else if (last == &use->member->next) {
2807                                 last = 0;
2808                         }
2809                 }
2810         }
2811         return ret;
2812 }
2813
2814 static struct triple **triple_targ(struct compile_state *state,
2815         struct triple *ins, struct triple **last)
2816 {
2817         return do_triple_targ(state, ins, last, 1, 1);
2818 }
2819
2820 static struct triple **triple_edge_targ(struct compile_state *state,
2821         struct triple *ins, struct triple **last)
2822 {
2823         return do_triple_targ(state, ins, last, 
2824                 state->functions_joined, !state->functions_joined);
2825 }
2826
2827 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2828 {
2829         struct triple *next;
2830         int lhs, i;
2831         lhs = ins->lhs;
2832         next = ins->next;
2833         for(i = 0; i < lhs; i++) {
2834                 struct triple *piece;
2835                 piece = LHS(ins, i);
2836                 if (next != piece) {
2837                         internal_error(state, ins, "malformed lhs on %s",
2838                                 tops(ins->op));
2839                 }
2840                 if (next->op != OP_PIECE) {
2841                         internal_error(state, ins, "bad lhs op %s at %d on %s",
2842                                 tops(next->op), i, tops(ins->op));
2843                 }
2844                 if (next->u.cval != i) {
2845                         internal_error(state, ins, "bad u.cval of %d %d expected",
2846                                 next->u.cval, i);
2847                 }
2848                 next = next->next;
2849         }
2850         return next;
2851 }
2852
2853 /* Function piece accessor functions */
2854 static struct triple *do_farg(struct compile_state *state, 
2855         struct triple *func, unsigned index)
2856 {
2857         struct type *ftype;
2858         struct triple *first, *arg;
2859         unsigned i;
2860
2861         ftype = func->type;
2862         if((index < 0) || (index >= (ftype->elements + 2))) {
2863                 internal_error(state, func, "bad argument index: %d", index);
2864         }
2865         first = RHS(func, 0);
2866         arg = first->next;
2867         for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2868                 /* do nothing */
2869         }
2870         if (arg->op != OP_ADECL) {
2871                 internal_error(state, 0, "arg not adecl?");
2872         }
2873         return arg;
2874 }
2875 static struct triple *fresult(struct compile_state *state, struct triple *func)
2876 {
2877         return do_farg(state, func, 0);
2878 }
2879 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2880 {
2881         return do_farg(state, func, 1);
2882 }
2883 static struct triple *farg(struct compile_state *state, 
2884         struct triple *func, unsigned index)
2885 {
2886         return do_farg(state, func, index + 2);
2887 }
2888
2889
2890 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2891 {
2892         struct triple *first, *ins;
2893         fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2894         first = ins = RHS(func, 0);
2895         do {
2896                 if (triple_is_label(state, ins) && ins->use) {
2897                         fprintf(fp, "%p:\n", ins);
2898                 }
2899                 display_triple(fp, ins);
2900
2901                 if (triple_is_branch(state, ins)) {
2902                         fprintf(fp, "\n");
2903                 }
2904                 if (ins->next->prev != ins) {
2905                         internal_error(state, ins->next, "bad prev");
2906                 }
2907                 ins = ins->next;
2908         } while(ins != first);
2909 }
2910
2911 static void verify_use(struct compile_state *state,
2912         struct triple *user, struct triple *used)
2913 {
2914         int size, i;
2915         size = TRIPLE_SIZE(user);
2916         for(i = 0; i < size; i++) {
2917                 if (user->param[i] == used) {
2918                         break;
2919                 }
2920         }
2921         if (triple_is_branch(state, user)) {
2922                 if (user->next == used) {
2923                         i = -1;
2924                 }
2925         }
2926         if (i == size) {
2927                 internal_error(state, user, "%s(%p) does not use %s(%p)",
2928                         tops(user->op), user, tops(used->op), used);
2929         }
2930 }
2931
2932 static int find_rhs_use(struct compile_state *state, 
2933         struct triple *user, struct triple *used)
2934 {
2935         struct triple **param;
2936         int size, i;
2937         verify_use(state, user, used);
2938
2939 #if DEBUG_ROMCC_WARNINGS
2940 #warning "AUDIT ME ->rhs"
2941 #endif
2942         size = user->rhs;
2943         param = &RHS(user, 0);
2944         for(i = 0; i < size; i++) {
2945                 if (param[i] == used) {
2946                         return i;
2947                 }
2948         }
2949         return -1;
2950 }
2951
2952 static void free_triple(struct compile_state *state, struct triple *ptr)
2953 {
2954         size_t size;
2955         size = sizeof(*ptr) - sizeof(ptr->param) +
2956                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2957         ptr->prev->next = ptr->next;
2958         ptr->next->prev = ptr->prev;
2959         if (ptr->use) {
2960                 internal_error(state, ptr, "ptr->use != 0");
2961         }
2962         put_occurance(ptr->occurance);
2963         memset(ptr, -1, size);
2964         xfree(ptr);
2965 }
2966
2967 static void release_triple(struct compile_state *state, struct triple *ptr)
2968 {
2969         struct triple_set *set, *next;
2970         struct triple **expr;
2971         struct block *block;
2972         if (ptr == &unknown_triple) {
2973                 return;
2974         }
2975         valid_ins(state, ptr);
2976         /* Make certain the we are not the first or last element of a block */
2977         block = block_of_triple(state, ptr);
2978         if (block) {
2979                 if ((block->last == ptr) && (block->first == ptr)) {
2980                         block->last = block->first = 0;
2981                 }
2982                 else if (block->last == ptr) {
2983                         block->last = ptr->prev;
2984                 }
2985                 else if (block->first == ptr) {
2986                         block->first = ptr->next;
2987                 }
2988         }
2989         /* Remove ptr from use chains where it is the user */
2990         expr = triple_rhs(state, ptr, 0);
2991         for(; expr; expr = triple_rhs(state, ptr, expr)) {
2992                 if (*expr) {
2993                         unuse_triple(*expr, ptr);
2994                 }
2995         }
2996         expr = triple_lhs(state, ptr, 0);
2997         for(; expr; expr = triple_lhs(state, ptr, expr)) {
2998                 if (*expr) {
2999                         unuse_triple(*expr, ptr);
3000                 }
3001         }
3002         expr = triple_misc(state, ptr, 0);
3003         for(; expr; expr = triple_misc(state, ptr, expr)) {
3004                 if (*expr) {
3005                         unuse_triple(*expr, ptr);
3006                 }
3007         }
3008         expr = triple_targ(state, ptr, 0);
3009         for(; expr; expr = triple_targ(state, ptr, expr)) {
3010                 if (*expr){
3011                         unuse_triple(*expr, ptr);
3012                 }
3013         }
3014         /* Reomve ptr from use chains where it is used */
3015         for(set = ptr->use; set; set = next) {
3016                 next = set->next;
3017                 valid_ins(state, set->member);
3018                 expr = triple_rhs(state, set->member, 0);
3019                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3020                         if (*expr == ptr) {
3021                                 *expr = &unknown_triple;
3022                         }
3023                 }
3024                 expr = triple_lhs(state, set->member, 0);
3025                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3026                         if (*expr == ptr) {
3027                                 *expr = &unknown_triple;
3028                         }
3029                 }
3030                 expr = triple_misc(state, set->member, 0);
3031                 for(; expr; expr = triple_misc(state, set->member, expr)) {
3032                         if (*expr == ptr) {
3033                                 *expr = &unknown_triple;
3034                         }
3035                 }
3036                 expr = triple_targ(state, set->member, 0);
3037                 for(; expr; expr = triple_targ(state, set->member, expr)) {
3038                         if (*expr == ptr) {
3039                                 *expr = &unknown_triple;
3040                         }
3041                 }
3042                 unuse_triple(ptr, set->member);
3043         }
3044         free_triple(state, ptr);
3045 }
3046
3047 static void print_triples(struct compile_state *state);
3048 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3049
3050 #define TOK_UNKNOWN       0
3051 #define TOK_SPACE         1
3052 #define TOK_SEMI          2
3053 #define TOK_LBRACE        3
3054 #define TOK_RBRACE        4
3055 #define TOK_COMMA         5
3056 #define TOK_EQ            6
3057 #define TOK_COLON         7
3058 #define TOK_LBRACKET      8
3059 #define TOK_RBRACKET      9
3060 #define TOK_LPAREN        10
3061 #define TOK_RPAREN        11
3062 #define TOK_STAR          12
3063 #define TOK_DOTS          13
3064 #define TOK_MORE          14
3065 #define TOK_LESS          15
3066 #define TOK_TIMESEQ       16
3067 #define TOK_DIVEQ         17
3068 #define TOK_MODEQ         18
3069 #define TOK_PLUSEQ        19
3070 #define TOK_MINUSEQ       20
3071 #define TOK_SLEQ          21
3072 #define TOK_SREQ          22
3073 #define TOK_ANDEQ         23
3074 #define TOK_XOREQ         24
3075 #define TOK_OREQ          25
3076 #define TOK_EQEQ          26
3077 #define TOK_NOTEQ         27
3078 #define TOK_QUEST         28
3079 #define TOK_LOGOR         29
3080 #define TOK_LOGAND        30
3081 #define TOK_OR            31
3082 #define TOK_AND           32
3083 #define TOK_XOR           33
3084 #define TOK_LESSEQ        34
3085 #define TOK_MOREEQ        35
3086 #define TOK_SL            36
3087 #define TOK_SR            37
3088 #define TOK_PLUS          38
3089 #define TOK_MINUS         39
3090 #define TOK_DIV           40
3091 #define TOK_MOD           41
3092 #define TOK_PLUSPLUS      42
3093 #define TOK_MINUSMINUS    43
3094 #define TOK_BANG          44
3095 #define TOK_ARROW         45
3096 #define TOK_DOT           46
3097 #define TOK_TILDE         47
3098 #define TOK_LIT_STRING    48
3099 #define TOK_LIT_CHAR      49
3100 #define TOK_LIT_INT       50
3101 #define TOK_LIT_FLOAT     51
3102 #define TOK_MACRO         52
3103 #define TOK_CONCATENATE   53
3104
3105 #define TOK_IDENT         54
3106 #define TOK_STRUCT_NAME   55
3107 #define TOK_ENUM_CONST    56
3108 #define TOK_TYPE_NAME     57
3109
3110 #define TOK_AUTO          58
3111 #define TOK_BREAK         59
3112 #define TOK_CASE          60
3113 #define TOK_CHAR          61
3114 #define TOK_CONST         62
3115 #define TOK_CONTINUE      63
3116 #define TOK_DEFAULT       64
3117 #define TOK_DO            65
3118 #define TOK_DOUBLE        66
3119 #define TOK_ELSE          67
3120 #define TOK_ENUM          68
3121 #define TOK_EXTERN        69
3122 #define TOK_FLOAT         70
3123 #define TOK_FOR           71
3124 #define TOK_GOTO          72
3125 #define TOK_IF            73
3126 #define TOK_INLINE        74
3127 #define TOK_INT           75
3128 #define TOK_LONG          76
3129 #define TOK_REGISTER      77
3130 #define TOK_RESTRICT      78
3131 #define TOK_RETURN        79
3132 #define TOK_SHORT         80
3133 #define TOK_SIGNED        81
3134 #define TOK_SIZEOF        82
3135 #define TOK_STATIC        83
3136 #define TOK_STRUCT        84
3137 #define TOK_SWITCH        85
3138 #define TOK_TYPEDEF       86
3139 #define TOK_UNION         87
3140 #define TOK_UNSIGNED      88
3141 #define TOK_VOID          89
3142 #define TOK_VOLATILE      90
3143 #define TOK_WHILE         91
3144 #define TOK_ASM           92
3145 #define TOK_ATTRIBUTE     93
3146 #define TOK_ALIGNOF       94
3147 #define TOK_FIRST_KEYWORD TOK_AUTO
3148 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
3149
3150 #define TOK_MDEFINE       100
3151 #define TOK_MDEFINED      101
3152 #define TOK_MUNDEF        102
3153 #define TOK_MINCLUDE      103
3154 #define TOK_MLINE         104
3155 #define TOK_MERROR        105
3156 #define TOK_MWARNING      106
3157 #define TOK_MPRAGMA       107
3158 #define TOK_MIFDEF        108
3159 #define TOK_MIFNDEF       109
3160 #define TOK_MELIF         110
3161 #define TOK_MENDIF        111
3162
3163 #define TOK_FIRST_MACRO   TOK_MDEFINE
3164 #define TOK_LAST_MACRO    TOK_MENDIF
3165          
3166 #define TOK_MIF           112
3167 #define TOK_MELSE         113
3168 #define TOK_MIDENT        114
3169
3170 #define TOK_EOL           115
3171 #define TOK_EOF           116
3172
3173 static const char *tokens[] = {
3174 [TOK_UNKNOWN     ] = ":unknown:",
3175 [TOK_SPACE       ] = ":space:",
3176 [TOK_SEMI        ] = ";",
3177 [TOK_LBRACE      ] = "{",
3178 [TOK_RBRACE      ] = "}",
3179 [TOK_COMMA       ] = ",",
3180 [TOK_EQ          ] = "=",
3181 [TOK_COLON       ] = ":",
3182 [TOK_LBRACKET    ] = "[",
3183 [TOK_RBRACKET    ] = "]",
3184 [TOK_LPAREN      ] = "(",
3185 [TOK_RPAREN      ] = ")",
3186 [TOK_STAR        ] = "*",
3187 [TOK_DOTS        ] = "...",
3188 [TOK_MORE        ] = ">",
3189 [TOK_LESS        ] = "<",
3190 [TOK_TIMESEQ     ] = "*=",
3191 [TOK_DIVEQ       ] = "/=",
3192 [TOK_MODEQ       ] = "%=",
3193 [TOK_PLUSEQ      ] = "+=",
3194 [TOK_MINUSEQ     ] = "-=",
3195 [TOK_SLEQ        ] = "<<=",
3196 [TOK_SREQ        ] = ">>=",
3197 [TOK_ANDEQ       ] = "&=",
3198 [TOK_XOREQ       ] = "^=",
3199 [TOK_OREQ        ] = "|=",
3200 [TOK_EQEQ        ] = "==",
3201 [TOK_NOTEQ       ] = "!=",
3202 [TOK_QUEST       ] = "?",
3203 [TOK_LOGOR       ] = "||",
3204 [TOK_LOGAND      ] = "&&",
3205 [TOK_OR          ] = "|",
3206 [TOK_AND         ] = "&",
3207 [TOK_XOR         ] = "^",
3208 [TOK_LESSEQ      ] = "<=",
3209 [TOK_MOREEQ      ] = ">=",
3210 [TOK_SL          ] = "<<",
3211 [TOK_SR          ] = ">>",
3212 [TOK_PLUS        ] = "+",
3213 [TOK_MINUS       ] = "-",
3214 [TOK_DIV         ] = "/",
3215 [TOK_MOD         ] = "%",
3216 [TOK_PLUSPLUS    ] = "++",
3217 [TOK_MINUSMINUS  ] = "--",
3218 [TOK_BANG        ] = "!",
3219 [TOK_ARROW       ] = "->",
3220 [TOK_DOT         ] = ".",
3221 [TOK_TILDE       ] = "~",
3222 [TOK_LIT_STRING  ] = ":string:",
3223 [TOK_IDENT       ] = ":ident:",
3224 [TOK_TYPE_NAME   ] = ":typename:",
3225 [TOK_LIT_CHAR    ] = ":char:",
3226 [TOK_LIT_INT     ] = ":integer:",
3227 [TOK_LIT_FLOAT   ] = ":float:",
3228 [TOK_MACRO       ] = "#",
3229 [TOK_CONCATENATE ] = "##",
3230
3231 [TOK_AUTO        ] = "auto",
3232 [TOK_BREAK       ] = "break",
3233 [TOK_CASE        ] = "case",
3234 [TOK_CHAR        ] = "char",
3235 [TOK_CONST       ] = "const",
3236 [TOK_CONTINUE    ] = "continue",
3237 [TOK_DEFAULT     ] = "default",
3238 [TOK_DO          ] = "do",
3239 [TOK_DOUBLE      ] = "double",
3240 [TOK_ELSE        ] = "else",
3241 [TOK_ENUM        ] = "enum",
3242 [TOK_EXTERN      ] = "extern",
3243 [TOK_FLOAT       ] = "float",
3244 [TOK_FOR         ] = "for",
3245 [TOK_GOTO        ] = "goto",
3246 [TOK_IF          ] = "if",
3247 [TOK_INLINE      ] = "inline",
3248 [TOK_INT         ] = "int",
3249 [TOK_LONG        ] = "long",
3250 [TOK_REGISTER    ] = "register",
3251 [TOK_RESTRICT    ] = "restrict",
3252 [TOK_RETURN      ] = "return",
3253 [TOK_SHORT       ] = "short",
3254 [TOK_SIGNED      ] = "signed",
3255 [TOK_SIZEOF      ] = "sizeof",
3256 [TOK_STATIC      ] = "static",
3257 [TOK_STRUCT      ] = "struct",
3258 [TOK_SWITCH      ] = "switch",
3259 [TOK_TYPEDEF     ] = "typedef",
3260 [TOK_UNION       ] = "union",
3261 [TOK_UNSIGNED    ] = "unsigned",
3262 [TOK_VOID        ] = "void",
3263 [TOK_VOLATILE    ] = "volatile",
3264 [TOK_WHILE       ] = "while",
3265 [TOK_ASM         ] = "asm",
3266 [TOK_ATTRIBUTE   ] = "__attribute__",
3267 [TOK_ALIGNOF     ] = "__alignof__",
3268
3269 [TOK_MDEFINE     ] = "#define",
3270 [TOK_MDEFINED    ] = "#defined",
3271 [TOK_MUNDEF      ] = "#undef",
3272 [TOK_MINCLUDE    ] = "#include",
3273 [TOK_MLINE       ] = "#line",
3274 [TOK_MERROR      ] = "#error",
3275 [TOK_MWARNING    ] = "#warning",
3276 [TOK_MPRAGMA     ] = "#pragma",
3277 [TOK_MIFDEF      ] = "#ifdef",
3278 [TOK_MIFNDEF     ] = "#ifndef",
3279 [TOK_MELIF       ] = "#elif",
3280 [TOK_MENDIF      ] = "#endif",
3281
3282 [TOK_MIF         ] = "#if",
3283 [TOK_MELSE       ] = "#else",
3284 [TOK_MIDENT      ] = "#:ident:",
3285 [TOK_EOL         ] = "EOL", 
3286 [TOK_EOF         ] = "EOF",
3287 };
3288
3289 static unsigned int hash(const char *str, int str_len)
3290 {
3291         unsigned int hash;
3292         const char *end;
3293         end = str + str_len;
3294         hash = 0;
3295         for(; str < end; str++) {
3296                 hash = (hash *263) + *str;
3297         }
3298         hash = hash & (HASH_TABLE_SIZE -1);
3299         return hash;
3300 }
3301
3302 static struct hash_entry *lookup(
3303         struct compile_state *state, const char *name, int name_len)
3304 {
3305         struct hash_entry *entry;
3306         unsigned int index;
3307         index = hash(name, name_len);
3308         entry = state->hash_table[index];
3309         while(entry && 
3310                 ((entry->name_len != name_len) ||
3311                         (memcmp(entry->name, name, name_len) != 0))) {
3312                 entry = entry->next;
3313         }
3314         if (!entry) {
3315                 char *new_name;
3316                 /* Get a private copy of the name */
3317                 new_name = xmalloc(name_len + 1, "hash_name");
3318                 memcpy(new_name, name, name_len);
3319                 new_name[name_len] = '\0';
3320
3321                 /* Create a new hash entry */
3322                 entry = xcmalloc(sizeof(*entry), "hash_entry");
3323                 entry->next = state->hash_table[index];
3324                 entry->name = new_name;
3325                 entry->name_len = name_len;
3326
3327                 /* Place the new entry in the hash table */
3328                 state->hash_table[index] = entry;
3329         }
3330         return entry;
3331 }
3332
3333 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3334 {
3335         struct hash_entry *entry;
3336         entry = tk->ident;
3337         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3338                 (entry->tok == TOK_ENUM_CONST) ||
3339                 ((entry->tok >= TOK_FIRST_KEYWORD) && 
3340                         (entry->tok <= TOK_LAST_KEYWORD)))) {
3341                 tk->tok = entry->tok;
3342         }
3343 }
3344
3345 static void ident_to_macro(struct compile_state *state, struct token *tk)
3346 {
3347         struct hash_entry *entry;
3348         entry = tk->ident;
3349         if (!entry)
3350                 return;
3351         if ((entry->tok >= TOK_FIRST_MACRO) && (entry->tok <= TOK_LAST_MACRO)) {
3352                 tk->tok = entry->tok;
3353         }
3354         else if (entry->tok == TOK_IF) {
3355                 tk->tok = TOK_MIF;
3356         }
3357         else if (entry->tok == TOK_ELSE) {
3358                 tk->tok = TOK_MELSE;
3359         }
3360         else {
3361                 tk->tok = TOK_MIDENT;
3362         }
3363 }
3364
3365 static void hash_keyword(
3366         struct compile_state *state, const char *keyword, int tok)
3367 {
3368         struct hash_entry *entry;
3369         entry = lookup(state, keyword, strlen(keyword));
3370         if (entry && entry->tok != TOK_UNKNOWN) {
3371                 die("keyword %s already hashed", keyword);
3372         }
3373         entry->tok  = tok;
3374 }
3375
3376 static void romcc_symbol(
3377         struct compile_state *state, struct hash_entry *ident,
3378         struct symbol **chain, struct triple *def, struct type *type, int depth)
3379 {
3380         struct symbol *sym;
3381         if (*chain && ((*chain)->scope_depth >= depth)) {
3382                 error(state, 0, "%s already defined", ident->name);
3383         }
3384         sym = xcmalloc(sizeof(*sym), "symbol");
3385         sym->ident = ident;
3386         sym->def   = def;
3387         sym->type  = type;
3388         sym->scope_depth = depth;
3389         sym->next = *chain;
3390         *chain    = sym;
3391 }
3392
3393 static void symbol(
3394         struct compile_state *state, struct hash_entry *ident,
3395         struct symbol **chain, struct triple *def, struct type *type)
3396 {
3397         romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3398 }
3399
3400 static void var_symbol(struct compile_state *state, 
3401         struct hash_entry *ident, struct triple *def)
3402 {
3403         if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3404                 internal_error(state, 0, "bad var type");
3405         }
3406         symbol(state, ident, &ident->sym_ident, def, def->type);
3407 }
3408
3409 static void label_symbol(struct compile_state *state, 
3410         struct hash_entry *ident, struct triple *label, int depth)
3411 {
3412         romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3413 }
3414
3415 static void start_scope(struct compile_state *state)
3416 {
3417         state->scope_depth++;
3418 }
3419
3420 static void end_scope_syms(struct compile_state *state,
3421         struct symbol **chain, int depth)
3422 {
3423         struct symbol *sym, *next;
3424         sym = *chain;
3425         while(sym && (sym->scope_depth == depth)) {
3426                 next = sym->next;
3427                 xfree(sym);
3428                 sym = next;
3429         }
3430         *chain = sym;
3431 }
3432
3433 static void end_scope(struct compile_state *state)
3434 {
3435         int i;
3436         int depth;
3437         /* Walk through the hash table and remove all symbols
3438          * in the current scope. 
3439          */
3440         depth = state->scope_depth;
3441         for(i = 0; i < HASH_TABLE_SIZE; i++) {
3442                 struct hash_entry *entry;
3443                 entry = state->hash_table[i];
3444                 while(entry) {
3445                         end_scope_syms(state, &entry->sym_label, depth);
3446                         end_scope_syms(state, &entry->sym_tag,   depth);
3447                         end_scope_syms(state, &entry->sym_ident, depth);
3448                         entry = entry->next;
3449                 }
3450         }
3451         state->scope_depth = depth - 1;
3452 }
3453
3454 static void register_keywords(struct compile_state *state)
3455 {
3456         hash_keyword(state, "auto",          TOK_AUTO);
3457         hash_keyword(state, "break",         TOK_BREAK);
3458         hash_keyword(state, "case",          TOK_CASE);
3459         hash_keyword(state, "char",          TOK_CHAR);
3460         hash_keyword(state, "const",         TOK_CONST);
3461         hash_keyword(state, "continue",      TOK_CONTINUE);
3462         hash_keyword(state, "default",       TOK_DEFAULT);
3463         hash_keyword(state, "do",            TOK_DO);
3464         hash_keyword(state, "double",        TOK_DOUBLE);
3465         hash_keyword(state, "else",          TOK_ELSE);
3466         hash_keyword(state, "enum",          TOK_ENUM);
3467         hash_keyword(state, "extern",        TOK_EXTERN);
3468         hash_keyword(state, "float",         TOK_FLOAT);
3469         hash_keyword(state, "for",           TOK_FOR);
3470         hash_keyword(state, "goto",          TOK_GOTO);
3471         hash_keyword(state, "if",            TOK_IF);
3472         hash_keyword(state, "inline",        TOK_INLINE);
3473         hash_keyword(state, "int",           TOK_INT);
3474         hash_keyword(state, "long",          TOK_LONG);
3475         hash_keyword(state, "register",      TOK_REGISTER);
3476         hash_keyword(state, "restrict",      TOK_RESTRICT);
3477         hash_keyword(state, "return",        TOK_RETURN);
3478         hash_keyword(state, "short",         TOK_SHORT);
3479         hash_keyword(state, "signed",        TOK_SIGNED);
3480         hash_keyword(state, "sizeof",        TOK_SIZEOF);
3481         hash_keyword(state, "static",        TOK_STATIC);
3482         hash_keyword(state, "struct",        TOK_STRUCT);
3483         hash_keyword(state, "switch",        TOK_SWITCH);
3484         hash_keyword(state, "typedef",       TOK_TYPEDEF);
3485         hash_keyword(state, "union",         TOK_UNION);
3486         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
3487         hash_keyword(state, "void",          TOK_VOID);
3488         hash_keyword(state, "volatile",      TOK_VOLATILE);
3489         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
3490         hash_keyword(state, "while",         TOK_WHILE);
3491         hash_keyword(state, "asm",           TOK_ASM);
3492         hash_keyword(state, "__asm__",       TOK_ASM);
3493         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3494         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
3495 }
3496
3497 static void register_macro_keywords(struct compile_state *state)
3498 {
3499         hash_keyword(state, "define",        TOK_MDEFINE);
3500         hash_keyword(state, "defined",       TOK_MDEFINED);
3501         hash_keyword(state, "undef",         TOK_MUNDEF);
3502         hash_keyword(state, "include",       TOK_MINCLUDE);
3503         hash_keyword(state, "line",          TOK_MLINE);
3504         hash_keyword(state, "error",         TOK_MERROR);
3505         hash_keyword(state, "warning",       TOK_MWARNING);
3506         hash_keyword(state, "pragma",        TOK_MPRAGMA);
3507         hash_keyword(state, "ifdef",         TOK_MIFDEF);
3508         hash_keyword(state, "ifndef",        TOK_MIFNDEF);
3509         hash_keyword(state, "elif",          TOK_MELIF);
3510         hash_keyword(state, "endif",         TOK_MENDIF);
3511 }
3512
3513
3514 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3515 {
3516         if (ident->sym_define != 0) {
3517                 struct macro *macro;
3518                 struct macro_arg *arg, *anext;
3519                 macro = ident->sym_define;
3520                 ident->sym_define = 0;
3521                 
3522                 /* Free the macro arguments... */
3523                 anext = macro->args;
3524                 while(anext) {
3525                         arg = anext;
3526                         anext = arg->next;
3527                         xfree(arg);
3528                 }
3529
3530                 /* Free the macro buffer */
3531                 xfree(macro->buf);
3532
3533                 /* Now free the macro itself */
3534                 xfree(macro);
3535         }
3536 }
3537
3538 static void do_define_macro(struct compile_state *state, 
3539         struct hash_entry *ident, const char *body, 
3540         int argc, struct macro_arg *args)
3541 {
3542         struct macro *macro;
3543         struct macro_arg *arg;
3544         size_t body_len;
3545
3546         /* Find the length of the body */
3547         body_len = strlen(body);
3548         macro = ident->sym_define;
3549         if (macro != 0) {
3550                 int identical_bodies, identical_args;
3551                 struct macro_arg *oarg;
3552                 /* Explicitly allow identical redfinitions of the same macro */
3553                 identical_bodies = 
3554                         (macro->buf_len == body_len) &&
3555                         (memcmp(macro->buf, body, body_len) == 0);
3556                 identical_args = macro->argc == argc;
3557                 oarg = macro->args;
3558                 arg = args;
3559                 while(identical_args && arg) {
3560                         identical_args = oarg->ident == arg->ident;
3561                         arg = arg->next;
3562                         oarg = oarg->next;
3563                 }
3564                 if (identical_bodies && identical_args) {
3565                         xfree(body);
3566                         return;
3567                 }
3568                 error(state, 0, "macro %s already defined\n", ident->name);
3569         }
3570 #if 0
3571         fprintf(state->errout, "#define %s: `%*.*s'\n",
3572                 ident->name, body_len, body_len, body);
3573 #endif
3574         macro = xmalloc(sizeof(*macro), "macro");
3575         macro->ident   = ident;
3576         macro->buf     = body;
3577         macro->buf_len = body_len;
3578         macro->args    = args;
3579         macro->argc    = argc;
3580
3581         ident->sym_define = macro;
3582 }
3583         
3584 static void define_macro(
3585         struct compile_state *state,
3586         struct hash_entry *ident,
3587         const char *body, int body_len,
3588         int argc, struct macro_arg *args)
3589 {
3590         char *buf;
3591         buf = xmalloc(body_len + 1, "macro buf");
3592         memcpy(buf, body, body_len);
3593         buf[body_len] = '\0';
3594         do_define_macro(state, ident, buf, argc, args);
3595 }
3596
3597 static void register_builtin_macro(struct compile_state *state,
3598         const char *name, const char *value)
3599 {
3600         struct hash_entry *ident;
3601
3602         if (value[0] == '(') {
3603                 internal_error(state, 0, "Builtin macros with arguments not supported");
3604         }
3605         ident = lookup(state, name, strlen(name));
3606         define_macro(state, ident, value, strlen(value), -1, 0);
3607 }
3608
3609 static void register_builtin_macros(struct compile_state *state)
3610 {
3611         char buf[30];
3612         char scratch[30];
3613         time_t now;
3614         struct tm *tm;
3615         now = time(NULL);
3616         tm = localtime(&now);
3617
3618         register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3619         register_builtin_macro(state, "__PRE_RAM__", VERSION_MAJOR);
3620         register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3621         register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3622         register_builtin_macro(state, "__LINE__", "54321");
3623
3624         strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3625         sprintf(buf, "\"%s\"", scratch);
3626         register_builtin_macro(state, "__DATE__", buf);
3627
3628         strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3629         sprintf(buf, "\"%s\"", scratch);
3630         register_builtin_macro(state, "__TIME__", buf);
3631
3632         /* I can't be a conforming implementation of C :( */
3633         register_builtin_macro(state, "__STDC__", "0");
3634         /* In particular I don't conform to C99 */
3635         register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3636         
3637 }
3638
3639 static void process_cmdline_macros(struct compile_state *state)
3640 {
3641         const char **macro, *name;
3642         struct hash_entry *ident;
3643         for(macro = state->compiler->defines; (name = *macro); macro++) {
3644                 const char *body;
3645                 size_t name_len;
3646
3647                 name_len = strlen(name);
3648                 body = strchr(name, '=');
3649                 if (!body) {
3650                         body = "\0";
3651                 } else {
3652                         name_len = body - name;
3653                         body++;
3654                 }
3655                 ident = lookup(state, name, name_len);
3656                 define_macro(state, ident, body, strlen(body), -1, 0);
3657         }
3658         for(macro = state->compiler->undefs; (name = *macro); macro++) {
3659                 ident = lookup(state, name, strlen(name));
3660                 undef_macro(state, ident);
3661         }
3662 }
3663
3664 static int spacep(int c)
3665 {
3666         int ret = 0;
3667         switch(c) {
3668         case ' ':
3669         case '\t':
3670         case '\f':
3671         case '\v':
3672         case '\r':
3673                 ret = 1;
3674                 break;
3675         }
3676         return ret;
3677 }
3678
3679 static int digitp(int c)
3680 {
3681         int ret = 0;
3682         switch(c) {
3683         case '0': case '1': case '2': case '3': case '4': 
3684         case '5': case '6': case '7': case '8': case '9':
3685                 ret = 1;
3686                 break;
3687         }
3688         return ret;
3689 }
3690 static int digval(int c)
3691 {
3692         int val = -1;
3693         if ((c >= '0') && (c <= '9')) {
3694                 val = c - '0';
3695         }
3696         return val;
3697 }
3698
3699 static int hexdigitp(int c)
3700 {
3701         int ret = 0;
3702         switch(c) {
3703         case '0': case '1': case '2': case '3': case '4': 
3704         case '5': case '6': case '7': case '8': case '9':
3705         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3706         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3707                 ret = 1;
3708                 break;
3709         }
3710         return ret;
3711 }
3712 static int hexdigval(int c) 
3713 {
3714         int val = -1;
3715         if ((c >= '0') && (c <= '9')) {
3716                 val = c - '0';
3717         }
3718         else if ((c >= 'A') && (c <= 'F')) {
3719                 val = 10 + (c - 'A');
3720         }
3721         else if ((c >= 'a') && (c <= 'f')) {
3722                 val = 10 + (c - 'a');
3723         }
3724         return val;
3725 }
3726
3727 static int octdigitp(int c)
3728 {
3729         int ret = 0;
3730         switch(c) {
3731         case '0': case '1': case '2': case '3': 
3732         case '4': case '5': case '6': case '7':
3733                 ret = 1;
3734                 break;
3735         }
3736         return ret;
3737 }
3738 static int octdigval(int c)
3739 {
3740         int val = -1;
3741         if ((c >= '0') && (c <= '7')) {
3742                 val = c - '0';
3743         }
3744         return val;
3745 }
3746
3747 static int letterp(int c)
3748 {
3749         int ret = 0;
3750         switch(c) {
3751         case 'a': case 'b': case 'c': case 'd': case 'e':
3752         case 'f': case 'g': case 'h': case 'i': case 'j':
3753         case 'k': case 'l': case 'm': case 'n': case 'o':
3754         case 'p': case 'q': case 'r': case 's': case 't':
3755         case 'u': case 'v': case 'w': case 'x': case 'y':
3756         case 'z':
3757         case 'A': case 'B': case 'C': case 'D': case 'E':
3758         case 'F': case 'G': case 'H': case 'I': case 'J':
3759         case 'K': case 'L': case 'M': case 'N': case 'O':
3760         case 'P': case 'Q': case 'R': case 'S': case 'T':
3761         case 'U': case 'V': case 'W': case 'X': case 'Y':
3762         case 'Z':
3763         case '_':
3764                 ret = 1;
3765                 break;
3766         }
3767         return ret;
3768 }
3769
3770 static const char *identifier(const char *str, const char *end)
3771 {
3772         if (letterp(*str)) {
3773                 for(; str < end; str++) {
3774                         int c;
3775                         c = *str;
3776                         if (!letterp(c) && !digitp(c)) {
3777                                 break;
3778                         }
3779                 }
3780         }
3781         return str;
3782 }
3783
3784 static int char_value(struct compile_state *state,
3785         const signed char **strp, const signed char *end)
3786 {
3787         const signed char *str;
3788         int c;
3789         str = *strp;
3790         c = *str++;
3791         if ((c == '\\') && (str < end)) {
3792                 switch(*str) {
3793                 case 'n':  c = '\n'; str++; break;
3794                 case 't':  c = '\t'; str++; break;
3795                 case 'v':  c = '\v'; str++; break;
3796                 case 'b':  c = '\b'; str++; break;
3797                 case 'r':  c = '\r'; str++; break;
3798                 case 'f':  c = '\f'; str++; break;
3799                 case 'a':  c = '\a'; str++; break;
3800                 case '\\': c = '\\'; str++; break;
3801                 case '?':  c = '?';  str++; break;
3802                 case '\'': c = '\''; str++; break;
3803                 case '"':  c = '"';  str++; break;
3804                 case 'x': 
3805                         c = 0;
3806                         str++;
3807                         while((str < end) && hexdigitp(*str)) {
3808                                 c <<= 4;
3809                                 c += hexdigval(*str);
3810                                 str++;
3811                         }
3812                         break;
3813                 case '0': case '1': case '2': case '3': 
3814                 case '4': case '5': case '6': case '7':
3815                         c = 0;
3816                         while((str < end) && octdigitp(*str)) {
3817                                 c <<= 3;
3818                                 c += octdigval(*str);
3819                                 str++;
3820                         }
3821                         break;
3822                 default:
3823                         error(state, 0, "Invalid character constant");
3824                         break;
3825                 }
3826         }
3827         *strp = str;
3828         return c;
3829 }
3830
3831 static const char *next_char(struct file_state *file, const char *pos, int index)
3832 {
3833         const char *end = file->buf + file->size;
3834         while(pos < end) {
3835                 /* Lookup the character */
3836                 int size = 1;
3837                 int c = *pos;
3838                 /* Is this a trigraph? */
3839                 if (file->trigraphs &&
3840                         (c == '?') && ((end - pos) >= 3) && (pos[1] == '?')) 
3841                 {
3842                         switch(pos[2]) {
3843                         case '=': c = '#'; break;
3844                         case '/': c = '\\'; break;
3845                         case '\'': c = '^'; break;
3846                         case '(': c = '['; break;
3847                         case ')': c = ']'; break;
3848                         case '!': c = '!'; break;
3849                         case '<': c = '{'; break;
3850                         case '>': c = '}'; break;
3851                         case '-': c = '~'; break;
3852                         }
3853                         if (c != '?') {
3854                                 size = 3;
3855                         }
3856                 }
3857                 /* Is this an escaped newline? */
3858                 if (file->join_lines &&
3859                         (c == '\\') && (pos + size < end) && ((pos[1] == '\n') || ((pos[1] == '\r') && (pos[2] == '\n'))))
3860                 {
3861                         int cr_offset = ((pos[1] == '\r') && (pos[2] == '\n'))?1:0;
3862                         /* At the start of a line just eat it */
3863                         if (pos == file->pos) {
3864                                 file->line++;
3865                                 file->report_line++;
3866                                 file->line_start = pos + size + 1 + cr_offset;
3867                         }
3868                         pos += size + 1 + cr_offset;
3869                 }
3870                 /* Do I need to ga any farther? */
3871                 else if (index == 0) {
3872                         break;
3873                 }
3874                 /* Process a normal character */
3875                 else {
3876                         pos += size;
3877                         index -= 1;
3878                 }
3879         }
3880         return pos;
3881 }
3882
3883 static int get_char(struct file_state *file, const char *pos)
3884 {
3885         const char *end = file->buf + file->size;
3886         int c;
3887         c = -1;
3888         pos = next_char(file, pos, 0);
3889         if (pos < end) {
3890                 /* Lookup the character */
3891                 c = *pos;
3892                 /* If it is a trigraph get the trigraph value */
3893                 if (file->trigraphs &&
3894                         (c == '?') && ((end - pos) >= 3) && (pos[1] == '?')) 
3895                 {
3896                         switch(pos[2]) {
3897                         case '=': c = '#'; break;
3898                         case '/': c = '\\'; break;
3899                         case '\'': c = '^'; break;
3900                         case '(': c = '['; break;
3901                         case ')': c = ']'; break;
3902                         case '!': c = '!'; break;
3903                         case '<': c = '{'; break;
3904                         case '>': c = '}'; break;
3905                         case '-': c = '~'; break;
3906                         }
3907                 }
3908         }
3909         return c;
3910 }
3911
3912 static void eat_chars(struct file_state *file, const char *targ)
3913 {
3914         const char *pos = file->pos;
3915         while(pos < targ) {
3916                 /* Do we have a newline? */
3917                 if (pos[0] == '\n') {
3918                         file->line++;
3919                         file->report_line++;
3920                         file->line_start = pos + 1;
3921                 }
3922                 pos++;
3923         }
3924         file->pos = pos;
3925 }
3926
3927
3928 static size_t char_strlen(struct file_state *file, const char *src, const char *end)
3929 {
3930         size_t len;
3931         len = 0;
3932         while(src < end) {
3933                 src = next_char(file, src, 1);
3934                 len++;
3935         }
3936         return len;
3937 }
3938
3939 static void char_strcpy(char *dest, 
3940         struct file_state *file, const char *src, const char *end)
3941 {
3942         while(src < end) {
3943                 int c;
3944                 c = get_char(file, src);
3945                 src = next_char(file, src, 1);
3946                 *dest++ = c;
3947         }
3948 }
3949
3950 static char *char_strdup(struct file_state *file, 
3951         const char *start, const char *end, const char *id)
3952 {
3953         char *str;
3954         size_t str_len;
3955         str_len = char_strlen(file, start, end);
3956         str = xcmalloc(str_len + 1, id);
3957         char_strcpy(str, file, start, end);
3958         str[str_len] = '\0';
3959         return str;
3960 }
3961
3962 static const char *after_digits(struct file_state *file, const char *ptr)
3963 {
3964         while(digitp(get_char(file, ptr))) {
3965                 ptr = next_char(file, ptr, 1);
3966         }
3967         return ptr;
3968 }
3969
3970 static const char *after_octdigits(struct file_state *file, const char *ptr)
3971 {
3972         while(octdigitp(get_char(file, ptr))) {
3973                 ptr = next_char(file, ptr, 1);
3974         }
3975         return ptr;
3976 }
3977
3978 static const char *after_hexdigits(struct file_state *file, const char *ptr)
3979 {
3980         while(hexdigitp(get_char(file, ptr))) {
3981                 ptr = next_char(file, ptr, 1);
3982         }
3983         return ptr;
3984 }
3985
3986 static const char *after_alnums(struct file_state *file, const char *ptr)
3987 {
3988         int c;
3989         c = get_char(file, ptr);
3990         while(letterp(c) || digitp(c)) {
3991                 ptr = next_char(file, ptr, 1);
3992                 c = get_char(file, ptr);
3993         }
3994         return ptr;
3995 }
3996
3997 static void save_string(struct file_state *file,
3998         struct token *tk, const char *start, const char *end, const char *id)
3999 {
4000         char *str;
4001
4002         /* Create a private copy of the string */
4003         str = char_strdup(file, start, end, id);
4004
4005         /* Store the copy in the token */
4006         tk->val.str = str;
4007         tk->str_len = strlen(str);
4008 }
4009
4010 static void raw_next_token(struct compile_state *state, 
4011         struct file_state *file, struct token *tk)
4012 {
4013         const char *token;
4014         int c, c1, c2, c3;
4015         const char *tokp;
4016         int eat;
4017         int tok;
4018
4019         tk->str_len = 0;
4020         tk->ident = 0;
4021         token = tokp = next_char(file, file->pos, 0);
4022         tok = TOK_UNKNOWN;
4023         c  = get_char(file, tokp);
4024         tokp = next_char(file, tokp, 1);
4025         eat = 0;
4026         c1 = get_char(file, tokp);
4027         c2 = get_char(file, next_char(file, tokp, 1));
4028         c3 = get_char(file, next_char(file, tokp, 2));
4029
4030         /* The end of the file */
4031         if (c == -1) {
4032                 tok = TOK_EOF;
4033         }
4034         /* Whitespace */
4035         else if (spacep(c)) {
4036                 tok = TOK_SPACE;
4037                 while (spacep(get_char(file, tokp))) {
4038                         tokp = next_char(file, tokp, 1);
4039                 }
4040         }
4041         /* EOL Comments */
4042         else if ((c == '/') && (c1 == '/')) {
4043                 tok = TOK_SPACE;
4044                 tokp = next_char(file, tokp, 1);
4045                 while((c = get_char(file, tokp)) != -1) {
4046                         /* Advance to the next character only after we verify
4047                          * the current character is not a newline.  
4048                          * EOL is special to the preprocessor so we don't
4049                          * want to loose any.
4050                          */
4051                         if (c == '\n') {
4052                                 break;
4053                         }
4054                         tokp = next_char(file, tokp, 1);
4055                 }
4056         }
4057         /* Comments */
4058         else if ((c == '/') && (c1 == '*')) {
4059                 tokp = next_char(file, tokp, 2);
4060                 c = c2;
4061                 while((c1 = get_char(file, tokp)) != -1) {
4062                         tokp = next_char(file, tokp, 1);
4063                         if ((c == '*') && (c1 == '/')) {
4064                                 tok = TOK_SPACE;
4065                                 break;
4066                         }
4067                         c = c1;
4068                 }
4069                 if (tok == TOK_UNKNOWN) {
4070                         error(state, 0, "unterminated comment");
4071                 }
4072         }
4073         /* string constants */
4074         else if ((c == '"') || ((c == 'L') && (c1 == '"'))) {
4075                 int wchar, multiline;
4076
4077                 wchar = 0;
4078                 multiline = 0;
4079                 if (c == 'L') {
4080                         wchar = 1;
4081                         tokp = next_char(file, tokp, 1);
4082                 }
4083                 while((c = get_char(file, tokp)) != -1) {
4084                         tokp = next_char(file, tokp, 1);
4085                         if (c == '\n') {
4086                                 multiline = 1;
4087                         }
4088                         else if (c == '\\') {
4089                                 tokp = next_char(file, tokp, 1);
4090                         }
4091                         else if (c == '"') {
4092                                 tok = TOK_LIT_STRING;
4093                                 break;
4094                         }
4095                 }
4096                 if (tok == TOK_UNKNOWN) {
4097                         error(state, 0, "unterminated string constant");
4098                 }
4099                 if (multiline) {
4100                         warning(state, 0, "multiline string constant");
4101                 }
4102
4103                 /* Save the string value */
4104                 save_string(file, tk, token, tokp, "literal string");
4105         }
4106         /* character constants */
4107         else if ((c == '\'') || ((c == 'L') && (c1 == '\''))) {
4108                 int wchar, multiline;
4109
4110                 wchar = 0;
4111                 multiline = 0;
4112                 if (c == 'L') {
4113                         wchar = 1;
4114                         tokp = next_char(file, tokp, 1);
4115                 }
4116                 while((c = get_char(file, tokp)) != -1) {
4117                         tokp = next_char(file, tokp, 1);
4118                         if (c == '\n') {
4119                                 multiline = 1;
4120                         }
4121                         else if (c == '\\') {
4122                                 tokp = next_char(file, tokp, 1);
4123                         }
4124                         else if (c == '\'') {
4125                                 tok = TOK_LIT_CHAR;
4126                                 break;
4127                         }
4128                 }
4129                 if (tok == TOK_UNKNOWN) {
4130                         error(state, 0, "unterminated character constant");
4131                 }
4132                 if (multiline) {
4133                         warning(state, 0, "multiline character constant");
4134                 }
4135
4136                 /* Save the character value */
4137                 save_string(file, tk, token, tokp, "literal character");
4138         }
4139         /* integer and floating constants 
4140          * Integer Constants
4141          * {digits}
4142          * 0[Xx]{hexdigits}
4143          * 0{octdigit}+
4144          * 
4145          * Floating constants
4146          * {digits}.{digits}[Ee][+-]?{digits}
4147          * {digits}.{digits}
4148          * {digits}[Ee][+-]?{digits}
4149          * .{digits}[Ee][+-]?{digits}
4150          * .{digits}
4151          */
4152         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4153                 const char *next;
4154                 int is_float;
4155                 int cn;
4156                 is_float = 0;
4157                 if (c != '.') {
4158                         next = after_digits(file, tokp);
4159                 }
4160                 else {
4161                         next = token;
4162                 }
4163                 cn = get_char(file, next);
4164                 if (cn == '.') {
4165                         next = next_char(file, next, 1);
4166                         next = after_digits(file, next);
4167                         is_float = 1;
4168                 }
4169                 cn = get_char(file, next);
4170                 if ((cn == 'e') || (cn == 'E')) {
4171                         const char *new;
4172                         next = next_char(file, next, 1);
4173                         cn = get_char(file, next);
4174                         if ((cn == '+') || (cn == '-')) {
4175                                 next = next_char(file, next, 1);
4176                         }
4177                         new = after_digits(file, next);
4178                         is_float |= (new != next);
4179                         next = new;
4180                 }
4181                 if (is_float) {
4182                         tok = TOK_LIT_FLOAT;
4183                         cn = get_char(file, next);
4184                         if ((cn  == 'f') || (cn == 'F') || (cn == 'l') || (cn == 'L')) {
4185                                 next = next_char(file, next, 1);
4186                         }
4187                 }
4188                 if (!is_float && digitp(c)) {
4189                         tok = TOK_LIT_INT;
4190                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4191                                 next = next_char(file, tokp, 1);
4192                                 next = after_hexdigits(file, next);
4193                         }
4194                         else if (c == '0') {
4195                                 next = after_octdigits(file, tokp);
4196                         }
4197                         else {
4198                                 next = after_digits(file, tokp);
4199                         }
4200                         /* crazy integer suffixes */
4201                         cn = get_char(file, next);
4202                         if ((cn == 'u') || (cn == 'U')) {
4203                                 next = next_char(file, next, 1);
4204                                 cn = get_char(file, next);
4205                                 if ((cn == 'l') || (cn == 'L')) {
4206                                         next = next_char(file, next, 1);
4207                                         cn = get_char(file, next);
4208                                 }
4209                                 if ((cn == 'l') || (cn == 'L')) {
4210                                         next = next_char(file, next, 1);
4211                                 }
4212                         }
4213                         else if ((cn == 'l') || (cn == 'L')) {
4214                                 next = next_char(file, next, 1);
4215                                 cn = get_char(file, next);
4216                                 if ((cn == 'l') || (cn == 'L')) {
4217                                         next = next_char(file, next, 1);
4218                                         cn = get_char(file, next);
4219                                 }
4220                                 if ((cn == 'u') || (cn == 'U')) {
4221                                         next = next_char(file, next, 1);
4222                                 }
4223                         }
4224                 }
4225                 tokp = next;
4226
4227                 /* Save the integer/floating point value */
4228                 save_string(file, tk, token, tokp, "literal number");
4229         }
4230         /* identifiers */
4231         else if (letterp(c)) {
4232                 tok = TOK_IDENT;
4233
4234                 /* Find and save the identifier string */
4235                 tokp = after_alnums(file, tokp);
4236                 save_string(file, tk, token, tokp, "identifier");
4237
4238                 /* Look up to see which identifier it is */
4239                 tk->ident = lookup(state, tk->val.str, tk->str_len);
4240
4241                 /* Free the identifier string */
4242                 tk->str_len = 0;
4243                 xfree(tk->val.str);
4244
4245                 /* See if this identifier can be macro expanded */
4246                 tk->val.notmacro = 0;
4247                 c = get_char(file, tokp);
4248                 if (c == '$') {
4249                         tokp = next_char(file, tokp, 1);
4250                         tk->val.notmacro = 1;
4251                 }
4252         }
4253         /* C99 alternate macro characters */
4254         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) { 
4255                 eat += 3;
4256                 tok = TOK_CONCATENATE; 
4257         }
4258         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { eat += 2; tok = TOK_DOTS; }
4259         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { eat += 2; tok = TOK_SLEQ; }
4260         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { eat += 2; tok = TOK_SREQ; }
4261         else if ((c == '*') && (c1 == '=')) { eat += 1; tok = TOK_TIMESEQ; }
4262         else if ((c == '/') && (c1 == '=')) { eat += 1; tok = TOK_DIVEQ; }
4263         else if ((c == '%') && (c1 == '=')) { eat += 1; tok = TOK_MODEQ; }
4264         else if ((c == '+') && (c1 == '=')) { eat += 1; tok = TOK_PLUSEQ; }
4265         else if ((c == '-') && (c1 == '=')) { eat += 1; tok = TOK_MINUSEQ; }
4266         else if ((c == '&') && (c1 == '=')) { eat += 1; tok = TOK_ANDEQ; }
4267         else if ((c == '^') && (c1 == '=')) { eat += 1; tok = TOK_XOREQ; }
4268         else if ((c == '|') && (c1 == '=')) { eat += 1; tok = TOK_OREQ; }
4269         else if ((c == '=') && (c1 == '=')) { eat += 1; tok = TOK_EQEQ; }
4270         else if ((c == '!') && (c1 == '=')) { eat += 1; tok = TOK_NOTEQ; }
4271         else if ((c == '|') && (c1 == '|')) { eat += 1; tok = TOK_LOGOR; }
4272         else if ((c == '&') && (c1 == '&')) { eat += 1; tok = TOK_LOGAND; }
4273         else if ((c == '<') && (c1 == '=')) { eat += 1; tok = TOK_LESSEQ; }
4274         else if ((c == '>') && (c1 == '=')) { eat += 1; tok = TOK_MOREEQ; }
4275         else if ((c == '<') && (c1 == '<')) { eat += 1; tok = TOK_SL; }
4276         else if ((c == '>') && (c1 == '>')) { eat += 1; tok = TOK_SR; }
4277         else if ((c == '+') && (c1 == '+')) { eat += 1; tok = TOK_PLUSPLUS; }
4278         else if ((c == '-') && (c1 == '-')) { eat += 1; tok = TOK_MINUSMINUS; }
4279         else if ((c == '-') && (c1 == '>')) { eat += 1; tok = TOK_ARROW; }
4280         else if ((c == '<') && (c1 == ':')) { eat += 1; tok = TOK_LBRACKET; }
4281         else if ((c == ':') && (c1 == '>')) { eat += 1; tok = TOK_RBRACKET; }
4282         else if ((c == '<') && (c1 == '%')) { eat += 1; tok = TOK_LBRACE; }
4283         else if ((c == '%') && (c1 == '>')) { eat += 1; tok = TOK_RBRACE; }
4284         else if ((c == '%') && (c1 == ':')) { eat += 1; tok = TOK_MACRO; }
4285         else if ((c == '#') && (c1 == '#')) { eat += 1; tok = TOK_CONCATENATE; }
4286         else if (c == ';') { tok = TOK_SEMI; }
4287         else if (c == '{') { tok = TOK_LBRACE; }
4288         else if (c == '}') { tok = TOK_RBRACE; }
4289         else if (c == ',') { tok = TOK_COMMA; }
4290         else if (c == '=') { tok = TOK_EQ; }
4291         else if (c == ':') { tok = TOK_COLON; }
4292         else if (c == '[') { tok = TOK_LBRACKET; }
4293         else if (c == ']') { tok = TOK_RBRACKET; }
4294         else if (c == '(') { tok = TOK_LPAREN; }
4295         else if (c == ')') { tok = TOK_RPAREN; }
4296         else if (c == '*') { tok = TOK_STAR; }
4297         else if (c == '>') { tok = TOK_MORE; }
4298         else if (c == '<') { tok = TOK_LESS; }
4299         else if (c == '?') { tok = TOK_QUEST; }
4300         else if (c == '|') { tok = TOK_OR; }
4301         else if (c == '&') { tok = TOK_AND; }
4302         else if (c == '^') { tok = TOK_XOR; }
4303         else if (c == '+') { tok = TOK_PLUS; }
4304         else if (c == '-') { tok = TOK_MINUS; }
4305         else if (c == '/') { tok = TOK_DIV; }
4306         else if (c == '%') { tok = TOK_MOD; }
4307         else if (c == '!') { tok = TOK_BANG; }
4308         else if (c == '.') { tok = TOK_DOT; }
4309         else if (c == '~') { tok = TOK_TILDE; }
4310         else if (c == '#') { tok = TOK_MACRO; }
4311         else if (c == '\n') { tok = TOK_EOL; }
4312
4313         tokp = next_char(file, tokp, eat);
4314         eat_chars(file, tokp);
4315         tk->tok = tok;
4316         tk->pos = token;
4317 }
4318
4319 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4320 {
4321         if (tk->tok != tok) {
4322                 const char *name1, *name2;
4323                 name1 = tokens[tk->tok];
4324                 name2 = "";
4325                 if ((tk->tok == TOK_IDENT) || (tk->tok == TOK_MIDENT)) {
4326                         name2 = tk->ident->name;
4327                 }
4328                 error(state, 0, "\tfound %s %s expected %s",
4329                         name1, name2, tokens[tok]);
4330         }
4331 }
4332
4333 struct macro_arg_value {
4334         struct hash_entry *ident;
4335         char *value;
4336         size_t len;
4337 };
4338 static struct macro_arg_value *read_macro_args(
4339         struct compile_state *state, struct macro *macro, 
4340         struct file_state *file, struct token *tk)
4341 {
4342         struct macro_arg_value *argv;
4343         struct macro_arg *arg;
4344         int paren_depth;
4345         int i;
4346
4347         if (macro->argc == 0) {
4348                 do {
4349                         raw_next_token(state, file, tk);
4350                 } while(tk->tok == TOK_SPACE);
4351                 return NULL;
4352         }
4353         argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4354         for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4355                 argv[i].value = 0;
4356                 argv[i].len   = 0;
4357                 argv[i].ident = arg->ident;
4358         }
4359         paren_depth = 0;
4360         i = 0;
4361         
4362         for(;;) {
4363                 const char *start;
4364                 size_t len;
4365                 start = file->pos;
4366                 raw_next_token(state, file, tk);
4367                 
4368                 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4369                         (argv[i].ident != state->i___VA_ARGS__)) 
4370                 {
4371                         i++;
4372                         if (i >= macro->argc) {
4373                                 error(state, 0, "too many args to %s\n",
4374                                         macro->ident->name);
4375                         }
4376                         continue;
4377                 }
4378                 
4379                 if (tk->tok == TOK_LPAREN) {
4380                         paren_depth++;
4381                 }
4382                 
4383                 if (tk->tok == TOK_RPAREN) {
4384                         if (paren_depth == 0) {
4385                                 break;
4386                         }
4387                         paren_depth--;
4388                 }
4389                 if (tk->tok == TOK_EOF) {
4390                         error(state, 0, "End of file encountered while parsing macro arguments");
4391                 }
4392
4393                 len = char_strlen(file, start, file->pos);
4394                 argv[i].value = xrealloc(
4395                         argv[i].value, argv[i].len + len, "macro args");
4396                 char_strcpy((char *)argv[i].value + argv[i].len, file, start, file->pos);
4397                 argv[i].len += len;
4398         }
4399         if (i != macro->argc -1) {
4400                 error(state, 0, "missing %s arg %d\n", 
4401                         macro->ident->name, i +2);
4402         }
4403         return argv;
4404 }
4405
4406
4407 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4408 {
4409         int i;
4410         for(i = 0; i < macro->argc; i++) {
4411                 xfree(argv[i].value);
4412         }
4413         xfree(argv);
4414 }
4415
4416 struct macro_buf {
4417         char *str;
4418         size_t len, pos;
4419 };
4420
4421 static void grow_macro_buf(struct compile_state *state,
4422         const char *id, struct macro_buf *buf,
4423         size_t grow)
4424 {
4425         if ((buf->pos + grow) >= buf->len) {
4426                 buf->str = xrealloc(buf->str, buf->len + grow, id);
4427                 buf->len += grow;
4428         }
4429 }
4430
4431 static void append_macro_text(struct compile_state *state,
4432         const char *id, struct macro_buf *buf,
4433         const char *fstart, size_t flen)
4434 {
4435         grow_macro_buf(state, id, buf, flen);
4436         memcpy(buf->str + buf->pos, fstart, flen);
4437 #if 0
4438         fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4439                 buf->pos, buf->pos, buf->str,
4440                 flen, flen, buf->str + buf->pos);
4441 #endif
4442         buf->pos += flen;
4443 }
4444
4445
4446 static void append_macro_chars(struct compile_state *state,
4447         const char *id, struct macro_buf *buf,
4448         struct file_state *file, const char *start, const char *end)
4449 {
4450         size_t flen;
4451         flen = char_strlen(file, start, end);
4452         grow_macro_buf(state, id, buf, flen);
4453         char_strcpy(buf->str + buf->pos, file, start, end);
4454 #if 0
4455         fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4456                 buf->pos, buf->pos, buf->str,
4457                 flen, flen, buf->str + buf->pos);
4458 #endif
4459         buf->pos += flen;
4460 }
4461
4462 static int compile_macro(struct compile_state *state, 
4463         struct file_state **filep, struct token *tk);
4464
4465 static void macro_expand_args(struct compile_state *state, 
4466         struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4467 {
4468         int i;
4469         
4470         for(i = 0; i < macro->argc; i++) {
4471                 struct file_state fmacro, *file;
4472                 struct macro_buf buf;
4473
4474                 fmacro.prev        = 0;
4475                 fmacro.basename    = argv[i].ident->name;
4476                 fmacro.dirname     = "";
4477                 fmacro.buf         = (char *)argv[i].value;
4478                 fmacro.size        = argv[i].len;
4479                 fmacro.pos         = fmacro.buf;
4480                 fmacro.line        = 1;
4481                 fmacro.line_start  = fmacro.buf;
4482                 fmacro.report_line = 1;
4483                 fmacro.report_name = fmacro.basename;
4484                 fmacro.report_dir  = fmacro.dirname;
4485                 fmacro.macro       = 1;
4486                 fmacro.trigraphs   = 0;
4487                 fmacro.join_lines  = 0;
4488
4489                 buf.len = argv[i].len;
4490                 buf.str = xmalloc(buf.len, argv[i].ident->name);
4491                 buf.pos = 0;
4492
4493                 file = &fmacro;
4494                 for(;;) {
4495                         raw_next_token(state, file, tk);
4496                         
4497                         /* If we have recursed into another macro body
4498                          * get out of it.
4499                          */
4500                         if (tk->tok == TOK_EOF) {
4501                                 struct file_state *old;
4502                                 old = file;
4503                                 file = file->prev;
4504                                 if (!file) {
4505                                         break;
4506                                 }
4507                                 /* old->basename is used keep it */
4508                                 xfree(old->dirname);
4509                                 xfree(old->buf);
4510                                 xfree(old);
4511                                 continue;
4512                         }
4513                         else if (tk->ident && tk->ident->sym_define) {
4514                                 if (compile_macro(state, &file, tk)) {
4515                                         continue;
4516                                 }
4517                         }
4518
4519                         append_macro_chars(state, macro->ident->name, &buf,
4520                                 file, tk->pos, file->pos);
4521                 }
4522                         
4523                 xfree(argv[i].value);
4524                 argv[i].value = buf.str;
4525                 argv[i].len   = buf.pos;
4526         }
4527         return;
4528 }
4529
4530 static void expand_macro(struct compile_state *state,
4531         struct macro *macro, struct macro_buf *buf,
4532         struct macro_arg_value *argv, struct token *tk)
4533 {
4534         struct file_state fmacro;
4535         const char space[] = " ";
4536         const char *fstart;
4537         size_t flen;
4538         int i, j;
4539
4540         /* Place the macro body in a dummy file */
4541         fmacro.prev        = 0;
4542         fmacro.basename    = macro->ident->name;
4543         fmacro.dirname     = "";
4544         fmacro.buf         = macro->buf;
4545         fmacro.size        = macro->buf_len;
4546         fmacro.pos         = fmacro.buf;
4547         fmacro.line        = 1;
4548         fmacro.line_start  = fmacro.buf;
4549         fmacro.report_line = 1;
4550         fmacro.report_name = fmacro.basename;
4551         fmacro.report_dir  = fmacro.dirname;
4552         fmacro.macro       = 1;
4553         fmacro.trigraphs   = 0;
4554         fmacro.join_lines  = 0;
4555         
4556         /* Allocate a buffer to hold the macro expansion */
4557         buf->len = macro->buf_len + 3;
4558         buf->str = xmalloc(buf->len, macro->ident->name);
4559         buf->pos = 0;
4560         
4561         fstart = fmacro.pos;
4562         raw_next_token(state, &fmacro, tk);
4563         while(tk->tok != TOK_EOF) {
4564                 flen = fmacro.pos - fstart;
4565                 switch(tk->tok) {
4566                 case TOK_IDENT:
4567                         for(i = 0; i < macro->argc; i++) {
4568                                 if (argv[i].ident == tk->ident) {
4569                                         break;
4570                                 }
4571                         }
4572                         if (i >= macro->argc) {
4573                                 break;
4574                         }
4575                         /* Substitute macro parameter */
4576                         fstart = argv[i].value;
4577                         flen   = argv[i].len;
4578                         break;
4579                 case TOK_MACRO:
4580                         if (macro->argc < 0) {
4581                                 break;
4582                         }
4583                         do {
4584                                 raw_next_token(state, &fmacro, tk);
4585                         } while(tk->tok == TOK_SPACE);
4586                         check_tok(state, tk, TOK_IDENT);
4587                         for(i = 0; i < macro->argc; i++) {
4588                                 if (argv[i].ident == tk->ident) {
4589                                         break;
4590                                 }
4591                         }
4592                         if (i >= macro->argc) {
4593                                 error(state, 0, "parameter `%s' not found",
4594                                         tk->ident->name);
4595                         }
4596                         /* Stringize token */
4597                         append_macro_text(state, macro->ident->name, buf, "\"", 1);
4598                         for(j = 0; j < argv[i].len; j++) {
4599                                 char *str = argv[i].value + j;
4600                                 size_t len = 1;
4601                                 if (*str == '\\') {
4602                                         str = "\\";
4603                                         len = 2;
4604                                 } 
4605                                 else if (*str == '"') {
4606                                         str = "\\\"";
4607                                         len = 2;
4608                                 }
4609                                 append_macro_text(state, macro->ident->name, buf, str, len);
4610                         }
4611                         append_macro_text(state, macro->ident->name, buf, "\"", 1);
4612                         fstart = 0;
4613                         flen   = 0;
4614                         break;
4615                 case TOK_CONCATENATE:
4616                         /* Concatenate tokens */
4617                         /* Delete the previous whitespace token */
4618                         if (buf->str[buf->pos - 1] == ' ') {
4619                                 buf->pos -= 1;
4620                         }
4621                         /* Skip the next sequence of whitspace tokens */
4622                         do {
4623                                 fstart = fmacro.pos;
4624                                 raw_next_token(state, &fmacro, tk);
4625                         } while(tk->tok == TOK_SPACE);
4626                         /* Restart at the top of the loop.
4627                          * I need to process the non white space token.
4628                          */
4629                         continue;
4630                         break;
4631                 case TOK_SPACE:
4632                         /* Collapse multiple spaces into one */
4633                         if (buf->str[buf->pos - 1] != ' ') {
4634                                 fstart = space;
4635                                 flen   = 1;
4636                         } else {
4637                                 fstart = 0;
4638                                 flen   = 0;
4639                         }
4640                         break;
4641                 default:
4642                         break;
4643                 }
4644
4645                 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4646                 
4647                 fstart = fmacro.pos;
4648                 raw_next_token(state, &fmacro, tk);
4649         }
4650 }
4651
4652 static void tag_macro_name(struct compile_state *state,
4653         struct macro *macro, struct macro_buf *buf,
4654         struct token *tk)
4655 {
4656         /* Guard all instances of the macro name in the replacement
4657          * text from further macro expansion.
4658          */
4659         struct file_state fmacro;
4660         const char *fstart;
4661         size_t flen;
4662
4663         /* Put the old macro expansion buffer in a file */
4664         fmacro.prev        = 0;
4665         fmacro.basename    = macro->ident->name;
4666         fmacro.dirname     = "";
4667         fmacro.buf         = buf->str;
4668         fmacro.size        = buf->pos;
4669         fmacro.pos         = fmacro.buf;
4670         fmacro.line        = 1;
4671         fmacro.line_start  = fmacro.buf;
4672         fmacro.report_line = 1;
4673         fmacro.report_name = fmacro.basename;
4674         fmacro.report_dir  = fmacro.dirname;
4675         fmacro.macro       = 1;
4676         fmacro.trigraphs   = 0;
4677         fmacro.join_lines  = 0;
4678         
4679         /* Allocate a new macro expansion buffer */
4680         buf->len = macro->buf_len + 3;
4681         buf->str = xmalloc(buf->len, macro->ident->name);
4682         buf->pos = 0;
4683         
4684         fstart = fmacro.pos;
4685         raw_next_token(state, &fmacro, tk);
4686         while(tk->tok != TOK_EOF) {
4687                 flen = fmacro.pos - fstart;
4688                 if ((tk->tok == TOK_IDENT) &&
4689                         (tk->ident == macro->ident) &&
4690                         (tk->val.notmacro == 0)) 
4691                 {
4692                         append_macro_text(state, macro->ident->name, buf, fstart, flen);
4693                         fstart = "$";
4694                         flen   = 1;
4695                 }
4696
4697                 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4698                 
4699                 fstart = fmacro.pos;
4700                 raw_next_token(state, &fmacro, tk);
4701         }
4702         xfree(fmacro.buf);
4703 }
4704
4705 static int compile_macro(struct compile_state *state, 
4706         struct file_state **filep, struct token *tk)
4707 {
4708         struct file_state *file;
4709         struct hash_entry *ident;
4710         struct macro *macro;
4711         struct macro_arg_value *argv;
4712         struct macro_buf buf;
4713
4714 #if 0
4715         fprintf(state->errout, "macro: %s\n", tk->ident->name);
4716 #endif
4717         ident = tk->ident;
4718         macro = ident->sym_define;
4719
4720         /* If this token comes from a macro expansion ignore it */
4721         if (tk->val.notmacro) {
4722                 return 0;
4723         }
4724         /* If I am a function like macro and the identifier is not followed
4725          * by a left parenthesis, do nothing.
4726          */
4727         if ((macro->argc >= 0) && (get_char(*filep, (*filep)->pos) != '(')) {
4728                 return 0;
4729         }
4730
4731         /* Read in the macro arguments */
4732         argv = 0;
4733         if (macro->argc >= 0) {
4734                 raw_next_token(state, *filep, tk);
4735                 check_tok(state, tk, TOK_LPAREN);
4736
4737                 argv = read_macro_args(state, macro, *filep, tk);
4738
4739                 check_tok(state, tk, TOK_RPAREN);
4740         }
4741         /* Macro expand the macro arguments */
4742         macro_expand_args(state, macro, argv, tk);
4743
4744         buf.str = 0;
4745         buf.len = 0;
4746         buf.pos = 0;
4747         if (ident == state->i___FILE__) {
4748                 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4749                 buf.str = xmalloc(buf.len, ident->name);
4750                 sprintf(buf.str, "\"%s\"", state->file->basename);
4751                 buf.pos = strlen(buf.str);
4752         }
4753         else if (ident == state->i___LINE__) {
4754                 buf.len = 30;
4755                 buf.str = xmalloc(buf.len, ident->name);
4756                 sprintf(buf.str, "%d", state->file->line);
4757                 buf.pos = strlen(buf.str);
4758         }
4759         else {
4760                 expand_macro(state, macro, &buf, argv, tk);
4761         }
4762         /* Tag the macro name with a $ so it will no longer
4763          * be regonized as a canidate for macro expansion.
4764          */
4765         tag_macro_name(state, macro, &buf, tk);
4766
4767 #if 0
4768         fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4769                 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4770 #endif
4771
4772         free_macro_args(macro, argv);
4773
4774         file = xmalloc(sizeof(*file), "file_state");
4775         file->prev        = *filep;
4776         file->basename    = xstrdup(ident->name);
4777         file->dirname     = xstrdup("");
4778         file->buf         = buf.str;
4779         file->size        = buf.pos;
4780         file->pos         = file->buf;
4781         file->line        = 1;
4782         file->line_start  = file->pos;
4783         file->report_line = 1;
4784         file->report_name = file->basename;
4785         file->report_dir  = file->dirname;
4786         file->macro       = 1;
4787         file->trigraphs   = 0;
4788         file->join_lines  = 0;
4789         *filep = file;
4790         return 1;
4791 }
4792
4793 static void eat_tokens(struct compile_state *state, int targ_tok)
4794 {
4795         if (state->eat_depth > 0) {
4796                 internal_error(state, 0, "Already eating...");
4797         }
4798         state->eat_depth = state->if_depth;
4799         state->eat_targ = targ_tok;
4800 }
4801 static int if_eat(struct compile_state *state)
4802 {
4803         return state->eat_depth > 0;
4804 }
4805 static int if_value(struct compile_state *state)
4806 {
4807         int index, offset;
4808         index = state->if_depth / CHAR_BIT;
4809         offset = state->if_depth % CHAR_BIT;
4810         return !!(state->if_bytes[index] & (1 << (offset)));
4811 }
4812 static void set_if_value(struct compile_state *state, int value) 
4813 {
4814         int index, offset;
4815         index = state->if_depth / CHAR_BIT;
4816         offset = state->if_depth % CHAR_BIT;
4817
4818         state->if_bytes[index] &= ~(1 << offset);
4819         if (value) {
4820                 state->if_bytes[index] |= (1 << offset);
4821         }
4822 }
4823 static void in_if(struct compile_state *state, const char *name)
4824 {
4825         if (state->if_depth <= 0) {
4826                 error(state, 0, "%s without #if", name);
4827         }
4828 }
4829 static void enter_if(struct compile_state *state)
4830 {
4831         state->if_depth += 1;
4832         if (state->if_depth > MAX_PP_IF_DEPTH) {
4833                 error(state, 0, "#if depth too great");
4834         }
4835 }
4836 static void reenter_if(struct compile_state *state, const char *name)
4837 {
4838         in_if(state, name);
4839         if ((state->eat_depth == state->if_depth) &&
4840                 (state->eat_targ == TOK_MELSE)) {
4841                 state->eat_depth = 0;
4842                 state->eat_targ = 0;
4843         }
4844 }
4845 static void enter_else(struct compile_state *state, const char *name)
4846 {
4847         in_if(state, name);
4848         if ((state->eat_depth == state->if_depth) &&
4849                 (state->eat_targ == TOK_MELSE)) {
4850                 state->eat_depth = 0;
4851                 state->eat_targ = 0;
4852         }
4853 }
4854 static void exit_if(struct compile_state *state, const char *name)
4855 {
4856         in_if(state, name);
4857         if (state->eat_depth == state->if_depth) {
4858                 state->eat_depth = 0;
4859                 state->eat_targ = 0;
4860         }
4861         state->if_depth -= 1;
4862 }
4863
4864 static void raw_token(struct compile_state *state, struct token *tk)
4865 {
4866         struct file_state *file;
4867         int rescan;
4868
4869         file = state->file;
4870         raw_next_token(state, file, tk);
4871         do {
4872                 rescan = 0;
4873                 file = state->file;
4874                 /* Exit out of an include directive or macro call */
4875                 if ((tk->tok == TOK_EOF) && 
4876                         (file != state->macro_file) && file->prev) 
4877                 {
4878                         state->file = file->prev;
4879                         /* file->basename is used keep it */
4880                         xfree(file->dirname);
4881                         xfree(file->buf);
4882                         xfree(file);
4883                         file = 0;
4884                         raw_next_token(state, state->file, tk);
4885                         rescan = 1;
4886                 }
4887         } while(rescan);
4888 }
4889
4890 static void pp_token(struct compile_state *state, struct token *tk)
4891 {
4892         struct file_state *file;
4893         int rescan;
4894
4895         raw_token(state, tk);
4896         do {
4897                 rescan = 0;
4898                 file = state->file;
4899                 if (tk->tok == TOK_SPACE) {
4900                         raw_token(state, tk);
4901                         rescan = 1;
4902                 }
4903                 else if (tk->tok == TOK_IDENT) {
4904                         if (state->token_base == 0) {
4905                                 ident_to_keyword(state, tk);
4906                         } else {
4907                                 ident_to_macro(state, tk);
4908                         }
4909                 }
4910         } while(rescan);
4911 }
4912
4913 static void preprocess(struct compile_state *state, struct token *tk);
4914
4915 static void token(struct compile_state *state, struct token *tk)
4916 {
4917         int rescan;
4918         pp_token(state, tk);
4919         do {
4920                 rescan = 0;
4921                 /* Process a macro directive */
4922                 if (tk->tok == TOK_MACRO) {
4923                         /* Only match preprocessor directives at the start of a line */
4924                         const char *ptr;
4925                         ptr = state->file->line_start;
4926                         while((ptr < tk->pos)
4927                                 && spacep(get_char(state->file, ptr)))
4928                         {
4929                                 ptr = next_char(state->file, ptr, 1);
4930                         }
4931                         if (ptr == tk->pos) {
4932                                 preprocess(state, tk);
4933                                 rescan = 1;
4934                         }
4935                 }
4936                 /* Expand a macro call */
4937                 else if (tk->ident && tk->ident->sym_define) {
4938                         rescan = compile_macro(state, &state->file, tk);
4939                         if (rescan) {
4940                                 pp_token(state, tk);
4941                         }
4942                 }
4943                 /* Eat tokens disabled by the preprocessor 
4944                  * (Unless we are parsing a preprocessor directive 
4945                  */
4946                 else if (if_eat(state) && (state->token_base == 0)) {
4947                         pp_token(state, tk);
4948                         rescan = 1;
4949                 }
4950                 /* Make certain EOL only shows up in preprocessor directives */
4951                 else if ((tk->tok == TOK_EOL) && (state->token_base == 0)) {
4952                         pp_token(state, tk);
4953                         rescan = 1;
4954                 }
4955                 /* Error on unknown tokens */
4956                 else if (tk->tok == TOK_UNKNOWN) {
4957                         error(state, 0, "unknown token");
4958                 }
4959         } while(rescan);
4960 }
4961
4962
4963 static inline struct token *get_token(struct compile_state *state, int offset)
4964 {
4965         int index;
4966         index = state->token_base + offset;
4967         if (index >= sizeof(state->token)/sizeof(state->token[0])) {
4968                 internal_error(state, 0, "token array to small");
4969         }
4970         return &state->token[index];
4971 }
4972
4973 static struct token *do_eat_token(struct compile_state *state, int tok)
4974 {
4975         struct token *tk;
4976         int i;
4977         check_tok(state, get_token(state, 1), tok);
4978         
4979         /* Free the old token value */
4980         tk = get_token(state, 0);
4981         if (tk->str_len) {
4982                 memset((void *)tk->val.str, -1, tk->str_len);
4983                 xfree(tk->val.str);
4984         }
4985         /* Overwrite the old token with newer tokens */
4986         for(i = state->token_base; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4987                 state->token[i] = state->token[i + 1];
4988         }
4989         /* Clear the last token */
4990         memset(&state->token[i], 0, sizeof(state->token[i]));
4991         state->token[i].tok = -1;
4992
4993         /* Return the token */
4994         return tk;
4995 }
4996
4997 static int raw_peek(struct compile_state *state)
4998 {
4999         struct token *tk1;
5000         tk1 = get_token(state, 1);
5001         if (tk1->tok == -1) {
5002                 raw_token(state, tk1);
5003         }
5004         return tk1->tok;
5005 }
5006
5007 static struct token *raw_eat(struct compile_state *state, int tok)
5008 {
5009         raw_peek(state);
5010         return do_eat_token(state, tok);
5011 }
5012
5013 static int pp_peek(struct compile_state *state)
5014 {
5015         struct token *tk1;
5016         tk1 = get_token(state, 1);
5017         if (tk1->tok == -1) {
5018                 pp_token(state, tk1);
5019         }
5020         return tk1->tok;
5021 }
5022
5023 static struct token *pp_eat(struct compile_state *state, int tok)
5024 {
5025         pp_peek(state);
5026         return do_eat_token(state, tok);
5027 }
5028
5029 static int peek(struct compile_state *state)
5030 {
5031         struct token *tk1;
5032         tk1 = get_token(state, 1);
5033         if (tk1->tok == -1) {
5034                 token(state, tk1);
5035         }
5036         return tk1->tok;
5037 }
5038
5039 static int peek2(struct compile_state *state)
5040 {
5041         struct token *tk1, *tk2;
5042         tk1 = get_token(state, 1);
5043         tk2 = get_token(state, 2);
5044         if (tk1->tok == -1) {
5045                 token(state, tk1);
5046         }
5047         if (tk2->tok == -1) {
5048                 token(state, tk2);
5049         }
5050         return tk2->tok;
5051 }
5052
5053 static struct token *eat(struct compile_state *state, int tok)
5054 {
5055         peek(state);
5056         return do_eat_token(state, tok);
5057 }
5058
5059 static void compile_file(struct compile_state *state, const char *filename, int local)
5060 {
5061         char cwd[MAX_CWD_SIZE];
5062         const char *subdir, *base;
5063         int subdir_len;
5064         struct file_state *file;
5065         char *basename;
5066         file = xmalloc(sizeof(*file), "file_state");
5067
5068         base = strrchr(filename, '/');
5069         subdir = filename;
5070         if (base != 0) {
5071                 subdir_len = base - filename;
5072                 base++;
5073         }
5074         else {
5075                 base = filename;
5076                 subdir_len = 0;
5077         }
5078         basename = xmalloc(strlen(base) +1, "basename");
5079         strcpy(basename, base);
5080         file->basename = basename;
5081
5082         if (getcwd(cwd, sizeof(cwd)) == 0) {
5083                 die("cwd buffer to small");
5084         }
5085         if ((subdir[0] == '/') || ((subdir[1] == ':') && ((subdir[2] == '/') || (subdir[2] == '\\')))) {
5086                 file->dirname = xmalloc(subdir_len + 1, "dirname");
5087                 memcpy(file->dirname, subdir, subdir_len);
5088                 file->dirname[subdir_len] = '\0';
5089         }
5090         else {
5091                 const char *dir;
5092                 int dirlen;
5093                 const char **path;
5094                 /* Find the appropriate directory... */
5095                 dir = 0;
5096                 if (!state->file && exists(cwd, filename)) {
5097                         dir = cwd;
5098                 }
5099                 if (local && state->file && exists(state->file->dirname, filename)) {
5100                         dir = state->file->dirname;
5101                 }
5102                 for(path = state->compiler->include_paths; !dir && *path; path++) {
5103                         if (exists(*path, filename)) {
5104                                 dir = *path;
5105                         }
5106                 }
5107                 if (!dir) {
5108                         error(state, 0, "Cannot open `%s'\n", filename);
5109                 }
5110                 dirlen = strlen(dir);
5111                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5112                 memcpy(file->dirname, dir, dirlen);
5113                 file->dirname[dirlen] = '/';
5114                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5115                 file->dirname[dirlen + 1 + subdir_len] = '\0';
5116         }
5117         file->buf = slurp_file(file->dirname, file->basename, &file->size);
5118
5119         file->pos = file->buf;
5120         file->line_start = file->pos;
5121         file->line = 1;
5122
5123         file->report_line = 1;
5124         file->report_name = file->basename;
5125         file->report_dir  = file->dirname;
5126         file->macro       = 0;
5127         file->trigraphs   = (state->compiler->flags & COMPILER_TRIGRAPHS)? 1: 0;
5128         file->join_lines  = 1;
5129
5130         file->prev = state->file;
5131         state->file = file;
5132 }
5133
5134 static struct triple *constant_expr(struct compile_state *state);
5135 static void integral(struct compile_state *state, struct triple *def);
5136
5137 static int mcexpr(struct compile_state *state)
5138 {
5139         struct triple *cvalue;
5140         cvalue = constant_expr(state);
5141         integral(state, cvalue);
5142         if (cvalue->op != OP_INTCONST) {
5143                 error(state, 0, "integer constant expected");
5144         }
5145         return cvalue->u.cval != 0;
5146 }
5147
5148 static void preprocess(struct compile_state *state, struct token *current_token)
5149 {
5150         /* Doing much more with the preprocessor would require
5151          * a parser and a major restructuring.
5152          * Postpone that for later.
5153          */
5154         int old_token_base;
5155         int tok;
5156         
5157         state->macro_file = state->file;
5158
5159         old_token_base = state->token_base;
5160         state->token_base = current_token - state->token;
5161
5162         tok = pp_peek(state);
5163         switch(tok) {
5164         case TOK_LIT_INT:
5165         {
5166                 struct token *tk;
5167                 int override_line;
5168                 tk = pp_eat(state, TOK_LIT_INT);
5169                 override_line = strtoul(tk->val.str, 0, 10);
5170                 /* I have a preprocessor  line marker parse it */
5171                 if (pp_peek(state) == TOK_LIT_STRING) {
5172                         const char *token, *base;
5173                         char *name, *dir;
5174                         int name_len, dir_len;
5175                         tk = pp_eat(state, TOK_LIT_STRING);
5176                         name = xmalloc(tk->str_len, "report_name");
5177                         token = tk->val.str + 1;
5178                         base = strrchr(token, '/');
5179                         name_len = tk->str_len -2;
5180                         if (base != 0) {
5181                                 dir_len = base - token;
5182                                 base++;
5183                                 name_len -= base - token;
5184                         } else {
5185                                 dir_len = 0;
5186                                 base = token;
5187                         }
5188                         memcpy(name, base, name_len);
5189                         name[name_len] = '\0';
5190                         dir = xmalloc(dir_len + 1, "report_dir");
5191                         memcpy(dir, token, dir_len);
5192                         dir[dir_len] = '\0';
5193                         state->file->report_line = override_line - 1;
5194                         state->file->report_name = name;
5195                         state->file->report_dir = dir;
5196                         state->file->macro      = 0;
5197                 }
5198                 break;
5199         }
5200         case TOK_MLINE:
5201         {
5202                 struct token *tk;
5203                 pp_eat(state, TOK_MLINE);
5204                 tk = eat(state, TOK_LIT_INT);
5205                 state->file->report_line = strtoul(tk->val.str, 0, 10) -1;
5206                 if (pp_peek(state) == TOK_LIT_STRING) {
5207                         const char *token, *base;
5208                         char *name, *dir;
5209                         int name_len, dir_len;
5210                         tk = pp_eat(state, TOK_LIT_STRING);
5211                         name = xmalloc(tk->str_len, "report_name");
5212                         token = tk->val.str + 1;
5213                         base = strrchr(token, '/');
5214                         name_len = tk->str_len - 2;
5215                         if (base != 0) {
5216                                 dir_len = base - token;
5217                                 base++;
5218                                 name_len -= base - token;
5219                         } else {
5220                                 dir_len = 0;
5221                                 base = token;
5222                         }
5223                         memcpy(name, base, name_len);
5224                         name[name_len] = '\0';
5225                         dir = xmalloc(dir_len + 1, "report_dir");
5226                         memcpy(dir, token, dir_len);
5227                         dir[dir_len] = '\0';
5228                         state->file->report_name = name;
5229                         state->file->report_dir = dir;
5230                         state->file->macro      = 0;
5231                 }
5232                 break;
5233         }
5234         case TOK_MUNDEF:
5235         {
5236                 struct hash_entry *ident;
5237                 pp_eat(state, TOK_MUNDEF);
5238                 if (if_eat(state))  /* quit early when #if'd out */
5239                         break;
5240                 
5241                 ident = pp_eat(state, TOK_MIDENT)->ident;
5242
5243                 undef_macro(state, ident);
5244                 break;
5245         }
5246         case TOK_MPRAGMA:
5247                 pp_eat(state, TOK_MPRAGMA);
5248                 if (if_eat(state))  /* quit early when #if'd out */
5249                         break;
5250                 warning(state, 0, "Ignoring pragma"); 
5251                 break;
5252         case TOK_MELIF:
5253                 pp_eat(state, TOK_MELIF);
5254                 reenter_if(state, "#elif");
5255                 if (if_eat(state))   /* quit early when #if'd out */
5256                         break;
5257                 /* If the #if was taken the #elif just disables the following code */
5258                 if (if_value(state)) {
5259                         eat_tokens(state, TOK_MENDIF);
5260                 }
5261                 /* If the previous #if was not taken see if the #elif enables the 
5262                  * trailing code.
5263                  */
5264                 else {
5265                         set_if_value(state, mcexpr(state));
5266                         if (!if_value(state)) {
5267                                 eat_tokens(state, TOK_MELSE);
5268                         }
5269                 }
5270                 break;
5271         case TOK_MIF:
5272                 pp_eat(state, TOK_MIF);
5273                 enter_if(state);
5274                 if (if_eat(state))  /* quit early when #if'd out */
5275                         break;
5276                 set_if_value(state, mcexpr(state));
5277                 if (!if_value(state)) {
5278                         eat_tokens(state, TOK_MELSE);
5279                 }
5280                 break;
5281         case TOK_MIFNDEF:
5282         {
5283                 struct hash_entry *ident;
5284
5285                 pp_eat(state, TOK_MIFNDEF);
5286                 enter_if(state);
5287                 if (if_eat(state))  /* quit early when #if'd out */
5288                         break;
5289                 ident = pp_eat(state, TOK_MIDENT)->ident;
5290                 set_if_value(state, ident->sym_define == 0);
5291                 if (!if_value(state)) {
5292                         eat_tokens(state, TOK_MELSE);
5293                 }
5294                 break;
5295         }
5296         case TOK_MIFDEF:
5297         {
5298                 struct hash_entry *ident;
5299                 pp_eat(state, TOK_MIFDEF);
5300                 enter_if(state);
5301                 if (if_eat(state))  /* quit early when #if'd out */
5302                         break;
5303                 ident = pp_eat(state, TOK_MIDENT)->ident;
5304                 set_if_value(state, ident->sym_define != 0);
5305                 if (!if_value(state)) {
5306                         eat_tokens(state, TOK_MELSE);
5307                 }
5308                 break;
5309         }
5310         case TOK_MELSE:
5311                 pp_eat(state, TOK_MELSE);
5312                 enter_else(state, "#else");
5313                 if (!if_eat(state) && if_value(state)) {
5314                         eat_tokens(state, TOK_MENDIF);
5315                 }
5316                 break;
5317         case TOK_MENDIF:
5318                 pp_eat(state, TOK_MENDIF);
5319                 exit_if(state, "#endif");
5320                 break;
5321         case TOK_MDEFINE:
5322         {
5323                 struct hash_entry *ident;
5324                 struct macro_arg *args, **larg;
5325                 const char *mstart, *mend;
5326                 int argc;
5327
5328                 pp_eat(state, TOK_MDEFINE);
5329                 if (if_eat(state))  /* quit early when #if'd out */
5330                         break;
5331                 ident = pp_eat(state, TOK_MIDENT)->ident;
5332                 argc = -1;
5333                 args = 0;
5334                 larg = &args;
5335
5336                 /* Parse macro parameters */
5337                 if (raw_peek(state) == TOK_LPAREN) {
5338                         raw_eat(state, TOK_LPAREN);
5339                         argc += 1;
5340
5341                         for(;;) {
5342                                 struct macro_arg *narg, *arg;
5343                                 struct hash_entry *aident;
5344                                 int tok;
5345
5346                                 tok = pp_peek(state);
5347                                 if (!args && (tok == TOK_RPAREN)) {
5348                                         break;
5349                                 }
5350                                 else if (tok == TOK_DOTS) {
5351                                         pp_eat(state, TOK_DOTS);
5352                                         aident = state->i___VA_ARGS__;
5353                                 } 
5354                                 else {
5355                                         aident = pp_eat(state, TOK_MIDENT)->ident;
5356                                 }
5357                                 
5358                                 narg = xcmalloc(sizeof(*arg), "macro arg");
5359                                 narg->ident = aident;
5360
5361                                 /* Verify I don't have a duplicate identifier */
5362                                 for(arg = args; arg; arg = arg->next) {
5363                                         if (arg->ident == narg->ident) {
5364                                                 error(state, 0, "Duplicate macro arg `%s'",
5365                                                         narg->ident->name);
5366                                         }
5367                                 }
5368                                 /* Add the new argument to the end of the list */
5369                                 *larg = narg;
5370                                 larg = &narg->next;
5371                                 argc += 1;
5372
5373                                 if ((aident == state->i___VA_ARGS__) ||
5374                                         (pp_peek(state) != TOK_COMMA)) {
5375                                         break;
5376                                 }
5377                                 pp_eat(state, TOK_COMMA);
5378                         }
5379                         pp_eat(state, TOK_RPAREN);
5380                 }
5381                 /* Remove leading whitespace */
5382                 while(raw_peek(state) == TOK_SPACE) {
5383                         raw_eat(state, TOK_SPACE);
5384                 }
5385
5386                 /* Remember the start of the macro body */
5387                 tok = raw_peek(state);
5388                 mend = mstart = get_token(state, 1)->pos;
5389
5390                 /* Find the end of the macro */
5391                 for(tok = raw_peek(state); tok != TOK_EOL; tok = raw_peek(state)) {
5392                         raw_eat(state, tok);
5393                         /* Remember the end of the last non space token */
5394                         raw_peek(state);
5395                         if (tok != TOK_SPACE) {
5396                                 mend = get_token(state, 1)->pos;
5397                         }
5398                 }
5399                 
5400                 /* Now that I have found the body defined the token */
5401                 do_define_macro(state, ident,
5402                         char_strdup(state->file, mstart, mend, "macro buf"),
5403                         argc, args);
5404                 break;
5405         }
5406         case TOK_MERROR:
5407         {
5408                 const char *start, *end;
5409                 int len;
5410                 
5411                 pp_eat(state, TOK_MERROR);
5412                 /* Find the start of the line */
5413                 raw_peek(state);
5414                 start = get_token(state, 1)->pos;
5415
5416                 /* Find the end of the line */
5417                 while((tok = raw_peek(state)) != TOK_EOL) {
5418                         raw_eat(state, tok);
5419                 }
5420                 end = get_token(state, 1)->pos;
5421                 len = end - start;
5422                 if (!if_eat(state)) {
5423                         error(state, 0, "%*.*s", len, len, start);
5424                 }
5425                 break;
5426         }
5427         case TOK_MWARNING:
5428         {
5429                 const char *start, *end;
5430                 int len;
5431                 
5432                 pp_eat(state, TOK_MWARNING);
5433
5434                 /* Find the start of the line */
5435                 raw_peek(state);
5436                 start = get_token(state, 1)->pos;
5437                  
5438                 /* Find the end of the line */
5439                 while((tok = raw_peek(state)) != TOK_EOL) {
5440                         raw_eat(state, tok);
5441                 }
5442                 end = get_token(state, 1)->pos;
5443                 len = end - start;
5444                 if (!if_eat(state)) {
5445                         warning(state, 0, "%*.*s", len, len, start);
5446                 }
5447                 break;
5448         }
5449         case TOK_MINCLUDE:
5450         {
5451                 char *name;
5452                 int local;
5453                 local = 0;
5454                 name = 0;
5455
5456                 pp_eat(state, TOK_MINCLUDE);
5457                 if (if_eat(state)) {
5458                         /* Find the end of the line */
5459                         while((tok = raw_peek(state)) != TOK_EOL) {
5460                                 raw_eat(state, tok);
5461                         }
5462                         break;
5463                 }
5464                 tok = peek(state);
5465                 if (tok == TOK_LIT_STRING) {
5466                         struct token *tk;
5467                         const char *token;
5468                         int name_len;
5469                         tk = eat(state, TOK_LIT_STRING);
5470                         name = xmalloc(tk->str_len, "include");
5471                         token = tk->val.str +1;
5472                         name_len = tk->str_len -2;
5473                         if (*token == '"') {
5474                                 token++;
5475                                 name_len--;
5476                         }
5477                         memcpy(name, token, name_len);
5478                         name[name_len] = '\0';
5479                         local = 1;
5480                 }
5481                 else if (tok == TOK_LESS) {
5482                         struct macro_buf buf;
5483                         eat(state, TOK_LESS);
5484
5485                         buf.len = 40;
5486                         buf.str = xmalloc(buf.len, "include");
5487                         buf.pos = 0;
5488
5489                         tok = peek(state);
5490                         while((tok != TOK_MORE) &&
5491                                 (tok != TOK_EOL) && (tok != TOK_EOF))
5492                         {
5493                                 struct token *tk;
5494                                 tk = eat(state, tok);
5495                                 append_macro_chars(state, "include", &buf,
5496                                         state->file, tk->pos, state->file->pos);
5497                                 tok = peek(state);
5498                         }
5499                         append_macro_text(state, "include", &buf, "\0", 1);
5500                         if (peek(state) != TOK_MORE) {
5501                                 error(state, 0, "Unterminated include directive");
5502                         }
5503                         eat(state, TOK_MORE);
5504                         local = 0;
5505                         name = buf.str;
5506                 }
5507                 else {
5508                         error(state, 0, "Invalid include directive");
5509                 }
5510                 /* Error if there are any tokens after the include */
5511                 if (pp_peek(state) != TOK_EOL) {
5512                         error(state, 0, "garbage after include directive");
5513                 }
5514                 if (!if_eat(state)) {
5515                         compile_file(state, name, local);
5516                 }
5517                 xfree(name);
5518                 break;
5519         }
5520         case TOK_EOL:
5521                 /* Ignore # without a follwing ident */
5522                 break;
5523         default:
5524         {
5525                 const char *name1, *name2;
5526                 name1 = tokens[tok];
5527                 name2 = "";
5528                 if (tok == TOK_MIDENT) {
5529                         name2 = get_token(state, 1)->ident->name;
5530                 }
5531                 error(state, 0, "Invalid preprocessor directive: %s %s", 
5532                         name1, name2);
5533                 break;
5534         }
5535         }
5536         /* Consume the rest of the macro line */
5537         do {
5538                 tok = pp_peek(state);
5539                 pp_eat(state, tok);
5540         } while((tok != TOK_EOF) && (tok != TOK_EOL));
5541         state->token_base = old_token_base;
5542         state->macro_file = NULL;
5543         return;
5544 }
5545
5546 /* Type helper functions */
5547
5548 static struct type *new_type(
5549         unsigned int type, struct type *left, struct type *right)
5550 {
5551         struct type *result;
5552         result = xmalloc(sizeof(*result), "type");
5553         result->type = type;
5554         result->left = left;
5555         result->right = right;
5556         result->field_ident = 0;
5557         result->type_ident = 0;
5558         result->elements = 0;
5559         return result;
5560 }
5561
5562 static struct type *clone_type(unsigned int specifiers, struct type *old)
5563 {
5564         struct type *result;
5565         result = xmalloc(sizeof(*result), "type");
5566         memcpy(result, old, sizeof(*result));
5567         result->type &= TYPE_MASK;
5568         result->type |= specifiers;
5569         return result;
5570 }
5571
5572 static struct type *dup_type(struct compile_state *state, struct type *orig)
5573 {
5574         struct type *new;
5575         new = xcmalloc(sizeof(*new), "type");
5576         new->type = orig->type;
5577         new->field_ident = orig->field_ident;
5578         new->type_ident  = orig->type_ident;
5579         new->elements    = orig->elements;
5580         if (orig->left) {
5581                 new->left = dup_type(state, orig->left);
5582         }
5583         if (orig->right) {
5584                 new->right = dup_type(state, orig->right);
5585         }
5586         return new;
5587 }
5588
5589
5590 static struct type *invalid_type(struct compile_state *state, struct type *type)
5591 {
5592         struct type *invalid, *member;
5593         invalid = 0;
5594         if (!type) {
5595                 internal_error(state, 0, "type missing?");
5596         }
5597         switch(type->type & TYPE_MASK) {
5598         case TYPE_VOID:
5599         case TYPE_CHAR:         case TYPE_UCHAR:
5600         case TYPE_SHORT:        case TYPE_USHORT:
5601         case TYPE_INT:          case TYPE_UINT:
5602         case TYPE_LONG:         case TYPE_ULONG:
5603         case TYPE_LLONG:        case TYPE_ULLONG:
5604         case TYPE_POINTER:
5605         case TYPE_ENUM:
5606                 break;
5607         case TYPE_BITFIELD:
5608                 invalid = invalid_type(state, type->left);
5609                 break;
5610         case TYPE_ARRAY:
5611                 invalid = invalid_type(state, type->left);
5612                 break;
5613         case TYPE_STRUCT:
5614         case TYPE_TUPLE:
5615                 member = type->left;
5616                 while(member && (invalid == 0) && 
5617                         ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5618                         invalid = invalid_type(state, member->left);
5619                         member = member->right;
5620                 }
5621                 if (!invalid) {
5622                         invalid = invalid_type(state, member);
5623                 }
5624                 break;
5625         case TYPE_UNION:
5626         case TYPE_JOIN:
5627                 member = type->left;
5628                 while(member && (invalid == 0) &&
5629                         ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5630                         invalid = invalid_type(state, member->left);
5631                         member = member->right;
5632                 }
5633                 if (!invalid) {
5634                         invalid = invalid_type(state, member);
5635                 }
5636                 break;
5637         default:
5638                 invalid = type;
5639                 break;
5640         }
5641         return invalid;
5642         
5643 }
5644
5645 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
5646 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5647 static inline ulong_t mask_uint(ulong_t x)
5648 {
5649         if (SIZEOF_INT < SIZEOF_LONG) {
5650                 ulong_t mask = (1ULL << ((ulong_t)(SIZEOF_INT))) -1;
5651                 x &= mask;
5652         }
5653         return x;
5654 }
5655 #define MASK_UINT(X)      (mask_uint(X))
5656 #define MASK_ULONG(X)    (X)
5657
5658 static struct type void_type    = { .type  = TYPE_VOID };
5659 static struct type char_type    = { .type  = TYPE_CHAR };
5660 static struct type uchar_type   = { .type  = TYPE_UCHAR };
5661 #if DEBUG_ROMCC_WARNING
5662 static struct type short_type   = { .type  = TYPE_SHORT };
5663 #endif
5664 static struct type ushort_type  = { .type  = TYPE_USHORT };
5665 static struct type int_type     = { .type  = TYPE_INT };
5666 static struct type uint_type    = { .type  = TYPE_UINT };
5667 static struct type long_type    = { .type  = TYPE_LONG };
5668 static struct type ulong_type   = { .type  = TYPE_ULONG };
5669 static struct type unknown_type = { .type  = TYPE_UNKNOWN };
5670
5671 static struct type void_ptr_type  = {
5672         .type = TYPE_POINTER,
5673         .left = &void_type,
5674 };
5675
5676 #if DEBUG_ROMCC_WARNING
5677 static struct type void_func_type = { 
5678         .type  = TYPE_FUNCTION,
5679         .left  = &void_type,
5680         .right = &void_type,
5681 };
5682 #endif
5683
5684 static size_t bits_to_bytes(size_t size)
5685 {
5686         return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5687 }
5688
5689 static struct triple *variable(struct compile_state *state, struct type *type)
5690 {
5691         struct triple *result;
5692         if ((type->type & STOR_MASK) != STOR_PERM) {
5693                 result = triple(state, OP_ADECL, type, 0, 0);
5694                 generate_lhs_pieces(state, result);
5695         }
5696         else {
5697                 result = triple(state, OP_SDECL, type, 0, 0);
5698         }
5699         return result;
5700 }
5701
5702 static void stor_of(FILE *fp, struct type *type)
5703 {
5704         switch(type->type & STOR_MASK) {
5705         case STOR_AUTO:
5706                 fprintf(fp, "auto ");
5707                 break;
5708         case STOR_STATIC:
5709                 fprintf(fp, "static ");
5710                 break;
5711         case STOR_LOCAL:
5712                 fprintf(fp, "local ");
5713                 break;
5714         case STOR_EXTERN:
5715                 fprintf(fp, "extern ");
5716                 break;
5717         case STOR_REGISTER:
5718                 fprintf(fp, "register ");
5719                 break;
5720         case STOR_TYPEDEF:
5721                 fprintf(fp, "typedef ");
5722                 break;
5723         case STOR_INLINE | STOR_LOCAL:
5724                 fprintf(fp, "inline ");
5725                 break;
5726         case STOR_INLINE | STOR_STATIC:
5727                 fprintf(fp, "static inline");
5728                 break;
5729         case STOR_INLINE | STOR_EXTERN:
5730                 fprintf(fp, "extern inline");
5731                 break;
5732         default:
5733                 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5734                 break;
5735         }
5736 }
5737 static void qual_of(FILE *fp, struct type *type)
5738 {
5739         if (type->type & QUAL_CONST) {
5740                 fprintf(fp, " const");
5741         }
5742         if (type->type & QUAL_VOLATILE) {
5743                 fprintf(fp, " volatile");
5744         }
5745         if (type->type & QUAL_RESTRICT) {
5746                 fprintf(fp, " restrict");
5747         }
5748 }
5749
5750 static void name_of(FILE *fp, struct type *type)
5751 {
5752         unsigned int base_type;
5753         base_type = type->type & TYPE_MASK;
5754         if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5755                 stor_of(fp, type);
5756         }
5757         switch(base_type) {
5758         case TYPE_VOID:
5759                 fprintf(fp, "void");
5760                 qual_of(fp, type);
5761                 break;
5762         case TYPE_CHAR:
5763                 fprintf(fp, "signed char");
5764                 qual_of(fp, type);
5765                 break;
5766         case TYPE_UCHAR:
5767                 fprintf(fp, "unsigned char");
5768                 qual_of(fp, type);
5769                 break;
5770         case TYPE_SHORT:
5771                 fprintf(fp, "signed short");
5772                 qual_of(fp, type);
5773                 break;
5774         case TYPE_USHORT:
5775                 fprintf(fp, "unsigned short");
5776                 qual_of(fp, type);
5777                 break;
5778         case TYPE_INT:
5779                 fprintf(fp, "signed int");
5780                 qual_of(fp, type);
5781                 break;
5782         case TYPE_UINT:
5783                 fprintf(fp, "unsigned int");
5784                 qual_of(fp, type);
5785                 break;
5786         case TYPE_LONG:
5787                 fprintf(fp, "signed long");
5788                 qual_of(fp, type);
5789                 break;
5790         case TYPE_ULONG:
5791                 fprintf(fp, "unsigned long");
5792                 qual_of(fp, type);
5793                 break;
5794         case TYPE_POINTER:
5795                 name_of(fp, type->left);
5796                 fprintf(fp, " * ");
5797                 qual_of(fp, type);
5798                 break;
5799         case TYPE_PRODUCT:
5800                 name_of(fp, type->left);
5801                 fprintf(fp, ", ");
5802                 name_of(fp, type->right);
5803                 break;
5804         case TYPE_OVERLAP:
5805                 name_of(fp, type->left);
5806                 fprintf(fp, ",| ");
5807                 name_of(fp, type->right);
5808                 break;
5809         case TYPE_ENUM:
5810                 fprintf(fp, "enum %s", 
5811                         (type->type_ident)? type->type_ident->name : "");
5812                 qual_of(fp, type);
5813                 break;
5814         case TYPE_STRUCT:
5815                 fprintf(fp, "struct %s { ", 
5816                         (type->type_ident)? type->type_ident->name : "");
5817                 name_of(fp, type->left);
5818                 fprintf(fp, " } ");
5819                 qual_of(fp, type);
5820                 break;
5821         case TYPE_UNION:
5822                 fprintf(fp, "union %s { ", 
5823                         (type->type_ident)? type->type_ident->name : "");
5824                 name_of(fp, type->left);
5825                 fprintf(fp, " } ");
5826                 qual_of(fp, type);
5827                 break;
5828         case TYPE_FUNCTION:
5829                 name_of(fp, type->left);
5830                 fprintf(fp, " (*)(");
5831                 name_of(fp, type->right);
5832                 fprintf(fp, ")");
5833                 break;
5834         case TYPE_ARRAY:
5835                 name_of(fp, type->left);
5836                 fprintf(fp, " [%ld]", (long)(type->elements));
5837                 break;
5838         case TYPE_TUPLE:
5839                 fprintf(fp, "tuple { "); 
5840                 name_of(fp, type->left);
5841                 fprintf(fp, " } ");
5842                 qual_of(fp, type);
5843                 break;
5844         case TYPE_JOIN:
5845                 fprintf(fp, "join { ");
5846                 name_of(fp, type->left);
5847                 fprintf(fp, " } ");
5848                 qual_of(fp, type);
5849                 break;
5850         case TYPE_BITFIELD:
5851                 name_of(fp, type->left);
5852                 fprintf(fp, " : %d ", type->elements);
5853                 qual_of(fp, type);
5854                 break;
5855         case TYPE_UNKNOWN:
5856                 fprintf(fp, "unknown_t");
5857                 break;
5858         default:
5859                 fprintf(fp, "????: %x", base_type);
5860                 break;
5861         }
5862         if (type->field_ident && type->field_ident->name) {
5863                 fprintf(fp, " .%s", type->field_ident->name);
5864         }
5865 }
5866
5867 static size_t align_of(struct compile_state *state, struct type *type)
5868 {
5869         size_t align;
5870         align = 0;
5871         switch(type->type & TYPE_MASK) {
5872         case TYPE_VOID:
5873                 align = 1;
5874                 break;
5875         case TYPE_BITFIELD:
5876                 align = 1;
5877                 break;
5878         case TYPE_CHAR:
5879         case TYPE_UCHAR:
5880                 align = ALIGNOF_CHAR;
5881                 break;
5882         case TYPE_SHORT:
5883         case TYPE_USHORT:
5884                 align = ALIGNOF_SHORT;
5885                 break;
5886         case TYPE_INT:
5887         case TYPE_UINT:
5888         case TYPE_ENUM:
5889                 align = ALIGNOF_INT;
5890                 break;
5891         case TYPE_LONG:
5892         case TYPE_ULONG:
5893                 align = ALIGNOF_LONG;
5894                 break;
5895         case TYPE_POINTER:
5896                 align = ALIGNOF_POINTER;
5897                 break;
5898         case TYPE_PRODUCT:
5899         case TYPE_OVERLAP:
5900         {
5901                 size_t left_align, right_align;
5902                 left_align  = align_of(state, type->left);
5903                 right_align = align_of(state, type->right);
5904                 align = (left_align >= right_align) ? left_align : right_align;
5905                 break;
5906         }
5907         case TYPE_ARRAY:
5908                 align = align_of(state, type->left);
5909                 break;
5910         case TYPE_STRUCT:
5911         case TYPE_TUPLE:
5912         case TYPE_UNION:
5913         case TYPE_JOIN:
5914                 align = align_of(state, type->left);
5915                 break;
5916         default:
5917                 error(state, 0, "alignof not yet defined for type\n");
5918                 break;
5919         }
5920         return align;
5921 }
5922
5923 static size_t reg_align_of(struct compile_state *state, struct type *type)
5924 {
5925         size_t align;
5926         align = 0;
5927         switch(type->type & TYPE_MASK) {
5928         case TYPE_VOID:
5929                 align = 1;
5930                 break;
5931         case TYPE_BITFIELD:
5932                 align = 1;
5933                 break;
5934         case TYPE_CHAR:
5935         case TYPE_UCHAR:
5936                 align = REG_ALIGNOF_CHAR;
5937                 break;
5938         case TYPE_SHORT:
5939         case TYPE_USHORT:
5940                 align = REG_ALIGNOF_SHORT;
5941                 break;
5942         case TYPE_INT:
5943         case TYPE_UINT:
5944         case TYPE_ENUM:
5945                 align = REG_ALIGNOF_INT;
5946                 break;
5947         case TYPE_LONG:
5948         case TYPE_ULONG:
5949                 align = REG_ALIGNOF_LONG;
5950                 break;
5951         case TYPE_POINTER:
5952                 align = REG_ALIGNOF_POINTER;
5953                 break;
5954         case TYPE_PRODUCT:
5955         case TYPE_OVERLAP:
5956         {
5957                 size_t left_align, right_align;
5958                 left_align  = reg_align_of(state, type->left);
5959                 right_align = reg_align_of(state, type->right);
5960                 align = (left_align >= right_align) ? left_align : right_align;
5961                 break;
5962         }
5963         case TYPE_ARRAY:
5964                 align = reg_align_of(state, type->left);
5965                 break;
5966         case TYPE_STRUCT:
5967         case TYPE_UNION:
5968         case TYPE_TUPLE:
5969         case TYPE_JOIN:
5970                 align = reg_align_of(state, type->left);
5971                 break;
5972         default:
5973                 error(state, 0, "alignof not yet defined for type\n");
5974                 break;
5975         }
5976         return align;
5977 }
5978
5979 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
5980 {
5981         return bits_to_bytes(align_of(state, type));
5982 }
5983 static size_t size_of(struct compile_state *state, struct type *type);
5984 static size_t reg_size_of(struct compile_state *state, struct type *type);
5985
5986 static size_t needed_padding(struct compile_state *state, 
5987         struct type *type, size_t offset)
5988 {
5989         size_t padding, align;
5990         align = align_of(state, type);
5991         /* Align to the next machine word if the bitfield does completely
5992          * fit into the current word.
5993          */
5994         if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
5995                 size_t size;
5996                 size = size_of(state, type);
5997                 if ((offset + type->elements)/size != offset/size) {
5998                         align = size;
5999                 }
6000         }
6001         padding = 0;
6002         if (offset % align) {
6003                 padding = align - (offset % align);
6004         }
6005         return padding;
6006 }
6007
6008 static size_t reg_needed_padding(struct compile_state *state, 
6009         struct type *type, size_t offset)
6010 {
6011         size_t padding, align;
6012         align = reg_align_of(state, type);
6013         /* Align to the next register word if the bitfield does completely
6014          * fit into the current register.
6015          */
6016         if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6017                 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG))) 
6018         {
6019                 align = REG_SIZEOF_REG;
6020         }
6021         padding = 0;
6022         if (offset % align) {
6023                 padding = align - (offset % align);
6024         }
6025         return padding;
6026 }
6027
6028 static size_t size_of(struct compile_state *state, struct type *type)
6029 {
6030         size_t size;
6031         size = 0;
6032         switch(type->type & TYPE_MASK) {
6033         case TYPE_VOID:
6034                 size = 0;
6035                 break;
6036         case TYPE_BITFIELD:
6037                 size = type->elements;
6038                 break;
6039         case TYPE_CHAR:
6040         case TYPE_UCHAR:
6041                 size = SIZEOF_CHAR;
6042                 break;
6043         case TYPE_SHORT:
6044         case TYPE_USHORT:
6045                 size = SIZEOF_SHORT;
6046                 break;
6047         case TYPE_INT:
6048         case TYPE_UINT:
6049         case TYPE_ENUM:
6050                 size = SIZEOF_INT;
6051                 break;
6052         case TYPE_LONG:
6053         case TYPE_ULONG:
6054                 size = SIZEOF_LONG;
6055                 break;
6056         case TYPE_POINTER:
6057                 size = SIZEOF_POINTER;
6058                 break;
6059         case TYPE_PRODUCT:
6060         {
6061                 size_t pad;
6062                 size = 0;
6063                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6064                         pad = needed_padding(state, type->left, size);
6065                         size = size + pad + size_of(state, type->left);
6066                         type = type->right;
6067                 }
6068                 pad = needed_padding(state, type, size);
6069                 size = size + pad + size_of(state, type);
6070                 break;
6071         }
6072         case TYPE_OVERLAP:
6073         {
6074                 size_t size_left, size_right;
6075                 size_left = size_of(state, type->left);
6076                 size_right = size_of(state, type->right);
6077                 size = (size_left >= size_right)? size_left : size_right;
6078                 break;
6079         }
6080         case TYPE_ARRAY:
6081                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6082                         internal_error(state, 0, "Invalid array type");
6083                 } else {
6084                         size = size_of(state, type->left) * type->elements;
6085                 }
6086                 break;
6087         case TYPE_STRUCT:
6088         case TYPE_TUPLE:
6089         {
6090                 size_t pad;
6091                 size = size_of(state, type->left);
6092                 /* Pad structures so their size is a multiples of their alignment */
6093                 pad = needed_padding(state, type, size);
6094                 size = size + pad;
6095                 break;
6096         }
6097         case TYPE_UNION:
6098         case TYPE_JOIN:
6099         {
6100                 size_t pad;
6101                 size = size_of(state, type->left);
6102                 /* Pad unions so their size is a multiple of their alignment */
6103                 pad = needed_padding(state, type, size);
6104                 size = size + pad;
6105                 break;
6106         }
6107         default:
6108                 internal_error(state, 0, "sizeof not yet defined for type");
6109                 break;
6110         }
6111         return size;
6112 }
6113
6114 static size_t reg_size_of(struct compile_state *state, struct type *type)
6115 {
6116         size_t size;
6117         size = 0;
6118         switch(type->type & TYPE_MASK) {
6119         case TYPE_VOID:
6120                 size = 0;
6121                 break;
6122         case TYPE_BITFIELD:
6123                 size = type->elements;
6124                 break;
6125         case TYPE_CHAR:
6126         case TYPE_UCHAR:
6127                 size = REG_SIZEOF_CHAR;
6128                 break;
6129         case TYPE_SHORT:
6130         case TYPE_USHORT:
6131                 size = REG_SIZEOF_SHORT;
6132                 break;
6133         case TYPE_INT:
6134         case TYPE_UINT:
6135         case TYPE_ENUM:
6136                 size = REG_SIZEOF_INT;
6137                 break;
6138         case TYPE_LONG:
6139         case TYPE_ULONG:
6140                 size = REG_SIZEOF_LONG;
6141                 break;
6142         case TYPE_POINTER:
6143                 size = REG_SIZEOF_POINTER;
6144                 break;
6145         case TYPE_PRODUCT:
6146         {
6147                 size_t pad;
6148                 size = 0;
6149                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6150                         pad = reg_needed_padding(state, type->left, size);
6151                         size = size + pad + reg_size_of(state, type->left);
6152                         type = type->right;
6153                 }
6154                 pad = reg_needed_padding(state, type, size);
6155                 size = size + pad + reg_size_of(state, type);
6156                 break;
6157         }
6158         case TYPE_OVERLAP:
6159         {
6160                 size_t size_left, size_right;
6161                 size_left  = reg_size_of(state, type->left);
6162                 size_right = reg_size_of(state, type->right);
6163                 size = (size_left >= size_right)? size_left : size_right;
6164                 break;
6165         }
6166         case TYPE_ARRAY:
6167                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6168                         internal_error(state, 0, "Invalid array type");
6169                 } else {
6170                         size = reg_size_of(state, type->left) * type->elements;
6171                 }
6172                 break;
6173         case TYPE_STRUCT:
6174         case TYPE_TUPLE:
6175         {
6176                 size_t pad;
6177                 size = reg_size_of(state, type->left);
6178                 /* Pad structures so their size is a multiples of their alignment */
6179                 pad = reg_needed_padding(state, type, size);
6180                 size = size + pad;
6181                 break;
6182         }
6183         case TYPE_UNION:
6184         case TYPE_JOIN:
6185         {
6186                 size_t pad;
6187                 size = reg_size_of(state, type->left);
6188                 /* Pad unions so their size is a multiple of their alignment */
6189                 pad = reg_needed_padding(state, type, size);
6190                 size = size + pad;
6191                 break;
6192         }
6193         default:
6194                 internal_error(state, 0, "sizeof not yet defined for type");
6195                 break;
6196         }
6197         return size;
6198 }
6199
6200 static size_t registers_of(struct compile_state *state, struct type *type)
6201 {
6202         size_t registers;
6203         registers = reg_size_of(state, type);
6204         registers += REG_SIZEOF_REG - 1;
6205         registers /= REG_SIZEOF_REG;
6206         return registers;
6207 }
6208
6209 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6210 {
6211         return bits_to_bytes(size_of(state, type));
6212 }
6213
6214 static size_t field_offset(struct compile_state *state, 
6215         struct type *type, struct hash_entry *field)
6216 {
6217         struct type *member;
6218         size_t size;
6219
6220         size = 0;
6221         member = 0;
6222         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6223                 member = type->left;
6224                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6225                         size += needed_padding(state, member->left, size);
6226                         if (member->left->field_ident == field) {
6227                                 member = member->left;
6228                                 break;
6229                         }
6230                         size += size_of(state, member->left);
6231                         member = member->right;
6232                 }
6233                 size += needed_padding(state, member, size);
6234         }
6235         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6236                 member = type->left;
6237                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6238                         if (member->left->field_ident == field) {
6239                                 member = member->left;
6240                                 break;
6241                         }
6242                         member = member->right;
6243                 }
6244         }
6245         else {
6246                 internal_error(state, 0, "field_offset only works on structures and unions");
6247         }
6248
6249         if (!member || (member->field_ident != field)) {
6250                 error(state, 0, "member %s not present", field->name);
6251         }
6252         return size;
6253 }
6254
6255 static size_t field_reg_offset(struct compile_state *state, 
6256         struct type *type, struct hash_entry *field)
6257 {
6258         struct type *member;
6259         size_t size;
6260
6261         size = 0;
6262         member = 0;
6263         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6264                 member = type->left;
6265                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6266                         size += reg_needed_padding(state, member->left, size);
6267                         if (member->left->field_ident == field) {
6268                                 member = member->left;
6269                                 break;
6270                         }
6271                         size += reg_size_of(state, member->left);
6272                         member = member->right;
6273                 }
6274         }
6275         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6276                 member = type->left;
6277                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6278                         if (member->left->field_ident == field) {
6279                                 member = member->left;
6280                                 break;
6281                         }
6282                         member = member->right;
6283                 }
6284         }
6285         else {
6286                 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6287         }
6288
6289         size += reg_needed_padding(state, member, size);
6290         if (!member || (member->field_ident != field)) {
6291                 error(state, 0, "member %s not present", field->name);
6292         }
6293         return size;
6294 }
6295
6296 static struct type *field_type(struct compile_state *state, 
6297         struct type *type, struct hash_entry *field)
6298 {
6299         struct type *member;
6300
6301         member = 0;
6302         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6303                 member = type->left;
6304                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6305                         if (member->left->field_ident == field) {
6306                                 member = member->left;
6307                                 break;
6308                         }
6309                         member = member->right;
6310                 }
6311         }
6312         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6313                 member = type->left;
6314                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6315                         if (member->left->field_ident == field) {
6316                                 member = member->left;
6317                                 break;
6318                         }
6319                         member = member->right;
6320                 }
6321         }
6322         else {
6323                 internal_error(state, 0, "field_type only works on structures and unions");
6324         }
6325         
6326         if (!member || (member->field_ident != field)) {
6327                 error(state, 0, "member %s not present", field->name);
6328         }
6329         return member;
6330 }
6331
6332 static size_t index_offset(struct compile_state *state, 
6333         struct type *type, ulong_t index)
6334 {
6335         struct type *member;
6336         size_t size;
6337         size = 0;
6338         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6339                 size = size_of(state, type->left) * index;
6340         }
6341         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6342                 ulong_t i;
6343                 member = type->left;
6344                 i = 0;
6345                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6346                         size += needed_padding(state, member->left, size);
6347                         if (i == index) {
6348                                 member = member->left;
6349                                 break;
6350                         }
6351                         size += size_of(state, member->left);
6352                         i++;
6353                         member = member->right;
6354                 }
6355                 size += needed_padding(state, member, size);
6356                 if (i != index) {
6357                         internal_error(state, 0, "Missing member index: %u", index);
6358                 }
6359         }
6360         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6361                 ulong_t i;
6362                 size = 0;
6363                 member = type->left;
6364                 i = 0;
6365                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6366                         if (i == index) {
6367                                 member = member->left;
6368                                 break;
6369                         }
6370                         i++;
6371                         member = member->right;
6372                 }
6373                 if (i != index) {
6374                         internal_error(state, 0, "Missing member index: %u", index);
6375                 }
6376         }
6377         else {
6378                 internal_error(state, 0, 
6379                         "request for index %u in something not an array, tuple or join",
6380                         index);
6381         }
6382         return size;
6383 }
6384
6385 static size_t index_reg_offset(struct compile_state *state, 
6386         struct type *type, ulong_t index)
6387 {
6388         struct type *member;
6389         size_t size;
6390         size = 0;
6391         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6392                 size = reg_size_of(state, type->left) * index;
6393         }
6394         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6395                 ulong_t i;
6396                 member = type->left;
6397                 i = 0;
6398                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6399                         size += reg_needed_padding(state, member->left, size);
6400                         if (i == index) {
6401                                 member = member->left;
6402                                 break;
6403                         }
6404                         size += reg_size_of(state, member->left);
6405                         i++;
6406                         member = member->right;
6407                 }
6408                 size += reg_needed_padding(state, member, size);
6409                 if (i != index) {
6410                         internal_error(state, 0, "Missing member index: %u", index);
6411                 }
6412                 
6413         }
6414         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6415                 ulong_t i;
6416                 size = 0;
6417                 member = type->left;
6418                 i = 0;
6419                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6420                         if (i == index) {
6421                                 member = member->left;
6422                                 break;
6423                         }
6424                         i++;
6425                         member = member->right;
6426                 }
6427                 if (i != index) {
6428                         internal_error(state, 0, "Missing member index: %u", index);
6429                 }
6430         }
6431         else {
6432                 internal_error(state, 0, 
6433                         "request for index %u in something not an array, tuple or join",
6434                         index);
6435         }
6436         return size;
6437 }
6438
6439 static struct type *index_type(struct compile_state *state,
6440         struct type *type, ulong_t index)
6441 {
6442         struct type *member;
6443         if (index >= type->elements) {
6444                 internal_error(state, 0, "Invalid element %u requested", index);
6445         }
6446         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6447                 member = type->left;
6448         }
6449         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6450                 ulong_t i;
6451                 member = type->left;
6452                 i = 0;
6453                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6454                         if (i == index) {
6455                                 member = member->left;
6456                                 break;
6457                         }
6458                         i++;
6459                         member = member->right;
6460                 }
6461                 if (i != index) {
6462                         internal_error(state, 0, "Missing member index: %u", index);
6463                 }
6464         }
6465         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6466                 ulong_t i;
6467                 member = type->left;
6468                 i = 0;
6469                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6470                         if (i == index) {
6471                                 member = member->left;
6472                                 break;
6473                         }
6474                         i++;
6475                         member = member->right;
6476                 }
6477                 if (i != index) {
6478                         internal_error(state, 0, "Missing member index: %u", index);
6479                 }
6480         }
6481         else {
6482                 member = 0;
6483                 internal_error(state, 0, 
6484                         "request for index %u in something not an array, tuple or join",
6485                         index);
6486         }
6487         return member;
6488 }
6489
6490 static struct type *unpack_type(struct compile_state *state, struct type *type)
6491 {
6492         /* If I have a single register compound type not a bit-field
6493          * find the real type.
6494          */
6495         struct type *start_type;
6496         size_t size;
6497         /* Get out early if I need multiple registers for this type */
6498         size = reg_size_of(state, type);
6499         if (size > REG_SIZEOF_REG) {
6500                 return type;
6501         }
6502         /* Get out early if I don't need any registers for this type */
6503         if (size == 0) {
6504                 return &void_type;
6505         }
6506         /* Loop until I have no more layers I can remove */
6507         do {
6508                 start_type = type;
6509                 switch(type->type & TYPE_MASK) {
6510                 case TYPE_ARRAY:
6511                         /* If I have a single element the unpacked type
6512                          * is that element.
6513                          */
6514                         if (type->elements == 1) {
6515                                 type = type->left;
6516                         }
6517                         break;
6518                 case TYPE_STRUCT:
6519                 case TYPE_TUPLE:
6520                         /* If I have a single element the unpacked type
6521                          * is that element.
6522                          */
6523                         if (type->elements == 1) {
6524                                 type = type->left;
6525                         }
6526                         /* If I have multiple elements the unpacked
6527                          * type is the non-void element.
6528                          */
6529                         else {
6530                                 struct type *next, *member;
6531                                 struct type *sub_type;
6532                                 sub_type = 0;
6533                                 next = type->left;
6534                                 while(next) {
6535                                         member = next;
6536                                         next = 0;
6537                                         if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6538                                                 next = member->right;
6539                                                 member = member->left;
6540                                         }
6541                                         if (reg_size_of(state, member) > 0) {
6542                                                 if (sub_type) {
6543                                                         internal_error(state, 0, "true compound type in a register");
6544                                                 }
6545                                                 sub_type = member;
6546                                         }
6547                                 }
6548                                 if (sub_type) {
6549                                         type = sub_type;
6550                                 }
6551                         }
6552                         break;
6553
6554                 case TYPE_UNION:
6555                 case TYPE_JOIN:
6556                         /* If I have a single element the unpacked type
6557                          * is that element.
6558                          */
6559                         if (type->elements == 1) {
6560                                 type = type->left;
6561                         }
6562                         /* I can't in general unpack union types */
6563                         break;
6564                 default:
6565                         /* If I'm not a compound type I can't unpack it */
6566                         break;
6567                 }
6568         } while(start_type != type);
6569         switch(type->type & TYPE_MASK) {
6570         case TYPE_STRUCT:
6571         case TYPE_ARRAY:
6572         case TYPE_TUPLE:
6573                 internal_error(state, 0, "irredicible type?");
6574                 break;
6575         }
6576         return type;
6577 }
6578
6579 static int equiv_types(struct type *left, struct type *right);
6580 static int is_compound_type(struct type *type);
6581
6582 static struct type *reg_type(
6583         struct compile_state *state, struct type *type, int reg_offset)
6584 {
6585         struct type *member;
6586         size_t size;
6587 #if 1
6588         struct type *invalid;
6589         invalid = invalid_type(state, type);
6590         if (invalid) {
6591                 fprintf(state->errout, "type: ");
6592                 name_of(state->errout, type);
6593                 fprintf(state->errout, "\n");
6594                 fprintf(state->errout, "invalid: ");
6595                 name_of(state->errout, invalid);
6596                 fprintf(state->errout, "\n");
6597                 internal_error(state, 0, "bad input type?");
6598         }
6599 #endif
6600
6601         size = reg_size_of(state, type);
6602         if (reg_offset > size) {
6603                 member = 0;
6604                 fprintf(state->errout, "type: ");
6605                 name_of(state->errout, type);
6606                 fprintf(state->errout, "\n");
6607                 internal_error(state, 0, "offset outside of type");
6608         }
6609         else {
6610                 switch(type->type & TYPE_MASK) {
6611                         /* Don't do anything with the basic types */
6612                 case TYPE_VOID:
6613                 case TYPE_CHAR:         case TYPE_UCHAR:
6614                 case TYPE_SHORT:        case TYPE_USHORT:
6615                 case TYPE_INT:          case TYPE_UINT:
6616                 case TYPE_LONG:         case TYPE_ULONG:
6617                 case TYPE_LLONG:        case TYPE_ULLONG:
6618                 case TYPE_FLOAT:        case TYPE_DOUBLE:
6619                 case TYPE_LDOUBLE:
6620                 case TYPE_POINTER:
6621                 case TYPE_ENUM:
6622                 case TYPE_BITFIELD:
6623                         member = type;
6624                         break;
6625                 case TYPE_ARRAY:
6626                         member = type->left;
6627                         size = reg_size_of(state, member);
6628                         if (size > REG_SIZEOF_REG) {
6629                                 member = reg_type(state, member, reg_offset % size);
6630                         }
6631                         break;
6632                 case TYPE_STRUCT:
6633                 case TYPE_TUPLE:
6634                 {
6635                         size_t offset;
6636                         offset = 0;
6637                         member = type->left;
6638                         while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6639                                 size = reg_size_of(state, member->left);
6640                                 offset += reg_needed_padding(state, member->left, offset);
6641                                 if ((offset + size) > reg_offset) {
6642                                         member = member->left;
6643                                         break;
6644                                 }
6645                                 offset += size;
6646                                 member = member->right;
6647                         }
6648                         offset += reg_needed_padding(state, member, offset);
6649                         member = reg_type(state, member, reg_offset - offset);
6650                         break;
6651                 }
6652                 case TYPE_UNION:
6653                 case TYPE_JOIN:
6654                 {
6655                         struct type *join, **jnext, *mnext;
6656                         join = new_type(TYPE_JOIN, 0, 0);
6657                         jnext = &join->left;
6658                         mnext = type->left;
6659                         while(mnext) {
6660                                 size_t size;
6661                                 member = mnext;
6662                                 mnext = 0;
6663                                 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6664                                         mnext = member->right;
6665                                         member = member->left;
6666                                 }
6667                                 size = reg_size_of(state, member);
6668                                 if (size > reg_offset) {
6669                                         struct type *part, *hunt;
6670                                         part = reg_type(state, member, reg_offset);
6671                                         /* See if this type is already in the union */
6672                                         hunt = join->left;
6673                                         while(hunt) {
6674                                                 struct type *test = hunt;
6675                                                 hunt = 0;
6676                                                 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6677                                                         hunt = test->right;
6678                                                         test = test->left;
6679                                                 }
6680                                                 if (equiv_types(part, test)) {
6681                                                         goto next;
6682                                                 }
6683                                         }
6684                                         /* Nope add it */
6685                                         if (!*jnext) {
6686                                                 *jnext = part;
6687                                         } else {
6688                                                 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6689                                                 jnext = &(*jnext)->right;
6690                                         }
6691                                         join->elements++;
6692                                 }
6693                         next:
6694                                 ;
6695                         }
6696                         if (join->elements == 0) {
6697                                 internal_error(state, 0, "No elements?");
6698                         }
6699                         member = join;
6700                         break;
6701                 }
6702                 default:
6703                         member = 0;
6704                         fprintf(state->errout, "type: ");
6705                         name_of(state->errout, type);
6706                         fprintf(state->errout, "\n");
6707                         internal_error(state, 0, "reg_type not yet defined for type");
6708                         
6709                 }
6710         }
6711         /* If I have a single register compound type not a bit-field
6712          * find the real type.
6713          */
6714         member = unpack_type(state, member);
6715                 ;
6716         size  = reg_size_of(state, member);
6717         if (size > REG_SIZEOF_REG) {
6718                 internal_error(state, 0, "Cannot find type of single register");
6719         }
6720 #if 1
6721         invalid = invalid_type(state, member);
6722         if (invalid) {
6723                 fprintf(state->errout, "type: ");
6724                 name_of(state->errout, member);
6725                 fprintf(state->errout, "\n");
6726                 fprintf(state->errout, "invalid: ");
6727                 name_of(state->errout, invalid);
6728                 fprintf(state->errout, "\n");
6729                 internal_error(state, 0, "returning bad type?");
6730         }
6731 #endif
6732         return member;
6733 }
6734
6735 static struct type *next_field(struct compile_state *state,
6736         struct type *type, struct type *prev_member) 
6737 {
6738         struct type *member;
6739         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6740                 internal_error(state, 0, "next_field only works on structures");
6741         }
6742         member = type->left;
6743         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6744                 if (!prev_member) {
6745                         member = member->left;
6746                         break;
6747                 }
6748                 if (member->left == prev_member) {
6749                         prev_member = 0;
6750                 }
6751                 member = member->right;
6752         }
6753         if (member == prev_member) {
6754                 prev_member = 0;
6755         }
6756         if (prev_member) {
6757                 internal_error(state, 0, "prev_member %s not present", 
6758                         prev_member->field_ident->name);
6759         }
6760         return member;
6761 }
6762
6763 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type, 
6764         size_t ret_offset, size_t mem_offset, void *arg);
6765
6766 static void walk_type_fields(struct compile_state *state,
6767         struct type *type, size_t reg_offset, size_t mem_offset,
6768         walk_type_fields_cb_t cb, void *arg);
6769
6770 static void walk_struct_fields(struct compile_state *state,
6771         struct type *type, size_t reg_offset, size_t mem_offset,
6772         walk_type_fields_cb_t cb, void *arg)
6773 {
6774         struct type *tptr;
6775         ulong_t i;
6776         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6777                 internal_error(state, 0, "walk_struct_fields only works on structures");
6778         }
6779         tptr = type->left;
6780         for(i = 0; i < type->elements; i++) {
6781                 struct type *mtype;
6782                 mtype = tptr;
6783                 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6784                         mtype = mtype->left;
6785                 }
6786                 walk_type_fields(state, mtype, 
6787                         reg_offset + 
6788                         field_reg_offset(state, type, mtype->field_ident),
6789                         mem_offset + 
6790                         field_offset(state, type, mtype->field_ident),
6791                         cb, arg);
6792                 tptr = tptr->right;
6793         }
6794         
6795 }
6796
6797 static void walk_type_fields(struct compile_state *state,
6798         struct type *type, size_t reg_offset, size_t mem_offset,
6799         walk_type_fields_cb_t cb, void *arg)
6800 {
6801         switch(type->type & TYPE_MASK) {
6802         case TYPE_STRUCT:
6803                 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6804                 break;
6805         case TYPE_CHAR:
6806         case TYPE_UCHAR:
6807         case TYPE_SHORT:
6808         case TYPE_USHORT:
6809         case TYPE_INT:
6810         case TYPE_UINT:
6811         case TYPE_LONG:
6812         case TYPE_ULONG:
6813                 cb(state, type, reg_offset, mem_offset, arg);
6814                 break;
6815         case TYPE_VOID:
6816                 break;
6817         default:
6818                 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6819         }
6820 }
6821
6822 static void arrays_complete(struct compile_state *state, struct type *type)
6823 {
6824         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6825                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6826                         error(state, 0, "array size not specified");
6827                 }
6828                 arrays_complete(state, type->left);
6829         }
6830 }
6831
6832 static unsigned int get_basic_type(struct type *type)
6833 {
6834         unsigned int basic;
6835         basic = type->type & TYPE_MASK;
6836         /* Convert enums to ints */
6837         if (basic == TYPE_ENUM) {
6838                 basic = TYPE_INT;
6839         }
6840         /* Convert bitfields to standard types */
6841         else if (basic == TYPE_BITFIELD) {
6842                 if (type->elements <= SIZEOF_CHAR) {
6843                         basic = TYPE_CHAR;
6844                 }
6845                 else if (type->elements <= SIZEOF_SHORT) {
6846                         basic = TYPE_SHORT;
6847                 }
6848                 else if (type->elements <= SIZEOF_INT) {
6849                         basic = TYPE_INT;
6850                 }
6851                 else if (type->elements <= SIZEOF_LONG) {
6852                         basic = TYPE_LONG;
6853                 }
6854                 if (!TYPE_SIGNED(type->left->type)) {
6855                         basic += 1;
6856                 }
6857         }
6858         return basic;
6859 }
6860
6861 static unsigned int do_integral_promotion(unsigned int type)
6862 {
6863         if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6864                 type = TYPE_INT;
6865         }
6866         return type;
6867 }
6868
6869 static unsigned int do_arithmetic_conversion(
6870         unsigned int left, unsigned int right)
6871 {
6872         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6873                 return TYPE_LDOUBLE;
6874         }
6875         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
6876                 return TYPE_DOUBLE;
6877         }
6878         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
6879                 return TYPE_FLOAT;
6880         }
6881         left = do_integral_promotion(left);
6882         right = do_integral_promotion(right);
6883         /* If both operands have the same size done */
6884         if (left == right) {
6885                 return left;
6886         }
6887         /* If both operands have the same signedness pick the larger */
6888         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
6889                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
6890         }
6891         /* If the signed type can hold everything use it */
6892         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
6893                 return left;
6894         }
6895         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
6896                 return right;
6897         }
6898         /* Convert to the unsigned type with the same rank as the signed type */
6899         else if (TYPE_SIGNED(left)) {
6900                 return TYPE_MKUNSIGNED(left);
6901         }
6902         else {
6903                 return TYPE_MKUNSIGNED(right);
6904         }
6905 }
6906
6907 /* see if two types are the same except for qualifiers */
6908 static int equiv_types(struct type *left, struct type *right)
6909 {
6910         unsigned int type;
6911         /* Error if the basic types do not match */
6912         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6913                 return 0;
6914         }
6915         type = left->type & TYPE_MASK;
6916         /* If the basic types match and it is a void type we are done */
6917         if (type == TYPE_VOID) {
6918                 return 1;
6919         }
6920         /* For bitfields we need to compare the sizes */
6921         else if (type == TYPE_BITFIELD) {
6922                 return (left->elements == right->elements) &&
6923                         (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
6924         }
6925         /* if the basic types match and it is an arithmetic type we are done */
6926         else if (TYPE_ARITHMETIC(type)) {
6927                 return 1;
6928         }
6929         /* If it is a pointer type recurse and keep testing */
6930         else if (type == TYPE_POINTER) {
6931                 return equiv_types(left->left, right->left);
6932         }
6933         else if (type == TYPE_ARRAY) {
6934                 return (left->elements == right->elements) &&
6935                         equiv_types(left->left, right->left);
6936         }
6937         /* test for struct equality */
6938         else if (type == TYPE_STRUCT) {
6939                 return left->type_ident == right->type_ident;
6940         }
6941         /* test for union equality */
6942         else if (type == TYPE_UNION) {
6943                 return left->type_ident == right->type_ident;
6944         }
6945         /* Test for equivalent functions */
6946         else if (type == TYPE_FUNCTION) {
6947                 return equiv_types(left->left, right->left) &&
6948                         equiv_types(left->right, right->right);
6949         }
6950         /* We only see TYPE_PRODUCT as part of function equivalence matching */
6951         /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
6952         else if (type == TYPE_PRODUCT) {
6953                 return equiv_types(left->left, right->left) &&
6954                         equiv_types(left->right, right->right);
6955         }
6956         /* We should see TYPE_OVERLAP when comparing joins */
6957         else if (type == TYPE_OVERLAP) {
6958                 return equiv_types(left->left, right->left) &&
6959                         equiv_types(left->right, right->right);
6960         }
6961         /* Test for equivalence of tuples */
6962         else if (type == TYPE_TUPLE) {
6963                 return (left->elements == right->elements) &&
6964                         equiv_types(left->left, right->left);
6965         }
6966         /* Test for equivalence of joins */
6967         else if (type == TYPE_JOIN) {
6968                 return (left->elements == right->elements) &&
6969                         equiv_types(left->left, right->left);
6970         }
6971         else {
6972                 return 0;
6973         }
6974 }
6975
6976 static int equiv_ptrs(struct type *left, struct type *right)
6977 {
6978         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
6979                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
6980                 return 0;
6981         }
6982         return equiv_types(left->left, right->left);
6983 }
6984
6985 static struct type *compatible_types(struct type *left, struct type *right)
6986 {
6987         struct type *result;
6988         unsigned int type, qual_type;
6989         /* Error if the basic types do not match */
6990         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6991                 return 0;
6992         }
6993         type = left->type & TYPE_MASK;
6994         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
6995         result = 0;
6996         /* if the basic types match and it is an arithmetic type we are done */
6997         if (TYPE_ARITHMETIC(type)) {
6998                 result = new_type(qual_type, 0, 0);
6999         }
7000         /* If it is a pointer type recurse and keep testing */
7001         else if (type == TYPE_POINTER) {
7002                 result = compatible_types(left->left, right->left);
7003                 if (result) {
7004                         result = new_type(qual_type, result, 0);
7005                 }
7006         }
7007         /* test for struct equality */
7008         else if (type == TYPE_STRUCT) {
7009                 if (left->type_ident == right->type_ident) {
7010                         result = left;
7011                 }
7012         }
7013         /* test for union equality */
7014         else if (type == TYPE_UNION) {
7015                 if (left->type_ident == right->type_ident) {
7016                         result = left;
7017                 }
7018         }
7019         /* Test for equivalent functions */
7020         else if (type == TYPE_FUNCTION) {
7021                 struct type *lf, *rf;
7022                 lf = compatible_types(left->left, right->left);
7023                 rf = compatible_types(left->right, right->right);
7024                 if (lf && rf) {
7025                         result = new_type(qual_type, lf, rf);
7026                 }
7027         }
7028         /* We only see TYPE_PRODUCT as part of function equivalence matching */
7029         else if (type == TYPE_PRODUCT) {
7030                 struct type *lf, *rf;
7031                 lf = compatible_types(left->left, right->left);
7032                 rf = compatible_types(left->right, right->right);
7033                 if (lf && rf) {
7034                         result = new_type(qual_type, lf, rf);
7035                 }
7036         }
7037         else {
7038                 /* Nothing else is compatible */
7039         }
7040         return result;
7041 }
7042
7043 /* See if left is a equivalent to right or right is a union member of left */
7044 static int is_subset_type(struct type *left, struct type *right)
7045 {
7046         if (equiv_types(left, right)) {
7047                 return 1;
7048         }
7049         if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7050                 struct type *member, *mnext;
7051                 mnext = left->left;
7052                 while(mnext) {
7053                         member = mnext;
7054                         mnext = 0;
7055                         if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7056                                 mnext = member->right;
7057                                 member = member->left;
7058                         }
7059                         if (is_subset_type( member, right)) {
7060                                 return 1;
7061                         }
7062                 }
7063         }
7064         return 0;
7065 }
7066
7067 static struct type *compatible_ptrs(struct type *left, struct type *right)
7068 {
7069         struct type *result;
7070         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7071                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7072                 return 0;
7073         }
7074         result = compatible_types(left->left, right->left);
7075         if (result) {
7076                 unsigned int qual_type;
7077                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7078                 result = new_type(qual_type, result, 0);
7079         }
7080         return result;
7081         
7082 }
7083 static struct triple *integral_promotion(
7084         struct compile_state *state, struct triple *def)
7085 {
7086         struct type *type;
7087         type = def->type;
7088         /* As all operations are carried out in registers
7089          * the values are converted on load I just convert
7090          * logical type of the operand.
7091          */
7092         if (TYPE_INTEGER(type->type)) {
7093                 unsigned int int_type;
7094                 int_type = type->type & ~TYPE_MASK;
7095                 int_type |= do_integral_promotion(get_basic_type(type));
7096                 if (int_type != type->type) {
7097                         if (def->op != OP_LOAD) {
7098                                 def->type = new_type(int_type, 0, 0);
7099                         }
7100                         else {
7101                                 def = triple(state, OP_CONVERT, 
7102                                         new_type(int_type, 0, 0), def, 0);
7103                         }
7104                 }
7105         }
7106         return def;
7107 }
7108
7109
7110 static void arithmetic(struct compile_state *state, struct triple *def)
7111 {
7112         if (!TYPE_ARITHMETIC(def->type->type)) {
7113                 error(state, 0, "arithmetic type expexted");
7114         }
7115 }
7116
7117 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7118 {
7119         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7120                 error(state, def, "pointer or arithmetic type expected");
7121         }
7122 }
7123
7124 static int is_integral(struct triple *ins)
7125 {
7126         return TYPE_INTEGER(ins->type->type);
7127 }
7128
7129 static void integral(struct compile_state *state, struct triple *def)
7130 {
7131         if (!is_integral(def)) {
7132                 error(state, 0, "integral type expected");
7133         }
7134 }
7135
7136
7137 static void bool(struct compile_state *state, struct triple *def)
7138 {
7139         if (!TYPE_ARITHMETIC(def->type->type) &&
7140                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7141                 error(state, 0, "arithmetic or pointer type expected");
7142         }
7143 }
7144
7145 static int is_signed(struct type *type)
7146 {
7147         if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7148                 type = type->left;
7149         }
7150         return !!TYPE_SIGNED(type->type);
7151 }
7152 static int is_compound_type(struct type *type)
7153 {
7154         int is_compound;
7155         switch((type->type & TYPE_MASK)) {
7156         case TYPE_ARRAY:
7157         case TYPE_STRUCT:
7158         case TYPE_TUPLE:
7159         case TYPE_UNION:
7160         case TYPE_JOIN: 
7161                 is_compound = 1;
7162                 break;
7163         default:
7164                 is_compound = 0;
7165                 break;
7166         }
7167         return is_compound;
7168 }
7169
7170 /* Is this value located in a register otherwise it must be in memory */
7171 static int is_in_reg(struct compile_state *state, struct triple *def)
7172 {
7173         int in_reg;
7174         if (def->op == OP_ADECL) {
7175                 in_reg = 1;
7176         }
7177         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7178                 in_reg = 0;
7179         }
7180         else if (triple_is_part(state, def)) {
7181                 in_reg = is_in_reg(state, MISC(def, 0));
7182         }
7183         else {
7184                 internal_error(state, def, "unknown expr storage location");
7185                 in_reg = -1;
7186         }
7187         return in_reg;
7188 }
7189
7190 /* Is this an auto or static variable location? Something that can
7191  * be assigned to.  Otherwise it must must be a pure value, a temporary.
7192  */
7193 static int is_lvalue(struct compile_state *state, struct triple *def)
7194 {
7195         int ret;
7196         ret = 0;
7197         if (!def) {
7198                 return 0;
7199         }
7200         if ((def->op == OP_ADECL) || 
7201                 (def->op == OP_SDECL) || 
7202                 (def->op == OP_DEREF) ||
7203                 (def->op == OP_BLOBCONST) ||
7204                 (def->op == OP_LIST)) {
7205                 ret = 1;
7206         }
7207         else if (triple_is_part(state, def)) {
7208                 ret = is_lvalue(state, MISC(def, 0));
7209         }
7210         return ret;
7211 }
7212
7213 static void clvalue(struct compile_state *state, struct triple *def)
7214 {
7215         if (!def) {
7216                 internal_error(state, def, "nothing where lvalue expected?");
7217         }
7218         if (!is_lvalue(state, def)) { 
7219                 error(state, def, "lvalue expected");
7220         }
7221 }
7222 static void lvalue(struct compile_state *state, struct triple *def)
7223 {
7224         clvalue(state, def);
7225         if (def->type->type & QUAL_CONST) {
7226                 error(state, def, "modifable lvalue expected");
7227         }
7228 }
7229
7230 static int is_pointer(struct triple *def)
7231 {
7232         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7233 }
7234
7235 static void pointer(struct compile_state *state, struct triple *def)
7236 {
7237         if (!is_pointer(def)) {
7238                 error(state, def, "pointer expected");
7239         }
7240 }
7241
7242 static struct triple *int_const(
7243         struct compile_state *state, struct type *type, ulong_t value)
7244 {
7245         struct triple *result;
7246         switch(type->type & TYPE_MASK) {
7247         case TYPE_CHAR:
7248         case TYPE_INT:   case TYPE_UINT:
7249         case TYPE_LONG:  case TYPE_ULONG:
7250                 break;
7251         default:
7252                 internal_error(state, 0, "constant for unknown type");
7253         }
7254         result = triple(state, OP_INTCONST, type, 0, 0);
7255         result->u.cval = value;
7256         return result;
7257 }
7258
7259
7260 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7261
7262 static struct triple *do_mk_addr_expr(struct compile_state *state, 
7263         struct triple *expr, struct type *type, ulong_t offset)
7264 {
7265         struct triple *result;
7266         struct type *ptr_type;
7267         clvalue(state, expr);
7268
7269         ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7270
7271         
7272         result = 0;
7273         if (expr->op == OP_ADECL) {
7274                 error(state, expr, "address of auto variables not supported");
7275         }
7276         else if (expr->op == OP_SDECL) {
7277                 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7278                 MISC(result, 0) = expr;
7279                 result->u.cval = offset;
7280         }
7281         else if (expr->op == OP_DEREF) {
7282                 result = triple(state, OP_ADD, ptr_type,
7283                         RHS(expr, 0),
7284                         int_const(state, &ulong_type, offset));
7285         }
7286         else if (expr->op == OP_BLOBCONST) {
7287                 FINISHME();
7288                 internal_error(state, expr, "not yet implemented");
7289         }
7290         else if (expr->op == OP_LIST) {
7291                 error(state, 0, "Function addresses not supported");
7292         }
7293         else if (triple_is_part(state, expr)) {
7294                 struct triple *part;
7295                 part = expr;
7296                 expr = MISC(expr, 0);
7297                 if (part->op == OP_DOT) {
7298                         offset += bits_to_bytes(
7299                                 field_offset(state, expr->type, part->u.field));
7300                 }
7301                 else if (part->op == OP_INDEX) {
7302                         offset += bits_to_bytes(
7303                                 index_offset(state, expr->type, part->u.cval));
7304                 }
7305                 else {
7306                         internal_error(state, part, "unhandled part type");
7307                 }
7308                 result = do_mk_addr_expr(state, expr, type, offset);
7309         }
7310         if (!result) {
7311                 internal_error(state, expr, "cannot take address of expression");
7312         }
7313         return result;
7314 }
7315
7316 static struct triple *mk_addr_expr(
7317         struct compile_state *state, struct triple *expr, ulong_t offset)
7318 {
7319         return do_mk_addr_expr(state, expr, expr->type, offset);
7320 }
7321
7322 static struct triple *mk_deref_expr(
7323         struct compile_state *state, struct triple *expr)
7324 {
7325         struct type *base_type;
7326         pointer(state, expr);
7327         base_type = expr->type->left;
7328         return triple(state, OP_DEREF, base_type, expr, 0);
7329 }
7330
7331 /* lvalue conversions always apply except when certain operators
7332  * are applied.  So I apply apply it when I know no more
7333  * operators will be applied.
7334  */
7335 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7336 {
7337         /* Tranform an array to a pointer to the first element */
7338         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7339                 struct type *type;
7340                 type = new_type(
7341                         TYPE_POINTER | (def->type->type & QUAL_MASK),
7342                         def->type->left, 0);
7343                 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7344                         struct triple *addrconst;
7345                         if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7346                                 internal_error(state, def, "bad array constant");
7347                         }
7348                         addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7349                         MISC(addrconst, 0) = def;
7350                         def = addrconst;
7351                 }
7352                 else {
7353                         def = triple(state, OP_CONVERT, type, def, 0);
7354                 }
7355         }
7356         /* Transform a function to a pointer to it */
7357         else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7358                 def = mk_addr_expr(state, def, 0);
7359         }
7360         return def;
7361 }
7362
7363 static struct triple *deref_field(
7364         struct compile_state *state, struct triple *expr, struct hash_entry *field)
7365 {
7366         struct triple *result;
7367         struct type *type, *member;
7368         ulong_t offset;
7369         if (!field) {
7370                 internal_error(state, 0, "No field passed to deref_field");
7371         }
7372         result = 0;
7373         type = expr->type;
7374         if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7375                 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7376                 error(state, 0, "request for member %s in something not a struct or union",
7377                         field->name);
7378         }
7379         member = field_type(state, type, field);
7380         if ((type->type & STOR_MASK) == STOR_PERM) {
7381                 /* Do the pointer arithmetic to get a deref the field */
7382                 offset = bits_to_bytes(field_offset(state, type, field));
7383                 result = do_mk_addr_expr(state, expr, member, offset);
7384                 result = mk_deref_expr(state, result);
7385         }
7386         else {
7387                 /* Find the variable for the field I want. */
7388                 result = triple(state, OP_DOT, member, expr, 0);
7389                 result->u.field = field;
7390         }
7391         return result;
7392 }
7393
7394 static struct triple *deref_index(
7395         struct compile_state *state, struct triple *expr, size_t index)
7396 {
7397         struct triple *result;
7398         struct type *type, *member;
7399         ulong_t offset;
7400
7401         result = 0;
7402         type = expr->type;
7403         member = index_type(state, type, index);
7404
7405         if ((type->type & STOR_MASK) == STOR_PERM) {
7406                 offset = bits_to_bytes(index_offset(state, type, index));
7407                 result = do_mk_addr_expr(state, expr, member, offset);
7408                 result = mk_deref_expr(state, result);
7409         }
7410         else {
7411                 result = triple(state, OP_INDEX, member, expr, 0);
7412                 result->u.cval = index;
7413         }
7414         return result;
7415 }
7416
7417 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7418 {
7419         int op;
7420         if  (!def) {
7421                 return 0;
7422         }
7423 #if DEBUG_ROMCC_WARNINGS
7424 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7425 #endif
7426         /* Transform lvalues into something we can read */
7427         def = lvalue_conversion(state, def);
7428         if (!is_lvalue(state, def)) {
7429                 return def;
7430         }
7431         if (is_in_reg(state, def)) {
7432                 op = OP_READ;
7433         } else {
7434                 if (def->op == OP_SDECL) {
7435                         def = mk_addr_expr(state, def, 0);
7436                         def = mk_deref_expr(state, def);
7437                 }
7438                 op = OP_LOAD;
7439         }
7440         def = triple(state, op, def->type, def, 0);
7441         if (def->type->type & QUAL_VOLATILE) {
7442                 def->id |= TRIPLE_FLAG_VOLATILE;
7443         }
7444         return def;
7445 }
7446
7447 int is_write_compatible(struct compile_state *state, 
7448         struct type *dest, struct type *rval)
7449 {
7450         int compatible = 0;
7451         /* Both operands have arithmetic type */
7452         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7453                 compatible = 1;
7454         }
7455         /* One operand is a pointer and the other is a pointer to void */
7456         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7457                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7458                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7459                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7460                 compatible = 1;
7461         }
7462         /* If both types are the same without qualifiers we are good */
7463         else if (equiv_ptrs(dest, rval)) {
7464                 compatible = 1;
7465         }
7466         /* test for struct/union equality  */
7467         else if (equiv_types(dest, rval)) {
7468                 compatible = 1;
7469         }
7470         return compatible;
7471 }
7472
7473 static void write_compatible(struct compile_state *state,
7474         struct type *dest, struct type *rval)
7475 {
7476         if (!is_write_compatible(state, dest, rval)) {
7477                 FILE *fp = state->errout;
7478                 fprintf(fp, "dest: ");
7479                 name_of(fp, dest);
7480                 fprintf(fp,"\nrval: ");
7481                 name_of(fp, rval);
7482                 fprintf(fp, "\n");
7483                 error(state, 0, "Incompatible types in assignment");
7484         }
7485 }
7486
7487 static int is_init_compatible(struct compile_state *state,
7488         struct type *dest, struct type *rval)
7489 {
7490         int compatible = 0;
7491         if (is_write_compatible(state, dest, rval)) {
7492                 compatible = 1;
7493         }
7494         else if (equiv_types(dest, rval)) {
7495                 compatible = 1;
7496         }
7497         return compatible;
7498 }
7499
7500 static struct triple *write_expr(
7501         struct compile_state *state, struct triple *dest, struct triple *rval)
7502 {
7503         struct triple *def;
7504         int op;
7505
7506         def = 0;
7507         if (!rval) {
7508                 internal_error(state, 0, "missing rval");
7509         }
7510
7511         if (rval->op == OP_LIST) {
7512                 internal_error(state, 0, "expression of type OP_LIST?");
7513         }
7514         if (!is_lvalue(state, dest)) {
7515                 internal_error(state, 0, "writing to a non lvalue?");
7516         }
7517         if (dest->type->type & QUAL_CONST) {
7518                 internal_error(state, 0, "modifable lvalue expexted");
7519         }
7520
7521         write_compatible(state, dest->type, rval->type);
7522         if (!equiv_types(dest->type, rval->type)) {
7523                 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7524         }
7525
7526         /* Now figure out which assignment operator to use */
7527         op = -1;
7528         if (is_in_reg(state, dest)) {
7529                 def = triple(state, OP_WRITE, dest->type, rval, dest);
7530                 if (MISC(def, 0) != dest) {
7531                         internal_error(state, def, "huh?");
7532                 }
7533                 if (RHS(def, 0) != rval) {
7534                         internal_error(state, def, "huh?");
7535                 }
7536         } else {
7537                 def = triple(state, OP_STORE, dest->type, dest, rval);
7538         }
7539         if (def->type->type & QUAL_VOLATILE) {
7540                 def->id |= TRIPLE_FLAG_VOLATILE;
7541         }
7542         return def;
7543 }
7544
7545 static struct triple *init_expr(
7546         struct compile_state *state, struct triple *dest, struct triple *rval)
7547 {
7548         struct triple *def;
7549
7550         def = 0;
7551         if (!rval) {
7552                 internal_error(state, 0, "missing rval");
7553         }
7554         if ((dest->type->type & STOR_MASK) != STOR_PERM) {
7555                 rval = read_expr(state, rval);
7556                 def = write_expr(state, dest, rval);
7557         }
7558         else {
7559                 /* Fill in the array size if necessary */
7560                 if (((dest->type->type & TYPE_MASK) == TYPE_ARRAY) &&
7561                         ((rval->type->type & TYPE_MASK) == TYPE_ARRAY)) {
7562                         if (dest->type->elements == ELEMENT_COUNT_UNSPECIFIED) {
7563                                 dest->type->elements = rval->type->elements;
7564                         }
7565                 }
7566                 if (!equiv_types(dest->type, rval->type)) {
7567                         error(state, 0, "Incompatible types in inializer");
7568                 }
7569                 MISC(dest, 0) = rval;
7570                 insert_triple(state, dest, rval);
7571                 rval->id |= TRIPLE_FLAG_FLATTENED;
7572                 use_triple(MISC(dest, 0), dest);
7573         }
7574         return def;
7575 }
7576
7577 struct type *arithmetic_result(
7578         struct compile_state *state, struct triple *left, struct triple *right)
7579 {
7580         struct type *type;
7581         /* Sanity checks to ensure I am working with arithmetic types */
7582         arithmetic(state, left);
7583         arithmetic(state, right);
7584         type = new_type(
7585                 do_arithmetic_conversion(
7586                         get_basic_type(left->type),
7587                         get_basic_type(right->type)),
7588                 0, 0);
7589         return type;
7590 }
7591
7592 struct type *ptr_arithmetic_result(
7593         struct compile_state *state, struct triple *left, struct triple *right)
7594 {
7595         struct type *type;
7596         /* Sanity checks to ensure I am working with the proper types */
7597         ptr_arithmetic(state, left);
7598         arithmetic(state, right);
7599         if (TYPE_ARITHMETIC(left->type->type) && 
7600                 TYPE_ARITHMETIC(right->type->type)) {
7601                 type = arithmetic_result(state, left, right);
7602         }
7603         else if (TYPE_PTR(left->type->type)) {
7604                 type = left->type;
7605         }
7606         else {
7607                 internal_error(state, 0, "huh?");
7608                 type = 0;
7609         }
7610         return type;
7611 }
7612
7613 /* boolean helper function */
7614
7615 static struct triple *ltrue_expr(struct compile_state *state, 
7616         struct triple *expr)
7617 {
7618         switch(expr->op) {
7619         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
7620         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
7621         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
7622                 /* If the expression is already boolean do nothing */
7623                 break;
7624         default:
7625                 expr = triple(state, OP_LTRUE, &int_type, expr, 0);
7626                 break;
7627         }
7628         return expr;
7629 }
7630
7631 static struct triple *lfalse_expr(struct compile_state *state, 
7632         struct triple *expr)
7633 {
7634         return triple(state, OP_LFALSE, &int_type, expr, 0);
7635 }
7636
7637 static struct triple *mkland_expr(
7638         struct compile_state *state,
7639         struct triple *left, struct triple *right)
7640 {
7641         struct triple *def, *val, *var, *jmp, *mid, *end;
7642         struct triple *lstore, *rstore;
7643
7644         /* Generate some intermediate triples */
7645         end = label(state);
7646         var = variable(state, &int_type);
7647         
7648         /* Store the left hand side value */
7649         lstore = write_expr(state, var, left);
7650
7651         /* Jump if the value is false */
7652         jmp =  branch(state, end, 
7653                 lfalse_expr(state, read_expr(state, var)));
7654         mid = label(state);
7655         
7656         /* Store the right hand side value */
7657         rstore = write_expr(state, var, right);
7658
7659         /* An expression for the computed value */
7660         val = read_expr(state, var);
7661
7662         /* Generate the prog for a logical and */
7663         def = mkprog(state, var, lstore, jmp, mid, rstore, end, val, 0UL);
7664         
7665         return def;
7666 }
7667
7668 static struct triple *mklor_expr(
7669         struct compile_state *state,
7670         struct triple *left, struct triple *right)
7671 {
7672         struct triple *def, *val, *var, *jmp, *mid, *end;
7673
7674         /* Generate some intermediate triples */
7675         end = label(state);
7676         var = variable(state, &int_type);
7677         
7678         /* Store the left hand side value */
7679         left = write_expr(state, var, left);
7680         
7681         /* Jump if the value is true */
7682         jmp = branch(state, end, read_expr(state, var));
7683         mid = label(state);
7684         
7685         /* Store the right hand side value */
7686         right = write_expr(state, var, right);
7687                 
7688         /* An expression for the computed value*/
7689         val = read_expr(state, var);
7690
7691         /* Generate the prog for a logical or */
7692         def = mkprog(state, var, left, jmp, mid, right, end, val, 0UL);
7693
7694         return def;
7695 }
7696
7697 static struct triple *mkcond_expr(
7698         struct compile_state *state, 
7699         struct triple *test, struct triple *left, struct triple *right)
7700 {
7701         struct triple *def, *val, *var, *jmp1, *jmp2, *top, *mid, *end;
7702         struct type *result_type;
7703         unsigned int left_type, right_type;
7704         bool(state, test);
7705         left_type = left->type->type;
7706         right_type = right->type->type;
7707         result_type = 0;
7708         /* Both operands have arithmetic type */
7709         if (TYPE_ARITHMETIC(left_type) && TYPE_ARITHMETIC(right_type)) {
7710                 result_type = arithmetic_result(state, left, right);
7711         }
7712         /* Both operands have void type */
7713         else if (((left_type & TYPE_MASK) == TYPE_VOID) &&
7714                 ((right_type & TYPE_MASK) == TYPE_VOID)) {
7715                 result_type = &void_type;
7716         }
7717         /* pointers to the same type... */
7718         else if ((result_type = compatible_ptrs(left->type, right->type))) {
7719                 ;
7720         }
7721         /* Both operands are pointers and left is a pointer to void */
7722         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7723                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7724                 ((left->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7725                 result_type = right->type;
7726         }
7727         /* Both operands are pointers and right is a pointer to void */
7728         else if (((left_type & TYPE_MASK) == TYPE_POINTER) &&
7729                 ((right_type & TYPE_MASK) == TYPE_POINTER) &&
7730                 ((right->type->left->type & TYPE_MASK) == TYPE_VOID)) {
7731                 result_type = left->type;
7732         }
7733         if (!result_type) {
7734                 error(state, 0, "Incompatible types in conditional expression");
7735         }
7736         /* Generate some intermediate triples */
7737         mid = label(state);
7738         end = label(state);
7739         var = variable(state, result_type);
7740
7741         /* Branch if the test is false */
7742         jmp1 = branch(state, mid, lfalse_expr(state, read_expr(state, test)));
7743         top = label(state);
7744
7745         /* Store the left hand side value */
7746         left = write_expr(state, var, left);
7747
7748         /* Branch to the end */
7749         jmp2 = branch(state, end, 0);
7750
7751         /* Store the right hand side value */
7752         right = write_expr(state, var, right);
7753         
7754         /* An expression for the computed value */
7755         val = read_expr(state, var);
7756
7757         /* Generate the prog for a conditional expression */
7758         def = mkprog(state, var, jmp1, top, left, jmp2, mid, right, end, val, 0UL);
7759
7760         return def;
7761 }
7762
7763
7764 static int expr_depth(struct compile_state *state, struct triple *ins)
7765 {
7766 #if DEBUG_ROMCC_WARNINGS
7767 #warning "FIXME move optimal ordering of subexpressions into the optimizer"
7768 #endif
7769         int count;
7770         count = 0;
7771         if (!ins || (ins->id & TRIPLE_FLAG_FLATTENED)) {
7772                 count = 0;
7773         }
7774         else if (ins->op == OP_DEREF) {
7775                 count = expr_depth(state, RHS(ins, 0)) - 1;
7776         }
7777         else if (ins->op == OP_VAL) {
7778                 count = expr_depth(state, RHS(ins, 0)) - 1;
7779         }
7780         else if (ins->op == OP_FCALL) {
7781                 /* Don't figure the depth of a call just guess it is huge */
7782                 count = 1000;
7783         }
7784         else {
7785                 struct triple **expr;
7786                 expr = triple_rhs(state, ins, 0);
7787                 for(;expr; expr = triple_rhs(state, ins, expr)) {
7788                         if (*expr) {
7789                                 int depth;
7790                                 depth = expr_depth(state, *expr);
7791                                 if (depth > count) {
7792                                         count = depth;
7793                                 }
7794                         }
7795                 }
7796         }
7797         return count + 1;
7798 }
7799
7800 static struct triple *flatten_generic(
7801         struct compile_state *state, struct triple *first, struct triple *ptr,
7802         int ignored)
7803 {
7804         struct rhs_vector {
7805                 int depth;
7806                 struct triple **ins;
7807         } vector[MAX_RHS];
7808         int i, rhs, lhs;
7809         /* Only operations with just a rhs and a lhs should come here */
7810         rhs = ptr->rhs;
7811         lhs = ptr->lhs;
7812         if (TRIPLE_SIZE(ptr) != lhs + rhs + ignored) {
7813                 internal_error(state, ptr, "unexpected args for: %d %s",
7814                         ptr->op, tops(ptr->op));
7815         }
7816         /* Find the depth of the rhs elements */
7817         for(i = 0; i < rhs; i++) {
7818                 vector[i].ins = &RHS(ptr, i);
7819                 vector[i].depth = expr_depth(state, *vector[i].ins);
7820         }
7821         /* Selection sort the rhs */
7822         for(i = 0; i < rhs; i++) {
7823                 int j, max = i;
7824                 for(j = i + 1; j < rhs; j++ ) {
7825                         if (vector[j].depth > vector[max].depth) {
7826                                 max = j;
7827                         }
7828                 }
7829                 if (max != i) {
7830                         struct rhs_vector tmp;
7831                         tmp = vector[i];
7832                         vector[i] = vector[max];
7833                         vector[max] = tmp;
7834                 }
7835         }
7836         /* Now flatten the rhs elements */
7837         for(i = 0; i < rhs; i++) {
7838                 *vector[i].ins = flatten(state, first, *vector[i].ins);
7839                 use_triple(*vector[i].ins, ptr);
7840         }
7841         if (lhs) {
7842                 insert_triple(state, first, ptr);
7843                 ptr->id |= TRIPLE_FLAG_FLATTENED;
7844                 ptr->id &= ~TRIPLE_FLAG_LOCAL;
7845                 
7846                 /* Now flatten the lhs elements */
7847                 for(i = 0; i < lhs; i++) {
7848                         struct triple **ins = &LHS(ptr, i);
7849                         *ins = flatten(state, first, *ins);
7850                         use_triple(*ins, ptr);
7851                 }
7852         }
7853         return ptr;
7854 }
7855
7856 static struct triple *flatten_prog(
7857         struct compile_state *state, struct triple *first, struct triple *ptr)
7858 {
7859         struct triple *head, *body, *val;
7860         head = RHS(ptr, 0);
7861         RHS(ptr, 0) = 0;
7862         val  = head->prev;
7863         body = head->next;
7864         release_triple(state, head);
7865         release_triple(state, ptr);
7866         val->next        = first;
7867         body->prev       = first->prev;
7868         body->prev->next = body;
7869         val->next->prev  = val;
7870
7871         if (triple_is_cbranch(state, body->prev) ||
7872                 triple_is_call(state, body->prev)) {
7873                 unuse_triple(first, body->prev);
7874                 use_triple(body, body->prev);
7875         }
7876         
7877         if (!(val->id & TRIPLE_FLAG_FLATTENED)) {
7878                 internal_error(state, val, "val not flattened?");
7879         }
7880
7881         return val;
7882 }
7883
7884
7885 static struct triple *flatten_part(
7886         struct compile_state *state, struct triple *first, struct triple *ptr)
7887 {
7888         if (!triple_is_part(state, ptr)) {
7889                 internal_error(state, ptr,  "not a part");
7890         }
7891         if (ptr->rhs || ptr->lhs || ptr->targ || (ptr->misc != 1)) {
7892                 internal_error(state, ptr, "unexpected args for: %d %s",
7893                         ptr->op, tops(ptr->op));
7894         }
7895         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7896         use_triple(MISC(ptr, 0), ptr);
7897         return flatten_generic(state, first, ptr, 1);
7898 }
7899
7900 static struct triple *flatten(
7901         struct compile_state *state, struct triple *first, struct triple *ptr)
7902 {
7903         struct triple *orig_ptr;
7904         if (!ptr)
7905                 return 0;
7906         do {
7907                 orig_ptr = ptr;
7908                 /* Only flatten triples once */
7909                 if (ptr->id & TRIPLE_FLAG_FLATTENED) {
7910                         return ptr;
7911                 }
7912                 switch(ptr->op) {
7913                 case OP_VAL:
7914                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7915                         return MISC(ptr, 0);
7916                         break;
7917                 case OP_PROG:
7918                         ptr = flatten_prog(state, first, ptr);
7919                         break;
7920                 case OP_FCALL:
7921                         ptr = flatten_generic(state, first, ptr, 1);
7922                         insert_triple(state, first, ptr);
7923                         ptr->id |= TRIPLE_FLAG_FLATTENED;
7924                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
7925                         if (ptr->next != ptr) {
7926                                 use_triple(ptr->next, ptr);
7927                         }
7928                         break;
7929                 case OP_READ:
7930                 case OP_LOAD:
7931                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7932                         use_triple(RHS(ptr, 0), ptr);
7933                         break;
7934                 case OP_WRITE:
7935                         ptr = flatten_generic(state, first, ptr, 1);
7936                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7937                         use_triple(MISC(ptr, 0), ptr);
7938                         break;
7939                 case OP_BRANCH:
7940                         use_triple(TARG(ptr, 0), ptr);
7941                         break;
7942                 case OP_CBRANCH:
7943                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7944                         use_triple(RHS(ptr, 0), ptr);
7945                         use_triple(TARG(ptr, 0), ptr);
7946                         insert_triple(state, first, ptr);
7947                         ptr->id |= TRIPLE_FLAG_FLATTENED;
7948                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
7949                         if (ptr->next != ptr) {
7950                                 use_triple(ptr->next, ptr);
7951                         }
7952                         break;
7953                 case OP_CALL:
7954                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
7955                         use_triple(MISC(ptr, 0), ptr);
7956                         use_triple(TARG(ptr, 0), ptr);
7957                         insert_triple(state, first, ptr);
7958                         ptr->id |= TRIPLE_FLAG_FLATTENED;
7959                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
7960                         if (ptr->next != ptr) {
7961                                 use_triple(ptr->next, ptr);
7962                         }
7963                         break;
7964                 case OP_RET:
7965                         RHS(ptr, 0) = flatten(state, first, RHS(ptr, 0));
7966                         use_triple(RHS(ptr, 0), ptr);
7967                         break;
7968                 case OP_BLOBCONST:
7969                         insert_triple(state, state->global_pool, ptr);
7970                         ptr->id |= TRIPLE_FLAG_FLATTENED;
7971                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
7972                         ptr = triple(state, OP_SDECL, ptr->type, ptr, 0);
7973                         use_triple(MISC(ptr, 0), ptr);
7974                         break;
7975                 case OP_DEREF:
7976                         /* Since OP_DEREF is just a marker delete it when I flatten it */
7977                         ptr = RHS(ptr, 0);
7978                         RHS(orig_ptr, 0) = 0;
7979                         free_triple(state, orig_ptr);
7980                         break;
7981                 case OP_DOT:
7982                         if (RHS(ptr, 0)->op == OP_DEREF) {
7983                                 struct triple *base, *left;
7984                                 ulong_t offset;
7985                                 base = MISC(ptr, 0);
7986                                 offset = bits_to_bytes(field_offset(state, base->type, ptr->u.field));
7987                                 left = RHS(base, 0);
7988                                 ptr = triple(state, OP_ADD, left->type, 
7989                                         read_expr(state, left),
7990                                         int_const(state, &ulong_type, offset));
7991                                 free_triple(state, base);
7992                         }
7993                         else {
7994                                 ptr = flatten_part(state, first, ptr);
7995                         }
7996                         break;
7997                 case OP_INDEX:
7998                         if (RHS(ptr, 0)->op == OP_DEREF) {
7999                                 struct triple *base, *left;
8000                                 ulong_t offset;
8001                                 base = MISC(ptr, 0);
8002                                 offset = bits_to_bytes(index_offset(state, base->type, ptr->u.cval));
8003                                 left = RHS(base, 0);
8004                                 ptr = triple(state, OP_ADD, left->type,
8005                                         read_expr(state, left),
8006                                         int_const(state, &long_type, offset));
8007                                 free_triple(state, base);
8008                         }
8009                         else {
8010                                 ptr = flatten_part(state, first, ptr);
8011                         }
8012                         break;
8013                 case OP_PIECE:
8014                         ptr = flatten_part(state, first, ptr);
8015                         use_triple(ptr, MISC(ptr, 0));
8016                         break;
8017                 case OP_ADDRCONST:
8018                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8019                         use_triple(MISC(ptr, 0), ptr);
8020                         break;
8021                 case OP_SDECL:
8022                         first = state->global_pool;
8023                         MISC(ptr, 0) = flatten(state, first, MISC(ptr, 0));
8024                         use_triple(MISC(ptr, 0), ptr);
8025                         insert_triple(state, first, ptr);
8026                         ptr->id |= TRIPLE_FLAG_FLATTENED;
8027                         ptr->id &= ~TRIPLE_FLAG_LOCAL;
8028                         return ptr;
8029                 case OP_ADECL:
8030                         ptr = flatten_generic(state, first, ptr, 0);
8031                         break;
8032                 default:
8033                         /* Flatten the easy cases we don't override */
8034                         ptr = flatten_generic(state, first, ptr, 0);
8035                         break;
8036                 }
8037         } while(ptr && (ptr != orig_ptr));
8038         if (ptr && !(ptr->id & TRIPLE_FLAG_FLATTENED)) {
8039                 insert_triple(state, first, ptr);
8040                 ptr->id |= TRIPLE_FLAG_FLATTENED;
8041                 ptr->id &= ~TRIPLE_FLAG_LOCAL;
8042         }
8043         return ptr;
8044 }
8045
8046 static void release_expr(struct compile_state *state, struct triple *expr)
8047 {
8048         struct triple *head;
8049         head = label(state);
8050         flatten(state, head, expr);
8051         while(head->next != head) {
8052                 release_triple(state, head->next);
8053         }
8054         free_triple(state, head);
8055 }
8056
8057 static int replace_rhs_use(struct compile_state *state,
8058         struct triple *orig, struct triple *new, struct triple *use)
8059 {
8060         struct triple **expr;
8061         int found;
8062         found = 0;
8063         expr = triple_rhs(state, use, 0);
8064         for(;expr; expr = triple_rhs(state, use, expr)) {
8065                 if (*expr == orig) {
8066                         *expr = new;
8067                         found = 1;
8068                 }
8069         }
8070         if (found) {
8071                 unuse_triple(orig, use);
8072                 use_triple(new, use);
8073         }
8074         return found;
8075 }
8076
8077 static int replace_lhs_use(struct compile_state *state,
8078         struct triple *orig, struct triple *new, struct triple *use)
8079 {
8080         struct triple **expr;
8081         int found;
8082         found = 0;
8083         expr = triple_lhs(state, use, 0);
8084         for(;expr; expr = triple_lhs(state, use, expr)) {
8085                 if (*expr == orig) {
8086                         *expr = new;
8087                         found = 1;
8088                 }
8089         }
8090         if (found) {
8091                 unuse_triple(orig, use);
8092                 use_triple(new, use);
8093         }
8094         return found;
8095 }
8096
8097 static int replace_misc_use(struct compile_state *state,
8098         struct triple *orig, struct triple *new, struct triple *use)
8099 {
8100         struct triple **expr;
8101         int found;
8102         found = 0;
8103         expr = triple_misc(state, use, 0);
8104         for(;expr; expr = triple_misc(state, use, expr)) {
8105                 if (*expr == orig) {
8106                         *expr = new;
8107                         found = 1;
8108                 }
8109         }
8110         if (found) {
8111                 unuse_triple(orig, use);
8112                 use_triple(new, use);
8113         }
8114         return found;
8115 }
8116
8117 static int replace_targ_use(struct compile_state *state,
8118         struct triple *orig, struct triple *new, struct triple *use)
8119 {
8120         struct triple **expr;
8121         int found;
8122         found = 0;
8123         expr = triple_targ(state, use, 0);
8124         for(;expr; expr = triple_targ(state, use, expr)) {
8125                 if (*expr == orig) {
8126                         *expr = new;
8127                         found = 1;
8128                 }
8129         }
8130         if (found) {
8131                 unuse_triple(orig, use);
8132                 use_triple(new, use);
8133         }
8134         return found;
8135 }
8136
8137 static void replace_use(struct compile_state *state,
8138         struct triple *orig, struct triple *new, struct triple *use)
8139 {
8140         int found;
8141         found = 0;
8142         found |= replace_rhs_use(state, orig, new, use);
8143         found |= replace_lhs_use(state, orig, new, use);
8144         found |= replace_misc_use(state, orig, new, use);
8145         found |= replace_targ_use(state, orig, new, use);
8146         if (!found) {
8147                 internal_error(state, use, "use without use");
8148         }
8149 }
8150
8151 static void propogate_use(struct compile_state *state,
8152         struct triple *orig, struct triple *new)
8153 {
8154         struct triple_set *user, *next;
8155         for(user = orig->use; user; user = next) {
8156                 /* Careful replace_use modifies the use chain and
8157                  * removes use.  So we must get a copy of the next
8158                  * entry early.
8159                  */
8160                 next = user->next;
8161                 replace_use(state, orig, new, user->member);
8162         }
8163         if (orig->use) {
8164                 internal_error(state, orig, "used after propogate_use");
8165         }
8166 }
8167
8168 /*
8169  * Code generators
8170  * ===========================
8171  */
8172
8173 static struct triple *mk_cast_expr(
8174         struct compile_state *state, struct type *type, struct triple *expr)
8175 {
8176         struct triple *def;
8177         def = read_expr(state, expr);
8178         def = triple(state, OP_CONVERT, type, def, 0);
8179         return def;
8180 }
8181
8182 static struct triple *mk_add_expr(
8183         struct compile_state *state, struct triple *left, struct triple *right)
8184 {
8185         struct type *result_type;
8186         /* Put pointer operands on the left */
8187         if (is_pointer(right)) {
8188                 struct triple *tmp;
8189                 tmp = left;
8190                 left = right;
8191                 right = tmp;
8192         }
8193         left  = read_expr(state, left);
8194         right = read_expr(state, right);
8195         result_type = ptr_arithmetic_result(state, left, right);
8196         if (is_pointer(left)) {
8197                 struct type *ptr_math;
8198                 int op;
8199                 if (is_signed(right->type)) {
8200                         ptr_math = &long_type;
8201                         op = OP_SMUL;
8202                 } else {
8203                         ptr_math = &ulong_type;
8204                         op = OP_UMUL;
8205                 }
8206                 if (!equiv_types(right->type, ptr_math)) {
8207                         right = mk_cast_expr(state, ptr_math, right);
8208                 }
8209                 right = triple(state, op, ptr_math, right, 
8210                         int_const(state, ptr_math, 
8211                                 size_of_in_bytes(state, left->type->left)));
8212         }
8213         return triple(state, OP_ADD, result_type, left, right);
8214 }
8215
8216 static struct triple *mk_sub_expr(
8217         struct compile_state *state, struct triple *left, struct triple *right)
8218 {
8219         struct type *result_type;
8220         result_type = ptr_arithmetic_result(state, left, right);
8221         left  = read_expr(state, left);
8222         right = read_expr(state, right);
8223         if (is_pointer(left)) {
8224                 struct type *ptr_math;
8225                 int op;
8226                 if (is_signed(right->type)) {
8227                         ptr_math = &long_type;
8228                         op = OP_SMUL;
8229                 } else {
8230                         ptr_math = &ulong_type;
8231                         op = OP_UMUL;
8232                 }
8233                 if (!equiv_types(right->type, ptr_math)) {
8234                         right = mk_cast_expr(state, ptr_math, right);
8235                 }
8236                 right = triple(state, op, ptr_math, right, 
8237                         int_const(state, ptr_math, 
8238                                 size_of_in_bytes(state, left->type->left)));
8239         }
8240         return triple(state, OP_SUB, result_type, left, right);
8241 }
8242
8243 static struct triple *mk_pre_inc_expr(
8244         struct compile_state *state, struct triple *def)
8245 {
8246         struct triple *val;
8247         lvalue(state, def);
8248         val = mk_add_expr(state, def, int_const(state, &int_type, 1));
8249         return triple(state, OP_VAL, def->type,
8250                 write_expr(state, def, val),
8251                 val);
8252 }
8253
8254 static struct triple *mk_pre_dec_expr(
8255         struct compile_state *state, struct triple *def)
8256 {
8257         struct triple *val;
8258         lvalue(state, def);
8259         val = mk_sub_expr(state, def, int_const(state, &int_type, 1));
8260         return triple(state, OP_VAL, def->type,
8261                 write_expr(state, def, val),
8262                 val);
8263 }
8264
8265 static struct triple *mk_post_inc_expr(
8266         struct compile_state *state, struct triple *def)
8267 {
8268         struct triple *val;
8269         lvalue(state, def);
8270         val = read_expr(state, def);
8271         return triple(state, OP_VAL, def->type,
8272                 write_expr(state, def,
8273                         mk_add_expr(state, val, int_const(state, &int_type, 1)))
8274                 , val);
8275 }
8276
8277 static struct triple *mk_post_dec_expr(
8278         struct compile_state *state, struct triple *def)
8279 {
8280         struct triple *val;
8281         lvalue(state, def);
8282         val = read_expr(state, def);
8283         return triple(state, OP_VAL, def->type, 
8284                 write_expr(state, def,
8285                         mk_sub_expr(state, val, int_const(state, &int_type, 1)))
8286                 , val);
8287 }
8288
8289 static struct triple *mk_subscript_expr(
8290         struct compile_state *state, struct triple *left, struct triple *right)
8291 {
8292         left  = read_expr(state, left);
8293         right = read_expr(state, right);
8294         if (!is_pointer(left) && !is_pointer(right)) {
8295                 error(state, left, "subscripted value is not a pointer");
8296         }
8297         return mk_deref_expr(state, mk_add_expr(state, left, right));
8298 }
8299
8300
8301 /*
8302  * Compile time evaluation
8303  * ===========================
8304  */
8305 static int is_const(struct triple *ins)
8306 {
8307         return IS_CONST_OP(ins->op);
8308 }
8309
8310 static int is_simple_const(struct triple *ins)
8311 {
8312         /* Is this a constant that u.cval has the value.
8313          * Or equivalently is this a constant that read_const
8314          * works on.
8315          * So far only OP_INTCONST qualifies.  
8316          */
8317         return (ins->op == OP_INTCONST);
8318 }
8319
8320 static int constants_equal(struct compile_state *state, 
8321         struct triple *left, struct triple *right)
8322 {
8323         int equal;
8324         if ((left->op == OP_UNKNOWNVAL) || (right->op == OP_UNKNOWNVAL)) {
8325                 equal = 0;
8326         }
8327         else if (!is_const(left) || !is_const(right)) {
8328                 equal = 0;
8329         }
8330         else if (left->op != right->op) {
8331                 equal = 0;
8332         }
8333         else if (!equiv_types(left->type, right->type)) {
8334                 equal = 0;
8335         }
8336         else {
8337                 equal = 0;
8338                 switch(left->op) {
8339                 case OP_INTCONST:
8340                         if (left->u.cval == right->u.cval) {
8341                                 equal = 1;
8342                         }
8343                         break;
8344                 case OP_BLOBCONST:
8345                 {
8346                         size_t lsize, rsize, bytes;
8347                         lsize = size_of(state, left->type);
8348                         rsize = size_of(state, right->type);
8349                         if (lsize != rsize) {
8350                                 break;
8351                         }
8352                         bytes = bits_to_bytes(lsize);
8353                         if (memcmp(left->u.blob, right->u.blob, bytes) == 0) {
8354                                 equal = 1;
8355                         }
8356                         break;
8357                 }
8358                 case OP_ADDRCONST:
8359                         if ((MISC(left, 0) == MISC(right, 0)) &&
8360                                 (left->u.cval == right->u.cval)) {
8361                                 equal = 1;
8362                         }
8363                         break;
8364                 default:
8365                         internal_error(state, left, "uknown constant type");
8366                         break;
8367                 }
8368         }
8369         return equal;
8370 }
8371
8372 static int is_zero(struct triple *ins)
8373 {
8374         return is_simple_const(ins) && (ins->u.cval == 0);
8375 }
8376
8377 static int is_one(struct triple *ins)
8378 {
8379         return is_simple_const(ins) && (ins->u.cval == 1);
8380 }
8381
8382 #if DEBUG_ROMCC_WARNING
8383 static long_t bit_count(ulong_t value)
8384 {
8385         int count;
8386         int i;
8387         count = 0;
8388         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8389                 ulong_t mask;
8390                 mask = 1;
8391                 mask <<= i;
8392                 if (value & mask) {
8393                         count++;
8394                 }
8395         }
8396         return count;
8397         
8398 }
8399 #endif
8400
8401 static long_t bsr(ulong_t value)
8402 {
8403         int i;
8404         for(i = (sizeof(ulong_t)*8) -1; i >= 0; i--) {
8405                 ulong_t mask;
8406                 mask = 1;
8407                 mask <<= i;
8408                 if (value & mask) {
8409                         return i;
8410                 }
8411         }
8412         return -1;
8413 }
8414
8415 static long_t bsf(ulong_t value)
8416 {
8417         int i;
8418         for(i = 0; i < (sizeof(ulong_t)*8); i++) {
8419                 ulong_t mask;
8420                 mask = 1;
8421                 mask <<= 1;
8422                 if (value & mask) {
8423                         return i;
8424                 }
8425         }
8426         return -1;
8427 }
8428
8429 static long_t ilog2(ulong_t value)
8430 {
8431         return bsr(value);
8432 }
8433
8434 static long_t tlog2(struct triple *ins)
8435 {
8436         return ilog2(ins->u.cval);
8437 }
8438
8439 static int is_pow2(struct triple *ins)
8440 {
8441         ulong_t value, mask;
8442         long_t log;
8443         if (!is_const(ins)) {
8444                 return 0;
8445         }
8446         value = ins->u.cval;
8447         log = ilog2(value);
8448         if (log == -1) {
8449                 return 0;
8450         }
8451         mask = 1;
8452         mask <<= log;
8453         return  ((value & mask) == value);
8454 }
8455
8456 static ulong_t read_const(struct compile_state *state,
8457         struct triple *ins, struct triple *rhs)
8458 {
8459         switch(rhs->type->type &TYPE_MASK) {
8460         case TYPE_CHAR:   
8461         case TYPE_SHORT:
8462         case TYPE_INT:
8463         case TYPE_LONG:
8464         case TYPE_UCHAR:   
8465         case TYPE_USHORT:  
8466         case TYPE_UINT:
8467         case TYPE_ULONG:
8468         case TYPE_POINTER:
8469         case TYPE_BITFIELD:
8470                 break;
8471         default:
8472                 fprintf(state->errout, "type: ");
8473                 name_of(state->errout, rhs->type);
8474                 fprintf(state->errout, "\n");
8475                 internal_warning(state, rhs, "bad type to read_const");
8476                 break;
8477         }
8478         if (!is_simple_const(rhs)) {
8479                 internal_error(state, rhs, "bad op to read_const");
8480         }
8481         return rhs->u.cval;
8482 }
8483
8484 static long_t read_sconst(struct compile_state *state,
8485         struct triple *ins, struct triple *rhs)
8486 {
8487         return (long_t)(rhs->u.cval);
8488 }
8489
8490 int const_ltrue(struct compile_state *state, struct triple *ins, struct triple *rhs)
8491 {
8492         if (!is_const(rhs)) {
8493                 internal_error(state, 0, "non const passed to const_true");
8494         }
8495         return !is_zero(rhs);
8496 }
8497
8498 int const_eq(struct compile_state *state, struct triple *ins,
8499         struct triple *left, struct triple *right)
8500 {
8501         int result;
8502         if (!is_const(left) || !is_const(right)) {
8503                 internal_warning(state, ins, "non const passed to const_eq");
8504                 result = -1;
8505         }
8506         else if (left == right) {
8507                 result = 1;
8508         }
8509         else if (is_simple_const(left) && is_simple_const(right)) {
8510                 ulong_t lval, rval;
8511                 lval = read_const(state, ins, left);
8512                 rval = read_const(state, ins, right);
8513                 result = (lval == rval);
8514         }
8515         else if ((left->op == OP_ADDRCONST) && 
8516                 (right->op == OP_ADDRCONST)) {
8517                 result = (MISC(left, 0) == MISC(right, 0)) &&
8518                         (left->u.cval == right->u.cval);
8519         }
8520         else {
8521                 internal_warning(state, ins, "incomparable constants passed to const_eq");
8522                 result = -1;
8523         }
8524         return result;
8525         
8526 }
8527
8528 int const_ucmp(struct compile_state *state, struct triple *ins,
8529         struct triple *left, struct triple *right)
8530 {
8531         int result;
8532         if (!is_const(left) || !is_const(right)) {
8533                 internal_warning(state, ins, "non const past to const_ucmp");
8534                 result = -2;
8535         }
8536         else if (left == right) {
8537                 result = 0;
8538         }
8539         else if (is_simple_const(left) && is_simple_const(right)) {
8540                 ulong_t lval, rval;
8541                 lval = read_const(state, ins, left);
8542                 rval = read_const(state, ins, right);
8543                 result = 0;
8544                 if (lval > rval) {
8545                         result = 1;
8546                 } else if (rval > lval) {
8547                         result = -1;
8548                 }
8549         }
8550         else if ((left->op == OP_ADDRCONST) && 
8551                 (right->op == OP_ADDRCONST) &&
8552                 (MISC(left, 0) == MISC(right, 0))) {
8553                 result = 0;
8554                 if (left->u.cval > right->u.cval) {
8555                         result = 1;
8556                 } else if (left->u.cval < right->u.cval) {
8557                         result = -1;
8558                 }
8559         }
8560         else {
8561                 internal_warning(state, ins, "incomparable constants passed to const_ucmp");
8562                 result = -2;
8563         }
8564         return result;
8565 }
8566
8567 int const_scmp(struct compile_state *state, struct triple *ins,
8568         struct triple *left, struct triple *right)
8569 {
8570         int result;
8571         if (!is_const(left) || !is_const(right)) {
8572                 internal_warning(state, ins, "non const past to ucmp_const");
8573                 result = -2;
8574         }
8575         else if (left == right) {
8576                 result = 0;
8577         }
8578         else if (is_simple_const(left) && is_simple_const(right)) {
8579                 long_t lval, rval;
8580                 lval = read_sconst(state, ins, left);
8581                 rval = read_sconst(state, ins, right);
8582                 result = 0;
8583                 if (lval > rval) {
8584                         result = 1;
8585                 } else if (rval > lval) {
8586                         result = -1;
8587                 }
8588         }
8589         else {
8590                 internal_warning(state, ins, "incomparable constants passed to const_scmp");
8591                 result = -2;
8592         }
8593         return result;
8594 }
8595
8596 static void unuse_rhs(struct compile_state *state, struct triple *ins)
8597 {
8598         struct triple **expr;
8599         expr = triple_rhs(state, ins, 0);
8600         for(;expr;expr = triple_rhs(state, ins, expr)) {
8601                 if (*expr) {
8602                         unuse_triple(*expr, ins);
8603                         *expr = 0;
8604                 }
8605         }
8606 }
8607
8608 static void unuse_lhs(struct compile_state *state, struct triple *ins)
8609 {
8610         struct triple **expr;
8611         expr = triple_lhs(state, ins, 0);
8612         for(;expr;expr = triple_lhs(state, ins, expr)) {
8613                 unuse_triple(*expr, ins);
8614                 *expr = 0;
8615         }
8616 }
8617
8618 #if DEBUG_ROMCC_WARNING
8619 static void unuse_misc(struct compile_state *state, struct triple *ins)
8620 {
8621         struct triple **expr;
8622         expr = triple_misc(state, ins, 0);
8623         for(;expr;expr = triple_misc(state, ins, expr)) {
8624                 unuse_triple(*expr, ins);
8625                 *expr = 0;
8626         }
8627 }
8628
8629 static void unuse_targ(struct compile_state *state, struct triple *ins)
8630 {
8631         int i;
8632         struct triple **slot;
8633         slot = &TARG(ins, 0);
8634         for(i = 0; i < ins->targ; i++) {
8635                 unuse_triple(slot[i], ins);
8636                 slot[i] = 0;
8637         }
8638 }
8639
8640 static void check_lhs(struct compile_state *state, struct triple *ins)
8641 {
8642         struct triple **expr;
8643         expr = triple_lhs(state, ins, 0);
8644         for(;expr;expr = triple_lhs(state, ins, expr)) {
8645                 internal_error(state, ins, "unexpected lhs");
8646         }
8647         
8648 }
8649 #endif
8650
8651 static void check_misc(struct compile_state *state, struct triple *ins)
8652 {
8653         struct triple **expr;
8654         expr = triple_misc(state, ins, 0);
8655         for(;expr;expr = triple_misc(state, ins, expr)) {
8656                 if (*expr) {
8657                         internal_error(state, ins, "unexpected misc");
8658                 }
8659         }
8660 }
8661
8662 static void check_targ(struct compile_state *state, struct triple *ins)
8663 {
8664         struct triple **expr;
8665         expr = triple_targ(state, ins, 0);
8666         for(;expr;expr = triple_targ(state, ins, expr)) {
8667                 internal_error(state, ins, "unexpected targ");
8668         }
8669 }
8670
8671 static void wipe_ins(struct compile_state *state, struct triple *ins)
8672 {
8673         /* Becareful which instructions you replace the wiped
8674          * instruction with, as there are not enough slots
8675          * in all instructions to hold all others.
8676          */
8677         check_targ(state, ins);
8678         check_misc(state, ins);
8679         unuse_rhs(state, ins);
8680         unuse_lhs(state, ins);
8681         ins->lhs  = 0;
8682         ins->rhs  = 0;
8683         ins->misc = 0;
8684         ins->targ = 0;
8685 }
8686
8687 #if DEBUG_ROMCC_WARNING
8688 static void wipe_branch(struct compile_state *state, struct triple *ins)
8689 {
8690         /* Becareful which instructions you replace the wiped
8691          * instruction with, as there are not enough slots
8692          * in all instructions to hold all others.
8693          */
8694         unuse_rhs(state, ins);
8695         unuse_lhs(state, ins);
8696         unuse_misc(state, ins);
8697         unuse_targ(state, ins);
8698         ins->lhs  = 0;
8699         ins->rhs  = 0;
8700         ins->misc = 0;
8701         ins->targ = 0;
8702 }
8703 #endif
8704
8705 static void mkcopy(struct compile_state *state, 
8706         struct triple *ins, struct triple *rhs)
8707 {
8708         struct block *block;
8709         if (!equiv_types(ins->type, rhs->type)) {
8710                 FILE *fp = state->errout;
8711                 fprintf(fp, "src type: ");
8712                 name_of(fp, rhs->type);
8713                 fprintf(fp, "\ndst type: ");
8714                 name_of(fp, ins->type);
8715                 fprintf(fp, "\n");
8716                 internal_error(state, ins, "mkcopy type mismatch");
8717         }
8718         block = block_of_triple(state, ins);
8719         wipe_ins(state, ins);
8720         ins->op = OP_COPY;
8721         ins->rhs  = 1;
8722         ins->u.block = block;
8723         RHS(ins, 0) = rhs;
8724         use_triple(RHS(ins, 0), ins);
8725 }
8726
8727 static void mkconst(struct compile_state *state, 
8728         struct triple *ins, ulong_t value)
8729 {
8730         if (!is_integral(ins) && !is_pointer(ins)) {
8731                 fprintf(state->errout, "type: ");
8732                 name_of(state->errout, ins->type);
8733                 fprintf(state->errout, "\n");
8734                 internal_error(state, ins, "unknown type to make constant value: %ld",
8735                         value);
8736         }
8737         wipe_ins(state, ins);
8738         ins->op = OP_INTCONST;
8739         ins->u.cval = value;
8740 }
8741
8742 static void mkaddr_const(struct compile_state *state,
8743         struct triple *ins, struct triple *sdecl, ulong_t value)
8744 {
8745         if ((sdecl->op != OP_SDECL) && (sdecl->op != OP_LABEL)) {
8746                 internal_error(state, ins, "bad base for addrconst");
8747         }
8748         wipe_ins(state, ins);
8749         ins->op = OP_ADDRCONST;
8750         ins->misc = 1;
8751         MISC(ins, 0) = sdecl;
8752         ins->u.cval = value;
8753         use_triple(sdecl, ins);
8754 }
8755
8756 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8757 static void print_tuple(struct compile_state *state, 
8758         struct triple *ins, struct triple *tuple)
8759 {
8760         FILE *fp = state->dbgout;
8761         fprintf(fp, "%5s %p tuple: %p ", tops(ins->op), ins, tuple);
8762         name_of(fp, tuple->type);
8763         if (tuple->lhs > 0) {
8764                 fprintf(fp, " lhs: ");
8765                 name_of(fp, LHS(tuple, 0)->type);
8766         }
8767         fprintf(fp, "\n");
8768         
8769 }
8770 #endif
8771
8772 static struct triple *decompose_with_tuple(struct compile_state *state, 
8773         struct triple *ins, struct triple *tuple)
8774 {
8775         struct triple *next;
8776         next = ins->next;
8777         flatten(state, next, tuple);
8778 #if DEBUG_DECOMPOSE_PRINT_TUPLES
8779         print_tuple(state, ins, tuple);
8780 #endif
8781
8782         if (!is_compound_type(tuple->type) && (tuple->lhs > 0)) {
8783                 struct triple *tmp;
8784                 if (tuple->lhs != 1) {
8785                         internal_error(state, tuple, "plain type in multiple registers?");
8786                 }
8787                 tmp = LHS(tuple, 0);
8788                 release_triple(state, tuple);
8789                 tuple = tmp;
8790         }
8791
8792         propogate_use(state, ins, tuple);
8793         release_triple(state, ins);
8794         
8795         return next;
8796 }
8797
8798 static struct triple *decompose_unknownval(struct compile_state *state,
8799         struct triple *ins)
8800 {
8801         struct triple *tuple;
8802         ulong_t i;
8803
8804 #if DEBUG_DECOMPOSE_HIRES
8805         FILE *fp = state->dbgout;
8806         fprintf(fp, "unknown type: ");
8807         name_of(fp, ins->type);
8808         fprintf(fp, "\n");
8809 #endif
8810
8811         get_occurance(ins->occurance);
8812         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1, 
8813                 ins->occurance);
8814
8815         for(i = 0; i < tuple->lhs; i++) {
8816                 struct type *piece_type;
8817                 struct triple *unknown;
8818
8819                 piece_type = reg_type(state, ins->type, i * REG_SIZEOF_REG);
8820                 get_occurance(tuple->occurance);
8821                 unknown = alloc_triple(state, OP_UNKNOWNVAL, piece_type, 0, 0,
8822                         tuple->occurance);
8823                 LHS(tuple, i) = unknown;
8824         }
8825         return decompose_with_tuple(state, ins, tuple);
8826 }
8827
8828
8829 static struct triple *decompose_read(struct compile_state *state, 
8830         struct triple *ins)
8831 {
8832         struct triple *tuple, *lval;
8833         ulong_t i;
8834
8835         lval = RHS(ins, 0);
8836
8837         if (lval->op == OP_PIECE) {
8838                 return ins->next;
8839         }
8840         get_occurance(ins->occurance);
8841         tuple = alloc_triple(state, OP_TUPLE, lval->type, -1, -1,
8842                 ins->occurance);
8843
8844         if ((tuple->lhs != lval->lhs) &&
8845                 (!triple_is_def(state, lval) || (tuple->lhs != 1))) 
8846         {
8847                 internal_error(state, ins, "lhs size inconsistency?");
8848         }
8849         for(i = 0; i < tuple->lhs; i++) {
8850                 struct triple *piece, *read, *bitref;
8851                 if ((i != 0) || !triple_is_def(state, lval)) {
8852                         piece = LHS(lval, i);
8853                 } else {
8854                         piece = lval;
8855                 }
8856
8857                 /* See if the piece is really a bitref */
8858                 bitref = 0;
8859                 if (piece->op == OP_BITREF) {
8860                         bitref = piece;
8861                         piece = RHS(bitref, 0);
8862                 }
8863
8864                 get_occurance(tuple->occurance);
8865                 read = alloc_triple(state, OP_READ, piece->type, -1, -1, 
8866                         tuple->occurance);
8867                 RHS(read, 0) = piece;
8868
8869                 if (bitref) {
8870                         struct triple *extract;
8871                         int op;
8872                         if (is_signed(bitref->type->left)) {
8873                                 op = OP_SEXTRACT;
8874                         } else {
8875                                 op = OP_UEXTRACT;
8876                         }
8877                         get_occurance(tuple->occurance);
8878                         extract = alloc_triple(state, op, bitref->type, -1, -1,
8879                                 tuple->occurance);
8880                         RHS(extract, 0) = read;
8881                         extract->u.bitfield.size   = bitref->u.bitfield.size;
8882                         extract->u.bitfield.offset = bitref->u.bitfield.offset;
8883
8884                         read = extract;
8885                 }
8886
8887                 LHS(tuple, i) = read;
8888         }
8889         return decompose_with_tuple(state, ins, tuple);
8890 }
8891
8892 static struct triple *decompose_write(struct compile_state *state, 
8893         struct triple *ins)
8894 {
8895         struct triple *tuple, *lval, *val;
8896         ulong_t i;
8897         
8898         lval = MISC(ins, 0);
8899         val = RHS(ins, 0);
8900         get_occurance(ins->occurance);
8901         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8902                 ins->occurance);
8903
8904         if ((tuple->lhs != lval->lhs) &&
8905                 (!triple_is_def(state, lval) || tuple->lhs != 1)) 
8906         {
8907                 internal_error(state, ins, "lhs size inconsistency?");
8908         }
8909         for(i = 0; i < tuple->lhs; i++) {
8910                 struct triple *piece, *write, *pval, *bitref;
8911                 if ((i != 0) || !triple_is_def(state, lval)) {
8912                         piece = LHS(lval, i);
8913                 } else {
8914                         piece = lval;
8915                 }
8916                 if ((i == 0) && (tuple->lhs == 1) && (val->lhs == 0)) {
8917                         pval = val;
8918                 }
8919                 else {
8920                         if (i > val->lhs) {
8921                                 internal_error(state, ins, "lhs size inconsistency?");
8922                         }
8923                         pval = LHS(val, i);
8924                 }
8925                 
8926                 /* See if the piece is really a bitref */
8927                 bitref = 0;
8928                 if (piece->op == OP_BITREF) {
8929                         struct triple *read, *deposit;
8930                         bitref = piece;
8931                         piece = RHS(bitref, 0);
8932
8933                         /* Read the destination register */
8934                         get_occurance(tuple->occurance);
8935                         read = alloc_triple(state, OP_READ, piece->type, -1, -1,
8936                                 tuple->occurance);
8937                         RHS(read, 0) = piece;
8938
8939                         /* Deposit the new bitfield value */
8940                         get_occurance(tuple->occurance);
8941                         deposit = alloc_triple(state, OP_DEPOSIT, piece->type, -1, -1,
8942                                 tuple->occurance);
8943                         RHS(deposit, 0) = read;
8944                         RHS(deposit, 1) = pval;
8945                         deposit->u.bitfield.size   = bitref->u.bitfield.size;
8946                         deposit->u.bitfield.offset = bitref->u.bitfield.offset;
8947
8948                         /* Now write the newly generated value */
8949                         pval = deposit;
8950                 }
8951
8952                 get_occurance(tuple->occurance);
8953                 write = alloc_triple(state, OP_WRITE, piece->type, -1, -1, 
8954                         tuple->occurance);
8955                 MISC(write, 0) = piece;
8956                 RHS(write, 0) = pval;
8957                 LHS(tuple, i) = write;
8958         }
8959         return decompose_with_tuple(state, ins, tuple);
8960 }
8961
8962 struct decompose_load_info {
8963         struct occurance *occurance;
8964         struct triple *lval;
8965         struct triple *tuple;
8966 };
8967 static void decompose_load_cb(struct compile_state *state,
8968         struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
8969 {
8970         struct decompose_load_info *info = arg;
8971         struct triple *load;
8972         
8973         if (reg_offset > info->tuple->lhs) {
8974                 internal_error(state, info->tuple, "lhs to small?");
8975         }
8976         get_occurance(info->occurance);
8977         load = alloc_triple(state, OP_LOAD, type, -1, -1, info->occurance);
8978         RHS(load, 0) = mk_addr_expr(state, info->lval, mem_offset);
8979         LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = load;
8980 }
8981
8982 static struct triple *decompose_load(struct compile_state *state, 
8983         struct triple *ins)
8984 {
8985         struct triple *tuple;
8986         struct decompose_load_info info;
8987
8988         if (!is_compound_type(ins->type)) {
8989                 return ins->next;
8990         }
8991         get_occurance(ins->occurance);
8992         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
8993                 ins->occurance);
8994
8995         info.occurance = ins->occurance;
8996         info.lval      = RHS(ins, 0);
8997         info.tuple     = tuple;
8998         walk_type_fields(state, ins->type, 0, 0, decompose_load_cb, &info);
8999
9000         return decompose_with_tuple(state, ins, tuple);
9001 }
9002
9003
9004 struct decompose_store_info {
9005         struct occurance *occurance;
9006         struct triple *lval;
9007         struct triple *val;
9008         struct triple *tuple;
9009 };
9010 static void decompose_store_cb(struct compile_state *state,
9011         struct type *type, size_t reg_offset, size_t mem_offset, void *arg)
9012 {
9013         struct decompose_store_info *info = arg;
9014         struct triple *store;
9015         
9016         if (reg_offset > info->tuple->lhs) {
9017                 internal_error(state, info->tuple, "lhs to small?");
9018         }
9019         get_occurance(info->occurance);
9020         store = alloc_triple(state, OP_STORE, type, -1, -1, info->occurance);
9021         RHS(store, 0) = mk_addr_expr(state, info->lval, mem_offset);
9022         RHS(store, 1) = LHS(info->val, reg_offset);
9023         LHS(info->tuple, reg_offset/REG_SIZEOF_REG) = store;
9024 }
9025
9026 static struct triple *decompose_store(struct compile_state *state, 
9027         struct triple *ins)
9028 {
9029         struct triple *tuple;
9030         struct decompose_store_info info;
9031
9032         if (!is_compound_type(ins->type)) {
9033                 return ins->next;
9034         }
9035         get_occurance(ins->occurance);
9036         tuple = alloc_triple(state, OP_TUPLE, ins->type, -1, -1,
9037                 ins->occurance);
9038
9039         info.occurance = ins->occurance;
9040         info.lval      = RHS(ins, 0);
9041         info.val       = RHS(ins, 1);
9042         info.tuple     = tuple;
9043         walk_type_fields(state, ins->type, 0, 0, decompose_store_cb, &info);
9044
9045         return decompose_with_tuple(state, ins, tuple);
9046 }
9047
9048 static struct triple *decompose_dot(struct compile_state *state, 
9049         struct triple *ins)
9050 {
9051         struct triple *tuple, *lval;
9052         struct type *type;
9053         size_t reg_offset;
9054         int i, idx;
9055
9056         lval = MISC(ins, 0);
9057         reg_offset = field_reg_offset(state, lval->type, ins->u.field);
9058         idx  = reg_offset/REG_SIZEOF_REG;
9059         type = field_type(state, lval->type, ins->u.field);
9060 #if DEBUG_DECOMPOSE_HIRES
9061         {
9062                 FILE *fp = state->dbgout;
9063                 fprintf(fp, "field type: ");
9064                 name_of(fp, type);
9065                 fprintf(fp, "\n");
9066         }
9067 #endif
9068
9069         get_occurance(ins->occurance);
9070         tuple = alloc_triple(state, OP_TUPLE, type, -1, -1, 
9071                 ins->occurance);
9072
9073         if (((ins->type->type & TYPE_MASK) == TYPE_BITFIELD) &&
9074                 (tuple->lhs != 1))
9075         {
9076                 internal_error(state, ins, "multi register bitfield?");
9077         }
9078
9079         for(i = 0; i < tuple->lhs; i++, idx++) {
9080                 struct triple *piece;
9081                 if (!triple_is_def(state, lval)) {
9082                         if (idx > lval->lhs) {
9083                                 internal_error(state, ins, "inconsistent lhs count");
9084                         }
9085                         piece = LHS(lval, idx);
9086                 } else {
9087                         if (idx != 0) {
9088                                 internal_error(state, ins, "bad reg_offset into def");
9089                         }
9090                         if (i != 0) {
9091                                 internal_error(state, ins, "bad reg count from def");
9092                         }
9093                         piece = lval;
9094                 }
9095
9096                 /* Remember the offset of the bitfield */
9097                 if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
9098                         get_occurance(ins->occurance);
9099                         piece = build_triple(state, OP_BITREF, type, piece, 0,
9100                                 ins->occurance);
9101                         piece->u.bitfield.size   = size_of(state, type);
9102                         piece->u.bitfield.offset = reg_offset % REG_SIZEOF_REG;
9103                 }
9104                 else if ((reg_offset % REG_SIZEOF_REG) != 0) {
9105                         internal_error(state, ins, 
9106                                 "request for a nonbitfield sub register?");
9107                 }
9108
9109                 LHS(tuple, i) = piece;
9110         }
9111
9112         return decompose_with_tuple(state, ins, tuple);
9113 }
9114
9115 static struct triple *decompose_index(struct compile_state *state, 
9116         struct triple *ins)
9117 {
9118         struct triple *tuple, *lval;
9119         struct type *type;
9120         int i, idx;
9121
9122         lval = MISC(ins, 0);
9123         idx = index_reg_offset(state, lval->type, ins->u.cval)/REG_SIZEOF_REG;
9124         type = index_type(state, lval->type, ins->u.cval);
9125 #if DEBUG_DECOMPOSE_HIRES
9126 {
9127         FILE *fp = state->dbgout;
9128         fprintf(fp, "index type: ");
9129         name_of(fp, type);
9130         fprintf(fp, "\n");
9131 }
9132 #endif
9133
9134         get_occurance(ins->occurance);
9135         tuple = alloc_triple(state, OP_TUPLE, type, -1, -1, 
9136                 ins->occurance);
9137
9138         for(i = 0; i < tuple->lhs; i++, idx++) {
9139                 struct triple *piece;
9140                 if (!triple_is_def(state, lval)) {
9141                         if (idx > lval->lhs) {
9142                                 internal_error(state, ins, "inconsistent lhs count");
9143                         }
9144                         piece = LHS(lval, idx);
9145                 } else {
9146                         if (idx != 0) {
9147                                 internal_error(state, ins, "bad reg_offset into def");
9148                         }
9149                         if (i != 0) {
9150                                 internal_error(state, ins, "bad reg count from def");
9151                         }
9152                         piece = lval;
9153                 }
9154                 LHS(tuple, i) = piece;
9155         }
9156
9157         return decompose_with_tuple(state, ins, tuple);
9158 }
9159
9160 static void decompose_compound_types(struct compile_state *state)
9161 {
9162         struct triple *ins, *next, *first;
9163         FILE *fp;
9164         fp = state->dbgout;
9165         first = state->first;
9166         ins = first;
9167
9168         /* Pass one expand compound values into pseudo registers.
9169          */
9170         next = first;
9171         do {
9172                 ins = next;
9173                 next = ins->next;
9174                 switch(ins->op) {
9175                 case OP_UNKNOWNVAL:
9176                         next = decompose_unknownval(state, ins);
9177                         break;
9178
9179                 case OP_READ:
9180                         next = decompose_read(state, ins);
9181                         break;
9182
9183                 case OP_WRITE:
9184                         next = decompose_write(state, ins);
9185                         break;
9186
9187
9188                 /* Be very careful with the load/store logic. These
9189                  * operations must convert from the in register layout
9190                  * to the in memory layout, which is nontrivial.
9191                  */
9192                 case OP_LOAD:
9193                         next = decompose_load(state, ins);
9194                         break;
9195                 case OP_STORE:
9196                         next = decompose_store(state, ins);
9197                         break;
9198
9199                 case OP_DOT:
9200                         next = decompose_dot(state, ins);
9201                         break;
9202                 case OP_INDEX:
9203                         next = decompose_index(state, ins);
9204                         break;
9205                         
9206                 }
9207 #if DEBUG_DECOMPOSE_HIRES
9208                 fprintf(fp, "decompose next: %p \n", next);
9209                 fflush(fp);
9210                 fprintf(fp, "next->op: %d %s\n",
9211                         next->op, tops(next->op));
9212                 /* High resolution debugging mode */
9213                 print_triples(state);
9214 #endif
9215         } while (next != first);
9216
9217         /* Pass two remove the tuples.
9218          */
9219         ins = first;
9220         do {
9221                 next = ins->next;
9222                 if (ins->op == OP_TUPLE) {
9223                         if (ins->use) {
9224                                 internal_error(state, ins, "tuple used");
9225                         }
9226                         else {
9227                                 release_triple(state, ins);
9228                         }
9229                 } 
9230                 ins = next;
9231         } while(ins != first);
9232         ins = first;
9233         do {
9234                 next = ins->next;
9235                 if (ins->op == OP_BITREF) {
9236                         if (ins->use) {
9237                                 internal_error(state, ins, "bitref used");
9238                         } 
9239                         else {
9240                                 release_triple(state, ins);
9241                         }
9242                 }
9243                 ins = next;
9244         } while(ins != first);
9245
9246         /* Pass three verify the state and set ->id to 0.
9247          */
9248         next = first;
9249         do {
9250                 ins = next;
9251                 next = ins->next;
9252                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9253                 if (triple_stores_block(state, ins)) {
9254                         ins->u.block = 0;
9255                 }
9256                 if (triple_is_def(state, ins)) {
9257                         if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9258                                 internal_error(state, ins, "multi register value remains?");
9259                         }
9260                 }
9261                 if (ins->op == OP_DOT) {
9262                         internal_error(state, ins, "OP_DOT remains?");
9263                 }
9264                 if (ins->op == OP_INDEX) {
9265                         internal_error(state, ins, "OP_INDEX remains?");
9266                 }
9267                 if (ins->op == OP_BITREF) {
9268                         internal_error(state, ins, "OP_BITREF remains?");
9269                 }
9270                 if (ins->op == OP_TUPLE) {
9271                         internal_error(state, ins, "OP_TUPLE remains?");
9272                 }
9273         } while(next != first);
9274 }
9275
9276 /* For those operations that cannot be simplified */
9277 static void simplify_noop(struct compile_state *state, struct triple *ins)
9278 {
9279         return;
9280 }
9281
9282 static void simplify_smul(struct compile_state *state, struct triple *ins)
9283 {
9284         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9285                 struct triple *tmp;
9286                 tmp = RHS(ins, 0);
9287                 RHS(ins, 0) = RHS(ins, 1);
9288                 RHS(ins, 1) = tmp;
9289         }
9290         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9291                 long_t left, right;
9292                 left  = read_sconst(state, ins, RHS(ins, 0));
9293                 right = read_sconst(state, ins, RHS(ins, 1));
9294                 mkconst(state, ins, left * right);
9295         }
9296         else if (is_zero(RHS(ins, 1))) {
9297                 mkconst(state, ins, 0);
9298         }
9299         else if (is_one(RHS(ins, 1))) {
9300                 mkcopy(state, ins, RHS(ins, 0));
9301         }
9302         else if (is_pow2(RHS(ins, 1))) {
9303                 struct triple *val;
9304                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9305                 ins->op = OP_SL;
9306                 insert_triple(state, state->global_pool, val);
9307                 unuse_triple(RHS(ins, 1), ins);
9308                 use_triple(val, ins);
9309                 RHS(ins, 1) = val;
9310         }
9311 }
9312
9313 static void simplify_umul(struct compile_state *state, struct triple *ins)
9314 {
9315         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9316                 struct triple *tmp;
9317                 tmp = RHS(ins, 0);
9318                 RHS(ins, 0) = RHS(ins, 1);
9319                 RHS(ins, 1) = tmp;
9320         }
9321         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9322                 ulong_t left, right;
9323                 left  = read_const(state, ins, RHS(ins, 0));
9324                 right = read_const(state, ins, RHS(ins, 1));
9325                 mkconst(state, ins, left * right);
9326         }
9327         else if (is_zero(RHS(ins, 1))) {
9328                 mkconst(state, ins, 0);
9329         }
9330         else if (is_one(RHS(ins, 1))) {
9331                 mkcopy(state, ins, RHS(ins, 0));
9332         }
9333         else if (is_pow2(RHS(ins, 1))) {
9334                 struct triple *val;
9335                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9336                 ins->op = OP_SL;
9337                 insert_triple(state, state->global_pool, val);
9338                 unuse_triple(RHS(ins, 1), ins);
9339                 use_triple(val, ins);
9340                 RHS(ins, 1) = val;
9341         }
9342 }
9343
9344 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9345 {
9346         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9347                 long_t left, right;
9348                 left  = read_sconst(state, ins, RHS(ins, 0));
9349                 right = read_sconst(state, ins, RHS(ins, 1));
9350                 mkconst(state, ins, left / right);
9351         }
9352         else if (is_zero(RHS(ins, 0))) {
9353                 mkconst(state, ins, 0);
9354         }
9355         else if (is_zero(RHS(ins, 1))) {
9356                 error(state, ins, "division by zero");
9357         }
9358         else if (is_one(RHS(ins, 1))) {
9359                 mkcopy(state, ins, RHS(ins, 0));
9360         }
9361         else if (is_pow2(RHS(ins, 1))) {
9362                 struct triple *val;
9363                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9364                 ins->op = OP_SSR;
9365                 insert_triple(state, state->global_pool, val);
9366                 unuse_triple(RHS(ins, 1), ins);
9367                 use_triple(val, ins);
9368                 RHS(ins, 1) = val;
9369         }
9370 }
9371
9372 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9373 {
9374         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9375                 ulong_t left, right;
9376                 left  = read_const(state, ins, RHS(ins, 0));
9377                 right = read_const(state, ins, RHS(ins, 1));
9378                 mkconst(state, ins, left / right);
9379         }
9380         else if (is_zero(RHS(ins, 0))) {
9381                 mkconst(state, ins, 0);
9382         }
9383         else if (is_zero(RHS(ins, 1))) {
9384                 error(state, ins, "division by zero");
9385         }
9386         else if (is_one(RHS(ins, 1))) {
9387                 mkcopy(state, ins, RHS(ins, 0));
9388         }
9389         else if (is_pow2(RHS(ins, 1))) {
9390                 struct triple *val;
9391                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9392                 ins->op = OP_USR;
9393                 insert_triple(state, state->global_pool, val);
9394                 unuse_triple(RHS(ins, 1), ins);
9395                 use_triple(val, ins);
9396                 RHS(ins, 1) = val;
9397         }
9398 }
9399
9400 static void simplify_smod(struct compile_state *state, struct triple *ins)
9401 {
9402         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9403                 long_t left, right;
9404                 left  = read_const(state, ins, RHS(ins, 0));
9405                 right = read_const(state, ins, RHS(ins, 1));
9406                 mkconst(state, ins, left % right);
9407         }
9408         else if (is_zero(RHS(ins, 0))) {
9409                 mkconst(state, ins, 0);
9410         }
9411         else if (is_zero(RHS(ins, 1))) {
9412                 error(state, ins, "division by zero");
9413         }
9414         else if (is_one(RHS(ins, 1))) {
9415                 mkconst(state, ins, 0);
9416         }
9417         else if (is_pow2(RHS(ins, 1))) {
9418                 struct triple *val;
9419                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9420                 ins->op = OP_AND;
9421                 insert_triple(state, state->global_pool, val);
9422                 unuse_triple(RHS(ins, 1), ins);
9423                 use_triple(val, ins);
9424                 RHS(ins, 1) = val;
9425         }
9426 }
9427
9428 static void simplify_umod(struct compile_state *state, struct triple *ins)
9429 {
9430         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9431                 ulong_t left, right;
9432                 left  = read_const(state, ins, RHS(ins, 0));
9433                 right = read_const(state, ins, RHS(ins, 1));
9434                 mkconst(state, ins, left % right);
9435         }
9436         else if (is_zero(RHS(ins, 0))) {
9437                 mkconst(state, ins, 0);
9438         }
9439         else if (is_zero(RHS(ins, 1))) {
9440                 error(state, ins, "division by zero");
9441         }
9442         else if (is_one(RHS(ins, 1))) {
9443                 mkconst(state, ins, 0);
9444         }
9445         else if (is_pow2(RHS(ins, 1))) {
9446                 struct triple *val;
9447                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9448                 ins->op = OP_AND;
9449                 insert_triple(state, state->global_pool, val);
9450                 unuse_triple(RHS(ins, 1), ins);
9451                 use_triple(val, ins);
9452                 RHS(ins, 1) = val;
9453         }
9454 }
9455
9456 static void simplify_add(struct compile_state *state, struct triple *ins)
9457 {
9458         /* start with the pointer on the left */
9459         if (is_pointer(RHS(ins, 1))) {
9460                 struct triple *tmp;
9461                 tmp = RHS(ins, 0);
9462                 RHS(ins, 0) = RHS(ins, 1);
9463                 RHS(ins, 1) = tmp;
9464         }
9465         if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9466                 if (RHS(ins, 0)->op == OP_INTCONST) {
9467                         ulong_t left, right;
9468                         left  = read_const(state, ins, RHS(ins, 0));
9469                         right = read_const(state, ins, RHS(ins, 1));
9470                         mkconst(state, ins, left + right);
9471                 }
9472                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9473                         struct triple *sdecl;
9474                         ulong_t left, right;
9475                         sdecl = MISC(RHS(ins, 0), 0);
9476                         left  = RHS(ins, 0)->u.cval;
9477                         right = RHS(ins, 1)->u.cval;
9478                         mkaddr_const(state, ins, sdecl, left + right);
9479                 }
9480                 else {
9481                         internal_warning(state, ins, "Optimize me!");
9482                 }
9483         }
9484         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9485                 struct triple *tmp;
9486                 tmp = RHS(ins, 1);
9487                 RHS(ins, 1) = RHS(ins, 0);
9488                 RHS(ins, 0) = tmp;
9489         }
9490 }
9491
9492 static void simplify_sub(struct compile_state *state, struct triple *ins)
9493 {
9494         if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9495                 if (RHS(ins, 0)->op == OP_INTCONST) {
9496                         ulong_t left, right;
9497                         left  = read_const(state, ins, RHS(ins, 0));
9498                         right = read_const(state, ins, RHS(ins, 1));
9499                         mkconst(state, ins, left - right);
9500                 }
9501                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9502                         struct triple *sdecl;
9503                         ulong_t left, right;
9504                         sdecl = MISC(RHS(ins, 0), 0);
9505                         left  = RHS(ins, 0)->u.cval;
9506                         right = RHS(ins, 1)->u.cval;
9507                         mkaddr_const(state, ins, sdecl, left - right);
9508                 }
9509                 else {
9510                         internal_warning(state, ins, "Optimize me!");
9511                 }
9512         }
9513 }
9514
9515 static void simplify_sl(struct compile_state *state, struct triple *ins)
9516 {
9517         if (is_simple_const(RHS(ins, 1))) {
9518                 ulong_t right;
9519                 right = read_const(state, ins, RHS(ins, 1));
9520                 if (right >= (size_of(state, ins->type))) {
9521                         warning(state, ins, "left shift count >= width of type");
9522                 }
9523         }
9524         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9525                 ulong_t left, right;
9526                 left  = read_const(state, ins, RHS(ins, 0));
9527                 right = read_const(state, ins, RHS(ins, 1));
9528                 mkconst(state, ins,  left << right);
9529         }
9530 }
9531
9532 static void simplify_usr(struct compile_state *state, struct triple *ins)
9533 {
9534         if (is_simple_const(RHS(ins, 1))) {
9535                 ulong_t right;
9536                 right = read_const(state, ins, RHS(ins, 1));
9537                 if (right >= (size_of(state, ins->type))) {
9538                         warning(state, ins, "right shift count >= width of type");
9539                 }
9540         }
9541         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9542                 ulong_t left, right;
9543                 left  = read_const(state, ins, RHS(ins, 0));
9544                 right = read_const(state, ins, RHS(ins, 1));
9545                 mkconst(state, ins, left >> right);
9546         }
9547 }
9548
9549 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9550 {
9551         if (is_simple_const(RHS(ins, 1))) {
9552                 ulong_t right;
9553                 right = read_const(state, ins, RHS(ins, 1));
9554                 if (right >= (size_of(state, ins->type))) {
9555                         warning(state, ins, "right shift count >= width of type");
9556                 }
9557         }
9558         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9559                 long_t left, right;
9560                 left  = read_sconst(state, ins, RHS(ins, 0));
9561                 right = read_sconst(state, ins, RHS(ins, 1));
9562                 mkconst(state, ins, left >> right);
9563         }
9564 }
9565
9566 static void simplify_and(struct compile_state *state, struct triple *ins)
9567 {
9568         struct triple *left, *right;
9569         left = RHS(ins, 0);
9570         right = RHS(ins, 1);
9571
9572         if (is_simple_const(left) && is_simple_const(right)) {
9573                 ulong_t lval, rval;
9574                 lval = read_const(state, ins, left);
9575                 rval = read_const(state, ins, right);
9576                 mkconst(state, ins, lval & rval);
9577         }
9578         else if (is_zero(right) || is_zero(left)) {
9579                 mkconst(state, ins, 0);
9580         }
9581 }
9582
9583 static void simplify_or(struct compile_state *state, struct triple *ins)
9584 {
9585         struct triple *left, *right;
9586         left = RHS(ins, 0);
9587         right = RHS(ins, 1);
9588
9589         if (is_simple_const(left) && is_simple_const(right)) {
9590                 ulong_t lval, rval;
9591                 lval = read_const(state, ins, left);
9592                 rval = read_const(state, ins, right);
9593                 mkconst(state, ins, lval | rval);
9594         }
9595 #if 0 /* I need to handle type mismatches here... */
9596         else if (is_zero(right)) {
9597                 mkcopy(state, ins, left);
9598         }
9599         else if (is_zero(left)) {
9600                 mkcopy(state, ins, right);
9601         }
9602 #endif
9603 }
9604
9605 static void simplify_xor(struct compile_state *state, struct triple *ins)
9606 {
9607         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9608                 ulong_t left, right;
9609                 left  = read_const(state, ins, RHS(ins, 0));
9610                 right = read_const(state, ins, RHS(ins, 1));
9611                 mkconst(state, ins, left ^ right);
9612         }
9613 }
9614
9615 static void simplify_pos(struct compile_state *state, struct triple *ins)
9616 {
9617         if (is_const(RHS(ins, 0))) {
9618                 mkconst(state, ins, RHS(ins, 0)->u.cval);
9619         }
9620         else {
9621                 mkcopy(state, ins, RHS(ins, 0));
9622         }
9623 }
9624
9625 static void simplify_neg(struct compile_state *state, struct triple *ins)
9626 {
9627         if (is_simple_const(RHS(ins, 0))) {
9628                 ulong_t left;
9629                 left = read_const(state, ins, RHS(ins, 0));
9630                 mkconst(state, ins, -left);
9631         }
9632         else if (RHS(ins, 0)->op == OP_NEG) {
9633                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9634         }
9635 }
9636
9637 static void simplify_invert(struct compile_state *state, struct triple *ins)
9638 {
9639         if (is_simple_const(RHS(ins, 0))) {
9640                 ulong_t left;
9641                 left = read_const(state, ins, RHS(ins, 0));
9642                 mkconst(state, ins, ~left);
9643         }
9644 }
9645
9646 static void simplify_eq(struct compile_state *state, struct triple *ins)
9647 {
9648         struct triple *left, *right;
9649         left = RHS(ins, 0);
9650         right = RHS(ins, 1);
9651
9652         if (is_const(left) && is_const(right)) {
9653                 int val;
9654                 val = const_eq(state, ins, left, right);
9655                 if (val >= 0) {
9656                         mkconst(state, ins, val == 1);
9657                 }
9658         }
9659         else if (left == right) {
9660                 mkconst(state, ins, 1);
9661         }
9662 }
9663
9664 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9665 {
9666         struct triple *left, *right;
9667         left = RHS(ins, 0);
9668         right = RHS(ins, 1);
9669
9670         if (is_const(left) && is_const(right)) {
9671                 int val;
9672                 val = const_eq(state, ins, left, right);
9673                 if (val >= 0) {
9674                         mkconst(state, ins, val != 1);
9675                 }
9676         }
9677         if (left == right) {
9678                 mkconst(state, ins, 0);
9679         }
9680 }
9681
9682 static void simplify_sless(struct compile_state *state, struct triple *ins)
9683 {
9684         struct triple *left, *right;
9685         left = RHS(ins, 0);
9686         right = RHS(ins, 1);
9687
9688         if (is_const(left) && is_const(right)) {
9689                 int val;
9690                 val = const_scmp(state, ins, left, right);
9691                 if ((val >= -1) && (val <= 1)) {
9692                         mkconst(state, ins, val < 0);
9693                 }
9694         }
9695         else if (left == right) {
9696                 mkconst(state, ins, 0);
9697         }
9698 }
9699
9700 static void simplify_uless(struct compile_state *state, struct triple *ins)
9701 {
9702         struct triple *left, *right;
9703         left = RHS(ins, 0);
9704         right = RHS(ins, 1);
9705
9706         if (is_const(left) && is_const(right)) {
9707                 int val;
9708                 val = const_ucmp(state, ins, left, right);
9709                 if ((val >= -1) && (val <= 1)) {
9710                         mkconst(state, ins, val < 0);
9711                 }
9712         }
9713         else if (is_zero(right)) {
9714                 mkconst(state, ins, 0);
9715         }
9716         else if (left == right) {
9717                 mkconst(state, ins, 0);
9718         }
9719 }
9720
9721 static void simplify_smore(struct compile_state *state, struct triple *ins)
9722 {
9723         struct triple *left, *right;
9724         left = RHS(ins, 0);
9725         right = RHS(ins, 1);
9726
9727         if (is_const(left) && is_const(right)) {
9728                 int val;
9729                 val = const_scmp(state, ins, left, right);
9730                 if ((val >= -1) && (val <= 1)) {
9731                         mkconst(state, ins, val > 0);
9732                 }
9733         }
9734         else if (left == right) {
9735                 mkconst(state, ins, 0);
9736         }
9737 }
9738
9739 static void simplify_umore(struct compile_state *state, struct triple *ins)
9740 {
9741         struct triple *left, *right;
9742         left = RHS(ins, 0);
9743         right = RHS(ins, 1);
9744
9745         if (is_const(left) && is_const(right)) {
9746                 int val;
9747                 val = const_ucmp(state, ins, left, right);
9748                 if ((val >= -1) && (val <= 1)) {
9749                         mkconst(state, ins, val > 0);
9750                 }
9751         }
9752         else if (is_zero(left)) {
9753                 mkconst(state, ins, 0);
9754         }
9755         else if (left == right) {
9756                 mkconst(state, ins, 0);
9757         }
9758 }
9759
9760
9761 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9762 {
9763         struct triple *left, *right;
9764         left = RHS(ins, 0);
9765         right = RHS(ins, 1);
9766
9767         if (is_const(left) && is_const(right)) {
9768                 int val;
9769                 val = const_scmp(state, ins, left, right);
9770                 if ((val >= -1) && (val <= 1)) {
9771                         mkconst(state, ins, val <= 0);
9772                 }
9773         }
9774         else if (left == right) {
9775                 mkconst(state, ins, 1);
9776         }
9777 }
9778
9779 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9780 {
9781         struct triple *left, *right;
9782         left = RHS(ins, 0);
9783         right = RHS(ins, 1);
9784
9785         if (is_const(left) && is_const(right)) {
9786                 int val;
9787                 val = const_ucmp(state, ins, left, right);
9788                 if ((val >= -1) && (val <= 1)) {
9789                         mkconst(state, ins, val <= 0);
9790                 }
9791         }
9792         else if (is_zero(left)) {
9793                 mkconst(state, ins, 1);
9794         }
9795         else if (left == right) {
9796                 mkconst(state, ins, 1);
9797         }
9798 }
9799
9800 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9801 {
9802         struct triple *left, *right;
9803         left = RHS(ins, 0);
9804         right = RHS(ins, 1);
9805
9806         if (is_const(left) && is_const(right)) {
9807                 int val;
9808                 val = const_scmp(state, ins, left, right);
9809                 if ((val >= -1) && (val <= 1)) {
9810                         mkconst(state, ins, val >= 0);
9811                 }
9812         }
9813         else if (left == right) {
9814                 mkconst(state, ins, 1);
9815         }
9816 }
9817
9818 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9819 {
9820         struct triple *left, *right;
9821         left = RHS(ins, 0);
9822         right = RHS(ins, 1);
9823
9824         if (is_const(left) && is_const(right)) {
9825                 int val;
9826                 val = const_ucmp(state, ins, left, right);
9827                 if ((val >= -1) && (val <= 1)) {
9828                         mkconst(state, ins, val >= 0);
9829                 }
9830         }
9831         else if (is_zero(right)) {
9832                 mkconst(state, ins, 1);
9833         }
9834         else if (left == right) {
9835                 mkconst(state, ins, 1);
9836         }
9837 }
9838
9839 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9840 {
9841         struct triple *rhs;
9842         rhs = RHS(ins, 0);
9843
9844         if (is_const(rhs)) {
9845                 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9846         }
9847         /* Otherwise if I am the only user... */
9848         else if ((rhs->use) &&
9849                 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9850                 int need_copy = 1;
9851                 /* Invert a boolean operation */
9852                 switch(rhs->op) {
9853                 case OP_LTRUE:   rhs->op = OP_LFALSE;  break;
9854                 case OP_LFALSE:  rhs->op = OP_LTRUE;   break;
9855                 case OP_EQ:      rhs->op = OP_NOTEQ;   break;
9856                 case OP_NOTEQ:   rhs->op = OP_EQ;      break;
9857                 case OP_SLESS:   rhs->op = OP_SMOREEQ; break;
9858                 case OP_ULESS:   rhs->op = OP_UMOREEQ; break;
9859                 case OP_SMORE:   rhs->op = OP_SLESSEQ; break;
9860                 case OP_UMORE:   rhs->op = OP_ULESSEQ; break;
9861                 case OP_SLESSEQ: rhs->op = OP_SMORE;   break;
9862                 case OP_ULESSEQ: rhs->op = OP_UMORE;   break;
9863                 case OP_SMOREEQ: rhs->op = OP_SLESS;   break;
9864                 case OP_UMOREEQ: rhs->op = OP_ULESS;   break;
9865                 default:
9866                         need_copy = 0;
9867                         break;
9868                 }
9869                 if (need_copy) {
9870                         mkcopy(state, ins, rhs);
9871                 }
9872         }
9873 }
9874
9875 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9876 {
9877         struct triple *rhs;
9878         rhs = RHS(ins, 0);
9879
9880         if (is_const(rhs)) {
9881                 mkconst(state, ins, const_ltrue(state, ins, rhs));
9882         }
9883         else switch(rhs->op) {
9884         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
9885         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
9886         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9887                 mkcopy(state, ins, rhs);
9888         }
9889
9890 }
9891
9892 static void simplify_load(struct compile_state *state, struct triple *ins)
9893 {
9894         struct triple *addr, *sdecl, *blob;
9895
9896         /* If I am doing a load with a constant pointer from a constant
9897          * table get the value.
9898          */
9899         addr = RHS(ins, 0);
9900         if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
9901                 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
9902                 (blob->op == OP_BLOBCONST)) {
9903                 unsigned char buffer[SIZEOF_WORD];
9904                 size_t reg_size, mem_size;
9905                 const char *src, *end;
9906                 ulong_t val;
9907                 reg_size = reg_size_of(state, ins->type);
9908                 if (reg_size > REG_SIZEOF_REG) {
9909                         internal_error(state, ins, "load size greater than register");
9910                 }
9911                 mem_size = size_of(state, ins->type);
9912                 end = blob->u.blob;
9913                 end += bits_to_bytes(size_of(state, sdecl->type));
9914                 src = blob->u.blob;
9915                 src += addr->u.cval;
9916
9917                 if (src > end) {
9918                         error(state, ins, "Load address out of bounds");
9919                 }
9920
9921                 memset(buffer, 0, sizeof(buffer));
9922                 memcpy(buffer, src, bits_to_bytes(mem_size));
9923
9924                 switch(mem_size) {
9925                 case SIZEOF_I8:  val = *((uint8_t *) buffer); break;
9926                 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
9927                 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
9928                 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
9929                 default:
9930                         internal_error(state, ins, "mem_size: %d not handled",
9931                                 mem_size);
9932                         val = 0;
9933                         break;
9934                 }
9935                 mkconst(state, ins, val);
9936         }
9937 }
9938
9939 static void simplify_uextract(struct compile_state *state, struct triple *ins)
9940 {
9941         if (is_simple_const(RHS(ins, 0))) {
9942                 ulong_t val;
9943                 ulong_t mask;
9944                 val = read_const(state, ins, RHS(ins, 0));
9945                 mask = 1;
9946                 mask <<= ins->u.bitfield.size;
9947                 mask -= 1;
9948                 val >>= ins->u.bitfield.offset;
9949                 val &= mask;
9950                 mkconst(state, ins, val);
9951         }
9952 }
9953
9954 static void simplify_sextract(struct compile_state *state, struct triple *ins)
9955 {
9956         if (is_simple_const(RHS(ins, 0))) {
9957                 ulong_t val;
9958                 ulong_t mask;
9959                 long_t sval;
9960                 val = read_const(state, ins, RHS(ins, 0));
9961                 mask = 1;
9962                 mask <<= ins->u.bitfield.size;
9963                 mask -= 1;
9964                 val >>= ins->u.bitfield.offset;
9965                 val &= mask;
9966                 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
9967                 sval = val;
9968                 sval >>= (SIZEOF_LONG - ins->u.bitfield.size); 
9969                 mkconst(state, ins, sval);
9970         }
9971 }
9972
9973 static void simplify_deposit(struct compile_state *state, struct triple *ins)
9974 {
9975         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9976                 ulong_t targ, val;
9977                 ulong_t mask;
9978                 targ = read_const(state, ins, RHS(ins, 0));
9979                 val  = read_const(state, ins, RHS(ins, 1));
9980                 mask = 1;
9981                 mask <<= ins->u.bitfield.size;
9982                 mask -= 1;
9983                 mask <<= ins->u.bitfield.offset;
9984                 targ &= ~mask;
9985                 val <<= ins->u.bitfield.offset;
9986                 val &= mask;
9987                 targ |= val;
9988                 mkconst(state, ins, targ);
9989         }
9990 }
9991
9992 static void simplify_copy(struct compile_state *state, struct triple *ins)
9993 {
9994         struct triple *right;
9995         right = RHS(ins, 0);
9996         if (is_subset_type(ins->type, right->type)) {
9997                 ins->type = right->type;
9998         }
9999         if (equiv_types(ins->type, right->type)) {
10000                 ins->op = OP_COPY;/* I don't need to convert if the types match */
10001         } else {
10002                 if (ins->op == OP_COPY) {
10003                         internal_error(state, ins, "type mismatch on copy");
10004                 }
10005         }
10006         if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10007                 struct triple *sdecl;
10008                 ulong_t offset;
10009                 sdecl  = MISC(right, 0);
10010                 offset = right->u.cval;
10011                 mkaddr_const(state, ins, sdecl, offset);
10012         }
10013         else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10014                 switch(right->op) {
10015                 case OP_INTCONST:
10016                 {
10017                         ulong_t left;
10018                         left = read_const(state, ins, right);
10019                         /* Ensure I have not overflowed the destination. */
10020                         if (size_of(state, right->type) > size_of(state, ins->type)) {
10021                                 ulong_t mask;
10022                                 mask = 1;
10023                                 mask <<= size_of(state, ins->type);
10024                                 mask -= 1;
10025                                 left &= mask;
10026                         }
10027                         /* Ensure I am properly sign extended */
10028                         if (size_of(state, right->type) < size_of(state, ins->type) &&
10029                                 is_signed(right->type)) {
10030                                 long_t val;
10031                                 int shift;
10032                                 shift = SIZEOF_LONG - size_of(state, right->type);
10033                                 val = left;
10034                                 val <<= shift;
10035                                 val >>= shift;
10036                                 left = val;
10037                         }
10038                         mkconst(state, ins, left);
10039                         break;
10040                 }
10041                 default:
10042                         internal_error(state, ins, "uknown constant");
10043                         break;
10044                 }
10045         }
10046 }
10047
10048 static int phi_present(struct block *block)
10049 {
10050         struct triple *ptr;
10051         if (!block) {
10052                 return 0;
10053         }
10054         ptr = block->first;
10055         do {
10056                 if (ptr->op == OP_PHI) {
10057                         return 1;
10058                 }
10059                 ptr = ptr->next;
10060         } while(ptr != block->last);
10061         return 0;
10062 }
10063
10064 static int phi_dependency(struct block *block)
10065 {
10066         /* A block has a phi dependency if a phi function
10067          * depends on that block to exist, and makes a block
10068          * that is otherwise useless unsafe to remove.
10069          */
10070         if (block) {
10071                 struct block_set *edge;
10072                 for(edge = block->edges; edge; edge = edge->next) {
10073                         if (phi_present(edge->member)) {
10074                                 return 1;
10075                         }
10076                 }
10077         }
10078         return 0;
10079 }
10080
10081 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10082 {
10083         struct triple *targ;
10084         targ = TARG(ins, 0);
10085         /* During scc_transform temporary triples are allocated that
10086          * loop back onto themselves. If I see one don't advance the
10087          * target.
10088          */
10089         while(triple_is_structural(state, targ) && 
10090                 (targ->next != targ) && (targ->next != state->first)) {
10091                 targ = targ->next;
10092         }
10093         return targ;
10094 }
10095
10096
10097 static void simplify_branch(struct compile_state *state, struct triple *ins)
10098 {
10099         int simplified, loops;
10100         if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10101                 internal_error(state, ins, "not branch");
10102         }
10103         if (ins->use != 0) {
10104                 internal_error(state, ins, "branch use");
10105         }
10106         /* The challenge here with simplify branch is that I need to 
10107          * make modifications to the control flow graph as well
10108          * as to the branch instruction itself.  That is handled
10109          * by rebuilding the basic blocks after simplify all is called.
10110          */
10111
10112         /* If we have a branch to an unconditional branch update
10113          * our target.  But watch out for dependencies from phi
10114          * functions.
10115          * Also only do this a limited number of times so
10116          * we don't get into an infinite loop.
10117          */
10118         loops = 0;
10119         do {
10120                 struct triple *targ;
10121                 simplified = 0;
10122                 targ = branch_target(state, ins);
10123                 if ((targ != ins) && (targ->op == OP_BRANCH) && 
10124                         !phi_dependency(targ->u.block))
10125                 {
10126                         unuse_triple(TARG(ins, 0), ins);
10127                         TARG(ins, 0) = TARG(targ, 0);
10128                         use_triple(TARG(ins, 0), ins);
10129                         simplified = 1;
10130                 }
10131         } while(simplified && (++loops < 20));
10132
10133         /* If we have a conditional branch with a constant condition
10134          * make it an unconditional branch.
10135          */
10136         if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10137                 struct triple *targ;
10138                 ulong_t value;
10139                 value = read_const(state, ins, RHS(ins, 0));
10140                 unuse_triple(RHS(ins, 0), ins);
10141                 targ = TARG(ins, 0);
10142                 ins->rhs  = 0;
10143                 ins->targ = 1;
10144                 ins->op = OP_BRANCH;
10145                 if (value) {
10146                         unuse_triple(ins->next, ins);
10147                         TARG(ins, 0) = targ;
10148                 }
10149                 else {
10150                         unuse_triple(targ, ins);
10151                         TARG(ins, 0) = ins->next;
10152                 }
10153         }
10154
10155         /* If we have a branch to the next instruction,
10156          * make it a noop.
10157          */
10158         if (TARG(ins, 0) == ins->next) {
10159                 unuse_triple(TARG(ins, 0), ins);
10160                 if (ins->op == OP_CBRANCH) {
10161                         unuse_triple(RHS(ins, 0), ins);
10162                         unuse_triple(ins->next, ins);
10163                 }
10164                 ins->lhs = 0;
10165                 ins->rhs = 0;
10166                 ins->misc = 0;
10167                 ins->targ = 0;
10168                 ins->op = OP_NOOP;
10169                 if (ins->use) {
10170                         internal_error(state, ins, "noop use != 0");
10171                 }
10172         }
10173 }
10174
10175 static void simplify_label(struct compile_state *state, struct triple *ins)
10176 {
10177         /* Ignore volatile labels */
10178         if (!triple_is_pure(state, ins, ins->id)) {
10179                 return;
10180         }
10181         if (ins->use == 0) {
10182                 ins->op = OP_NOOP;
10183         }
10184         else if (ins->prev->op == OP_LABEL) {
10185                 /* In general it is not safe to merge one label that
10186                  * imediately follows another.  The problem is that the empty
10187                  * looking block may have phi functions that depend on it.
10188                  */
10189                 if (!phi_dependency(ins->prev->u.block)) {
10190                         struct triple_set *user, *next;
10191                         ins->op = OP_NOOP;
10192                         for(user = ins->use; user; user = next) {
10193                                 struct triple *use, **expr;
10194                                 next = user->next;
10195                                 use = user->member;
10196                                 expr = triple_targ(state, use, 0);
10197                                 for(;expr; expr = triple_targ(state, use, expr)) {
10198                                         if (*expr == ins) {
10199                                                 *expr = ins->prev;
10200                                                 unuse_triple(ins, use);
10201                                                 use_triple(ins->prev, use);
10202                                         }
10203                                         
10204                                 }
10205                         }
10206                         if (ins->use) {
10207                                 internal_error(state, ins, "noop use != 0");
10208                         }
10209                 }
10210         }
10211 }
10212
10213 static void simplify_phi(struct compile_state *state, struct triple *ins)
10214 {
10215         struct triple **slot;
10216         struct triple *value;
10217         int zrhs, i;
10218         ulong_t cvalue;
10219         slot = &RHS(ins, 0);
10220         zrhs = ins->rhs;
10221         if (zrhs == 0) {
10222                 return;
10223         }
10224         /* See if all of the rhs members of a phi have the same value */
10225         if (slot[0] && is_simple_const(slot[0])) {
10226                 cvalue = read_const(state, ins, slot[0]);
10227                 for(i = 1; i < zrhs; i++) {
10228                         if (    !slot[i] ||
10229                                 !is_simple_const(slot[i]) ||
10230                                 !equiv_types(slot[0]->type, slot[i]->type) ||
10231                                 (cvalue != read_const(state, ins, slot[i]))) {
10232                                 break;
10233                         }
10234                 }
10235                 if (i == zrhs) {
10236                         mkconst(state, ins, cvalue);
10237                         return;
10238                 }
10239         }
10240         
10241         /* See if all of rhs members of a phi are the same */
10242         value = slot[0];
10243         for(i = 1; i < zrhs; i++) {
10244                 if (slot[i] != value) {
10245                         break;
10246                 }
10247         }
10248         if (i == zrhs) {
10249                 /* If the phi has a single value just copy it */
10250                 if (!is_subset_type(ins->type, value->type)) {
10251                         internal_error(state, ins, "bad input type to phi");
10252                 }
10253                 /* Make the types match */
10254                 if (!equiv_types(ins->type, value->type)) {
10255                         ins->type = value->type;
10256                 }
10257                 /* Now make the actual copy */
10258                 mkcopy(state, ins, value);
10259                 return;
10260         }
10261 }
10262
10263
10264 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10265 {
10266         if (is_simple_const(RHS(ins, 0))) {
10267                 ulong_t left;
10268                 left = read_const(state, ins, RHS(ins, 0));
10269                 mkconst(state, ins, bsf(left));
10270         }
10271 }
10272
10273 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10274 {
10275         if (is_simple_const(RHS(ins, 0))) {
10276                 ulong_t left;
10277                 left = read_const(state, ins, RHS(ins, 0));
10278                 mkconst(state, ins, bsr(left));
10279         }
10280 }
10281
10282
10283 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10284 static const struct simplify_table {
10285         simplify_t func;
10286         unsigned long flag;
10287 } table_simplify[] = {
10288 #define simplify_sdivt    simplify_noop
10289 #define simplify_udivt    simplify_noop
10290 #define simplify_piece    simplify_noop
10291
10292 [OP_SDIVT      ] = { simplify_sdivt,    COMPILER_SIMPLIFY_ARITH },
10293 [OP_UDIVT      ] = { simplify_udivt,    COMPILER_SIMPLIFY_ARITH },
10294 [OP_SMUL       ] = { simplify_smul,     COMPILER_SIMPLIFY_ARITH },
10295 [OP_UMUL       ] = { simplify_umul,     COMPILER_SIMPLIFY_ARITH },
10296 [OP_SDIV       ] = { simplify_sdiv,     COMPILER_SIMPLIFY_ARITH },
10297 [OP_UDIV       ] = { simplify_udiv,     COMPILER_SIMPLIFY_ARITH },
10298 [OP_SMOD       ] = { simplify_smod,     COMPILER_SIMPLIFY_ARITH },
10299 [OP_UMOD       ] = { simplify_umod,     COMPILER_SIMPLIFY_ARITH },
10300 [OP_ADD        ] = { simplify_add,      COMPILER_SIMPLIFY_ARITH },
10301 [OP_SUB        ] = { simplify_sub,      COMPILER_SIMPLIFY_ARITH },
10302 [OP_SL         ] = { simplify_sl,       COMPILER_SIMPLIFY_SHIFT },
10303 [OP_USR        ] = { simplify_usr,      COMPILER_SIMPLIFY_SHIFT },
10304 [OP_SSR        ] = { simplify_ssr,      COMPILER_SIMPLIFY_SHIFT },
10305 [OP_AND        ] = { simplify_and,      COMPILER_SIMPLIFY_BITWISE },
10306 [OP_XOR        ] = { simplify_xor,      COMPILER_SIMPLIFY_BITWISE },
10307 [OP_OR         ] = { simplify_or,       COMPILER_SIMPLIFY_BITWISE },
10308 [OP_POS        ] = { simplify_pos,      COMPILER_SIMPLIFY_ARITH },
10309 [OP_NEG        ] = { simplify_neg,      COMPILER_SIMPLIFY_ARITH },
10310 [OP_INVERT     ] = { simplify_invert,   COMPILER_SIMPLIFY_BITWISE },
10311
10312 [OP_EQ         ] = { simplify_eq,       COMPILER_SIMPLIFY_LOGICAL },
10313 [OP_NOTEQ      ] = { simplify_noteq,    COMPILER_SIMPLIFY_LOGICAL },
10314 [OP_SLESS      ] = { simplify_sless,    COMPILER_SIMPLIFY_LOGICAL },
10315 [OP_ULESS      ] = { simplify_uless,    COMPILER_SIMPLIFY_LOGICAL },
10316 [OP_SMORE      ] = { simplify_smore,    COMPILER_SIMPLIFY_LOGICAL },
10317 [OP_UMORE      ] = { simplify_umore,    COMPILER_SIMPLIFY_LOGICAL },
10318 [OP_SLESSEQ    ] = { simplify_slesseq,  COMPILER_SIMPLIFY_LOGICAL },
10319 [OP_ULESSEQ    ] = { simplify_ulesseq,  COMPILER_SIMPLIFY_LOGICAL },
10320 [OP_SMOREEQ    ] = { simplify_smoreeq,  COMPILER_SIMPLIFY_LOGICAL },
10321 [OP_UMOREEQ    ] = { simplify_umoreeq,  COMPILER_SIMPLIFY_LOGICAL },
10322 [OP_LFALSE     ] = { simplify_lfalse,   COMPILER_SIMPLIFY_LOGICAL },
10323 [OP_LTRUE      ] = { simplify_ltrue,    COMPILER_SIMPLIFY_LOGICAL },
10324
10325 [OP_LOAD       ] = { simplify_load,     COMPILER_SIMPLIFY_OP },
10326 [OP_STORE      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10327
10328 [OP_UEXTRACT   ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10329 [OP_SEXTRACT   ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10330 [OP_DEPOSIT    ] = { simplify_deposit,  COMPILER_SIMPLIFY_BITFIELD },
10331
10332 [OP_NOOP       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10333
10334 [OP_INTCONST   ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10335 [OP_BLOBCONST  ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10336 [OP_ADDRCONST  ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10337 [OP_UNKNOWNVAL ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10338
10339 [OP_WRITE      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10340 [OP_READ       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10341 [OP_COPY       ] = { simplify_copy,     COMPILER_SIMPLIFY_COPY },
10342 [OP_CONVERT    ] = { simplify_copy,     COMPILER_SIMPLIFY_COPY },
10343 [OP_PIECE      ] = { simplify_piece,    COMPILER_SIMPLIFY_OP },
10344 [OP_ASM        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10345
10346 [OP_DOT        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10347 [OP_INDEX      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10348
10349 [OP_LIST       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10350 [OP_BRANCH     ] = { simplify_branch,   COMPILER_SIMPLIFY_BRANCH },
10351 [OP_CBRANCH    ] = { simplify_branch,   COMPILER_SIMPLIFY_BRANCH },
10352 [OP_CALL       ] = { simplify_noop,     COMPILER_SIMPLIFY_BRANCH },
10353 [OP_RET        ] = { simplify_noop,     COMPILER_SIMPLIFY_BRANCH },
10354 [OP_LABEL      ] = { simplify_label,    COMPILER_SIMPLIFY_LABEL },
10355 [OP_ADECL      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10356 [OP_SDECL      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10357 [OP_PHI        ] = { simplify_phi,      COMPILER_SIMPLIFY_PHI },
10358
10359 [OP_INB        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10360 [OP_INW        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10361 [OP_INL        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10362 [OP_OUTB       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10363 [OP_OUTW       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10364 [OP_OUTL       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10365 [OP_BSF        ] = { simplify_bsf,      COMPILER_SIMPLIFY_OP },
10366 [OP_BSR        ] = { simplify_bsr,      COMPILER_SIMPLIFY_OP },
10367 [OP_RDMSR      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10368 [OP_WRMSR      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },               
10369 [OP_HLT        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10370 };
10371
10372 static inline void debug_simplify(struct compile_state *state, 
10373         simplify_t do_simplify, struct triple *ins)
10374 {
10375 #if DEBUG_SIMPLIFY_HIRES
10376                 if (state->functions_joined && (do_simplify != simplify_noop)) {
10377                         /* High resolution debugging mode */
10378                         fprintf(state->dbgout, "simplifing: ");
10379                         display_triple(state->dbgout, ins);
10380                 }
10381 #endif
10382                 do_simplify(state, ins);
10383 #if DEBUG_SIMPLIFY_HIRES
10384                 if (state->functions_joined && (do_simplify != simplify_noop)) {
10385                         /* High resolution debugging mode */
10386                         fprintf(state->dbgout, "simplified: ");
10387                         display_triple(state->dbgout, ins);
10388                 }
10389 #endif
10390 }
10391 static void simplify(struct compile_state *state, struct triple *ins)
10392 {
10393         int op;
10394         simplify_t do_simplify;
10395         if (ins == &unknown_triple) {
10396                 internal_error(state, ins, "simplifying the unknown triple?");
10397         }
10398         do {
10399                 op = ins->op;
10400                 do_simplify = 0;
10401                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10402                         do_simplify = 0;
10403                 }
10404                 else {
10405                         do_simplify = table_simplify[op].func;
10406                 }
10407                 if (do_simplify && 
10408                         !(state->compiler->flags & table_simplify[op].flag)) {
10409                         do_simplify = simplify_noop;
10410                 }
10411                 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10412                         do_simplify = simplify_noop;
10413                 }
10414         
10415                 if (!do_simplify) {
10416                         internal_error(state, ins, "cannot simplify op: %d %s",
10417                                 op, tops(op));
10418                         return;
10419                 }
10420                 debug_simplify(state, do_simplify, ins);
10421         } while(ins->op != op);
10422 }
10423
10424 static void rebuild_ssa_form(struct compile_state *state);
10425
10426 static void simplify_all(struct compile_state *state)
10427 {
10428         struct triple *ins, *first;
10429         if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10430                 return;
10431         }
10432         first = state->first;
10433         ins = first->prev;
10434         do {
10435                 simplify(state, ins);
10436                 ins = ins->prev;
10437         } while(ins != first->prev);
10438         ins = first;
10439         do {
10440                 simplify(state, ins);
10441                 ins = ins->next;
10442         }while(ins != first);
10443         rebuild_ssa_form(state);
10444
10445         print_blocks(state, __func__, state->dbgout);
10446 }
10447
10448 /*
10449  * Builtins....
10450  * ============================
10451  */
10452
10453 static void register_builtin_function(struct compile_state *state,
10454         const char *name, int op, struct type *rtype, ...)
10455 {
10456         struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10457         struct triple *def, *arg, *result, *work, *last, *first, *retvar, *ret;
10458         struct hash_entry *ident;
10459         struct file_state file;
10460         int parameters;
10461         int name_len;
10462         va_list args;
10463         int i;
10464
10465         /* Dummy file state to get debug handling right */
10466         memset(&file, 0, sizeof(file));
10467         file.basename = "<built-in>";
10468         file.line = 1;
10469         file.report_line = 1;
10470         file.report_name = file.basename;
10471         file.prev = state->file;
10472         state->file = &file;
10473         state->function = name;
10474
10475         /* Find the Parameter count */
10476         valid_op(state, op);
10477         parameters = table_ops[op].rhs;
10478         if (parameters < 0 ) {
10479                 internal_error(state, 0, "Invalid builtin parameter count");
10480         }
10481
10482         /* Find the function type */
10483         ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10484         ftype->elements = parameters;
10485         next = &ftype->right;
10486         va_start(args, rtype);
10487         for(i = 0; i < parameters; i++) {
10488                 atype = va_arg(args, struct type *);
10489                 if (!*next) {
10490                         *next = atype;
10491                 } else {
10492                         *next = new_type(TYPE_PRODUCT, *next, atype);
10493                         next = &((*next)->right);
10494                 }
10495         }
10496         if (!*next) {
10497                 *next = &void_type;
10498         }
10499         va_end(args);
10500
10501         /* Get the initial closure type */
10502         ctype = new_type(TYPE_JOIN, &void_type, 0);
10503         ctype->elements = 1;
10504
10505         /* Get the return type */
10506         crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10507         crtype->elements = 2;
10508
10509         /* Generate the needed triples */
10510         def = triple(state, OP_LIST, ftype, 0, 0);
10511         first = label(state);
10512         RHS(def, 0) = first;
10513         result = flatten(state, first, variable(state, crtype));
10514         retvar = flatten(state, first, variable(state, &void_ptr_type));
10515         ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10516
10517         /* Now string them together */
10518         param = ftype->right;
10519         for(i = 0; i < parameters; i++) {
10520                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10521                         atype = param->left;
10522                 } else {
10523                         atype = param;
10524                 }
10525                 arg = flatten(state, first, variable(state, atype));
10526                 param = param->right;
10527         }
10528         work = new_triple(state, op, rtype, -1, parameters);
10529         generate_lhs_pieces(state, work);
10530         for(i = 0; i < parameters; i++) {
10531                 RHS(work, i) = read_expr(state, farg(state, def, i));
10532         }
10533         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10534                 work = write_expr(state, deref_index(state, result, 1), work);
10535         }
10536         work = flatten(state, first, work);
10537         last = flatten(state, first, label(state));
10538         ret  = flatten(state, first, ret);
10539         name_len = strlen(name);
10540         ident = lookup(state, name, name_len);
10541         ftype->type_ident = ident;
10542         symbol(state, ident, &ident->sym_ident, def, ftype);
10543         
10544         state->file = file.prev;
10545         state->function = 0;
10546         state->main_function = 0;
10547
10548         if (!state->functions) {
10549                 state->functions = def;
10550         } else {
10551                 insert_triple(state, state->functions, def);
10552         }
10553         if (state->compiler->debug & DEBUG_INLINE) {
10554                 FILE *fp = state->dbgout;
10555                 fprintf(fp, "\n");
10556                 loc(fp, state, 0);
10557                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10558                 display_func(state, fp, def);
10559                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10560         }
10561 }
10562
10563 static struct type *partial_struct(struct compile_state *state,
10564         const char *field_name, struct type *type, struct type *rest)
10565 {
10566         struct hash_entry *field_ident;
10567         struct type *result;
10568         int field_name_len;
10569
10570         field_name_len = strlen(field_name);
10571         field_ident = lookup(state, field_name, field_name_len);
10572
10573         result = clone_type(0, type);
10574         result->field_ident = field_ident;
10575
10576         if (rest) {
10577                 result = new_type(TYPE_PRODUCT, result, rest);
10578         }
10579         return result;
10580 }
10581
10582 static struct type *register_builtin_type(struct compile_state *state,
10583         const char *name, struct type *type)
10584 {
10585         struct hash_entry *ident;
10586         int name_len;
10587
10588         name_len = strlen(name);
10589         ident = lookup(state, name, name_len);
10590         
10591         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10592                 ulong_t elements = 0;
10593                 struct type *field;
10594                 type = new_type(TYPE_STRUCT, type, 0);
10595                 field = type->left;
10596                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10597                         elements++;
10598                         field = field->right;
10599                 }
10600                 elements++;
10601                 symbol(state, ident, &ident->sym_tag, 0, type);
10602                 type->type_ident = ident;
10603                 type->elements = elements;
10604         }
10605         symbol(state, ident, &ident->sym_ident, 0, type);
10606         ident->tok = TOK_TYPE_NAME;
10607         return type;
10608 }
10609
10610
10611 static void register_builtins(struct compile_state *state)
10612 {
10613         struct type *div_type, *ldiv_type;
10614         struct type *udiv_type, *uldiv_type;
10615         struct type *msr_type;
10616
10617         div_type = register_builtin_type(state, "__builtin_div_t",
10618                 partial_struct(state, "quot", &int_type,
10619                 partial_struct(state, "rem",  &int_type, 0)));
10620         ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10621                 partial_struct(state, "quot", &long_type,
10622                 partial_struct(state, "rem",  &long_type, 0)));
10623         udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10624                 partial_struct(state, "quot", &uint_type,
10625                 partial_struct(state, "rem",  &uint_type, 0)));
10626         uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10627                 partial_struct(state, "quot", &ulong_type,
10628                 partial_struct(state, "rem",  &ulong_type, 0)));
10629
10630         register_builtin_function(state, "__builtin_div",   OP_SDIVT, div_type,
10631                 &int_type, &int_type);
10632         register_builtin_function(state, "__builtin_ldiv",  OP_SDIVT, ldiv_type,
10633                 &long_type, &long_type);
10634         register_builtin_function(state, "__builtin_udiv",  OP_UDIVT, udiv_type,
10635                 &uint_type, &uint_type);
10636         register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10637                 &ulong_type, &ulong_type);
10638
10639         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type, 
10640                 &ushort_type);
10641         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10642                 &ushort_type);
10643         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,   
10644                 &ushort_type);
10645
10646         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type, 
10647                 &uchar_type, &ushort_type);
10648         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type, 
10649                 &ushort_type, &ushort_type);
10650         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type, 
10651                 &uint_type, &ushort_type);
10652         
10653         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type, 
10654                 &int_type);
10655         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type, 
10656                 &int_type);
10657
10658         msr_type = register_builtin_type(state, "__builtin_msr_t",
10659                 partial_struct(state, "lo", &ulong_type,
10660                 partial_struct(state, "hi", &ulong_type, 0)));
10661
10662         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10663                 &ulong_type);
10664         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10665                 &ulong_type, &ulong_type, &ulong_type);
10666         
10667         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type, 
10668                 &void_type);
10669 }
10670
10671 static struct type *declarator(
10672         struct compile_state *state, struct type *type, 
10673         struct hash_entry **ident, int need_ident);
10674 static void decl(struct compile_state *state, struct triple *first);
10675 static struct type *specifier_qualifier_list(struct compile_state *state);
10676 #if DEBUG_ROMCC_WARNING
10677 static int isdecl_specifier(int tok);
10678 #endif
10679 static struct type *decl_specifiers(struct compile_state *state);
10680 static int istype(int tok);
10681 static struct triple *expr(struct compile_state *state);
10682 static struct triple *assignment_expr(struct compile_state *state);
10683 static struct type *type_name(struct compile_state *state);
10684 static void statement(struct compile_state *state, struct triple *first);
10685
10686 static struct triple *call_expr(
10687         struct compile_state *state, struct triple *func)
10688 {
10689         struct triple *def;
10690         struct type *param, *type;
10691         ulong_t pvals, index;
10692
10693         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10694                 error(state, 0, "Called object is not a function");
10695         }
10696         if (func->op != OP_LIST) {
10697                 internal_error(state, 0, "improper function");
10698         }
10699         eat(state, TOK_LPAREN);
10700         /* Find the return type without any specifiers */
10701         type = clone_type(0, func->type->left);
10702         /* Count the number of rhs entries for OP_FCALL */
10703         param = func->type->right;
10704         pvals = 0;
10705         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10706                 pvals++;
10707                 param = param->right;
10708         }
10709         if ((param->type & TYPE_MASK) != TYPE_VOID) {
10710                 pvals++;
10711         }
10712         def = new_triple(state, OP_FCALL, type, -1, pvals);
10713         MISC(def, 0) = func;
10714
10715         param = func->type->right;
10716         for(index = 0; index < pvals; index++) {
10717                 struct triple *val;
10718                 struct type *arg_type;
10719                 val = read_expr(state, assignment_expr(state));
10720                 arg_type = param;
10721                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10722                         arg_type = param->left;
10723                 }
10724                 write_compatible(state, arg_type, val->type);
10725                 RHS(def, index) = val;
10726                 if (index != (pvals - 1)) {
10727                         eat(state, TOK_COMMA);
10728                         param = param->right;
10729                 }
10730         }
10731         eat(state, TOK_RPAREN);
10732         return def;
10733 }
10734
10735
10736 static struct triple *character_constant(struct compile_state *state)
10737 {
10738         struct triple *def;
10739         struct token *tk;
10740         const signed char *str, *end;
10741         int c;
10742         int str_len;
10743         tk = eat(state, TOK_LIT_CHAR);
10744         str = (signed char *)tk->val.str + 1;
10745         str_len = tk->str_len - 2;
10746         if (str_len <= 0) {
10747                 error(state, 0, "empty character constant");
10748         }
10749         end = str + str_len;
10750         c = char_value(state, &str, end);
10751         if (str != end) {
10752                 error(state, 0, "multibyte character constant not supported");
10753         }
10754         def = int_const(state, &char_type, (ulong_t)((long_t)c));
10755         return def;
10756 }
10757
10758 static struct triple *string_constant(struct compile_state *state)
10759 {
10760         struct triple *def;
10761         struct token *tk;
10762         struct type *type;
10763         const signed char *str, *end;
10764         signed char *buf, *ptr;
10765         int str_len;
10766
10767         buf = 0;
10768         type = new_type(TYPE_ARRAY, &char_type, 0);
10769         type->elements = 0;
10770         /* The while loop handles string concatenation */
10771         do {
10772                 tk = eat(state, TOK_LIT_STRING);
10773                 str = (signed char *)tk->val.str + 1;
10774                 str_len = tk->str_len - 2;
10775                 if (str_len < 0) {
10776                         error(state, 0, "negative string constant length");
10777                 }
10778                 end = str + str_len;
10779                 ptr = buf;
10780                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10781                 memcpy(buf, ptr, type->elements);
10782                 ptr = buf + type->elements;
10783                 do {
10784                         *ptr++ = char_value(state, &str, end);
10785                 } while(str < end);
10786                 type->elements = ptr - buf;
10787         } while(peek(state) == TOK_LIT_STRING);
10788         *ptr = '\0';
10789         type->elements += 1;
10790         def = triple(state, OP_BLOBCONST, type, 0, 0);
10791         def->u.blob = buf;
10792
10793         return def;
10794 }
10795
10796
10797 static struct triple *integer_constant(struct compile_state *state)
10798 {
10799         struct triple *def;
10800         unsigned long val;
10801         struct token *tk;
10802         char *end;
10803         int u, l, decimal;
10804         struct type *type;
10805
10806         tk = eat(state, TOK_LIT_INT);
10807         errno = 0;
10808         decimal = (tk->val.str[0] != '0');
10809         val = strtoul(tk->val.str, &end, 0);
10810         if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10811                 error(state, 0, "Integer constant to large");
10812         }
10813         u = l = 0;
10814         if ((*end == 'u') || (*end == 'U')) {
10815                 u = 1;
10816                         end++;
10817         }
10818         if ((*end == 'l') || (*end == 'L')) {
10819                 l = 1;
10820                 end++;
10821         }
10822         if ((*end == 'u') || (*end == 'U')) {
10823                 u = 1;
10824                 end++;
10825         }
10826         if (*end) {
10827                 error(state, 0, "Junk at end of integer constant");
10828         }
10829         if (u && l)  {
10830                 type = &ulong_type;
10831         }
10832         else if (l) {
10833                 type = &long_type;
10834                 if (!decimal && (val > LONG_T_MAX)) {
10835                         type = &ulong_type;
10836                 }
10837         }
10838         else if (u) {
10839                 type = &uint_type;
10840                 if (val > UINT_T_MAX) {
10841                         type = &ulong_type;
10842                 }
10843         }
10844         else {
10845                 type = &int_type;
10846                 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10847                         type = &uint_type;
10848                 }
10849                 else if (!decimal && (val > LONG_T_MAX)) {
10850                         type = &ulong_type;
10851                 }
10852                 else if (val > INT_T_MAX) {
10853                         type = &long_type;
10854                 }
10855         }
10856         def = int_const(state, type, val);
10857         return def;
10858 }
10859
10860 static struct triple *primary_expr(struct compile_state *state)
10861 {
10862         struct triple *def;
10863         int tok;
10864         tok = peek(state);
10865         switch(tok) {
10866         case TOK_IDENT:
10867         {
10868                 struct hash_entry *ident;
10869                 /* Here ident is either:
10870                  * a varable name
10871                  * a function name
10872                  */
10873                 ident = eat(state, TOK_IDENT)->ident;
10874                 if (!ident->sym_ident) {
10875                         error(state, 0, "%s undeclared", ident->name);
10876                 }
10877                 def = ident->sym_ident->def;
10878                 break;
10879         }
10880         case TOK_ENUM_CONST:
10881         {
10882                 struct hash_entry *ident;
10883                 /* Here ident is an enumeration constant */
10884                 ident = eat(state, TOK_ENUM_CONST)->ident;
10885                 if (!ident->sym_ident) {
10886                         error(state, 0, "%s undeclared", ident->name);
10887                 }
10888                 def = ident->sym_ident->def;
10889                 break;
10890         }
10891         case TOK_MIDENT:
10892         {
10893                 struct hash_entry *ident;
10894                 ident = eat(state, TOK_MIDENT)->ident;
10895                 warning(state, 0, "Replacing undefined macro: %s with 0",
10896                         ident->name);
10897                 def = int_const(state, &int_type, 0);
10898                 break;
10899         }
10900         case TOK_LPAREN:
10901                 eat(state, TOK_LPAREN);
10902                 def = expr(state);
10903                 eat(state, TOK_RPAREN);
10904                 break;
10905         case TOK_LIT_INT:
10906                 def = integer_constant(state);
10907                 break;
10908         case TOK_LIT_FLOAT:
10909                 eat(state, TOK_LIT_FLOAT);
10910                 error(state, 0, "Floating point constants not supported");
10911                 def = 0;
10912                 FINISHME();
10913                 break;
10914         case TOK_LIT_CHAR:
10915                 def = character_constant(state);
10916                 break;
10917         case TOK_LIT_STRING:
10918                 def = string_constant(state);
10919                 break;
10920         default:
10921                 def = 0;
10922                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
10923         }
10924         return def;
10925 }
10926
10927 static struct triple *postfix_expr(struct compile_state *state)
10928 {
10929         struct triple *def;
10930         int postfix;
10931         def = primary_expr(state);
10932         do {
10933                 struct triple *left;
10934                 int tok;
10935                 postfix = 1;
10936                 left = def;
10937                 switch((tok = peek(state))) {
10938                 case TOK_LBRACKET:
10939                         eat(state, TOK_LBRACKET);
10940                         def = mk_subscript_expr(state, left, expr(state));
10941                         eat(state, TOK_RBRACKET);
10942                         break;
10943                 case TOK_LPAREN:
10944                         def = call_expr(state, def);
10945                         break;
10946                 case TOK_DOT:
10947                 {
10948                         struct hash_entry *field;
10949                         eat(state, TOK_DOT);
10950                         field = eat(state, TOK_IDENT)->ident;
10951                         def = deref_field(state, def, field);
10952                         break;
10953                 }
10954                 case TOK_ARROW:
10955                 {
10956                         struct hash_entry *field;
10957                         eat(state, TOK_ARROW);
10958                         field = eat(state, TOK_IDENT)->ident;
10959                         def = mk_deref_expr(state, read_expr(state, def));
10960                         def = deref_field(state, def, field);
10961                         break;
10962                 }
10963                 case TOK_PLUSPLUS:
10964                         eat(state, TOK_PLUSPLUS);
10965                         def = mk_post_inc_expr(state, left);
10966                         break;
10967                 case TOK_MINUSMINUS:
10968                         eat(state, TOK_MINUSMINUS);
10969                         def = mk_post_dec_expr(state, left);
10970                         break;
10971                 default:
10972                         postfix = 0;
10973                         break;
10974                 }
10975         } while(postfix);
10976         return def;
10977 }
10978
10979 static struct triple *cast_expr(struct compile_state *state);
10980
10981 static struct triple *unary_expr(struct compile_state *state)
10982 {
10983         struct triple *def, *right;
10984         int tok;
10985         switch((tok = peek(state))) {
10986         case TOK_PLUSPLUS:
10987                 eat(state, TOK_PLUSPLUS);
10988                 def = mk_pre_inc_expr(state, unary_expr(state));
10989                 break;
10990         case TOK_MINUSMINUS:
10991                 eat(state, TOK_MINUSMINUS);
10992                 def = mk_pre_dec_expr(state, unary_expr(state));
10993                 break;
10994         case TOK_AND:
10995                 eat(state, TOK_AND);
10996                 def = mk_addr_expr(state, cast_expr(state), 0);
10997                 break;
10998         case TOK_STAR:
10999                 eat(state, TOK_STAR);
11000                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11001                 break;
11002         case TOK_PLUS:
11003                 eat(state, TOK_PLUS);
11004                 right = read_expr(state, cast_expr(state));
11005                 arithmetic(state, right);
11006                 def = integral_promotion(state, right);
11007                 break;
11008         case TOK_MINUS:
11009                 eat(state, TOK_MINUS);
11010                 right = read_expr(state, cast_expr(state));
11011                 arithmetic(state, right);
11012                 def = integral_promotion(state, right);
11013                 def = triple(state, OP_NEG, def->type, def, 0);
11014                 break;
11015         case TOK_TILDE:
11016                 eat(state, TOK_TILDE);
11017                 right = read_expr(state, cast_expr(state));
11018                 integral(state, right);
11019                 def = integral_promotion(state, right);
11020                 def = triple(state, OP_INVERT, def->type, def, 0);
11021                 break;
11022         case TOK_BANG:
11023                 eat(state, TOK_BANG);
11024                 right = read_expr(state, cast_expr(state));
11025                 bool(state, right);
11026                 def = lfalse_expr(state, right);
11027                 break;
11028         case TOK_SIZEOF:
11029         {
11030                 struct type *type;
11031                 int tok1, tok2;
11032                 eat(state, TOK_SIZEOF);
11033                 tok1 = peek(state);
11034                 tok2 = peek2(state);
11035                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11036                         eat(state, TOK_LPAREN);
11037                         type = type_name(state);
11038                         eat(state, TOK_RPAREN);
11039                 }
11040                 else {
11041                         struct triple *expr;
11042                         expr = unary_expr(state);
11043                         type = expr->type;
11044                         release_expr(state, expr);
11045                 }
11046                 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11047                 break;
11048         }
11049         case TOK_ALIGNOF:
11050         {
11051                 struct type *type;
11052                 int tok1, tok2;
11053                 eat(state, TOK_ALIGNOF);
11054                 tok1 = peek(state);
11055                 tok2 = peek2(state);
11056                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11057                         eat(state, TOK_LPAREN);
11058                         type = type_name(state);
11059                         eat(state, TOK_RPAREN);
11060                 }
11061                 else {
11062                         struct triple *expr;
11063                         expr = unary_expr(state);
11064                         type = expr->type;
11065                         release_expr(state, expr);
11066                 }
11067                 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11068                 break;
11069         }
11070         case TOK_MDEFINED:
11071         {
11072                 /* We only come here if we are called from the preprocessor */
11073                 struct hash_entry *ident;
11074                 int parens;
11075                 eat(state, TOK_MDEFINED);
11076                 parens = 0;
11077                 if (pp_peek(state) == TOK_LPAREN) {
11078                         pp_eat(state, TOK_LPAREN);
11079                         parens = 1;
11080                 }
11081                 ident = pp_eat(state, TOK_MIDENT)->ident;
11082                 if (parens) {
11083                         eat(state, TOK_RPAREN);
11084                 }
11085                 def = int_const(state, &int_type, ident->sym_define != 0);
11086                 break;
11087         }
11088         default:
11089                 def = postfix_expr(state);
11090                 break;
11091         }
11092         return def;
11093 }
11094
11095 static struct triple *cast_expr(struct compile_state *state)
11096 {
11097         struct triple *def;
11098         int tok1, tok2;
11099         tok1 = peek(state);
11100         tok2 = peek2(state);
11101         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11102                 struct type *type;
11103                 eat(state, TOK_LPAREN);
11104                 type = type_name(state);
11105                 eat(state, TOK_RPAREN);
11106                 def = mk_cast_expr(state, type, cast_expr(state));
11107         }
11108         else {
11109                 def = unary_expr(state);
11110         }
11111         return def;
11112 }
11113
11114 static struct triple *mult_expr(struct compile_state *state)
11115 {
11116         struct triple *def;
11117         int done;
11118         def = cast_expr(state);
11119         do {
11120                 struct triple *left, *right;
11121                 struct type *result_type;
11122                 int tok, op, sign;
11123                 done = 0;
11124                 tok = peek(state);
11125                 switch(tok) {
11126                 case TOK_STAR:
11127                 case TOK_DIV:
11128                 case TOK_MOD:
11129                         left = read_expr(state, def);
11130                         arithmetic(state, left);
11131
11132                         eat(state, tok);
11133
11134                         right = read_expr(state, cast_expr(state));
11135                         arithmetic(state, right);
11136
11137                         result_type = arithmetic_result(state, left, right);
11138                         sign = is_signed(result_type);
11139                         op = -1;
11140                         switch(tok) {
11141                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11142                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
11143                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
11144                         }
11145                         def = triple(state, op, result_type, left, right);
11146                         break;
11147                 default:
11148                         done = 1;
11149                         break;
11150                 }
11151         } while(!done);
11152         return def;
11153 }
11154
11155 static struct triple *add_expr(struct compile_state *state)
11156 {
11157         struct triple *def;
11158         int done;
11159         def = mult_expr(state);
11160         do {
11161                 done = 0;
11162                 switch( peek(state)) {
11163                 case TOK_PLUS:
11164                         eat(state, TOK_PLUS);
11165                         def = mk_add_expr(state, def, mult_expr(state));
11166                         break;
11167                 case TOK_MINUS:
11168                         eat(state, TOK_MINUS);
11169                         def = mk_sub_expr(state, def, mult_expr(state));
11170                         break;
11171                 default:
11172                         done = 1;
11173                         break;
11174                 }
11175         } while(!done);
11176         return def;
11177 }
11178
11179 static struct triple *shift_expr(struct compile_state *state)
11180 {
11181         struct triple *def;
11182         int done;
11183         def = add_expr(state);
11184         do {
11185                 struct triple *left, *right;
11186                 int tok, op;
11187                 done = 0;
11188                 switch((tok = peek(state))) {
11189                 case TOK_SL:
11190                 case TOK_SR:
11191                         left = read_expr(state, def);
11192                         integral(state, left);
11193                         left = integral_promotion(state, left);
11194
11195                         eat(state, tok);
11196
11197                         right = read_expr(state, add_expr(state));
11198                         integral(state, right);
11199                         right = integral_promotion(state, right);
11200                         
11201                         op = (tok == TOK_SL)? OP_SL : 
11202                                 is_signed(left->type)? OP_SSR: OP_USR;
11203
11204                         def = triple(state, op, left->type, left, right);
11205                         break;
11206                 default:
11207                         done = 1;
11208                         break;
11209                 }
11210         } while(!done);
11211         return def;
11212 }
11213
11214 static struct triple *relational_expr(struct compile_state *state)
11215 {
11216 #if DEBUG_ROMCC_WARNINGS
11217 #warning "Extend relational exprs to work on more than arithmetic types"
11218 #endif
11219         struct triple *def;
11220         int done;
11221         def = shift_expr(state);
11222         do {
11223                 struct triple *left, *right;
11224                 struct type *arg_type;
11225                 int tok, op, sign;
11226                 done = 0;
11227                 switch((tok = peek(state))) {
11228                 case TOK_LESS:
11229                 case TOK_MORE:
11230                 case TOK_LESSEQ:
11231                 case TOK_MOREEQ:
11232                         left = read_expr(state, def);
11233                         arithmetic(state, left);
11234
11235                         eat(state, tok);
11236
11237                         right = read_expr(state, shift_expr(state));
11238                         arithmetic(state, right);
11239
11240                         arg_type = arithmetic_result(state, left, right);
11241                         sign = is_signed(arg_type);
11242                         op = -1;
11243                         switch(tok) {
11244                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
11245                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
11246                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11247                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11248                         }
11249                         def = triple(state, op, &int_type, left, right);
11250                         break;
11251                 default:
11252                         done = 1;
11253                         break;
11254                 }
11255         } while(!done);
11256         return def;
11257 }
11258
11259 static struct triple *equality_expr(struct compile_state *state)
11260 {
11261 #if DEBUG_ROMCC_WARNINGS
11262 #warning "Extend equality exprs to work on more than arithmetic types"
11263 #endif
11264         struct triple *def;
11265         int done;
11266         def = relational_expr(state);
11267         do {
11268                 struct triple *left, *right;
11269                 int tok, op;
11270                 done = 0;
11271                 switch((tok = peek(state))) {
11272                 case TOK_EQEQ:
11273                 case TOK_NOTEQ:
11274                         left = read_expr(state, def);
11275                         arithmetic(state, left);
11276                         eat(state, tok);
11277                         right = read_expr(state, relational_expr(state));
11278                         arithmetic(state, right);
11279                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11280                         def = triple(state, op, &int_type, left, right);
11281                         break;
11282                 default:
11283                         done = 1;
11284                         break;
11285                 }
11286         } while(!done);
11287         return def;
11288 }
11289
11290 static struct triple *and_expr(struct compile_state *state)
11291 {
11292         struct triple *def;
11293         def = equality_expr(state);
11294         while(peek(state) == TOK_AND) {
11295                 struct triple *left, *right;
11296                 struct type *result_type;
11297                 left = read_expr(state, def);
11298                 integral(state, left);
11299                 eat(state, TOK_AND);
11300                 right = read_expr(state, equality_expr(state));
11301                 integral(state, right);
11302                 result_type = arithmetic_result(state, left, right);
11303                 def = triple(state, OP_AND, result_type, left, right);
11304         }
11305         return def;
11306 }
11307
11308 static struct triple *xor_expr(struct compile_state *state)
11309 {
11310         struct triple *def;
11311         def = and_expr(state);
11312         while(peek(state) == TOK_XOR) {
11313                 struct triple *left, *right;
11314                 struct type *result_type;
11315                 left = read_expr(state, def);
11316                 integral(state, left);
11317                 eat(state, TOK_XOR);
11318                 right = read_expr(state, and_expr(state));
11319                 integral(state, right);
11320                 result_type = arithmetic_result(state, left, right);
11321                 def = triple(state, OP_XOR, result_type, left, right);
11322         }
11323         return def;
11324 }
11325
11326 static struct triple *or_expr(struct compile_state *state)
11327 {
11328         struct triple *def;
11329         def = xor_expr(state);
11330         while(peek(state) == TOK_OR) {
11331                 struct triple *left, *right;
11332                 struct type *result_type;
11333                 left = read_expr(state, def);
11334                 integral(state, left);
11335                 eat(state, TOK_OR);
11336                 right = read_expr(state, xor_expr(state));
11337                 integral(state, right);
11338                 result_type = arithmetic_result(state, left, right);
11339                 def = triple(state, OP_OR, result_type, left, right);
11340         }
11341         return def;
11342 }
11343
11344 static struct triple *land_expr(struct compile_state *state)
11345 {
11346         struct triple *def;
11347         def = or_expr(state);
11348         while(peek(state) == TOK_LOGAND) {
11349                 struct triple *left, *right;
11350                 left = read_expr(state, def);
11351                 bool(state, left);
11352                 eat(state, TOK_LOGAND);
11353                 right = read_expr(state, or_expr(state));
11354                 bool(state, right);
11355
11356                 def = mkland_expr(state,
11357                         ltrue_expr(state, left),
11358                         ltrue_expr(state, right));
11359         }
11360         return def;
11361 }
11362
11363 static struct triple *lor_expr(struct compile_state *state)
11364 {
11365         struct triple *def;
11366         def = land_expr(state);
11367         while(peek(state) == TOK_LOGOR) {
11368                 struct triple *left, *right;
11369                 left = read_expr(state, def);
11370                 bool(state, left);
11371                 eat(state, TOK_LOGOR);
11372                 right = read_expr(state, land_expr(state));
11373                 bool(state, right);
11374
11375                 def = mklor_expr(state, 
11376                         ltrue_expr(state, left),
11377                         ltrue_expr(state, right));
11378         }
11379         return def;
11380 }
11381
11382 static struct triple *conditional_expr(struct compile_state *state)
11383 {
11384         struct triple *def;
11385         def = lor_expr(state);
11386         if (peek(state) == TOK_QUEST) {
11387                 struct triple *test, *left, *right;
11388                 bool(state, def);
11389                 test = ltrue_expr(state, read_expr(state, def));
11390                 eat(state, TOK_QUEST);
11391                 left = read_expr(state, expr(state));
11392                 eat(state, TOK_COLON);
11393                 right = read_expr(state, conditional_expr(state));
11394
11395                 def = mkcond_expr(state, test, left, right);
11396         }
11397         return def;
11398 }
11399
11400 struct cv_triple {
11401         struct triple *val;
11402         int id;
11403 };
11404
11405 static void set_cv(struct compile_state *state, struct cv_triple *cv,
11406         struct triple *dest, struct triple *val)
11407 {
11408         if (cv[dest->id].val) {
11409                 free_triple(state, cv[dest->id].val);
11410         }
11411         cv[dest->id].val = val;
11412 }
11413 static struct triple *get_cv(struct compile_state *state, struct cv_triple *cv,
11414         struct triple *src)
11415 {
11416         return cv[src->id].val;
11417 }
11418
11419 static struct triple *eval_const_expr(
11420         struct compile_state *state, struct triple *expr)
11421 {
11422         struct triple *def;
11423         if (is_const(expr)) {
11424                 def = expr;
11425         }
11426         else {
11427                 /* If we don't start out as a constant simplify into one */
11428                 struct triple *head, *ptr;
11429                 struct cv_triple *cv;
11430                 int i, count;
11431                 head = label(state); /* dummy initial triple */
11432                 flatten(state, head, expr);
11433                 count = 1;
11434                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11435                         count++;
11436                 }
11437                 cv = xcmalloc(sizeof(struct cv_triple)*count, "const value vector");
11438                 i = 1;
11439                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11440                         cv[i].val = 0;
11441                         cv[i].id  = ptr->id;
11442                         ptr->id   = i;
11443                         i++;
11444                 }
11445                 ptr = head->next;
11446                 do {
11447                         valid_ins(state, ptr);
11448                         if ((ptr->op == OP_PHI) || (ptr->op == OP_LIST)) {
11449                                 internal_error(state, ptr, 
11450                                         "unexpected %s in constant expression",
11451                                         tops(ptr->op));
11452                         }
11453                         else if (ptr->op == OP_LIST) {
11454                         }
11455                         else if (triple_is_structural(state, ptr)) {
11456                                 ptr = ptr->next;
11457                         }
11458                         else if (triple_is_ubranch(state, ptr)) {
11459                                 ptr = TARG(ptr, 0);
11460                         }
11461                         else if (triple_is_cbranch(state, ptr)) {
11462                                 struct triple *cond_val;
11463                                 cond_val = get_cv(state, cv, RHS(ptr, 0));
11464                                 if (!cond_val || !is_const(cond_val) || 
11465                                         (cond_val->op != OP_INTCONST)) 
11466                                 {
11467                                         internal_error(state, ptr, "bad branch condition");
11468                                 }
11469                                 if (cond_val->u.cval == 0) {
11470                                         ptr = ptr->next;
11471                                 } else {
11472                                         ptr = TARG(ptr, 0);
11473                                 }
11474                         }
11475                         else if (triple_is_branch(state, ptr)) {
11476                                 error(state, ptr, "bad branch type in constant expression");
11477                         }
11478                         else if (ptr->op == OP_WRITE) {
11479                                 struct triple *val;
11480                                 val = get_cv(state, cv, RHS(ptr, 0));
11481                                 
11482                                 set_cv(state, cv, MISC(ptr, 0), 
11483                                         copy_triple(state, val));
11484                                 set_cv(state, cv, ptr, 
11485                                         copy_triple(state, val));
11486                                 ptr = ptr->next;
11487                         }
11488                         else if (ptr->op == OP_READ) {
11489                                 set_cv(state, cv, ptr, 
11490                                         copy_triple(state, 
11491                                                 get_cv(state, cv, RHS(ptr, 0))));
11492                                 ptr = ptr->next;
11493                         }
11494                         else if (triple_is_pure(state, ptr, cv[ptr->id].id)) {
11495                                 struct triple *val, **rhs;
11496                                 val = copy_triple(state, ptr);
11497                                 rhs = triple_rhs(state, val, 0);
11498                                 for(; rhs; rhs = triple_rhs(state, val, rhs)) {
11499                                         if (!*rhs) {
11500                                                 internal_error(state, ptr, "Missing rhs");
11501                                         }
11502                                         *rhs = get_cv(state, cv, *rhs);
11503                                 }
11504                                 simplify(state, val);
11505                                 set_cv(state, cv, ptr, val);
11506                                 ptr = ptr->next;
11507                         }
11508                         else {
11509                                 error(state, ptr, "impure operation in constant expression");
11510                         }
11511                         
11512                 } while(ptr != head);
11513
11514                 /* Get the result value */
11515                 def = get_cv(state, cv, head->prev);
11516                 cv[head->prev->id].val = 0;
11517
11518                 /* Free the temporary values */
11519                 for(i = 0; i < count; i++) {
11520                         if (cv[i].val) {
11521                                 free_triple(state, cv[i].val);
11522                                 cv[i].val = 0;
11523                         }
11524                 }
11525                 xfree(cv);
11526                 /* Free the intermediate expressions */
11527                 while(head->next != head) {
11528                         release_triple(state, head->next);
11529                 }
11530                 free_triple(state, head);
11531         }
11532         if (!is_const(def)) {
11533                 error(state, expr, "Not a constant expression");
11534         }
11535         return def;
11536 }
11537
11538 static struct triple *constant_expr(struct compile_state *state)
11539 {
11540         return eval_const_expr(state, conditional_expr(state));
11541 }
11542
11543 static struct triple *assignment_expr(struct compile_state *state)
11544 {
11545         struct triple *def, *left, *right;
11546         int tok, op, sign;
11547         /* The C grammer in K&R shows assignment expressions
11548          * only taking unary expressions as input on their
11549          * left hand side.  But specifies the precedence of
11550          * assignemnt as the lowest operator except for comma.
11551          *
11552          * Allowing conditional expressions on the left hand side
11553          * of an assignement results in a grammar that accepts
11554          * a larger set of statements than standard C.   As long
11555          * as the subset of the grammar that is standard C behaves
11556          * correctly this should cause no problems.
11557          * 
11558          * For the extra token strings accepted by the grammar
11559          * none of them should produce a valid lvalue, so they
11560          * should not produce functioning programs.
11561          *
11562          * GCC has this bug as well, so surprises should be minimal.
11563          */
11564         def = conditional_expr(state);
11565         left = def;
11566         switch((tok = peek(state))) {
11567         case TOK_EQ:
11568                 lvalue(state, left);
11569                 eat(state, TOK_EQ);
11570                 def = write_expr(state, left, 
11571                         read_expr(state, assignment_expr(state)));
11572                 break;
11573         case TOK_TIMESEQ:
11574         case TOK_DIVEQ:
11575         case TOK_MODEQ:
11576                 lvalue(state, left);
11577                 arithmetic(state, left);
11578                 eat(state, tok);
11579                 right = read_expr(state, assignment_expr(state));
11580                 arithmetic(state, right);
11581
11582                 sign = is_signed(left->type);
11583                 op = -1;
11584                 switch(tok) {
11585                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11586                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
11587                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
11588                 }
11589                 def = write_expr(state, left,
11590                         triple(state, op, left->type, 
11591                                 read_expr(state, left), right));
11592                 break;
11593         case TOK_PLUSEQ:
11594                 lvalue(state, left);
11595                 eat(state, TOK_PLUSEQ);
11596                 def = write_expr(state, left,
11597                         mk_add_expr(state, left, assignment_expr(state)));
11598                 break;
11599         case TOK_MINUSEQ:
11600                 lvalue(state, left);
11601                 eat(state, TOK_MINUSEQ);
11602                 def = write_expr(state, left,
11603                         mk_sub_expr(state, left, assignment_expr(state)));
11604                 break;
11605         case TOK_SLEQ:
11606         case TOK_SREQ:
11607         case TOK_ANDEQ:
11608         case TOK_XOREQ:
11609         case TOK_OREQ:
11610                 lvalue(state, left);
11611                 integral(state, left);
11612                 eat(state, tok);
11613                 right = read_expr(state, assignment_expr(state));
11614                 integral(state, right);
11615                 right = integral_promotion(state, right);
11616                 sign = is_signed(left->type);
11617                 op = -1;
11618                 switch(tok) {
11619                 case TOK_SLEQ:  op = OP_SL; break;
11620                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
11621                 case TOK_ANDEQ: op = OP_AND; break;
11622                 case TOK_XOREQ: op = OP_XOR; break;
11623                 case TOK_OREQ:  op = OP_OR; break;
11624                 }
11625                 def = write_expr(state, left,
11626                         triple(state, op, left->type, 
11627                                 read_expr(state, left), right));
11628                 break;
11629         }
11630         return def;
11631 }
11632
11633 static struct triple *expr(struct compile_state *state)
11634 {
11635         struct triple *def;
11636         def = assignment_expr(state);
11637         while(peek(state) == TOK_COMMA) {
11638                 eat(state, TOK_COMMA);
11639                 def = mkprog(state, def, assignment_expr(state), 0UL);
11640         }
11641         return def;
11642 }
11643
11644 static void expr_statement(struct compile_state *state, struct triple *first)
11645 {
11646         if (peek(state) != TOK_SEMI) {
11647                 /* lvalue conversions always apply except when certian operators
11648                  * are applied.  I apply the lvalue conversions here
11649                  * as I know no more operators will be applied.
11650                  */
11651                 flatten(state, first, lvalue_conversion(state, expr(state)));
11652         }
11653         eat(state, TOK_SEMI);
11654 }
11655
11656 static void if_statement(struct compile_state *state, struct triple *first)
11657 {
11658         struct triple *test, *jmp1, *jmp2, *middle, *end;
11659
11660         jmp1 = jmp2 = middle = 0;
11661         eat(state, TOK_IF);
11662         eat(state, TOK_LPAREN);
11663         test = expr(state);
11664         bool(state, test);
11665         /* Cleanup and invert the test */
11666         test = lfalse_expr(state, read_expr(state, test));
11667         eat(state, TOK_RPAREN);
11668         /* Generate the needed pieces */
11669         middle = label(state);
11670         jmp1 = branch(state, middle, test);
11671         /* Thread the pieces together */
11672         flatten(state, first, test);
11673         flatten(state, first, jmp1);
11674         flatten(state, first, label(state));
11675         statement(state, first);
11676         if (peek(state) == TOK_ELSE) {
11677                 eat(state, TOK_ELSE);
11678                 /* Generate the rest of the pieces */
11679                 end = label(state);
11680                 jmp2 = branch(state, end, 0);
11681                 /* Thread them together */
11682                 flatten(state, first, jmp2);
11683                 flatten(state, first, middle);
11684                 statement(state, first);
11685                 flatten(state, first, end);
11686         }
11687         else {
11688                 flatten(state, first, middle);
11689         }
11690 }
11691
11692 static void for_statement(struct compile_state *state, struct triple *first)
11693 {
11694         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11695         struct triple *label1, *label2, *label3;
11696         struct hash_entry *ident;
11697
11698         eat(state, TOK_FOR);
11699         eat(state, TOK_LPAREN);
11700         head = test = tail = jmp1 = jmp2 = 0;
11701         if (peek(state) != TOK_SEMI) {
11702                 head = expr(state);
11703         } 
11704         eat(state, TOK_SEMI);
11705         if (peek(state) != TOK_SEMI) {
11706                 test = expr(state);
11707                 bool(state, test);
11708                 test = ltrue_expr(state, read_expr(state, test));
11709         }
11710         eat(state, TOK_SEMI);
11711         if (peek(state) != TOK_RPAREN) {
11712                 tail = expr(state);
11713         }
11714         eat(state, TOK_RPAREN);
11715         /* Generate the needed pieces */
11716         label1 = label(state);
11717         label2 = label(state);
11718         label3 = label(state);
11719         if (test) {
11720                 jmp1 = branch(state, label3, 0);
11721                 jmp2 = branch(state, label1, test);
11722         }
11723         else {
11724                 jmp2 = branch(state, label1, 0);
11725         }
11726         end = label(state);
11727         /* Remember where break and continue go */
11728         start_scope(state);
11729         ident = state->i_break;
11730         symbol(state, ident, &ident->sym_ident, end, end->type);
11731         ident = state->i_continue;
11732         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11733         /* Now include the body */
11734         flatten(state, first, head);
11735         flatten(state, first, jmp1);
11736         flatten(state, first, label1);
11737         statement(state, first);
11738         flatten(state, first, label2);
11739         flatten(state, first, tail);
11740         flatten(state, first, label3);
11741         flatten(state, first, test);
11742         flatten(state, first, jmp2);
11743         flatten(state, first, end);
11744         /* Cleanup the break/continue scope */
11745         end_scope(state);
11746 }
11747
11748 static void while_statement(struct compile_state *state, struct triple *first)
11749 {
11750         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11751         struct hash_entry *ident;
11752         eat(state, TOK_WHILE);
11753         eat(state, TOK_LPAREN);
11754         test = expr(state);
11755         bool(state, test);
11756         test = ltrue_expr(state, read_expr(state, test));
11757         eat(state, TOK_RPAREN);
11758         /* Generate the needed pieces */
11759         label1 = label(state);
11760         label2 = label(state);
11761         jmp1 = branch(state, label2, 0);
11762         jmp2 = branch(state, label1, test);
11763         end = label(state);
11764         /* Remember where break and continue go */
11765         start_scope(state);
11766         ident = state->i_break;
11767         symbol(state, ident, &ident->sym_ident, end, end->type);
11768         ident = state->i_continue;
11769         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11770         /* Thread them together */
11771         flatten(state, first, jmp1);
11772         flatten(state, first, label1);
11773         statement(state, first);
11774         flatten(state, first, label2);
11775         flatten(state, first, test);
11776         flatten(state, first, jmp2);
11777         flatten(state, first, end);
11778         /* Cleanup the break/continue scope */
11779         end_scope(state);
11780 }
11781
11782 static void do_statement(struct compile_state *state, struct triple *first)
11783 {
11784         struct triple *label1, *label2, *test, *end;
11785         struct hash_entry *ident;
11786         eat(state, TOK_DO);
11787         /* Generate the needed pieces */
11788         label1 = label(state);
11789         label2 = label(state);
11790         end = label(state);
11791         /* Remember where break and continue go */
11792         start_scope(state);
11793         ident = state->i_break;
11794         symbol(state, ident, &ident->sym_ident, end, end->type);
11795         ident = state->i_continue;
11796         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11797         /* Now include the body */
11798         flatten(state, first, label1);
11799         statement(state, first);
11800         /* Cleanup the break/continue scope */
11801         end_scope(state);
11802         /* Eat the rest of the loop */
11803         eat(state, TOK_WHILE);
11804         eat(state, TOK_LPAREN);
11805         test = read_expr(state, expr(state));
11806         bool(state, test);
11807         eat(state, TOK_RPAREN);
11808         eat(state, TOK_SEMI);
11809         /* Thread the pieces together */
11810         test = ltrue_expr(state, test);
11811         flatten(state, first, label2);
11812         flatten(state, first, test);
11813         flatten(state, first, branch(state, label1, test));
11814         flatten(state, first, end);
11815 }
11816
11817
11818 static void return_statement(struct compile_state *state, struct triple *first)
11819 {
11820         struct triple *jmp, *mv, *dest, *var, *val;
11821         int last;
11822         eat(state, TOK_RETURN);
11823
11824 #if DEBUG_ROMCC_WARNINGS
11825 #warning "FIXME implement a more general excess branch elimination"
11826 #endif
11827         val = 0;
11828         /* If we have a return value do some more work */
11829         if (peek(state) != TOK_SEMI) {
11830                 val = read_expr(state, expr(state));
11831         }
11832         eat(state, TOK_SEMI);
11833
11834         /* See if this last statement in a function */
11835         last = ((peek(state) == TOK_RBRACE) && 
11836                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11837
11838         /* Find the return variable */
11839         var = fresult(state, state->main_function);
11840
11841         /* Find the return destination */
11842         dest = state->i_return->sym_ident->def;
11843         mv = jmp = 0;
11844         /* If needed generate a jump instruction */
11845         if (!last) {
11846                 jmp = branch(state, dest, 0);
11847         }
11848         /* If needed generate an assignment instruction */
11849         if (val) {
11850                 mv = write_expr(state, deref_index(state, var, 1), val);
11851         }
11852         /* Now put the code together */
11853         if (mv) {
11854                 flatten(state, first, mv);
11855                 flatten(state, first, jmp);
11856         }
11857         else if (jmp) {
11858                 flatten(state, first, jmp);
11859         }
11860 }
11861
11862 static void break_statement(struct compile_state *state, struct triple *first)
11863 {
11864         struct triple *dest;
11865         eat(state, TOK_BREAK);
11866         eat(state, TOK_SEMI);
11867         if (!state->i_break->sym_ident) {
11868                 error(state, 0, "break statement not within loop or switch");
11869         }
11870         dest = state->i_break->sym_ident->def;
11871         flatten(state, first, branch(state, dest, 0));
11872 }
11873
11874 static void continue_statement(struct compile_state *state, struct triple *first)
11875 {
11876         struct triple *dest;
11877         eat(state, TOK_CONTINUE);
11878         eat(state, TOK_SEMI);
11879         if (!state->i_continue->sym_ident) {
11880                 error(state, 0, "continue statement outside of a loop");
11881         }
11882         dest = state->i_continue->sym_ident->def;
11883         flatten(state, first, branch(state, dest, 0));
11884 }
11885
11886 static void goto_statement(struct compile_state *state, struct triple *first)
11887 {
11888         struct hash_entry *ident;
11889         eat(state, TOK_GOTO);
11890         ident = eat(state, TOK_IDENT)->ident;
11891         if (!ident->sym_label) {
11892                 /* If this is a forward branch allocate the label now,
11893                  * it will be flattend in the appropriate location later.
11894                  */
11895                 struct triple *ins;
11896                 ins = label(state);
11897                 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11898         }
11899         eat(state, TOK_SEMI);
11900
11901         flatten(state, first, branch(state, ident->sym_label->def, 0));
11902 }
11903
11904 static void labeled_statement(struct compile_state *state, struct triple *first)
11905 {
11906         struct triple *ins;
11907         struct hash_entry *ident;
11908
11909         ident = eat(state, TOK_IDENT)->ident;
11910         if (ident->sym_label && ident->sym_label->def) {
11911                 ins = ident->sym_label->def;
11912                 put_occurance(ins->occurance);
11913                 ins->occurance = new_occurance(state);
11914         }
11915         else {
11916                 ins = label(state);
11917                 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11918         }
11919         if (ins->id & TRIPLE_FLAG_FLATTENED) {
11920                 error(state, 0, "label %s already defined", ident->name);
11921         }
11922         flatten(state, first, ins);
11923
11924         eat(state, TOK_COLON);
11925         statement(state, first);
11926 }
11927
11928 static void switch_statement(struct compile_state *state, struct triple *first)
11929 {
11930         struct triple *value, *top, *end, *dbranch;
11931         struct hash_entry *ident;
11932
11933         /* See if we have a valid switch statement */
11934         eat(state, TOK_SWITCH);
11935         eat(state, TOK_LPAREN);
11936         value = expr(state);
11937         integral(state, value);
11938         value = read_expr(state, value);
11939         eat(state, TOK_RPAREN);
11940         /* Generate the needed pieces */
11941         top = label(state);
11942         end = label(state);
11943         dbranch = branch(state, end, 0);
11944         /* Remember where case branches and break goes */
11945         start_scope(state);
11946         ident = state->i_switch;
11947         symbol(state, ident, &ident->sym_ident, value, value->type);
11948         ident = state->i_case;
11949         symbol(state, ident, &ident->sym_ident, top, top->type);
11950         ident = state->i_break;
11951         symbol(state, ident, &ident->sym_ident, end, end->type);
11952         ident = state->i_default;
11953         symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11954         /* Thread them together */
11955         flatten(state, first, value);
11956         flatten(state, first, top);
11957         flatten(state, first, dbranch);
11958         statement(state, first);
11959         flatten(state, first, end);
11960         /* Cleanup the switch scope */
11961         end_scope(state);
11962 }
11963
11964 static void case_statement(struct compile_state *state, struct triple *first)
11965 {
11966         struct triple *cvalue, *dest, *test, *jmp;
11967         struct triple *ptr, *value, *top, *dbranch;
11968
11969         /* See if w have a valid case statement */
11970         eat(state, TOK_CASE);
11971         cvalue = constant_expr(state);
11972         integral(state, cvalue);
11973         if (cvalue->op != OP_INTCONST) {
11974                 error(state, 0, "integer constant expected");
11975         }
11976         eat(state, TOK_COLON);
11977         if (!state->i_case->sym_ident) {
11978                 error(state, 0, "case statement not within a switch");
11979         }
11980
11981         /* Lookup the interesting pieces */
11982         top = state->i_case->sym_ident->def;
11983         value = state->i_switch->sym_ident->def;
11984         dbranch = state->i_default->sym_ident->def;
11985
11986         /* See if this case label has already been used */
11987         for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11988                 if (ptr->op != OP_EQ) {
11989                         continue;
11990                 }
11991                 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11992                         error(state, 0, "duplicate case %d statement",
11993                                 cvalue->u.cval);
11994                 }
11995         }
11996         /* Generate the needed pieces */
11997         dest = label(state);
11998         test = triple(state, OP_EQ, &int_type, value, cvalue);
11999         jmp = branch(state, dest, test);
12000         /* Thread the pieces together */
12001         flatten(state, dbranch, test);
12002         flatten(state, dbranch, jmp);
12003         flatten(state, dbranch, label(state));
12004         flatten(state, first, dest);
12005         statement(state, first);
12006 }
12007
12008 static void default_statement(struct compile_state *state, struct triple *first)
12009 {
12010         struct triple *dest;
12011         struct triple *dbranch, *end;
12012
12013         /* See if we have a valid default statement */
12014         eat(state, TOK_DEFAULT);
12015         eat(state, TOK_COLON);
12016
12017         if (!state->i_case->sym_ident) {
12018                 error(state, 0, "default statement not within a switch");
12019         }
12020
12021         /* Lookup the interesting pieces */
12022         dbranch = state->i_default->sym_ident->def;
12023         end = state->i_break->sym_ident->def;
12024
12025         /* See if a default statement has already happened */
12026         if (TARG(dbranch, 0) != end) {
12027                 error(state, 0, "duplicate default statement");
12028         }
12029
12030         /* Generate the needed pieces */
12031         dest = label(state);
12032
12033         /* Blame the branch on the default statement */
12034         put_occurance(dbranch->occurance);
12035         dbranch->occurance = new_occurance(state);
12036
12037         /* Thread the pieces together */
12038         TARG(dbranch, 0) = dest;
12039         use_triple(dest, dbranch);
12040         flatten(state, first, dest);
12041         statement(state, first);
12042 }
12043
12044 static void asm_statement(struct compile_state *state, struct triple *first)
12045 {
12046         struct asm_info *info;
12047         struct {
12048                 struct triple *constraint;
12049                 struct triple *expr;
12050         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12051         struct triple *def, *asm_str;
12052         int out, in, clobbers, more, colons, i;
12053         int flags;
12054
12055         flags = 0;
12056         eat(state, TOK_ASM);
12057         /* For now ignore the qualifiers */
12058         switch(peek(state)) {
12059         case TOK_CONST:
12060                 eat(state, TOK_CONST);
12061                 break;
12062         case TOK_VOLATILE:
12063                 eat(state, TOK_VOLATILE);
12064                 flags |= TRIPLE_FLAG_VOLATILE;
12065                 break;
12066         }
12067         eat(state, TOK_LPAREN);
12068         asm_str = string_constant(state);
12069
12070         colons = 0;
12071         out = in = clobbers = 0;
12072         /* Outputs */
12073         if ((colons == 0) && (peek(state) == TOK_COLON)) {
12074                 eat(state, TOK_COLON);
12075                 colons++;
12076                 more = (peek(state) == TOK_LIT_STRING);
12077                 while(more) {
12078                         struct triple *var;
12079                         struct triple *constraint;
12080                         char *str;
12081                         more = 0;
12082                         if (out > MAX_LHS) {
12083                                 error(state, 0, "Maximum output count exceeded.");
12084                         }
12085                         constraint = string_constant(state);
12086                         str = constraint->u.blob;
12087                         if (str[0] != '=') {
12088                                 error(state, 0, "Output constraint does not start with =");
12089                         }
12090                         constraint->u.blob = str + 1;
12091                         eat(state, TOK_LPAREN);
12092                         var = conditional_expr(state);
12093                         eat(state, TOK_RPAREN);
12094
12095                         lvalue(state, var);
12096                         out_param[out].constraint = constraint;
12097                         out_param[out].expr       = var;
12098                         if (peek(state) == TOK_COMMA) {
12099                                 eat(state, TOK_COMMA);
12100                                 more = 1;
12101                         }
12102                         out++;
12103                 }
12104         }
12105         /* Inputs */
12106         if ((colons == 1) && (peek(state) == TOK_COLON)) {
12107                 eat(state, TOK_COLON);
12108                 colons++;
12109                 more = (peek(state) == TOK_LIT_STRING);
12110                 while(more) {
12111                         struct triple *val;
12112                         struct triple *constraint;
12113                         char *str;
12114                         more = 0;
12115                         if (in > MAX_RHS) {
12116                                 error(state, 0, "Maximum input count exceeded.");
12117                         }
12118                         constraint = string_constant(state);
12119                         str = constraint->u.blob;
12120                         if (digitp(str[0] && str[1] == '\0')) {
12121                                 int val;
12122                                 val = digval(str[0]);
12123                                 if ((val < 0) || (val >= out)) {
12124                                         error(state, 0, "Invalid input constraint %d", val);
12125                                 }
12126                         }
12127                         eat(state, TOK_LPAREN);
12128                         val = conditional_expr(state);
12129                         eat(state, TOK_RPAREN);
12130
12131                         in_param[in].constraint = constraint;
12132                         in_param[in].expr       = val;
12133                         if (peek(state) == TOK_COMMA) {
12134                                 eat(state, TOK_COMMA);
12135                                 more = 1;
12136                         }
12137                         in++;
12138                 }
12139         }
12140
12141         /* Clobber */
12142         if ((colons == 2) && (peek(state) == TOK_COLON)) {
12143                 eat(state, TOK_COLON);
12144                 colons++;
12145                 more = (peek(state) == TOK_LIT_STRING);
12146                 while(more) {
12147                         struct triple *clobber;
12148                         more = 0;
12149                         if ((clobbers + out) > MAX_LHS) {
12150                                 error(state, 0, "Maximum clobber limit exceeded.");
12151                         }
12152                         clobber = string_constant(state);
12153
12154                         clob_param[clobbers].constraint = clobber;
12155                         if (peek(state) == TOK_COMMA) {
12156                                 eat(state, TOK_COMMA);
12157                                 more = 1;
12158                         }
12159                         clobbers++;
12160                 }
12161         }
12162         eat(state, TOK_RPAREN);
12163         eat(state, TOK_SEMI);
12164
12165
12166         info = xcmalloc(sizeof(*info), "asm_info");
12167         info->str = asm_str->u.blob;
12168         free_triple(state, asm_str);
12169
12170         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12171         def->u.ainfo = info;
12172         def->id |= flags;
12173
12174         /* Find the register constraints */
12175         for(i = 0; i < out; i++) {
12176                 struct triple *constraint;
12177                 constraint = out_param[i].constraint;
12178                 info->tmpl.lhs[i] = arch_reg_constraint(state, 
12179                         out_param[i].expr->type, constraint->u.blob);
12180                 free_triple(state, constraint);
12181         }
12182         for(; i - out < clobbers; i++) {
12183                 struct triple *constraint;
12184                 constraint = clob_param[i - out].constraint;
12185                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12186                 free_triple(state, constraint);
12187         }
12188         for(i = 0; i < in; i++) {
12189                 struct triple *constraint;
12190                 const char *str;
12191                 constraint = in_param[i].constraint;
12192                 str = constraint->u.blob;
12193                 if (digitp(str[0]) && str[1] == '\0') {
12194                         struct reg_info cinfo;
12195                         int val;
12196                         val = digval(str[0]);
12197                         cinfo.reg = info->tmpl.lhs[val].reg;
12198                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12199                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
12200                         if (cinfo.reg == REG_UNSET) {
12201                                 cinfo.reg = REG_VIRT0 + val;
12202                         }
12203                         if (cinfo.regcm == 0) {
12204                                 error(state, 0, "No registers for %d", val);
12205                         }
12206                         info->tmpl.lhs[val] = cinfo;
12207                         info->tmpl.rhs[i]   = cinfo;
12208                                 
12209                 } else {
12210                         info->tmpl.rhs[i] = arch_reg_constraint(state, 
12211                                 in_param[i].expr->type, str);
12212                 }
12213                 free_triple(state, constraint);
12214         }
12215
12216         /* Now build the helper expressions */
12217         for(i = 0; i < in; i++) {
12218                 RHS(def, i) = read_expr(state, in_param[i].expr);
12219         }
12220         flatten(state, first, def);
12221         for(i = 0; i < (out + clobbers); i++) {
12222                 struct type *type;
12223                 struct triple *piece;
12224                 if (i < out) {
12225                         type = out_param[i].expr->type;
12226                 } else {
12227                         size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12228                         if (size >= SIZEOF_LONG) {
12229                                 type = &ulong_type;
12230                         } 
12231                         else if (size >= SIZEOF_INT) {
12232                                 type = &uint_type;
12233                         }
12234                         else if (size >= SIZEOF_SHORT) {
12235                                 type = &ushort_type;
12236                         }
12237                         else {
12238                                 type = &uchar_type;
12239                         }
12240                 }
12241                 piece = triple(state, OP_PIECE, type, def, 0);
12242                 piece->u.cval = i;
12243                 LHS(def, i) = piece;
12244                 flatten(state, first, piece);
12245         }
12246         /* And write the helpers to their destinations */
12247         for(i = 0; i < out; i++) {
12248                 struct triple *piece;
12249                 piece = LHS(def, i);
12250                 flatten(state, first,
12251                         write_expr(state, out_param[i].expr, piece));
12252         }
12253 }
12254
12255
12256 static int isdecl(int tok)
12257 {
12258         switch(tok) {
12259         case TOK_AUTO:
12260         case TOK_REGISTER:
12261         case TOK_STATIC:
12262         case TOK_EXTERN:
12263         case TOK_TYPEDEF:
12264         case TOK_CONST:
12265         case TOK_RESTRICT:
12266         case TOK_VOLATILE:
12267         case TOK_VOID:
12268         case TOK_CHAR:
12269         case TOK_SHORT:
12270         case TOK_INT:
12271         case TOK_LONG:
12272         case TOK_FLOAT:
12273         case TOK_DOUBLE:
12274         case TOK_SIGNED:
12275         case TOK_UNSIGNED:
12276         case TOK_STRUCT:
12277         case TOK_UNION:
12278         case TOK_ENUM:
12279         case TOK_TYPE_NAME: /* typedef name */
12280                 return 1;
12281         default:
12282                 return 0;
12283         }
12284 }
12285
12286 static void compound_statement(struct compile_state *state, struct triple *first)
12287 {
12288         eat(state, TOK_LBRACE);
12289         start_scope(state);
12290
12291         /* statement-list opt */
12292         while (peek(state) != TOK_RBRACE) {
12293                 statement(state, first);
12294         }
12295         end_scope(state);
12296         eat(state, TOK_RBRACE);
12297 }
12298
12299 static void statement(struct compile_state *state, struct triple *first)
12300 {
12301         int tok;
12302         tok = peek(state);
12303         if (tok == TOK_LBRACE) {
12304                 compound_statement(state, first);
12305         }
12306         else if (tok == TOK_IF) {
12307                 if_statement(state, first); 
12308         }
12309         else if (tok == TOK_FOR) {
12310                 for_statement(state, first);
12311         }
12312         else if (tok == TOK_WHILE) {
12313                 while_statement(state, first);
12314         }
12315         else if (tok == TOK_DO) {
12316                 do_statement(state, first);
12317         }
12318         else if (tok == TOK_RETURN) {
12319                 return_statement(state, first);
12320         }
12321         else if (tok == TOK_BREAK) {
12322                 break_statement(state, first);
12323         }
12324         else if (tok == TOK_CONTINUE) {
12325                 continue_statement(state, first);
12326         }
12327         else if (tok == TOK_GOTO) {
12328                 goto_statement(state, first);
12329         }
12330         else if (tok == TOK_SWITCH) {
12331                 switch_statement(state, first);
12332         }
12333         else if (tok == TOK_ASM) {
12334                 asm_statement(state, first);
12335         }
12336         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12337                 labeled_statement(state, first); 
12338         }
12339         else if (tok == TOK_CASE) {
12340                 case_statement(state, first);
12341         }
12342         else if (tok == TOK_DEFAULT) {
12343                 default_statement(state, first);
12344         }
12345         else if (isdecl(tok)) {
12346                 /* This handles C99 intermixing of statements and decls */
12347                 decl(state, first);
12348         }
12349         else {
12350                 expr_statement(state, first);
12351         }
12352 }
12353
12354 static struct type *param_decl(struct compile_state *state)
12355 {
12356         struct type *type;
12357         struct hash_entry *ident;
12358         /* Cheat so the declarator will know we are not global */
12359         start_scope(state); 
12360         ident = 0;
12361         type = decl_specifiers(state);
12362         type = declarator(state, type, &ident, 0);
12363         type->field_ident = ident;
12364         end_scope(state);
12365         return type;
12366 }
12367
12368 static struct type *param_type_list(struct compile_state *state, struct type *type)
12369 {
12370         struct type *ftype, **next;
12371         ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12372         next = &ftype->right;
12373         ftype->elements = 1;
12374         while(peek(state) == TOK_COMMA) {
12375                 eat(state, TOK_COMMA);
12376                 if (peek(state) == TOK_DOTS) {
12377                         eat(state, TOK_DOTS);
12378                         error(state, 0, "variadic functions not supported");
12379                 }
12380                 else {
12381                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12382                         next = &((*next)->right);
12383                         ftype->elements++;
12384                 }
12385         }
12386         return ftype;
12387 }
12388
12389 static struct type *type_name(struct compile_state *state)
12390 {
12391         struct type *type;
12392         type = specifier_qualifier_list(state);
12393         /* abstract-declarator (may consume no tokens) */
12394         type = declarator(state, type, 0, 0);
12395         return type;
12396 }
12397
12398 static struct type *direct_declarator(
12399         struct compile_state *state, struct type *type, 
12400         struct hash_entry **pident, int need_ident)
12401 {
12402         struct hash_entry *ident;
12403         struct type *outer;
12404         int op;
12405         outer = 0;
12406         arrays_complete(state, type);
12407         switch(peek(state)) {
12408         case TOK_IDENT:
12409                 ident = eat(state, TOK_IDENT)->ident;
12410                 if (!ident) {
12411                         error(state, 0, "Unexpected identifier found");
12412                 }
12413                 /* The name of what we are declaring */
12414                 *pident = ident;
12415                 break;
12416         case TOK_LPAREN:
12417                 eat(state, TOK_LPAREN);
12418                 outer = declarator(state, type, pident, need_ident);
12419                 eat(state, TOK_RPAREN);
12420                 break;
12421         default:
12422                 if (need_ident) {
12423                         error(state, 0, "Identifier expected");
12424                 }
12425                 break;
12426         }
12427         do {
12428                 op = 1;
12429                 arrays_complete(state, type);
12430                 switch(peek(state)) {
12431                 case TOK_LPAREN:
12432                         eat(state, TOK_LPAREN);
12433                         type = param_type_list(state, type);
12434                         eat(state, TOK_RPAREN);
12435                         break;
12436                 case TOK_LBRACKET:
12437                 {
12438                         unsigned int qualifiers;
12439                         struct triple *value;
12440                         value = 0;
12441                         eat(state, TOK_LBRACKET);
12442                         if (peek(state) != TOK_RBRACKET) {
12443                                 value = constant_expr(state);
12444                                 integral(state, value);
12445                         }
12446                         eat(state, TOK_RBRACKET);
12447
12448                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12449                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12450                         if (value) {
12451                                 type->elements = value->u.cval;
12452                                 free_triple(state, value);
12453                         } else {
12454                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12455                                 op = 0;
12456                         }
12457                 }
12458                         break;
12459                 default:
12460                         op = 0;
12461                         break;
12462                 }
12463         } while(op);
12464         if (outer) {
12465                 struct type *inner;
12466                 arrays_complete(state, type);
12467                 FINISHME();
12468                 for(inner = outer; inner->left; inner = inner->left)
12469                         ;
12470                 inner->left = type;
12471                 type = outer;
12472         }
12473         return type;
12474 }
12475
12476 static struct type *declarator(
12477         struct compile_state *state, struct type *type, 
12478         struct hash_entry **pident, int need_ident)
12479 {
12480         while(peek(state) == TOK_STAR) {
12481                 eat(state, TOK_STAR);
12482                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12483         }
12484         type = direct_declarator(state, type, pident, need_ident);
12485         return type;
12486 }
12487
12488 static struct type *typedef_name(
12489         struct compile_state *state, unsigned int specifiers)
12490 {
12491         struct hash_entry *ident;
12492         struct type *type;
12493         ident = eat(state, TOK_TYPE_NAME)->ident;
12494         type = ident->sym_ident->type;
12495         specifiers |= type->type & QUAL_MASK;
12496         if ((specifiers & (STOR_MASK | QUAL_MASK)) != 
12497                 (type->type & (STOR_MASK | QUAL_MASK))) {
12498                 type = clone_type(specifiers, type);
12499         }
12500         return type;
12501 }
12502
12503 static struct type *enum_specifier(
12504         struct compile_state *state, unsigned int spec)
12505 {
12506         struct hash_entry *ident;
12507         ulong_t base;
12508         int tok;
12509         struct type *enum_type;
12510         enum_type = 0;
12511         ident = 0;
12512         eat(state, TOK_ENUM);
12513         tok = peek(state);
12514         if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12515                 ident = eat(state, tok)->ident;
12516         }
12517         base = 0;
12518         if (!ident || (peek(state) == TOK_LBRACE)) {
12519                 struct type **next;
12520                 eat(state, TOK_LBRACE);
12521                 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12522                 enum_type->type_ident = ident;
12523                 next = &enum_type->right;
12524                 do {
12525                         struct hash_entry *eident;
12526                         struct triple *value;
12527                         struct type *entry;
12528                         eident = eat(state, TOK_IDENT)->ident;
12529                         if (eident->sym_ident) {
12530                                 error(state, 0, "%s already declared", 
12531                                         eident->name);
12532                         }
12533                         eident->tok = TOK_ENUM_CONST;
12534                         if (peek(state) == TOK_EQ) {
12535                                 struct triple *val;
12536                                 eat(state, TOK_EQ);
12537                                 val = constant_expr(state);
12538                                 integral(state, val);
12539                                 base = val->u.cval;
12540                         }
12541                         value = int_const(state, &int_type, base);
12542                         symbol(state, eident, &eident->sym_ident, value, &int_type);
12543                         entry = new_type(TYPE_LIST, 0, 0);
12544                         entry->field_ident = eident;
12545                         *next = entry;
12546                         next = &entry->right;
12547                         base += 1;
12548                         if (peek(state) == TOK_COMMA) {
12549                                 eat(state, TOK_COMMA);
12550                         }
12551                 } while(peek(state) != TOK_RBRACE);
12552                 eat(state, TOK_RBRACE);
12553                 if (ident) {
12554                         symbol(state, ident, &ident->sym_tag, 0, enum_type);
12555                 }
12556         }
12557         if (ident && ident->sym_tag &&
12558                 ident->sym_tag->type &&
12559                 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12560                 enum_type = clone_type(spec, ident->sym_tag->type);
12561         }
12562         else if (ident && !enum_type) {
12563                 error(state, 0, "enum %s undeclared", ident->name);
12564         }
12565         return enum_type;
12566 }
12567
12568 static struct type *struct_declarator(
12569         struct compile_state *state, struct type *type, struct hash_entry **ident)
12570 {
12571         if (peek(state) != TOK_COLON) {
12572                 type = declarator(state, type, ident, 1);
12573         }
12574         if (peek(state) == TOK_COLON) {
12575                 struct triple *value;
12576                 eat(state, TOK_COLON);
12577                 value = constant_expr(state);
12578                 if (value->op != OP_INTCONST) {
12579                         error(state, 0, "Invalid constant expression");
12580                 }
12581                 if (value->u.cval > size_of(state, type)) {
12582                         error(state, 0, "bitfield larger than base type");
12583                 }
12584                 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12585                         error(state, 0, "bitfield base not an integer type");
12586                 }
12587                 type = new_type(TYPE_BITFIELD, type, 0);
12588                 type->elements = value->u.cval;
12589         }
12590         return type;
12591 }
12592
12593 static struct type *struct_or_union_specifier(
12594         struct compile_state *state, unsigned int spec)
12595 {
12596         struct type *struct_type;
12597         struct hash_entry *ident;
12598         unsigned int type_main;
12599         unsigned int type_join;
12600         int tok;
12601         struct_type = 0;
12602         ident = 0;
12603         switch(peek(state)) {
12604         case TOK_STRUCT:
12605                 eat(state, TOK_STRUCT);
12606                 type_main = TYPE_STRUCT;
12607                 type_join = TYPE_PRODUCT;
12608                 break;
12609         case TOK_UNION:
12610                 eat(state, TOK_UNION);
12611                 type_main = TYPE_UNION;
12612                 type_join = TYPE_OVERLAP;
12613                 break;
12614         default:
12615                 eat(state, TOK_STRUCT);
12616                 type_main = TYPE_STRUCT;
12617                 type_join = TYPE_PRODUCT;
12618                 break;
12619         }
12620         tok = peek(state);
12621         if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12622                 ident = eat(state, tok)->ident;
12623         }
12624         if (!ident || (peek(state) == TOK_LBRACE)) {
12625                 ulong_t elements;
12626                 struct type **next;
12627                 elements = 0;
12628                 eat(state, TOK_LBRACE);
12629                 next = &struct_type;
12630                 do {
12631                         struct type *base_type;
12632                         int done;
12633                         base_type = specifier_qualifier_list(state);
12634                         do {
12635                                 struct type *type;
12636                                 struct hash_entry *fident;
12637                                 done = 1;
12638                                 type = struct_declarator(state, base_type, &fident);
12639                                 elements++;
12640                                 if (peek(state) == TOK_COMMA) {
12641                                         done = 0;
12642                                         eat(state, TOK_COMMA);
12643                                 }
12644                                 type = clone_type(0, type);
12645                                 type->field_ident = fident;
12646                                 if (*next) {
12647                                         *next = new_type(type_join, *next, type);
12648                                         next = &((*next)->right);
12649                                 } else {
12650                                         *next = type;
12651                                 }
12652                         } while(!done);
12653                         eat(state, TOK_SEMI);
12654                 } while(peek(state) != TOK_RBRACE);
12655                 eat(state, TOK_RBRACE);
12656                 struct_type = new_type(type_main | spec, struct_type, 0);
12657                 struct_type->type_ident = ident;
12658                 struct_type->elements = elements;
12659                 if (ident) {
12660                         symbol(state, ident, &ident->sym_tag, 0, struct_type);
12661                 }
12662         }
12663         if (ident && ident->sym_tag && 
12664                 ident->sym_tag->type && 
12665                 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12666                 struct_type = clone_type(spec, ident->sym_tag->type);
12667         }
12668         else if (ident && !struct_type) {
12669                 error(state, 0, "%s %s undeclared", 
12670                         (type_main == TYPE_STRUCT)?"struct" : "union",
12671                         ident->name);
12672         }
12673         return struct_type;
12674 }
12675
12676 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12677 {
12678         unsigned int specifiers;
12679         switch(peek(state)) {
12680         case TOK_AUTO:
12681                 eat(state, TOK_AUTO);
12682                 specifiers = STOR_AUTO;
12683                 break;
12684         case TOK_REGISTER:
12685                 eat(state, TOK_REGISTER);
12686                 specifiers = STOR_REGISTER;
12687                 break;
12688         case TOK_STATIC:
12689                 eat(state, TOK_STATIC);
12690                 specifiers = STOR_STATIC;
12691                 break;
12692         case TOK_EXTERN:
12693                 eat(state, TOK_EXTERN);
12694                 specifiers = STOR_EXTERN;
12695                 break;
12696         case TOK_TYPEDEF:
12697                 eat(state, TOK_TYPEDEF);
12698                 specifiers = STOR_TYPEDEF;
12699                 break;
12700         default:
12701                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12702                         specifiers = STOR_LOCAL;
12703                 }
12704                 else {
12705                         specifiers = STOR_AUTO;
12706                 }
12707         }
12708         return specifiers;
12709 }
12710
12711 static unsigned int function_specifier_opt(struct compile_state *state)
12712 {
12713         /* Ignore the inline keyword */
12714         unsigned int specifiers;
12715         specifiers = 0;
12716         switch(peek(state)) {
12717         case TOK_INLINE:
12718                 eat(state, TOK_INLINE);
12719                 specifiers = STOR_INLINE;
12720         }
12721         return specifiers;
12722 }
12723
12724 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12725 {
12726         int tok = peek(state);
12727         switch(tok) {
12728         case TOK_COMMA:
12729         case TOK_LPAREN:
12730                 /* The empty attribute ignore it */
12731                 break;
12732         case TOK_IDENT:
12733         case TOK_ENUM_CONST:
12734         case TOK_TYPE_NAME:
12735         {
12736                 struct hash_entry *ident;
12737                 ident = eat(state, TOK_IDENT)->ident;
12738
12739                 if (ident == state->i_noinline) {
12740                         if (attributes & ATTRIB_ALWAYS_INLINE) {
12741                                 error(state, 0, "both always_inline and noinline attribtes");
12742                         }
12743                         attributes |= ATTRIB_NOINLINE;
12744                 }
12745                 else if (ident == state->i_always_inline) {
12746                         if (attributes & ATTRIB_NOINLINE) {
12747                                 error(state, 0, "both noinline and always_inline attribtes");
12748                         }
12749                         attributes |= ATTRIB_ALWAYS_INLINE;
12750                 }
12751                 else {
12752                         error(state, 0, "Unknown attribute:%s", ident->name);
12753                 }
12754                 break;
12755         }
12756         default:
12757                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12758                 break;
12759         }
12760         return attributes;
12761 }
12762
12763 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12764 {
12765         type = attrib(state, type);
12766         while(peek(state) == TOK_COMMA) {
12767                 eat(state, TOK_COMMA);
12768                 type = attrib(state, type);
12769         }
12770         return type;
12771 }
12772
12773 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12774 {
12775         if (peek(state) == TOK_ATTRIBUTE) {
12776                 eat(state, TOK_ATTRIBUTE);
12777                 eat(state, TOK_LPAREN);
12778                 eat(state, TOK_LPAREN);
12779                 type = attribute_list(state, type);
12780                 eat(state, TOK_RPAREN);
12781                 eat(state, TOK_RPAREN);
12782         }
12783         return type;
12784 }
12785
12786 static unsigned int type_qualifiers(struct compile_state *state)
12787 {
12788         unsigned int specifiers;
12789         int done;
12790         done = 0;
12791         specifiers = QUAL_NONE;
12792         do {
12793                 switch(peek(state)) {
12794                 case TOK_CONST:
12795                         eat(state, TOK_CONST);
12796                         specifiers |= QUAL_CONST;
12797                         break;
12798                 case TOK_VOLATILE:
12799                         eat(state, TOK_VOLATILE);
12800                         specifiers |= QUAL_VOLATILE;
12801                         break;
12802                 case TOK_RESTRICT:
12803                         eat(state, TOK_RESTRICT);
12804                         specifiers |= QUAL_RESTRICT;
12805                         break;
12806                 default:
12807                         done = 1;
12808                         break;
12809                 }
12810         } while(!done);
12811         return specifiers;
12812 }
12813
12814 static struct type *type_specifier(
12815         struct compile_state *state, unsigned int spec)
12816 {
12817         struct type *type;
12818         int tok;
12819         type = 0;
12820         switch((tok = peek(state))) {
12821         case TOK_VOID:
12822                 eat(state, TOK_VOID);
12823                 type = new_type(TYPE_VOID | spec, 0, 0);
12824                 break;
12825         case TOK_CHAR:
12826                 eat(state, TOK_CHAR);
12827                 type = new_type(TYPE_CHAR | spec, 0, 0);
12828                 break;
12829         case TOK_SHORT:
12830                 eat(state, TOK_SHORT);
12831                 if (peek(state) == TOK_INT) {
12832                         eat(state, TOK_INT);
12833                 }
12834                 type = new_type(TYPE_SHORT | spec, 0, 0);
12835                 break;
12836         case TOK_INT:
12837                 eat(state, TOK_INT);
12838                 type = new_type(TYPE_INT | spec, 0, 0);
12839                 break;
12840         case TOK_LONG:
12841                 eat(state, TOK_LONG);
12842                 switch(peek(state)) {
12843                 case TOK_LONG:
12844                         eat(state, TOK_LONG);
12845                         error(state, 0, "long long not supported");
12846                         break;
12847                 case TOK_DOUBLE:
12848                         eat(state, TOK_DOUBLE);
12849                         error(state, 0, "long double not supported");
12850                         break;
12851                 case TOK_INT:
12852                         eat(state, TOK_INT);
12853                         type = new_type(TYPE_LONG | spec, 0, 0);
12854                         break;
12855                 default:
12856                         type = new_type(TYPE_LONG | spec, 0, 0);
12857                         break;
12858                 }
12859                 break;
12860         case TOK_FLOAT:
12861                 eat(state, TOK_FLOAT);
12862                 error(state, 0, "type float not supported");
12863                 break;
12864         case TOK_DOUBLE:
12865                 eat(state, TOK_DOUBLE);
12866                 error(state, 0, "type double not supported");
12867                 break;
12868         case TOK_SIGNED:
12869                 eat(state, TOK_SIGNED);
12870                 switch(peek(state)) {
12871                 case TOK_LONG:
12872                         eat(state, TOK_LONG);
12873                         switch(peek(state)) {
12874                         case TOK_LONG:
12875                                 eat(state, TOK_LONG);
12876                                 error(state, 0, "type long long not supported");
12877                                 break;
12878                         case TOK_INT:
12879                                 eat(state, TOK_INT);
12880                                 type = new_type(TYPE_LONG | spec, 0, 0);
12881                                 break;
12882                         default:
12883                                 type = new_type(TYPE_LONG | spec, 0, 0);
12884                                 break;
12885                         }
12886                         break;
12887                 case TOK_INT:
12888                         eat(state, TOK_INT);
12889                         type = new_type(TYPE_INT | spec, 0, 0);
12890                         break;
12891                 case TOK_SHORT:
12892                         eat(state, TOK_SHORT);
12893                         type = new_type(TYPE_SHORT | spec, 0, 0);
12894                         break;
12895                 case TOK_CHAR:
12896                         eat(state, TOK_CHAR);
12897                         type = new_type(TYPE_CHAR | spec, 0, 0);
12898                         break;
12899                 default:
12900                         type = new_type(TYPE_INT | spec, 0, 0);
12901                         break;
12902                 }
12903                 break;
12904         case TOK_UNSIGNED:
12905                 eat(state, TOK_UNSIGNED);
12906                 switch(peek(state)) {
12907                 case TOK_LONG:
12908                         eat(state, TOK_LONG);
12909                         switch(peek(state)) {
12910                         case TOK_LONG:
12911                                 eat(state, TOK_LONG);
12912                                 error(state, 0, "unsigned long long not supported");
12913                                 break;
12914                         case TOK_INT:
12915                                 eat(state, TOK_INT);
12916                                 type = new_type(TYPE_ULONG | spec, 0, 0);
12917                                 break;
12918                         default:
12919                                 type = new_type(TYPE_ULONG | spec, 0, 0);
12920                                 break;
12921                         }
12922                         break;
12923                 case TOK_INT:
12924                         eat(state, TOK_INT);
12925                         type = new_type(TYPE_UINT | spec, 0, 0);
12926                         break;
12927                 case TOK_SHORT:
12928                         eat(state, TOK_SHORT);
12929                         type = new_type(TYPE_USHORT | spec, 0, 0);
12930                         break;
12931                 case TOK_CHAR:
12932                         eat(state, TOK_CHAR);
12933                         type = new_type(TYPE_UCHAR | spec, 0, 0);
12934                         break;
12935                 default:
12936                         type = new_type(TYPE_UINT | spec, 0, 0);
12937                         break;
12938                 }
12939                 break;
12940                 /* struct or union specifier */
12941         case TOK_STRUCT:
12942         case TOK_UNION:
12943                 type = struct_or_union_specifier(state, spec);
12944                 break;
12945                 /* enum-spefifier */
12946         case TOK_ENUM:
12947                 type = enum_specifier(state, spec);
12948                 break;
12949                 /* typedef name */
12950         case TOK_TYPE_NAME:
12951                 type = typedef_name(state, spec);
12952                 break;
12953         default:
12954                 error(state, 0, "bad type specifier %s", 
12955                         tokens[tok]);
12956                 break;
12957         }
12958         return type;
12959 }
12960
12961 static int istype(int tok)
12962 {
12963         switch(tok) {
12964         case TOK_CONST:
12965         case TOK_RESTRICT:
12966         case TOK_VOLATILE:
12967         case TOK_VOID:
12968         case TOK_CHAR:
12969         case TOK_SHORT:
12970         case TOK_INT:
12971         case TOK_LONG:
12972         case TOK_FLOAT:
12973         case TOK_DOUBLE:
12974         case TOK_SIGNED:
12975         case TOK_UNSIGNED:
12976         case TOK_STRUCT:
12977         case TOK_UNION:
12978         case TOK_ENUM:
12979         case TOK_TYPE_NAME:
12980                 return 1;
12981         default:
12982                 return 0;
12983         }
12984 }
12985
12986
12987 static struct type *specifier_qualifier_list(struct compile_state *state)
12988 {
12989         struct type *type;
12990         unsigned int specifiers = 0;
12991
12992         /* type qualifiers */
12993         specifiers |= type_qualifiers(state);
12994
12995         /* type specifier */
12996         type = type_specifier(state, specifiers);
12997
12998         return type;
12999 }
13000
13001 #if DEBUG_ROMCC_WARNING
13002 static int isdecl_specifier(int tok)
13003 {
13004         switch(tok) {
13005                 /* storage class specifier */
13006         case TOK_AUTO:
13007         case TOK_REGISTER:
13008         case TOK_STATIC:
13009         case TOK_EXTERN:
13010         case TOK_TYPEDEF:
13011                 /* type qualifier */
13012         case TOK_CONST:
13013         case TOK_RESTRICT:
13014         case TOK_VOLATILE:
13015                 /* type specifiers */
13016         case TOK_VOID:
13017         case TOK_CHAR:
13018         case TOK_SHORT:
13019         case TOK_INT:
13020         case TOK_LONG:
13021         case TOK_FLOAT:
13022         case TOK_DOUBLE:
13023         case TOK_SIGNED:
13024         case TOK_UNSIGNED:
13025                 /* struct or union specifier */
13026         case TOK_STRUCT:
13027         case TOK_UNION:
13028                 /* enum-spefifier */
13029         case TOK_ENUM:
13030                 /* typedef name */
13031         case TOK_TYPE_NAME:
13032                 /* function specifiers */
13033         case TOK_INLINE:
13034                 return 1;
13035         default:
13036                 return 0;
13037         }
13038 }
13039 #endif
13040
13041 static struct type *decl_specifiers(struct compile_state *state)
13042 {
13043         struct type *type;
13044         unsigned int specifiers;
13045         /* I am overly restrictive in the arragement of specifiers supported.
13046          * C is overly flexible in this department it makes interpreting
13047          * the parse tree difficult.
13048          */
13049         specifiers = 0;
13050
13051         /* storage class specifier */
13052         specifiers |= storage_class_specifier_opt(state);
13053
13054         /* function-specifier */
13055         specifiers |= function_specifier_opt(state);
13056
13057         /* attributes */
13058         specifiers |= attributes_opt(state, 0);
13059
13060         /* type qualifier */
13061         specifiers |= type_qualifiers(state);
13062
13063         /* type specifier */
13064         type = type_specifier(state, specifiers);
13065         return type;
13066 }
13067
13068 struct field_info {
13069         struct type *type;
13070         size_t offset;
13071 };
13072
13073 static struct field_info designator(struct compile_state *state, struct type *type)
13074 {
13075         int tok;
13076         struct field_info info;
13077         info.offset = ~0U;
13078         info.type = 0;
13079         do {
13080                 switch(peek(state)) {
13081                 case TOK_LBRACKET:
13082                 {
13083                         struct triple *value;
13084                         if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13085                                 error(state, 0, "Array designator not in array initializer");
13086                         }
13087                         eat(state, TOK_LBRACKET);
13088                         value = constant_expr(state);
13089                         eat(state, TOK_RBRACKET);
13090
13091                         info.type = type->left;
13092                         info.offset = value->u.cval * size_of(state, info.type);
13093                         break;
13094                 }
13095                 case TOK_DOT:
13096                 {
13097                         struct hash_entry *field;
13098                         if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13099                                 ((type->type & TYPE_MASK) != TYPE_UNION))
13100                         {
13101                                 error(state, 0, "Struct designator not in struct initializer");
13102                         }
13103                         eat(state, TOK_DOT);
13104                         field = eat(state, TOK_IDENT)->ident;
13105                         info.offset = field_offset(state, type, field);
13106                         info.type   = field_type(state, type, field);
13107                         break;
13108                 }
13109                 default:
13110                         error(state, 0, "Invalid designator");
13111                 }
13112                 tok = peek(state);
13113         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13114         eat(state, TOK_EQ);
13115         return info;
13116 }
13117
13118 static struct triple *initializer(
13119         struct compile_state *state, struct type *type)
13120 {
13121         struct triple *result;
13122 #if DEBUG_ROMCC_WARNINGS
13123 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13124 #endif
13125         if (peek(state) != TOK_LBRACE) {
13126                 result = assignment_expr(state);
13127                 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13128                         (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13129                         ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13130                         (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13131                         (equiv_types(type->left, result->type->left))) {
13132                         type->elements = result->type->elements;
13133                 }
13134                 if (is_lvalue(state, result) && 
13135                         ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13136                         (type->type & TYPE_MASK) != TYPE_ARRAY)
13137                 {
13138                         result = lvalue_conversion(state, result);
13139                 }
13140                 if (!is_init_compatible(state, type, result->type)) {
13141                         error(state, 0, "Incompatible types in initializer");
13142                 }
13143                 if (!equiv_types(type, result->type)) {
13144                         result = mk_cast_expr(state, type, result);
13145                 }
13146         }
13147         else {
13148                 int comma;
13149                 size_t max_offset;
13150                 struct field_info info;
13151                 void *buf;
13152                 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13153                         ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13154                         internal_error(state, 0, "unknown initializer type");
13155                 }
13156                 info.offset = 0;
13157                 info.type = type->left;
13158                 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13159                         info.type = next_field(state, type, 0);
13160                 }
13161                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13162                         max_offset = 0;
13163                 } else {
13164                         max_offset = size_of(state, type);
13165                 }
13166                 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13167                 eat(state, TOK_LBRACE);
13168                 do {
13169                         struct triple *value;
13170                         struct type *value_type;
13171                         size_t value_size;
13172                         void *dest;
13173                         int tok;
13174                         comma = 0;
13175                         tok = peek(state);
13176                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13177                                 info = designator(state, type);
13178                         }
13179                         if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13180                                 (info.offset >= max_offset)) {
13181                                 error(state, 0, "element beyond bounds");
13182                         }
13183                         value_type = info.type;
13184                         value = eval_const_expr(state, initializer(state, value_type));
13185                         value_size = size_of(state, value_type);
13186                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13187                                 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13188                                 (max_offset <= info.offset)) {
13189                                 void *old_buf;
13190                                 size_t old_size;
13191                                 old_buf = buf;
13192                                 old_size = max_offset;
13193                                 max_offset = info.offset + value_size;
13194                                 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13195                                 memcpy(buf, old_buf, bits_to_bytes(old_size));
13196                                 xfree(old_buf);
13197                         }
13198                         dest = ((char *)buf) + bits_to_bytes(info.offset);
13199 #if DEBUG_INITIALIZER
13200                         fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n", 
13201                                 dest - buf,
13202                                 bits_to_bytes(max_offset),
13203                                 bits_to_bytes(value_size),
13204                                 value->op);
13205 #endif
13206                         if (value->op == OP_BLOBCONST) {
13207                                 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13208                         }
13209                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13210 #if DEBUG_INITIALIZER
13211                                 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13212 #endif
13213                                 *((uint8_t *)dest) = value->u.cval & 0xff;
13214                         }
13215                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13216                                 *((uint16_t *)dest) = value->u.cval & 0xffff;
13217                         }
13218                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13219                                 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13220                         }
13221                         else {
13222                                 internal_error(state, 0, "unhandled constant initializer");
13223                         }
13224                         free_triple(state, value);
13225                         if (peek(state) == TOK_COMMA) {
13226                                 eat(state, TOK_COMMA);
13227                                 comma = 1;
13228                         }
13229                         info.offset += value_size;
13230                         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13231                                 info.type = next_field(state, type, info.type);
13232                                 info.offset = field_offset(state, type, 
13233                                         info.type->field_ident);
13234                         }
13235                 } while(comma && (peek(state) != TOK_RBRACE));
13236                 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13237                         ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13238                         type->elements = max_offset / size_of(state, type->left);
13239                 }
13240                 eat(state, TOK_RBRACE);
13241                 result = triple(state, OP_BLOBCONST, type, 0, 0);
13242                 result->u.blob = buf;
13243         }
13244         return result;
13245 }
13246
13247 static void resolve_branches(struct compile_state *state, struct triple *first)
13248 {
13249         /* Make a second pass and finish anything outstanding
13250          * with respect to branches.  The only outstanding item
13251          * is to see if there are goto to labels that have not
13252          * been defined and to error about them.
13253          */
13254         int i;
13255         struct triple *ins;
13256         /* Also error on branches that do not use their targets */
13257         ins = first;
13258         do {
13259                 if (!triple_is_ret(state, ins)) {
13260                         struct triple **expr ;
13261                         struct triple_set *set;
13262                         expr = triple_targ(state, ins, 0);
13263                         for(; expr; expr = triple_targ(state, ins, expr)) {
13264                                 struct triple *targ;
13265                                 targ = *expr;
13266                                 for(set = targ?targ->use:0; set; set = set->next) {
13267                                         if (set->member == ins) {
13268                                                 break;
13269                                         }
13270                                 }
13271                                 if (!set) {
13272                                         internal_error(state, ins, "targ not used");
13273                                 }
13274                         }
13275                 }
13276                 ins = ins->next;
13277         } while(ins != first);
13278         /* See if there are goto to labels that have not been defined */
13279         for(i = 0; i < HASH_TABLE_SIZE; i++) {
13280                 struct hash_entry *entry;
13281                 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13282                         struct triple *ins;
13283                         if (!entry->sym_label) {
13284                                 continue;
13285                         }
13286                         ins = entry->sym_label->def;
13287                         if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13288                                 error(state, ins, "label `%s' used but not defined",
13289                                         entry->name);
13290                         }
13291                 }
13292         }
13293 }
13294
13295 static struct triple *function_definition(
13296         struct compile_state *state, struct type *type)
13297 {
13298         struct triple *def, *tmp, *first, *end, *retvar, *result, *ret;
13299         struct triple *fname;
13300         struct type *fname_type;
13301         struct hash_entry *ident;
13302         struct type *param, *crtype, *ctype;
13303         int i;
13304         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13305                 error(state, 0, "Invalid function header");
13306         }
13307
13308         /* Verify the function type */
13309         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
13310                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13311                 (type->right->field_ident == 0)) {
13312                 error(state, 0, "Invalid function parameters");
13313         }
13314         param = type->right;
13315         i = 0;
13316         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13317                 i++;
13318                 if (!param->left->field_ident) {
13319                         error(state, 0, "No identifier for parameter %d\n", i);
13320                 }
13321                 param = param->right;
13322         }
13323         i++;
13324         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13325                 error(state, 0, "No identifier for paramter %d\n", i);
13326         }
13327         
13328         /* Get a list of statements for this function. */
13329         def = triple(state, OP_LIST, type, 0, 0);
13330
13331         /* Start a new scope for the passed parameters */
13332         start_scope(state);
13333
13334         /* Put a label at the very start of a function */
13335         first = label(state);
13336         RHS(def, 0) = first;
13337
13338         /* Put a label at the very end of a function */
13339         end = label(state);
13340         flatten(state, first, end);
13341         /* Remember where return goes */
13342         ident = state->i_return;
13343         symbol(state, ident, &ident->sym_ident, end, end->type);
13344
13345         /* Get the initial closure type */
13346         ctype = new_type(TYPE_JOIN, &void_type, 0);
13347         ctype->elements = 1;
13348
13349         /* Add a variable for the return value */
13350         crtype = new_type(TYPE_TUPLE, 
13351                 /* Remove all type qualifiers from the return type */
13352                 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13353         crtype->elements = 2;
13354         result = flatten(state, end, variable(state, crtype));
13355
13356         /* Allocate a variable for the return address */
13357         retvar = flatten(state, end, variable(state, &void_ptr_type));
13358
13359         /* Add in the return instruction */
13360         ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13361         ret = flatten(state, first, ret);
13362
13363         /* Walk through the parameters and create symbol table entries
13364          * for them.
13365          */
13366         param = type->right;
13367         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13368                 ident = param->left->field_ident;
13369                 tmp = variable(state, param->left);
13370                 var_symbol(state, ident, tmp);
13371                 flatten(state, end, tmp);
13372                 param = param->right;
13373         }
13374         if ((param->type & TYPE_MASK) != TYPE_VOID) {
13375                 /* And don't forget the last parameter */
13376                 ident = param->field_ident;
13377                 tmp = variable(state, param);
13378                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13379                 flatten(state, end, tmp);
13380         }
13381
13382         /* Add the declaration static const char __func__ [] = "func-name"  */
13383         fname_type = new_type(TYPE_ARRAY, 
13384                 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13385         fname_type->type |= QUAL_CONST | STOR_STATIC;
13386         fname_type->elements = strlen(state->function) + 1;
13387
13388         fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13389         fname->u.blob = (void *)state->function;
13390         fname = flatten(state, end, fname);
13391
13392         ident = state->i___func__;
13393         symbol(state, ident, &ident->sym_ident, fname, fname_type);
13394
13395         /* Remember which function I am compiling.
13396          * Also assume the last defined function is the main function.
13397          */
13398         state->main_function = def;
13399
13400         /* Now get the actual function definition */
13401         compound_statement(state, end);
13402
13403         /* Finish anything unfinished with branches */
13404         resolve_branches(state, first);
13405
13406         /* Remove the parameter scope */
13407         end_scope(state);
13408
13409
13410         /* Remember I have defined a function */
13411         if (!state->functions) {
13412                 state->functions = def;
13413         } else {
13414                 insert_triple(state, state->functions, def);
13415         }
13416         if (state->compiler->debug & DEBUG_INLINE) {
13417                 FILE *fp = state->dbgout;
13418                 fprintf(fp, "\n");
13419                 loc(fp, state, 0);
13420                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13421                 display_func(state, fp, def);
13422                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13423         }
13424
13425         return def;
13426 }
13427
13428 static struct triple *do_decl(struct compile_state *state, 
13429         struct type *type, struct hash_entry *ident)
13430 {
13431         struct triple *def;
13432         def = 0;
13433         /* Clean up the storage types used */
13434         switch (type->type & STOR_MASK) {
13435         case STOR_AUTO:
13436         case STOR_STATIC:
13437                 /* These are the good types I am aiming for */
13438                 break;
13439         case STOR_REGISTER:
13440                 type->type &= ~STOR_MASK;
13441                 type->type |= STOR_AUTO;
13442                 break;
13443         case STOR_LOCAL:
13444         case STOR_EXTERN:
13445                 type->type &= ~STOR_MASK;
13446                 type->type |= STOR_STATIC;
13447                 break;
13448         case STOR_TYPEDEF:
13449                 if (!ident) {
13450                         error(state, 0, "typedef without name");
13451                 }
13452                 symbol(state, ident, &ident->sym_ident, 0, type);
13453                 ident->tok = TOK_TYPE_NAME;
13454                 return 0;
13455                 break;
13456         default:
13457                 internal_error(state, 0, "Undefined storage class");
13458         }
13459         if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13460                 error(state, 0, "Function prototypes not supported");
13461         }
13462         if (ident && 
13463                 ((type->type & STOR_MASK) == STOR_STATIC) &&
13464                 ((type->type & QUAL_CONST) == 0)) {
13465                 error(state, 0, "non const static variables not supported");
13466         }
13467         if (ident) {
13468                 def = variable(state, type);
13469                 var_symbol(state, ident, def);
13470         }
13471         return def;
13472 }
13473
13474 static void decl(struct compile_state *state, struct triple *first)
13475 {
13476         struct type *base_type, *type;
13477         struct hash_entry *ident;
13478         struct triple *def;
13479         int global;
13480         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13481         base_type = decl_specifiers(state);
13482         ident = 0;
13483         type = declarator(state, base_type, &ident, 0);
13484         type->type = attributes_opt(state, type->type);
13485         if (global && ident && (peek(state) == TOK_LBRACE)) {
13486                 /* function */
13487                 type->type_ident = ident;
13488                 state->function = ident->name;
13489                 def = function_definition(state, type);
13490                 symbol(state, ident, &ident->sym_ident, def, type);
13491                 state->function = 0;
13492         }
13493         else {
13494                 int done;
13495                 flatten(state, first, do_decl(state, type, ident));
13496                 /* type or variable definition */
13497                 do {
13498                         done = 1;
13499                         if (peek(state) == TOK_EQ) {
13500                                 if (!ident) {
13501                                         error(state, 0, "cannot assign to a type");
13502                                 }
13503                                 eat(state, TOK_EQ);
13504                                 flatten(state, first,
13505                                         init_expr(state, 
13506                                                 ident->sym_ident->def, 
13507                                                 initializer(state, type)));
13508                         }
13509                         arrays_complete(state, type);
13510                         if (peek(state) == TOK_COMMA) {
13511                                 eat(state, TOK_COMMA);
13512                                 ident = 0;
13513                                 type = declarator(state, base_type, &ident, 0);
13514                                 flatten(state, first, do_decl(state, type, ident));
13515                                 done = 0;
13516                         }
13517                 } while(!done);
13518                 eat(state, TOK_SEMI);
13519         }
13520 }
13521
13522 static void decls(struct compile_state *state)
13523 {
13524         struct triple *list;
13525         int tok;
13526         list = label(state);
13527         while(1) {
13528                 tok = peek(state);
13529                 if (tok == TOK_EOF) {
13530                         return;
13531                 }
13532                 if (tok == TOK_SPACE) {
13533                         eat(state, TOK_SPACE);
13534                 }
13535                 decl(state, list);
13536                 if (list->next != list) {
13537                         error(state, 0, "global variables not supported");
13538                 }
13539         }
13540 }
13541
13542 /* 
13543  * Function inlining
13544  */
13545 struct triple_reg_set {
13546         struct triple_reg_set *next;
13547         struct triple *member;
13548         struct triple *new;
13549 };
13550 struct reg_block {
13551         struct block *block;
13552         struct triple_reg_set *in;
13553         struct triple_reg_set *out;
13554         int vertex;
13555 };
13556 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13557 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13558 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13559 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13560 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13561         void (*cb)(struct compile_state *state, struct block *block, void *arg),
13562         void *arg);
13563 static void print_block(
13564         struct compile_state *state, struct block *block, void *arg);
13565 static int do_triple_set(struct triple_reg_set **head, 
13566         struct triple *member, struct triple *new_member);
13567 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13568 static struct reg_block *compute_variable_lifetimes(
13569         struct compile_state *state, struct basic_blocks *bb);
13570 static void free_variable_lifetimes(struct compile_state *state, 
13571         struct basic_blocks *bb, struct reg_block *blocks);
13572 #if DEBUG_EXPLICIT_CLOSURES
13573 static void print_live_variables(struct compile_state *state, 
13574         struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13575 #endif
13576
13577
13578 static struct triple *call(struct compile_state *state,
13579         struct triple *retvar, struct triple *ret_addr, 
13580         struct triple *targ, struct triple *ret)
13581 {
13582         struct triple *call;
13583
13584         if (!retvar || !is_lvalue(state, retvar)) {
13585                 internal_error(state, 0, "writing to a non lvalue?");
13586         }
13587         write_compatible(state, retvar->type, &void_ptr_type);
13588
13589         call = new_triple(state, OP_CALL, &void_type, 1, 0);
13590         TARG(call, 0) = targ;
13591         MISC(call, 0) = ret;
13592         if (!targ || (targ->op != OP_LABEL)) {
13593                 internal_error(state, 0, "call not to a label");
13594         }
13595         if (!ret || (ret->op != OP_RET)) {
13596                 internal_error(state, 0, "call not matched with return");
13597         }
13598         return call;
13599 }
13600
13601 static void walk_functions(struct compile_state *state,
13602         void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13603         void *arg)
13604 {
13605         struct triple *func, *first;
13606         func = first = state->functions;
13607         do {
13608                 cb(state, func, arg);
13609                 func = func->next;
13610         } while(func != first);
13611 }
13612
13613 static void reverse_walk_functions(struct compile_state *state,
13614         void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13615         void *arg)
13616 {
13617         struct triple *func, *first;
13618         func = first = state->functions;
13619         do {
13620                 func = func->prev;
13621                 cb(state, func, arg);
13622         } while(func != first);
13623 }
13624
13625
13626 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13627 {
13628         struct triple *ptr, *first;
13629         if (func->u.cval == 0) {
13630                 return;
13631         }
13632         ptr = first = RHS(func, 0);
13633         do {
13634                 if (ptr->op == OP_FCALL) {
13635                         struct triple *called_func;
13636                         called_func = MISC(ptr, 0);
13637                         /* Mark the called function as used */
13638                         if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13639                                 called_func->u.cval++;
13640                         }
13641                         /* Remove the called function from the list */
13642                         called_func->prev->next = called_func->next;
13643                         called_func->next->prev = called_func->prev;
13644
13645                         /* Place the called function before me on the list */
13646                         called_func->next       = func;
13647                         called_func->prev       = func->prev;
13648                         called_func->prev->next = called_func;
13649                         called_func->next->prev = called_func;
13650                 }
13651                 ptr = ptr->next;
13652         } while(ptr != first);
13653         func->id |= TRIPLE_FLAG_FLATTENED;
13654 }
13655
13656 static void mark_live_functions(struct compile_state *state)
13657 {
13658         /* Ensure state->main_function is the last function in 
13659          * the list of functions.
13660          */
13661         if ((state->main_function->next != state->functions) ||
13662                 (state->functions->prev != state->main_function)) {
13663                 internal_error(state, 0, 
13664                         "state->main_function is not at the end of the function list ");
13665         }
13666         state->main_function->u.cval = 1;
13667         reverse_walk_functions(state, mark_live, 0);
13668 }
13669
13670 static int local_triple(struct compile_state *state, 
13671         struct triple *func, struct triple *ins)
13672 {
13673         int local = (ins->id & TRIPLE_FLAG_LOCAL);
13674 #if 0
13675         if (!local) {
13676                 FILE *fp = state->errout;
13677                 fprintf(fp, "global: ");
13678                 display_triple(fp, ins);
13679         }
13680 #endif
13681         return local;
13682 }
13683
13684 struct triple *copy_func(struct compile_state *state, struct triple *ofunc, 
13685         struct occurance *base_occurance)
13686 {
13687         struct triple *nfunc;
13688         struct triple *nfirst, *ofirst;
13689         struct triple *new, *old;
13690
13691         if (state->compiler->debug & DEBUG_INLINE) {
13692                 FILE *fp = state->dbgout;
13693                 fprintf(fp, "\n");
13694                 loc(fp, state, 0);
13695                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13696                 display_func(state, fp, ofunc);
13697                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13698         }
13699
13700         /* Make a new copy of the old function */
13701         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13702         nfirst = 0;
13703         ofirst = old = RHS(ofunc, 0);
13704         do {
13705                 struct triple *new;
13706                 struct occurance *occurance;
13707                 int old_lhs, old_rhs;
13708                 old_lhs = old->lhs;
13709                 old_rhs = old->rhs;
13710                 occurance = inline_occurance(state, base_occurance, old->occurance);
13711                 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13712                         MISC(old, 0)->u.cval += 1;
13713                 }
13714                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13715                         occurance);
13716                 if (!triple_stores_block(state, new)) {
13717                         memcpy(&new->u, &old->u, sizeof(new->u));
13718                 }
13719                 if (!nfirst) {
13720                         RHS(nfunc, 0) = nfirst = new;
13721                 }
13722                 else {
13723                         insert_triple(state, nfirst, new);
13724                 }
13725                 new->id |= TRIPLE_FLAG_FLATTENED;
13726                 new->id |= old->id & TRIPLE_FLAG_COPY;
13727                 
13728                 /* During the copy remember new as user of old */
13729                 use_triple(old, new);
13730
13731                 /* Remember which instructions are local */
13732                 old->id |= TRIPLE_FLAG_LOCAL;
13733                 old = old->next;
13734         } while(old != ofirst);
13735
13736         /* Make a second pass to fix up any unresolved references */
13737         old = ofirst;
13738         new = nfirst;
13739         do {
13740                 struct triple **oexpr, **nexpr;
13741                 int count, i;
13742                 /* Lookup where the copy is, to join pointers */
13743                 count = TRIPLE_SIZE(old);
13744                 for(i = 0; i < count; i++) {
13745                         oexpr = &old->param[i];
13746                         nexpr = &new->param[i];
13747                         if (*oexpr && !*nexpr) {
13748                                 if (!local_triple(state, ofunc, *oexpr)) {
13749                                         *nexpr = *oexpr;
13750                                 }
13751                                 else if ((*oexpr)->use) {
13752                                         *nexpr = (*oexpr)->use->member;
13753                                 }
13754                                 if (*nexpr == old) {
13755                                         internal_error(state, 0, "new == old?");
13756                                 }
13757                                 use_triple(*nexpr, new);
13758                         }
13759                         if (!*nexpr && *oexpr) {
13760                                 internal_error(state, 0, "Could not copy %d", i);
13761                         }
13762                 }
13763                 old = old->next;
13764                 new = new->next;
13765         } while((old != ofirst) && (new != nfirst));
13766         
13767         /* Make a third pass to cleanup the extra useses */
13768         old = ofirst;
13769         new = nfirst;
13770         do {
13771                 unuse_triple(old, new);
13772                 /* Forget which instructions are local */
13773                 old->id &= ~TRIPLE_FLAG_LOCAL;
13774                 old = old->next;
13775                 new = new->next;
13776         } while ((old != ofirst) && (new != nfirst));
13777         return nfunc;
13778 }
13779
13780 static void expand_inline_call(
13781         struct compile_state *state, struct triple *me, struct triple *fcall)
13782 {
13783         /* Inline the function call */
13784         struct type *ptype;
13785         struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13786         struct triple *end, *nend;
13787         int pvals, i;
13788
13789         /* Find the triples */
13790         ofunc = MISC(fcall, 0);
13791         if (ofunc->op != OP_LIST) {
13792                 internal_error(state, 0, "improper function");
13793         }
13794         nfunc = copy_func(state, ofunc, fcall->occurance);
13795         /* Prepend the parameter reading into the new function list */
13796         ptype = nfunc->type->right;
13797         pvals = fcall->rhs;
13798         for(i = 0; i < pvals; i++) {
13799                 struct type *atype;
13800                 struct triple *arg, *param;
13801                 atype = ptype;
13802                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13803                         atype = ptype->left;
13804                 }
13805                 param = farg(state, nfunc, i);
13806                 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13807                         internal_error(state, fcall, "param %d type mismatch", i);
13808                 }
13809                 arg = RHS(fcall, i);
13810                 flatten(state, fcall, write_expr(state, param, arg));
13811                 ptype = ptype->right;
13812         }
13813         result = 0;
13814         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13815                 result = read_expr(state, 
13816                         deref_index(state, fresult(state, nfunc), 1));
13817         }
13818         if (state->compiler->debug & DEBUG_INLINE) {
13819                 FILE *fp = state->dbgout;
13820                 fprintf(fp, "\n");
13821                 loc(fp, state, 0);
13822                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13823                 display_func(state, fp, nfunc);
13824                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13825         }
13826
13827         /* 
13828          * Get rid of the extra triples 
13829          */
13830         /* Remove the read of the return address */
13831         ins = RHS(nfunc, 0)->prev->prev;
13832         if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13833                 internal_error(state, ins, "Not return addres read?");
13834         }
13835         release_triple(state, ins);
13836         /* Remove the return instruction */
13837         ins = RHS(nfunc, 0)->prev;
13838         if (ins->op != OP_RET) {
13839                 internal_error(state, ins, "Not return?");
13840         }
13841         release_triple(state, ins);
13842         /* Remove the retaddres variable */
13843         retvar = fretaddr(state, nfunc);
13844         if ((retvar->lhs != 1) || 
13845                 (retvar->op != OP_ADECL) ||
13846                 (retvar->next->op != OP_PIECE) ||
13847                 (MISC(retvar->next, 0) != retvar)) {
13848                 internal_error(state, retvar, "Not the return address?");
13849         }
13850         release_triple(state, retvar->next);
13851         release_triple(state, retvar);
13852
13853         /* Remove the label at the start of the function */
13854         ins = RHS(nfunc, 0);
13855         if (ins->op != OP_LABEL) {
13856                 internal_error(state, ins, "Not label?");
13857         }
13858         nfirst = ins->next;
13859         free_triple(state, ins);
13860         /* Release the new function header */
13861         RHS(nfunc, 0) = 0;
13862         free_triple(state, nfunc);
13863
13864         /* Append the new function list onto the return list */
13865         end = fcall->prev;
13866         nend = nfirst->prev;
13867         end->next    = nfirst;
13868         nfirst->prev = end;
13869         nend->next   = fcall;
13870         fcall->prev  = nend;
13871
13872         /* Now the result reading code */
13873         if (result) {
13874                 result = flatten(state, fcall, result);
13875                 propogate_use(state, fcall, result);
13876         }
13877
13878         /* Release the original fcall instruction */
13879         release_triple(state, fcall);
13880
13881         return;
13882 }
13883
13884 /*
13885  *
13886  * Type of the result variable.
13887  * 
13888  *                                     result
13889  *                                        |
13890  *                             +----------+------------+
13891  *                             |                       |
13892  *                     union of closures         result_type
13893  *                             |
13894  *          +------------------+---------------+
13895  *          |                                  |
13896  *       closure1                    ...   closuerN
13897  *          |                                  | 
13898  *  +----+--+-+--------+-----+       +----+----+---+-----+
13899  *  |    |    |        |     |       |    |        |     |
13900  * var1 var2 var3 ... varN result   var1 var2 ... varN result
13901  *                           |
13902  *                  +--------+---------+
13903  *                  |                  |
13904  *          union of closures     result_type
13905  *                  |
13906  *            +-----+-------------------+
13907  *            |                         |
13908  *         closure1            ...  closureN
13909  *            |                         |
13910  *  +-----+---+----+----+      +----+---+----+-----+
13911  *  |     |        |    |      |    |        |     |
13912  * var1 var2 ... varN result  var1 var2 ... varN result
13913  */
13914
13915 static int add_closure_type(struct compile_state *state, 
13916         struct triple *func, struct type *closure_type)
13917 {
13918         struct type *type, *ctype, **next;
13919         struct triple *var, *new_var;
13920         int i;
13921
13922 #if 0
13923         FILE *fp = state->errout;
13924         fprintf(fp, "original_type: ");
13925         name_of(fp, fresult(state, func)->type);
13926         fprintf(fp, "\n");
13927 #endif
13928         /* find the original type */
13929         var = fresult(state, func);
13930         type = var->type;
13931         if (type->elements != 2) {
13932                 internal_error(state, var, "bad return type");
13933         }
13934
13935         /* Find the complete closure type and update it */
13936         ctype = type->left->left;
13937         next = &ctype->left;
13938         while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13939                 next = &(*next)->right;
13940         }
13941         *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13942         ctype->elements += 1;
13943
13944 #if 0
13945         fprintf(fp, "new_type: ");
13946         name_of(fp, type);
13947         fprintf(fp, "\n");
13948         fprintf(fp, "ctype: %p %d bits: %d ", 
13949                 ctype, ctype->elements, reg_size_of(state, ctype));
13950         name_of(fp, ctype);
13951         fprintf(fp, "\n");
13952 #endif
13953         
13954         /* Regenerate the variable with the new type definition */
13955         new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13956         new_var->id |= TRIPLE_FLAG_FLATTENED;
13957         for(i = 0; i < new_var->lhs; i++) {
13958                 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13959         }
13960         
13961         /* Point everyone at the new variable */
13962         propogate_use(state, var, new_var);
13963
13964         /* Release the original variable */
13965         for(i = 0; i < var->lhs; i++) {
13966                 release_triple(state, LHS(var, i));
13967         }
13968         release_triple(state, var);
13969         
13970         /* Return the index of the added closure type */
13971         return ctype->elements - 1;
13972 }
13973
13974 static struct triple *closure_expr(struct compile_state *state,
13975         struct triple *func, int closure_idx, int var_idx)
13976 {
13977         return deref_index(state,
13978                 deref_index(state,
13979                         deref_index(state, fresult(state, func), 0),
13980                         closure_idx),
13981                 var_idx);
13982 }
13983
13984
13985 static void insert_triple_set(
13986         struct triple_reg_set **head, struct triple *member)
13987 {
13988         struct triple_reg_set *new;
13989         new = xcmalloc(sizeof(*new), "triple_set");
13990         new->member = member;
13991         new->new    = 0;
13992         new->next   = *head;
13993         *head       = new;
13994 }
13995
13996 static int ordered_triple_set(
13997         struct triple_reg_set **head, struct triple *member)
13998 {
13999         struct triple_reg_set **ptr;
14000         if (!member)
14001                 return 0;
14002         ptr = head;
14003         while(*ptr) {
14004                 if (member == (*ptr)->member) {
14005                         return 0;
14006                 }
14007                 /* keep the list ordered */
14008                 if (member->id < (*ptr)->member->id) {
14009                         break;
14010                 }
14011                 ptr = &(*ptr)->next;
14012         }
14013         insert_triple_set(ptr, member);
14014         return 1;
14015 }
14016
14017
14018 static void free_closure_variables(struct compile_state *state,
14019         struct triple_reg_set **enclose)
14020 {
14021         struct triple_reg_set *entry, *next;
14022         for(entry = *enclose; entry; entry = next) {
14023                 next = entry->next;
14024                 do_triple_unset(enclose, entry->member);
14025         }
14026 }
14027
14028 static int lookup_closure_index(struct compile_state *state,
14029         struct triple *me, struct triple *val)
14030 {
14031         struct triple *first, *ins, *next;
14032         first = RHS(me, 0);
14033         ins = next = first;
14034         do {
14035                 struct triple *result;
14036                 struct triple *index0, *index1, *index2, *read, *write;
14037                 ins = next;
14038                 next = ins->next;
14039                 if (ins->op != OP_CALL) {
14040                         continue;
14041                 }
14042                 /* I am at a previous call point examine it closely */
14043                 if (ins->next->op != OP_LABEL) {
14044                         internal_error(state, ins, "call not followed by label");
14045                 }
14046                 /* Does this call does not enclose any variables? */
14047                 if ((ins->next->next->op != OP_INDEX) ||
14048                         (ins->next->next->u.cval != 0) ||
14049                         (result = MISC(ins->next->next, 0)) ||
14050                         (result->id & TRIPLE_FLAG_LOCAL)) {
14051                         continue;
14052                 }
14053                 index0 = ins->next->next;
14054                 /* The pattern is:
14055                  * 0 index result < 0 >
14056                  * 1 index 0 < ? >
14057                  * 2 index 1 < ? >
14058                  * 3 read  2
14059                  * 4 write 3 var
14060                  */
14061                 for(index0 = ins->next->next;
14062                         (index0->op == OP_INDEX) &&
14063                                 (MISC(index0, 0) == result) &&
14064                                 (index0->u.cval == 0) ; 
14065                         index0 = write->next)
14066                 {
14067                         index1 = index0->next;
14068                         index2 = index1->next;
14069                         read   = index2->next;
14070                         write  = read->next;
14071                         if ((index0->op != OP_INDEX) ||
14072                                 (index1->op != OP_INDEX) ||
14073                                 (index2->op != OP_INDEX) ||
14074                                 (read->op != OP_READ) ||
14075                                 (write->op != OP_WRITE) ||
14076                                 (MISC(index1, 0) != index0) ||
14077                                 (MISC(index2, 0) != index1) ||
14078                                 (RHS(read, 0) != index2) ||
14079                                 (RHS(write, 0) != read)) {
14080                                 internal_error(state, index0, "bad var read");
14081                         }
14082                         if (MISC(write, 0) == val) {
14083                                 return index2->u.cval;
14084                         }
14085                 }
14086         } while(next != first);
14087         return -1;
14088 }
14089
14090 static inline int enclose_triple(struct triple *ins)
14091 {
14092         return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14093 }
14094
14095 static void compute_closure_variables(struct compile_state *state,
14096         struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14097 {
14098         struct triple_reg_set *set, *vars, **last_var;
14099         struct basic_blocks bb;
14100         struct reg_block *rb;
14101         struct block *block;
14102         struct triple *old_result, *first, *ins;
14103         size_t count, idx;
14104         unsigned long used_indicies;
14105         int i, max_index;
14106 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14107 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14108         struct { 
14109                 unsigned id;
14110                 int index;
14111         } *info;
14112
14113         
14114         /* Find the basic blocks of this function */
14115         bb.func = me;
14116         bb.first = RHS(me, 0);
14117         old_result = 0;
14118         if (!triple_is_ret(state, bb.first->prev)) {
14119                 bb.func = 0;
14120         } else {
14121                 old_result = fresult(state, me);
14122         }
14123         analyze_basic_blocks(state, &bb);
14124
14125         /* Find which variables are currently alive in a given block */
14126         rb = compute_variable_lifetimes(state, &bb);
14127
14128         /* Find the variables that are currently alive */
14129         block = block_of_triple(state, fcall);
14130         if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14131                 internal_error(state, fcall, "No reg block? block: %p", block);
14132         }
14133
14134 #if DEBUG_EXPLICIT_CLOSURES
14135         print_live_variables(state, &bb, rb, state->dbgout);
14136         fflush(state->dbgout);
14137 #endif
14138
14139         /* Count the number of triples in the function */
14140         first = RHS(me, 0);
14141         ins = first;
14142         count = 0;
14143         do {
14144                 count++;
14145                 ins = ins->next;
14146         } while(ins != first);
14147
14148         /* Allocate some memory to temorary hold the id info */
14149         info = xcmalloc(sizeof(*info) * (count +1), "info");
14150
14151         /* Mark the local function */
14152         first = RHS(me, 0);
14153         ins = first;
14154         idx = 1;
14155         do {
14156                 info[idx].id = ins->id;
14157                 ins->id = TRIPLE_FLAG_LOCAL | idx;
14158                 idx++;
14159                 ins = ins->next;
14160         } while(ins != first);
14161
14162         /* 
14163          * Build the list of variables to enclose.
14164          *
14165          * A target it to put the same variable in the
14166          * same slot for ever call of a given function.
14167          * After coloring this removes all of the variable
14168          * manipulation code.
14169          *
14170          * The list of variables to enclose is built ordered
14171          * program order because except in corner cases this
14172          * gives me the stability of assignment I need.
14173          *
14174          * To gurantee that stability I lookup the variables
14175          * to see where they have been used before and
14176          * I build my final list with the assigned indicies.
14177          */
14178         vars = 0;
14179         if (enclose_triple(old_result)) {
14180                 ordered_triple_set(&vars, old_result);
14181         }
14182         for(set = rb[block->vertex].out; set; set = set->next) {
14183                 if (!enclose_triple(set->member)) {
14184                         continue;
14185                 }
14186                 if ((set->member == fcall) || (set->member == old_result)) {
14187                         continue;
14188                 }
14189                 if (!local_triple(state, me, set->member)) {
14190                         internal_error(state, set->member, "not local?");
14191                 }
14192                 ordered_triple_set(&vars, set->member);
14193         }
14194
14195         /* Lookup the current indicies of the live varialbe */
14196         used_indicies = 0;
14197         max_index = -1;
14198         for(set = vars; set ; set = set->next) {
14199                 struct triple *ins;
14200                 int index;
14201                 ins = set->member;
14202                 index  = lookup_closure_index(state, me, ins);
14203                 info[ID_BITS(ins->id)].index = index;
14204                 if (index < 0) {
14205                         continue;
14206                 }
14207                 if (index >= MAX_INDICIES) {
14208                         internal_error(state, ins, "index unexpectedly large");
14209                 }
14210                 if (used_indicies & (1 << index)) {
14211                         internal_error(state, ins, "index previously used?");
14212                 }
14213                 /* Remember which indicies have been used */
14214                 used_indicies |= (1 << index);
14215                 if (index > max_index) {
14216                         max_index = index;
14217                 }
14218         }
14219
14220         /* Walk through the live variables and make certain
14221          * everything is assigned an index.
14222          */
14223         for(set = vars; set; set = set->next) {
14224                 struct triple *ins;
14225                 int index;
14226                 ins = set->member;
14227                 index = info[ID_BITS(ins->id)].index;
14228                 if (index >= 0) {
14229                         continue;
14230                 }
14231                 /* Find the lowest unused index value */
14232                 for(index = 0; index < MAX_INDICIES; index++) {
14233                         if (!(used_indicies & (1 << index))) {
14234                                 break;
14235                         }
14236                 }
14237                 if (index == MAX_INDICIES) {
14238                         internal_error(state, ins, "no free indicies?");
14239                 }
14240                 info[ID_BITS(ins->id)].index = index;
14241                 /* Remember which indicies have been used */
14242                 used_indicies |= (1 << index);
14243                 if (index > max_index) {
14244                         max_index = index;
14245                 }
14246         }
14247
14248         /* Build the return list of variables with positions matching
14249          * their indicies.
14250          */
14251         *enclose = 0;
14252         last_var = enclose;
14253         for(i = 0; i <= max_index; i++) {
14254                 struct triple *var;
14255                 var = 0;
14256                 if (used_indicies & (1 << i)) {
14257                         for(set = vars; set; set = set->next) {
14258                                 int index;
14259                                 index = info[ID_BITS(set->member->id)].index;
14260                                 if (index == i) {
14261                                         var = set->member;
14262                                         break;
14263                                 }
14264                         }
14265                         if (!var) {
14266                                 internal_error(state, me, "missing variable");
14267                         }
14268                 }
14269                 insert_triple_set(last_var, var);
14270                 last_var = &(*last_var)->next;
14271         }
14272
14273 #if DEBUG_EXPLICIT_CLOSURES
14274         /* Print out the variables to be enclosed */
14275         loc(state->dbgout, state, fcall);
14276         fprintf(state->dbgout, "Alive: \n");
14277         for(set = *enclose; set; set = set->next) {
14278                 display_triple(state->dbgout, set->member);
14279         }
14280         fflush(state->dbgout);
14281 #endif
14282
14283         /* Clear the marks */
14284         ins = first;
14285         do {
14286                 ins->id = info[ID_BITS(ins->id)].id;
14287                 ins = ins->next;
14288         } while(ins != first);
14289
14290         /* Release the ordered list of live variables */
14291         free_closure_variables(state, &vars);
14292
14293         /* Release the storage of the old ids */
14294         xfree(info);
14295
14296         /* Release the variable lifetime information */
14297         free_variable_lifetimes(state, &bb, rb);
14298
14299         /* Release the basic blocks of this function */
14300         free_basic_blocks(state, &bb);
14301 }
14302
14303 static void expand_function_call(
14304         struct compile_state *state, struct triple *me, struct triple *fcall)
14305 {
14306         /* Generate an ordinary function call */
14307         struct type *closure_type, **closure_next;
14308         struct triple *func, *func_first, *func_last, *retvar;
14309         struct triple *first;
14310         struct type *ptype, *rtype;
14311         struct triple *jmp;
14312         struct triple *ret_addr, *ret_loc, *ret_set;
14313         struct triple_reg_set *enclose, *set;
14314         int closure_idx, pvals, i;
14315
14316 #if DEBUG_EXPLICIT_CLOSURES
14317         FILE *fp = state->dbgout;
14318         fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14319         display_func(state, fp, MISC(fcall, 0));
14320         display_func(state, fp, me);
14321         fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14322 #endif
14323
14324         /* Find the triples */
14325         func = MISC(fcall, 0);
14326         func_first = RHS(func, 0);
14327         retvar = fretaddr(state, func);
14328         func_last  = func_first->prev;
14329         first = fcall->next;
14330
14331         /* Find what I need to enclose */
14332         compute_closure_variables(state, me, fcall, &enclose);
14333
14334         /* Compute the closure type */
14335         closure_type = new_type(TYPE_TUPLE, 0, 0);
14336         closure_type->elements = 0;
14337         closure_next = &closure_type->left;
14338         for(set = enclose; set ; set = set->next) {
14339                 struct type *type;
14340                 type = &void_type;
14341                 if (set->member) {
14342                         type = set->member->type;
14343                 }
14344                 if (!*closure_next) {
14345                         *closure_next = type;
14346                 } else {
14347                         *closure_next = new_type(TYPE_PRODUCT, *closure_next, 
14348                                 type);
14349                         closure_next = &(*closure_next)->right;
14350                 }
14351                 closure_type->elements += 1;
14352         }
14353         if (closure_type->elements == 0) {
14354                 closure_type->type = TYPE_VOID;
14355         }
14356
14357
14358 #if DEBUG_EXPLICIT_CLOSURES
14359         fprintf(state->dbgout, "closure type: ");
14360         name_of(state->dbgout, closure_type);
14361         fprintf(state->dbgout, "\n");
14362 #endif
14363
14364         /* Update the called functions closure variable */
14365         closure_idx = add_closure_type(state, func, closure_type);
14366
14367         /* Generate some needed triples */
14368         ret_loc = label(state);
14369         ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14370
14371         /* Pass the parameters to the new function */
14372         ptype = func->type->right;
14373         pvals = fcall->rhs;
14374         for(i = 0; i < pvals; i++) {
14375                 struct type *atype;
14376                 struct triple *arg, *param;
14377                 atype = ptype;
14378                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14379                         atype = ptype->left;
14380                 }
14381                 param = farg(state, func, i);
14382                 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14383                         internal_error(state, fcall, "param type mismatch");
14384                 }
14385                 arg = RHS(fcall, i);
14386                 flatten(state, first, write_expr(state, param, arg));
14387                 ptype = ptype->right;
14388         }
14389         rtype = func->type->left;
14390
14391         /* Thread the triples together */
14392         ret_loc       = flatten(state, first, ret_loc);
14393
14394         /* Save the active variables in the result variable */
14395         for(i = 0, set = enclose; set ; set = set->next, i++) {
14396                 if (!set->member) {
14397                         continue;
14398                 }
14399                 flatten(state, ret_loc,
14400                         write_expr(state,
14401                                 closure_expr(state, func, closure_idx, i),
14402                                 read_expr(state, set->member)));
14403         }
14404
14405         /* Initialize the return value */
14406         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14407                 flatten(state, ret_loc, 
14408                         write_expr(state, 
14409                                 deref_index(state, fresult(state, func), 1),
14410                                 new_triple(state, OP_UNKNOWNVAL, rtype,  0, 0)));
14411         }
14412
14413         ret_addr      = flatten(state, ret_loc, ret_addr);
14414         ret_set       = flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14415         jmp           = flatten(state, ret_loc, 
14416                 call(state, retvar, ret_addr, func_first, func_last));
14417
14418         /* Find the result */
14419         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14420                 struct triple * result;
14421                 result = flatten(state, first, 
14422                         read_expr(state, 
14423                                 deref_index(state, fresult(state, func), 1)));
14424
14425                 propogate_use(state, fcall, result);
14426         }
14427
14428         /* Release the original fcall instruction */
14429         release_triple(state, fcall);
14430
14431         /* Restore the active variables from the result variable */
14432         for(i = 0, set = enclose; set ; set = set->next, i++) {
14433                 struct triple_set *use, *next;
14434                 struct triple *new;
14435                 struct basic_blocks bb;
14436                 if (!set->member || (set->member == fcall)) {
14437                         continue;
14438                 }
14439                 /* Generate an expression for the value */
14440                 new = flatten(state, first,
14441                         read_expr(state, 
14442                                 closure_expr(state, func, closure_idx, i)));
14443
14444
14445                 /* If the original is an lvalue restore the preserved value */
14446                 if (is_lvalue(state, set->member)) {
14447                         flatten(state, first,
14448                                 write_expr(state, set->member, new));
14449                         continue;
14450                 }
14451                 /*
14452                  * If the original is a value update the dominated uses.
14453                  */
14454                 
14455                 /* Analyze the basic blocks so I can see who dominates whom */
14456                 bb.func = me;
14457                 bb.first = RHS(me, 0);
14458                 if (!triple_is_ret(state, bb.first->prev)) {
14459                         bb.func = 0;
14460                 }
14461                 analyze_basic_blocks(state, &bb);
14462                 
14463
14464 #if DEBUG_EXPLICIT_CLOSURES
14465                 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14466                         set->member, new);
14467 #endif
14468                 /* If fcall dominates the use update the expression */
14469                 for(use = set->member->use; use; use = next) {
14470                         /* Replace use modifies the use chain and 
14471                          * removes use, so I must take a copy of the
14472                          * next entry early.
14473                          */
14474                         next = use->next;
14475                         if (!tdominates(state, fcall, use->member)) {
14476                                 continue;
14477                         }
14478                         replace_use(state, set->member, new, use->member);
14479                 }
14480
14481                 /* Release the basic blocks, the instructions will be
14482                  * different next time, and flatten/insert_triple does
14483                  * not update the block values so I can't cache the analysis.
14484                  */
14485                 free_basic_blocks(state, &bb);
14486         }
14487
14488         /* Release the closure variable list */
14489         free_closure_variables(state, &enclose);
14490
14491         if (state->compiler->debug & DEBUG_INLINE) {
14492                 FILE *fp = state->dbgout;
14493                 fprintf(fp, "\n");
14494                 loc(fp, state, 0);
14495                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14496                 display_func(state, fp, func);
14497                 display_func(state, fp, me);
14498                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14499         }
14500
14501         return;
14502 }
14503
14504 static int do_inline(struct compile_state *state, struct triple *func)
14505 {
14506         int do_inline;
14507         int policy;
14508
14509         policy = state->compiler->flags & COMPILER_INLINE_MASK;
14510         switch(policy) {
14511         case COMPILER_INLINE_ALWAYS:
14512                 do_inline = 1;
14513                 if (func->type->type & ATTRIB_NOINLINE) {
14514                         error(state, func, "noinline with always_inline compiler option");
14515                 }
14516                 break;
14517         case COMPILER_INLINE_NEVER:
14518                 do_inline = 0;
14519                 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14520                         error(state, func, "always_inline with noinline compiler option");
14521                 }
14522                 break;
14523         case COMPILER_INLINE_DEFAULTON:
14524                 switch(func->type->type & STOR_MASK) {
14525                 case STOR_STATIC | STOR_INLINE:
14526                 case STOR_LOCAL  | STOR_INLINE:
14527                 case STOR_EXTERN | STOR_INLINE:
14528                         do_inline = 1;
14529                         break;
14530                 default:
14531                         do_inline = 1;
14532                         break;
14533                 }
14534                 break;
14535         case COMPILER_INLINE_DEFAULTOFF:
14536                 switch(func->type->type & STOR_MASK) {
14537                 case STOR_STATIC | STOR_INLINE:
14538                 case STOR_LOCAL  | STOR_INLINE:
14539                 case STOR_EXTERN | STOR_INLINE:
14540                         do_inline = 1;
14541                         break;
14542                 default:
14543                         do_inline = 0;
14544                         break;
14545                 }
14546                 break;
14547         case COMPILER_INLINE_NOPENALTY:
14548                 switch(func->type->type & STOR_MASK) {
14549                 case STOR_STATIC | STOR_INLINE:
14550                 case STOR_LOCAL  | STOR_INLINE:
14551                 case STOR_EXTERN | STOR_INLINE:
14552                         do_inline = 1;
14553                         break;
14554                 default:
14555                         do_inline = (func->u.cval == 1);
14556                         break;
14557                 }
14558                 break;
14559         default:
14560                 do_inline = 0;
14561                 internal_error(state, 0, "Unimplemented inline policy");
14562                 break;
14563         }
14564         /* Force inlining */
14565         if (func->type->type & ATTRIB_NOINLINE) {
14566                 do_inline = 0;
14567         }
14568         if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14569                 do_inline = 1;
14570         }
14571         return do_inline;
14572 }
14573
14574 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14575 {
14576         struct triple *first, *ptr, *next;
14577         /* If the function is not used don't bother */
14578         if (me->u.cval <= 0) {
14579                 return;
14580         }
14581         if (state->compiler->debug & DEBUG_CALLS2) {
14582                 FILE *fp = state->dbgout;
14583                 fprintf(fp, "in: %s\n",
14584                         me->type->type_ident->name);
14585         }
14586
14587         first = RHS(me, 0);
14588         ptr = next = first;
14589         do {
14590                 struct triple *func, *prev;
14591                 ptr = next;
14592                 prev = ptr->prev;
14593                 next = ptr->next;
14594                 if (ptr->op != OP_FCALL) {
14595                         continue;
14596                 }
14597                 func = MISC(ptr, 0);
14598                 /* See if the function should be inlined */
14599                 if (!do_inline(state, func)) {
14600                         /* Put a label after the fcall */
14601                         post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14602                         continue;
14603                 }
14604                 if (state->compiler->debug & DEBUG_CALLS) {
14605                         FILE *fp = state->dbgout;
14606                         if (state->compiler->debug & DEBUG_CALLS2) {
14607                                 loc(fp, state, ptr);
14608                         }
14609                         fprintf(fp, "inlining %s\n",
14610                                 func->type->type_ident->name);
14611                         fflush(fp);
14612                 }
14613
14614                 /* Update the function use counts */
14615                 func->u.cval -= 1;
14616
14617                 /* Replace the fcall with the called function */
14618                 expand_inline_call(state, me, ptr);
14619
14620                 next = prev->next;
14621         } while (next != first);
14622
14623         ptr = next = first;
14624         do {
14625                 struct triple *prev, *func;
14626                 ptr = next;
14627                 prev = ptr->prev;
14628                 next = ptr->next;
14629                 if (ptr->op != OP_FCALL) {
14630                         continue;
14631                 }
14632                 func = MISC(ptr, 0);
14633                 if (state->compiler->debug & DEBUG_CALLS) {
14634                         FILE *fp = state->dbgout;
14635                         if (state->compiler->debug & DEBUG_CALLS2) {
14636                                 loc(fp, state, ptr);
14637                         }
14638                         fprintf(fp, "calling %s\n",
14639                                 func->type->type_ident->name);
14640                         fflush(fp);
14641                 }
14642                 /* Replace the fcall with the instruction sequence
14643                  * needed to make the call.
14644                  */
14645                 expand_function_call(state, me, ptr);
14646                 next = prev->next;
14647         } while(next != first);
14648 }
14649
14650 static void inline_functions(struct compile_state *state, struct triple *func)
14651 {
14652         inline_function(state, func, 0);
14653         reverse_walk_functions(state, inline_function, 0);
14654 }
14655
14656 static void insert_function(struct compile_state *state,
14657         struct triple *func, void *arg)
14658 {
14659         struct triple *first, *end, *ffirst, *fend;
14660
14661         if (state->compiler->debug & DEBUG_INLINE) {
14662                 FILE *fp = state->errout;
14663                 fprintf(fp, "%s func count: %d\n", 
14664                         func->type->type_ident->name, func->u.cval);
14665         }
14666         if (func->u.cval == 0) {
14667                 return;
14668         }
14669
14670         /* Find the end points of the lists */
14671         first  = arg;
14672         end    = first->prev;
14673         ffirst = RHS(func, 0);
14674         fend   = ffirst->prev;
14675
14676         /* splice the lists together */
14677         end->next    = ffirst;
14678         ffirst->prev = end;
14679         fend->next   = first;
14680         first->prev  = fend;
14681 }
14682
14683 struct triple *input_asm(struct compile_state *state)
14684 {
14685         struct asm_info *info;
14686         struct triple *def;
14687         int i, out;
14688         
14689         info = xcmalloc(sizeof(*info), "asm_info");
14690         info->str = "";
14691
14692         out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14693         memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14694
14695         def = new_triple(state, OP_ASM, &void_type, out, 0);
14696         def->u.ainfo = info;
14697         def->id |= TRIPLE_FLAG_VOLATILE;
14698         
14699         for(i = 0; i < out; i++) {
14700                 struct triple *piece;
14701                 piece = triple(state, OP_PIECE, &int_type, def, 0);
14702                 piece->u.cval = i;
14703                 LHS(def, i) = piece;
14704         }
14705
14706         return def;
14707 }
14708
14709 struct triple *output_asm(struct compile_state *state)
14710 {
14711         struct asm_info *info;
14712         struct triple *def;
14713         int in;
14714         
14715         info = xcmalloc(sizeof(*info), "asm_info");
14716         info->str = "";
14717
14718         in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14719         memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14720
14721         def = new_triple(state, OP_ASM, &void_type, 0, in);
14722         def->u.ainfo = info;
14723         def->id |= TRIPLE_FLAG_VOLATILE;
14724         
14725         return def;
14726 }
14727
14728 static void join_functions(struct compile_state *state)
14729 {
14730         struct triple *jmp, *start, *end, *call, *in, *out, *func;
14731         struct file_state file;
14732         struct type *pnext, *param;
14733         struct type *result_type, *args_type;
14734         int idx;
14735
14736         /* Be clear the functions have not been joined yet */
14737         state->functions_joined = 0;
14738
14739         /* Dummy file state to get debug handing right */
14740         memset(&file, 0, sizeof(file));
14741         file.basename = "";
14742         file.line = 0;
14743         file.report_line = 0;
14744         file.report_name = file.basename;
14745         file.prev = state->file;
14746         state->file = &file;
14747         state->function = "";
14748
14749         if (!state->main_function) {
14750                 error(state, 0, "No functions to compile\n");
14751         }
14752
14753         /* The type of arguments */
14754         args_type   = state->main_function->type->right;
14755         /* The return type without any specifiers */
14756         result_type = clone_type(0, state->main_function->type->left);
14757
14758
14759         /* Verify the external arguments */
14760         if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14761                 error(state, state->main_function, 
14762                         "Too many external input arguments");
14763         }
14764         if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14765                 error(state, state->main_function, 
14766                         "Too many external output arguments");
14767         }
14768
14769         /* Lay down the basic program structure */
14770         end           = label(state);
14771         start         = label(state);
14772         start         = flatten(state, state->first, start);
14773         end           = flatten(state, state->first, end);
14774         in            = input_asm(state);
14775         out           = output_asm(state);
14776         call          = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14777         MISC(call, 0) = state->main_function;
14778         in            = flatten(state, state->first, in);
14779         call          = flatten(state, state->first, call);
14780         out           = flatten(state, state->first, out);
14781
14782
14783         /* Read the external input arguments */
14784         pnext = args_type;
14785         idx = 0;
14786         while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14787                 struct triple *expr;
14788                 param = pnext;
14789                 pnext = 0;
14790                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14791                         pnext = param->right;
14792                         param = param->left;
14793                 }
14794                 if (registers_of(state, param) != 1) {
14795                         error(state, state->main_function, 
14796                                 "Arg: %d %s requires multiple registers", 
14797                                 idx + 1, param->field_ident->name);
14798                 }
14799                 expr = read_expr(state, LHS(in, idx));
14800                 RHS(call, idx) = expr;
14801                 expr = flatten(state, call, expr);
14802                 use_triple(expr, call);
14803
14804                 idx++;  
14805         }
14806
14807
14808         /* Write the external output arguments */
14809         pnext = result_type;
14810         if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14811                 pnext = result_type->left;
14812         }
14813         for(idx = 0; idx < out->rhs; idx++) {
14814                 struct triple *expr;
14815                 param = pnext;
14816                 pnext = 0;
14817                 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14818                         pnext = param->right;
14819                         param = param->left;
14820                 }
14821                 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14822                         param = 0;
14823                 }
14824                 if (param) {
14825                         if (registers_of(state, param) != 1) {
14826                                 error(state, state->main_function,
14827                                         "Result: %d %s requires multiple registers",
14828                                         idx, param->field_ident->name);
14829                         }
14830                         expr = read_expr(state, call);
14831                         if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14832                                 expr = deref_field(state, expr, param->field_ident);
14833                         }
14834                 } else {
14835                         expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14836                 }
14837                 flatten(state, out, expr);
14838                 RHS(out, idx) = expr;
14839                 use_triple(expr, out);
14840         }
14841
14842         /* Allocate a dummy containing function */
14843         func = triple(state, OP_LIST, 
14844                 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14845         func->type->type_ident = lookup(state, "", 0);
14846         RHS(func, 0) = state->first;
14847         func->u.cval = 1;
14848
14849         /* See which functions are called, and how often */
14850         mark_live_functions(state);
14851         inline_functions(state, func);
14852         walk_functions(state, insert_function, end);
14853
14854         if (start->next != end) {
14855                 jmp = flatten(state, start, branch(state, end, 0));
14856         }
14857
14858         /* OK now the functions have been joined. */
14859         state->functions_joined = 1;
14860
14861         /* Done now cleanup */
14862         state->file = file.prev;
14863         state->function = 0;
14864 }
14865
14866 /*
14867  * Data structurs for optimation.
14868  */
14869
14870
14871 static int do_use_block(
14872         struct block *used, struct block_set **head, struct block *user, 
14873         int front)
14874 {
14875         struct block_set **ptr, *new;
14876         if (!used)
14877                 return 0;
14878         if (!user)
14879                 return 0;
14880         ptr = head;
14881         while(*ptr) {
14882                 if ((*ptr)->member == user) {
14883                         return 0;
14884                 }
14885                 ptr = &(*ptr)->next;
14886         }
14887         new = xcmalloc(sizeof(*new), "block_set");
14888         new->member = user;
14889         if (front) {
14890                 new->next = *head;
14891                 *head = new;
14892         }
14893         else {
14894                 new->next = 0;
14895                 *ptr = new;
14896         }
14897         return 1;
14898 }
14899 static int do_unuse_block(
14900         struct block *used, struct block_set **head, struct block *unuser)
14901 {
14902         struct block_set *use, **ptr;
14903         int count;
14904         count = 0;
14905         ptr = head;
14906         while(*ptr) {
14907                 use = *ptr;
14908                 if (use->member == unuser) {
14909                         *ptr = use->next;
14910                         memset(use, -1, sizeof(*use));
14911                         xfree(use);
14912                         count += 1;
14913                 }
14914                 else {
14915                         ptr = &use->next;
14916                 }
14917         }
14918         return count;
14919 }
14920
14921 static void use_block(struct block *used, struct block *user)
14922 {
14923         int count;
14924         /* Append new to the head of the list, print_block
14925          * depends on this.
14926          */
14927         count = do_use_block(used, &used->use, user, 1); 
14928         used->users += count;
14929 }
14930 static void unuse_block(struct block *used, struct block *unuser)
14931 {
14932         int count;
14933         count = do_unuse_block(used, &used->use, unuser); 
14934         used->users -= count;
14935 }
14936
14937 static void add_block_edge(struct block *block, struct block *edge, int front)
14938 {
14939         int count;
14940         count = do_use_block(block, &block->edges, edge, front);
14941         block->edge_count += count;
14942 }
14943
14944 static void remove_block_edge(struct block *block, struct block *edge)
14945 {
14946         int count;
14947         count = do_unuse_block(block, &block->edges, edge);
14948         block->edge_count -= count;
14949 }
14950
14951 static void idom_block(struct block *idom, struct block *user)
14952 {
14953         do_use_block(idom, &idom->idominates, user, 0);
14954 }
14955
14956 static void unidom_block(struct block *idom, struct block *unuser)
14957 {
14958         do_unuse_block(idom, &idom->idominates, unuser);
14959 }
14960
14961 static void domf_block(struct block *block, struct block *domf)
14962 {
14963         do_use_block(block, &block->domfrontier, domf, 0);
14964 }
14965
14966 static void undomf_block(struct block *block, struct block *undomf)
14967 {
14968         do_unuse_block(block, &block->domfrontier, undomf);
14969 }
14970
14971 static void ipdom_block(struct block *ipdom, struct block *user)
14972 {
14973         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14974 }
14975
14976 static void unipdom_block(struct block *ipdom, struct block *unuser)
14977 {
14978         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14979 }
14980
14981 static void ipdomf_block(struct block *block, struct block *ipdomf)
14982 {
14983         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14984 }
14985
14986 static void unipdomf_block(struct block *block, struct block *unipdomf)
14987 {
14988         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
14989 }
14990
14991 static int walk_triples(
14992         struct compile_state *state, 
14993         int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
14994         void *arg)
14995 {
14996         struct triple *ptr;
14997         int result;
14998         ptr = state->first;
14999         do {
15000                 result = cb(state, ptr, arg);
15001                 if (ptr->next->prev != ptr) {
15002                         internal_error(state, ptr->next, "bad prev");
15003                 }
15004                 ptr = ptr->next;
15005         } while((result == 0) && (ptr != state->first));
15006         return result;
15007 }
15008
15009 #define PRINT_LIST 1
15010 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
15011 {
15012         FILE *fp = arg;
15013         int op;
15014         op = ins->op;
15015         if (op == OP_LIST) {
15016 #if !PRINT_LIST
15017                 return 0;
15018 #endif
15019         }
15020         if ((op == OP_LABEL) && (ins->use)) {
15021                 fprintf(fp, "\n%p:\n", ins);
15022         }
15023         display_triple(fp, ins);
15024
15025         if (triple_is_branch(state, ins) && ins->use && 
15026                 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
15027                 internal_error(state, ins, "branch used?");
15028         }
15029         if (triple_is_branch(state, ins)) {
15030                 fprintf(fp, "\n");
15031         }
15032         return 0;
15033 }
15034
15035 static void print_triples(struct compile_state *state)
15036 {
15037         if (state->compiler->debug & DEBUG_TRIPLES) {
15038                 FILE *fp = state->dbgout;
15039                 fprintf(fp, "--------------- triples ---------------\n");
15040                 walk_triples(state, do_print_triple, fp);
15041                 fprintf(fp, "\n");
15042         }
15043 }
15044
15045 struct cf_block {
15046         struct block *block;
15047 };
15048 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15049 {
15050         struct block_set *edge;
15051         if (!block || (cf[block->vertex].block == block)) {
15052                 return;
15053         }
15054         cf[block->vertex].block = block;
15055         for(edge = block->edges; edge; edge = edge->next) {
15056                 find_cf_blocks(cf, edge->member);
15057         }
15058 }
15059
15060 static void print_control_flow(struct compile_state *state,
15061         FILE *fp, struct basic_blocks *bb)
15062 {
15063         struct cf_block *cf;
15064         int i;
15065         fprintf(fp, "\ncontrol flow\n");
15066         cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15067         find_cf_blocks(cf, bb->first_block);
15068
15069         for(i = 1; i <= bb->last_vertex; i++) {
15070                 struct block *block;
15071                 struct block_set *edge;
15072                 block = cf[i].block;
15073                 if (!block)
15074                         continue;
15075                 fprintf(fp, "(%p) %d:", block, block->vertex);
15076                 for(edge = block->edges; edge; edge = edge->next) {
15077                         fprintf(fp, " %d", edge->member->vertex);
15078                 }
15079                 fprintf(fp, "\n");
15080         }
15081
15082         xfree(cf);
15083 }
15084
15085 static void free_basic_block(struct compile_state *state, struct block *block)
15086 {
15087         struct block_set *edge, *entry;
15088         struct block *child;
15089         if (!block) {
15090                 return;
15091         }
15092         if (block->vertex == -1) {
15093                 return;
15094         }
15095         block->vertex = -1;
15096         for(edge = block->edges; edge; edge = edge->next) {
15097                 if (edge->member) {
15098                         unuse_block(edge->member, block);
15099                 }
15100         }
15101         if (block->idom) {
15102                 unidom_block(block->idom, block);
15103         }
15104         block->idom = 0;
15105         if (block->ipdom) {
15106                 unipdom_block(block->ipdom, block);
15107         }
15108         block->ipdom = 0;
15109         while((entry = block->use)) {
15110                 child = entry->member;
15111                 unuse_block(block, child);
15112                 if (child && (child->vertex != -1)) {
15113                         for(edge = child->edges; edge; edge = edge->next) {
15114                                 edge->member = 0;
15115                         }
15116                 }
15117         }
15118         while((entry = block->idominates)) {
15119                 child = entry->member;
15120                 unidom_block(block, child);
15121                 if (child && (child->vertex != -1)) {
15122                         child->idom = 0;
15123                 }
15124         }
15125         while((entry = block->domfrontier)) {
15126                 child = entry->member;
15127                 undomf_block(block, child);
15128         }
15129         while((entry = block->ipdominates)) {
15130                 child = entry->member;
15131                 unipdom_block(block, child);
15132                 if (child && (child->vertex != -1)) {
15133                         child->ipdom = 0;
15134                 }
15135         }
15136         while((entry = block->ipdomfrontier)) {
15137                 child = entry->member;
15138                 unipdomf_block(block, child);
15139         }
15140         if (block->users != 0) {
15141                 internal_error(state, 0, "block still has users");
15142         }
15143         while((edge = block->edges)) {
15144                 child = edge->member;
15145                 remove_block_edge(block, child);
15146                 
15147                 if (child && (child->vertex != -1)) {
15148                         free_basic_block(state, child);
15149                 }
15150         }
15151         memset(block, -1, sizeof(*block));
15152 #ifndef WIN32
15153         xfree(block);
15154 #endif
15155 }
15156
15157 static void free_basic_blocks(struct compile_state *state, 
15158         struct basic_blocks *bb)
15159 {
15160         struct triple *first, *ins;
15161         free_basic_block(state, bb->first_block);
15162         bb->last_vertex = 0;
15163         bb->first_block = bb->last_block = 0;
15164         first = bb->first;
15165         ins = first;
15166         do {
15167                 if (triple_stores_block(state, ins)) {
15168                         ins->u.block = 0;
15169                 }
15170                 ins = ins->next;
15171         } while(ins != first);
15172         
15173 }
15174
15175 static struct block *basic_block(struct compile_state *state, 
15176         struct basic_blocks *bb, struct triple *first)
15177 {
15178         struct block *block;
15179         struct triple *ptr;
15180         if (!triple_is_label(state, first)) {
15181                 internal_error(state, first, "block does not start with a label");
15182         }
15183         /* See if this basic block has already been setup */
15184         if (first->u.block != 0) {
15185                 return first->u.block;
15186         }
15187         /* Allocate another basic block structure */
15188         bb->last_vertex += 1;
15189         block = xcmalloc(sizeof(*block), "block");
15190         block->first = block->last = first;
15191         block->vertex = bb->last_vertex;
15192         ptr = first;
15193         do {
15194                 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) { 
15195                         break;
15196                 }
15197                 block->last = ptr;
15198                 /* If ptr->u is not used remember where the baic block is */
15199                 if (triple_stores_block(state, ptr)) {
15200                         ptr->u.block = block;
15201                 }
15202                 if (triple_is_branch(state, ptr)) {
15203                         break;
15204                 }
15205                 ptr = ptr->next;
15206         } while (ptr != bb->first);
15207         if ((ptr == bb->first) ||
15208                 ((ptr->next == bb->first) && (
15209                         triple_is_end(state, ptr) || 
15210                         triple_is_ret(state, ptr))))
15211         {
15212                 /* The block has no outflowing edges */
15213         }
15214         else if (triple_is_label(state, ptr)) {
15215                 struct block *next;
15216                 next = basic_block(state, bb, ptr);
15217                 add_block_edge(block, next, 0);
15218                 use_block(next, block);
15219         }
15220         else if (triple_is_branch(state, ptr)) {
15221                 struct triple **expr, *first;
15222                 struct block *child;
15223                 /* Find the branch targets.
15224                  * I special case the first branch as that magically
15225                  * avoids some difficult cases for the register allocator.
15226                  */
15227                 expr = triple_edge_targ(state, ptr, 0);
15228                 if (!expr) {
15229                         internal_error(state, ptr, "branch without targets");
15230                 }
15231                 first = *expr;
15232                 expr = triple_edge_targ(state, ptr, expr);
15233                 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15234                         if (!*expr) continue;
15235                         child = basic_block(state, bb, *expr);
15236                         use_block(child, block);
15237                         add_block_edge(block, child, 0);
15238                 }
15239                 if (first) {
15240                         child = basic_block(state, bb, first);
15241                         use_block(child, block);
15242                         add_block_edge(block, child, 1);
15243
15244                         /* Be certain the return block of a call is
15245                          * in a basic block.  When it is not find
15246                          * start of the block, insert a label if
15247                          * necessary and build the basic block.
15248                          * Then add a fake edge from the start block
15249                          * to the return block of the function.
15250                          */
15251                         if (state->functions_joined && triple_is_call(state, ptr)
15252                                 && !block_of_triple(state, MISC(ptr, 0))) {
15253                                 struct block *tail;
15254                                 struct triple *start;
15255                                 start = triple_to_block_start(state, MISC(ptr, 0));
15256                                 if (!triple_is_label(state, start)) {
15257                                         start = pre_triple(state,
15258                                                 start, OP_LABEL, &void_type, 0, 0);
15259                                 }
15260                                 tail = basic_block(state, bb, start);
15261                                 add_block_edge(child, tail, 0);
15262                                 use_block(tail, child);
15263                         }
15264                 }
15265         }
15266         else {
15267                 internal_error(state, 0, "Bad basic block split");
15268         }
15269 #if 0
15270 {
15271         struct block_set *edge;
15272         FILE *fp = state->errout;
15273         fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15274                 block, block->vertex, 
15275                 block->first, block->last);
15276         for(edge = block->edges; edge; edge = edge->next) {
15277                 fprintf(fp, " %10p [%2d]",
15278                         edge->member ? edge->member->first : 0,
15279                         edge->member ? edge->member->vertex : -1);
15280         }
15281         fprintf(fp, "\n");
15282 }
15283 #endif
15284         return block;
15285 }
15286
15287
15288 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15289         void (*cb)(struct compile_state *state, struct block *block, void *arg),
15290         void *arg)
15291 {
15292         struct triple *ptr, *first;
15293         struct block *last_block;
15294         last_block = 0;
15295         first = bb->first;
15296         ptr = first;
15297         do {
15298                 if (triple_stores_block(state, ptr)) {
15299                         struct block *block;
15300                         block = ptr->u.block;
15301                         if (block && (block != last_block)) {
15302                                 cb(state, block, arg);
15303                         }
15304                         last_block = block;
15305                 }
15306                 ptr = ptr->next;
15307         } while(ptr != first);
15308 }
15309
15310 static void print_block(
15311         struct compile_state *state, struct block *block, void *arg)
15312 {
15313         struct block_set *user, *edge;
15314         struct triple *ptr;
15315         FILE *fp = arg;
15316
15317         fprintf(fp, "\nblock: %p (%d) ",
15318                 block, 
15319                 block->vertex);
15320
15321         for(edge = block->edges; edge; edge = edge->next) {
15322                 fprintf(fp, " %p<-%p",
15323                         edge->member,
15324                         (edge->member && edge->member->use)?
15325                         edge->member->use->member : 0);
15326         }
15327         fprintf(fp, "\n");
15328         if (block->first->op == OP_LABEL) {
15329                 fprintf(fp, "%p:\n", block->first);
15330         }
15331         for(ptr = block->first; ; ) {
15332                 display_triple(fp, ptr);
15333                 if (ptr == block->last)
15334                         break;
15335                 ptr = ptr->next;
15336                 if (ptr == block->first) {
15337                         internal_error(state, 0, "missing block last?");
15338                 }
15339         }
15340         fprintf(fp, "users %d: ", block->users);
15341         for(user = block->use; user; user = user->next) {
15342                 fprintf(fp, "%p (%d) ", 
15343                         user->member,
15344                         user->member->vertex);
15345         }
15346         fprintf(fp,"\n\n");
15347 }
15348
15349
15350 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15351 {
15352         fprintf(fp, "--------------- blocks ---------------\n");
15353         walk_blocks(state, &state->bb, print_block, fp);
15354 }
15355 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15356 {
15357         if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15358                 fprintf(fp, "After %s\n", func);
15359                 romcc_print_blocks(state, fp);
15360                 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15361                         print_dominators(state, fp, &state->bb);
15362                         print_dominance_frontiers(state, fp, &state->bb);
15363                 }
15364                 print_control_flow(state, fp, &state->bb);
15365         }
15366 }
15367
15368 static void prune_nonblock_triples(struct compile_state *state, 
15369         struct basic_blocks *bb)
15370 {
15371         struct block *block;
15372         struct triple *first, *ins, *next;
15373         /* Delete the triples not in a basic block */
15374         block = 0;
15375         first = bb->first;
15376         ins = first;
15377         do {
15378                 next = ins->next;
15379                 if (ins->op == OP_LABEL) {
15380                         block = ins->u.block;
15381                 }
15382                 if (!block) {
15383                         struct triple_set *use;
15384                         for(use = ins->use; use; use = use->next) {
15385                                 struct block *block;
15386                                 block = block_of_triple(state, use->member);
15387                                 if (block != 0) {
15388                                         internal_error(state, ins, "pruning used ins?");
15389                                 }
15390                         }
15391                         release_triple(state, ins);
15392                 }
15393                 if (block && block->last == ins) {
15394                         block = 0;
15395                 }
15396                 ins = next;
15397         } while(ins != first);
15398 }
15399
15400 static void setup_basic_blocks(struct compile_state *state, 
15401         struct basic_blocks *bb)
15402 {
15403         if (!triple_stores_block(state, bb->first)) {
15404                 internal_error(state, 0, "ins will not store block?");
15405         }
15406         /* Initialize the state */
15407         bb->first_block = bb->last_block = 0;
15408         bb->last_vertex = 0;
15409         free_basic_blocks(state, bb);
15410
15411         /* Find the basic blocks */
15412         bb->first_block = basic_block(state, bb, bb->first);
15413
15414         /* Be certain the last instruction of a function, or the
15415          * entire program is in a basic block.  When it is not find 
15416          * the start of the block, insert a label if necessary and build 
15417          * basic block.  Then add a fake edge from the start block
15418          * to the final block.
15419          */
15420         if (!block_of_triple(state, bb->first->prev)) {
15421                 struct triple *start;
15422                 struct block *tail;
15423                 start = triple_to_block_start(state, bb->first->prev);
15424                 if (!triple_is_label(state, start)) {
15425                         start = pre_triple(state,
15426                                 start, OP_LABEL, &void_type, 0, 0);
15427                 }
15428                 tail = basic_block(state, bb, start);
15429                 add_block_edge(bb->first_block, tail, 0);
15430                 use_block(tail, bb->first_block);
15431         }
15432         
15433         /* Find the last basic block.
15434          */
15435         bb->last_block = block_of_triple(state, bb->first->prev);
15436
15437         /* Delete the triples not in a basic block */
15438         prune_nonblock_triples(state, bb);
15439
15440 #if 0
15441         /* If we are debugging print what I have just done */
15442         if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15443                 print_blocks(state, state->dbgout);
15444                 print_control_flow(state, bb);
15445         }
15446 #endif
15447 }
15448
15449
15450 struct sdom_block {
15451         struct block *block;
15452         struct sdom_block *sdominates;
15453         struct sdom_block *sdom_next;
15454         struct sdom_block *sdom;
15455         struct sdom_block *label;
15456         struct sdom_block *parent;
15457         struct sdom_block *ancestor;
15458         int vertex;
15459 };
15460
15461
15462 static void unsdom_block(struct sdom_block *block)
15463 {
15464         struct sdom_block **ptr;
15465         if (!block->sdom_next) {
15466                 return;
15467         }
15468         ptr = &block->sdom->sdominates;
15469         while(*ptr) {
15470                 if ((*ptr) == block) {
15471                         *ptr = block->sdom_next;
15472                         return;
15473                 }
15474                 ptr = &(*ptr)->sdom_next;
15475         }
15476 }
15477
15478 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15479 {
15480         unsdom_block(block);
15481         block->sdom = sdom;
15482         block->sdom_next = sdom->sdominates;
15483         sdom->sdominates = block;
15484 }
15485
15486
15487
15488 static int initialize_sdblock(struct sdom_block *sd,
15489         struct block *parent, struct block *block, int vertex)
15490 {
15491         struct block_set *edge;
15492         if (!block || (sd[block->vertex].block == block)) {
15493                 return vertex;
15494         }
15495         vertex += 1;
15496         /* Renumber the blocks in a convinient fashion */
15497         block->vertex = vertex;
15498         sd[vertex].block    = block;
15499         sd[vertex].sdom     = &sd[vertex];
15500         sd[vertex].label    = &sd[vertex];
15501         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
15502         sd[vertex].ancestor = 0;
15503         sd[vertex].vertex   = vertex;
15504         for(edge = block->edges; edge; edge = edge->next) {
15505                 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15506         }
15507         return vertex;
15508 }
15509
15510 static int initialize_spdblock(
15511         struct compile_state *state, struct sdom_block *sd,
15512         struct block *parent, struct block *block, int vertex)
15513 {
15514         struct block_set *user;
15515         if (!block || (sd[block->vertex].block == block)) {
15516                 return vertex;
15517         }
15518         vertex += 1;
15519         /* Renumber the blocks in a convinient fashion */
15520         block->vertex = vertex;
15521         sd[vertex].block    = block;
15522         sd[vertex].sdom     = &sd[vertex];
15523         sd[vertex].label    = &sd[vertex];
15524         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
15525         sd[vertex].ancestor = 0;
15526         sd[vertex].vertex   = vertex;
15527         for(user = block->use; user; user = user->next) {
15528                 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15529         }
15530         return vertex;
15531 }
15532
15533 static int setup_spdblocks(struct compile_state *state, 
15534         struct basic_blocks *bb, struct sdom_block *sd)
15535 {
15536         struct block *block;
15537         int vertex;
15538         /* Setup as many sdpblocks as possible without using fake edges */
15539         vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15540
15541         /* Walk through the graph and find unconnected blocks.  Add a
15542          * fake edge from the unconnected blocks to the end of the
15543          * graph. 
15544          */
15545         block = bb->first_block->last->next->u.block;
15546         for(; block && block != bb->first_block; block = block->last->next->u.block) {
15547                 if (sd[block->vertex].block == block) {
15548                         continue;
15549                 }
15550 #if DEBUG_SDP_BLOCKS
15551                 {
15552                         FILE *fp = state->errout;
15553                         fprintf(fp, "Adding %d\n", vertex +1);
15554                 }
15555 #endif
15556                 add_block_edge(block, bb->last_block, 0);
15557                 use_block(bb->last_block, block);
15558
15559                 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15560         }
15561         return vertex;
15562 }
15563
15564 static void compress_ancestors(struct sdom_block *v)
15565 {
15566         /* This procedure assumes ancestor(v) != 0 */
15567         /* if (ancestor(ancestor(v)) != 0) {
15568          *      compress(ancestor(ancestor(v)));
15569          *      if (semi(label(ancestor(v))) < semi(label(v))) {
15570          *              label(v) = label(ancestor(v));
15571          *      }
15572          *      ancestor(v) = ancestor(ancestor(v));
15573          * }
15574          */
15575         if (!v->ancestor) {
15576                 return;
15577         }
15578         if (v->ancestor->ancestor) {
15579                 compress_ancestors(v->ancestor->ancestor);
15580                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15581                         v->label = v->ancestor->label;
15582                 }
15583                 v->ancestor = v->ancestor->ancestor;
15584         }
15585 }
15586
15587 static void compute_sdom(struct compile_state *state, 
15588         struct basic_blocks *bb, struct sdom_block *sd)
15589 {
15590         int i;
15591         /* // step 2 
15592          *  for each v <= pred(w) {
15593          *      u = EVAL(v);
15594          *      if (semi[u] < semi[w] { 
15595          *              semi[w] = semi[u]; 
15596          *      } 
15597          * }
15598          * add w to bucket(vertex(semi[w]));
15599          * LINK(parent(w), w);
15600          *
15601          * // step 3
15602          * for each v <= bucket(parent(w)) {
15603          *      delete v from bucket(parent(w));
15604          *      u = EVAL(v);
15605          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15606          * }
15607          */
15608         for(i = bb->last_vertex; i >= 2; i--) {
15609                 struct sdom_block *v, *parent, *next;
15610                 struct block_set *user;
15611                 struct block *block;
15612                 block = sd[i].block;
15613                 parent = sd[i].parent;
15614                 /* Step 2 */
15615                 for(user = block->use; user; user = user->next) {
15616                         struct sdom_block *v, *u;
15617                         v = &sd[user->member->vertex];
15618                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15619                         if (u->sdom->vertex < sd[i].sdom->vertex) {
15620                                 sd[i].sdom = u->sdom;
15621                         }
15622                 }
15623                 sdom_block(sd[i].sdom, &sd[i]);
15624                 sd[i].ancestor = parent;
15625                 /* Step 3 */
15626                 for(v = parent->sdominates; v; v = next) {
15627                         struct sdom_block *u;
15628                         next = v->sdom_next;
15629                         unsdom_block(v);
15630                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15631                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)? 
15632                                 u->block : parent->block;
15633                 }
15634         }
15635 }
15636
15637 static void compute_spdom(struct compile_state *state, 
15638         struct basic_blocks *bb, struct sdom_block *sd)
15639 {
15640         int i;
15641         /* // step 2 
15642          *  for each v <= pred(w) {
15643          *      u = EVAL(v);
15644          *      if (semi[u] < semi[w] { 
15645          *              semi[w] = semi[u]; 
15646          *      } 
15647          * }
15648          * add w to bucket(vertex(semi[w]));
15649          * LINK(parent(w), w);
15650          *
15651          * // step 3
15652          * for each v <= bucket(parent(w)) {
15653          *      delete v from bucket(parent(w));
15654          *      u = EVAL(v);
15655          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15656          * }
15657          */
15658         for(i = bb->last_vertex; i >= 2; i--) {
15659                 struct sdom_block *u, *v, *parent, *next;
15660                 struct block_set *edge;
15661                 struct block *block;
15662                 block = sd[i].block;
15663                 parent = sd[i].parent;
15664                 /* Step 2 */
15665                 for(edge = block->edges; edge; edge = edge->next) {
15666                         v = &sd[edge->member->vertex];
15667                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15668                         if (u->sdom->vertex < sd[i].sdom->vertex) {
15669                                 sd[i].sdom = u->sdom;
15670                         }
15671                 }
15672                 sdom_block(sd[i].sdom, &sd[i]);
15673                 sd[i].ancestor = parent;
15674                 /* Step 3 */
15675                 for(v = parent->sdominates; v; v = next) {
15676                         struct sdom_block *u;
15677                         next = v->sdom_next;
15678                         unsdom_block(v);
15679                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15680                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)? 
15681                                 u->block : parent->block;
15682                 }
15683         }
15684 }
15685
15686 static void compute_idom(struct compile_state *state, 
15687         struct basic_blocks *bb, struct sdom_block *sd)
15688 {
15689         int i;
15690         for(i = 2; i <= bb->last_vertex; i++) {
15691                 struct block *block;
15692                 block = sd[i].block;
15693                 if (block->idom->vertex != sd[i].sdom->vertex) {
15694                         block->idom = block->idom->idom;
15695                 }
15696                 idom_block(block->idom, block);
15697         }
15698         sd[1].block->idom = 0;
15699 }
15700
15701 static void compute_ipdom(struct compile_state *state, 
15702         struct basic_blocks *bb, struct sdom_block *sd)
15703 {
15704         int i;
15705         for(i = 2; i <= bb->last_vertex; i++) {
15706                 struct block *block;
15707                 block = sd[i].block;
15708                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15709                         block->ipdom = block->ipdom->ipdom;
15710                 }
15711                 ipdom_block(block->ipdom, block);
15712         }
15713         sd[1].block->ipdom = 0;
15714 }
15715
15716         /* Theorem 1:
15717          *   Every vertex of a flowgraph G = (V, E, r) except r has
15718          *   a unique immediate dominator.  
15719          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15720          *   rooted at r, called the dominator tree of G, such that 
15721          *   v dominates w if and only if v is a proper ancestor of w in
15722          *   the dominator tree.
15723          */
15724         /* Lemma 1:  
15725          *   If v and w are vertices of G such that v <= w,
15726          *   than any path from v to w must contain a common ancestor
15727          *   of v and w in T.
15728          */
15729         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
15730         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
15731         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
15732         /* Theorem 2:
15733          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
15734          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
15735          */
15736         /* Theorem 3:
15737          *   Let w != r and let u be a vertex for which sdom(u) is 
15738          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
15739          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15740          */
15741         /* Lemma 5:  Let vertices v,w satisfy v -> w.
15742          *           Then v -> idom(w) or idom(w) -> idom(v)
15743          */
15744
15745 static void find_immediate_dominators(struct compile_state *state,
15746         struct basic_blocks *bb)
15747 {
15748         struct sdom_block *sd;
15749         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15750          *           vi > w for (1 <= i <= k - 1}
15751          */
15752         /* Theorem 4:
15753          *   For any vertex w != r.
15754          *   sdom(w) = min(
15755          *                 {v|(v,w) <= E  and v < w } U 
15756          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15757          */
15758         /* Corollary 1:
15759          *   Let w != r and let u be a vertex for which sdom(u) is 
15760          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
15761          *   Then:
15762          *                   { sdom(w) if sdom(w) = sdom(u),
15763          *        idom(w) = {
15764          *                   { idom(u) otherwise
15765          */
15766         /* The algorithm consists of the following 4 steps.
15767          * Step 1.  Carry out a depth-first search of the problem graph.  
15768          *    Number the vertices from 1 to N as they are reached during
15769          *    the search.  Initialize the variables used in succeeding steps.
15770          * Step 2.  Compute the semidominators of all vertices by applying
15771          *    theorem 4.   Carry out the computation vertex by vertex in
15772          *    decreasing order by number.
15773          * Step 3.  Implicitly define the immediate dominator of each vertex
15774          *    by applying Corollary 1.
15775          * Step 4.  Explicitly define the immediate dominator of each vertex,
15776          *    carrying out the computation vertex by vertex in increasing order
15777          *    by number.
15778          */
15779         /* Step 1 initialize the basic block information */
15780         sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15781         initialize_sdblock(sd, 0, bb->first_block, 0);
15782 #if 0
15783         sd[1].size  = 0;
15784         sd[1].label = 0;
15785         sd[1].sdom  = 0;
15786 #endif
15787         /* Step 2 compute the semidominators */
15788         /* Step 3 implicitly define the immediate dominator of each vertex */
15789         compute_sdom(state, bb, sd);
15790         /* Step 4 explicitly define the immediate dominator of each vertex */
15791         compute_idom(state, bb, sd);
15792         xfree(sd);
15793 }
15794
15795 static void find_post_dominators(struct compile_state *state,
15796         struct basic_blocks *bb)
15797 {
15798         struct sdom_block *sd;
15799         int vertex;
15800         /* Step 1 initialize the basic block information */
15801         sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15802
15803         vertex = setup_spdblocks(state, bb, sd);
15804         if (vertex != bb->last_vertex) {
15805                 internal_error(state, 0, "missing %d blocks",
15806                         bb->last_vertex - vertex);
15807         }
15808
15809         /* Step 2 compute the semidominators */
15810         /* Step 3 implicitly define the immediate dominator of each vertex */
15811         compute_spdom(state, bb, sd);
15812         /* Step 4 explicitly define the immediate dominator of each vertex */
15813         compute_ipdom(state, bb, sd);
15814         xfree(sd);
15815 }
15816
15817
15818
15819 static void find_block_domf(struct compile_state *state, struct block *block)
15820 {
15821         struct block *child;
15822         struct block_set *user, *edge;
15823         if (block->domfrontier != 0) {
15824                 internal_error(state, block->first, "domfrontier present?");
15825         }
15826         for(user = block->idominates; user; user = user->next) {
15827                 child = user->member;
15828                 if (child->idom != block) {
15829                         internal_error(state, block->first, "bad idom");
15830                 }
15831                 find_block_domf(state, child);
15832         }
15833         for(edge = block->edges; edge; edge = edge->next) {
15834                 if (edge->member->idom != block) {
15835                         domf_block(block, edge->member);
15836                 }
15837         }
15838         for(user = block->idominates; user; user = user->next) {
15839                 struct block_set *frontier;
15840                 child = user->member;
15841                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15842                         if (frontier->member->idom != block) {
15843                                 domf_block(block, frontier->member);
15844                         }
15845                 }
15846         }
15847 }
15848
15849 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15850 {
15851         struct block *child;
15852         struct block_set *user;
15853         if (block->ipdomfrontier != 0) {
15854                 internal_error(state, block->first, "ipdomfrontier present?");
15855         }
15856         for(user = block->ipdominates; user; user = user->next) {
15857                 child = user->member;
15858                 if (child->ipdom != block) {
15859                         internal_error(state, block->first, "bad ipdom");
15860                 }
15861                 find_block_ipdomf(state, child);
15862         }
15863         for(user = block->use; user; user = user->next) {
15864                 if (user->member->ipdom != block) {
15865                         ipdomf_block(block, user->member);
15866                 }
15867         }
15868         for(user = block->ipdominates; user; user = user->next) {
15869                 struct block_set *frontier;
15870                 child = user->member;
15871                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15872                         if (frontier->member->ipdom != block) {
15873                                 ipdomf_block(block, frontier->member);
15874                         }
15875                 }
15876         }
15877 }
15878
15879 static void print_dominated(
15880         struct compile_state *state, struct block *block, void *arg)
15881 {
15882         struct block_set *user;
15883         FILE *fp = arg;
15884
15885         fprintf(fp, "%d:", block->vertex);
15886         for(user = block->idominates; user; user = user->next) {
15887                 fprintf(fp, " %d", user->member->vertex);
15888                 if (user->member->idom != block) {
15889                         internal_error(state, user->member->first, "bad idom");
15890                 }
15891         }
15892         fprintf(fp,"\n");
15893 }
15894
15895 static void print_dominated2(
15896         struct compile_state *state, FILE *fp, int depth, struct block *block)
15897 {
15898         struct block_set *user;
15899         struct triple *ins;
15900         struct occurance *ptr, *ptr2;
15901         const char *filename1, *filename2;
15902         int equal_filenames;
15903         int i;
15904         for(i = 0; i < depth; i++) {
15905                 fprintf(fp, "   ");
15906         }
15907         fprintf(fp, "%3d: %p (%p - %p) @", 
15908                 block->vertex, block, block->first, block->last);
15909         ins = block->first;
15910         while(ins != block->last && (ins->occurance->line == 0)) {
15911                 ins = ins->next;
15912         }
15913         ptr = ins->occurance;
15914         ptr2 = block->last->occurance;
15915         filename1 = ptr->filename? ptr->filename : "";
15916         filename2 = ptr2->filename? ptr2->filename : "";
15917         equal_filenames = (strcmp(filename1, filename2) == 0);
15918         if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15919                 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15920         } else if (equal_filenames) {
15921                 fprintf(fp, " %s:(%d - %d)",
15922                         ptr->filename, ptr->line, ptr2->line);
15923         } else {
15924                 fprintf(fp, " (%s:%d - %s:%d)",
15925                         ptr->filename, ptr->line,
15926                         ptr2->filename, ptr2->line);
15927         }
15928         fprintf(fp, "\n");
15929         for(user = block->idominates; user; user = user->next) {
15930                 print_dominated2(state, fp, depth + 1, user->member);
15931         }
15932 }
15933
15934 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15935 {
15936         fprintf(fp, "\ndominates\n");
15937         walk_blocks(state, bb, print_dominated, fp);
15938         fprintf(fp, "dominates\n");
15939         print_dominated2(state, fp, 0, bb->first_block);
15940 }
15941
15942
15943 static int print_frontiers(
15944         struct compile_state *state, FILE *fp, struct block *block, int vertex)
15945 {
15946         struct block_set *user, *edge;
15947
15948         if (!block || (block->vertex != vertex + 1)) {
15949                 return vertex;
15950         }
15951         vertex += 1;
15952
15953         fprintf(fp, "%d:", block->vertex);
15954         for(user = block->domfrontier; user; user = user->next) {
15955                 fprintf(fp, " %d", user->member->vertex);
15956         }
15957         fprintf(fp, "\n");
15958         
15959         for(edge = block->edges; edge; edge = edge->next) {
15960                 vertex = print_frontiers(state, fp, edge->member, vertex);
15961         }
15962         return vertex;
15963 }
15964 static void print_dominance_frontiers(struct compile_state *state,
15965         FILE *fp, struct basic_blocks *bb)
15966 {
15967         fprintf(fp, "\ndominance frontiers\n");
15968         print_frontiers(state, fp, bb->first_block, 0);
15969         
15970 }
15971
15972 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15973 {
15974         /* Find the immediate dominators */
15975         find_immediate_dominators(state, bb);
15976         /* Find the dominance frontiers */
15977         find_block_domf(state, bb->first_block);
15978         /* If debuging print the print what I have just found */
15979         if (state->compiler->debug & DEBUG_FDOMINATORS) {
15980                 print_dominators(state, state->dbgout, bb);
15981                 print_dominance_frontiers(state, state->dbgout, bb);
15982                 print_control_flow(state, state->dbgout, bb);
15983         }
15984 }
15985
15986
15987 static void print_ipdominated(
15988         struct compile_state *state, struct block *block, void *arg)
15989 {
15990         struct block_set *user;
15991         FILE *fp = arg;
15992
15993         fprintf(fp, "%d:", block->vertex);
15994         for(user = block->ipdominates; user; user = user->next) {
15995                 fprintf(fp, " %d", user->member->vertex);
15996                 if (user->member->ipdom != block) {
15997                         internal_error(state, user->member->first, "bad ipdom");
15998                 }
15999         }
16000         fprintf(fp, "\n");
16001 }
16002
16003 static void print_ipdominators(struct compile_state *state, FILE *fp,
16004         struct basic_blocks *bb)
16005 {
16006         fprintf(fp, "\nipdominates\n");
16007         walk_blocks(state, bb, print_ipdominated, fp);
16008 }
16009
16010 static int print_pfrontiers(
16011         struct compile_state *state, FILE *fp, struct block *block, int vertex)
16012 {
16013         struct block_set *user;
16014
16015         if (!block || (block->vertex != vertex + 1)) {
16016                 return vertex;
16017         }
16018         vertex += 1;
16019
16020         fprintf(fp, "%d:", block->vertex);
16021         for(user = block->ipdomfrontier; user; user = user->next) {
16022                 fprintf(fp, " %d", user->member->vertex);
16023         }
16024         fprintf(fp, "\n");
16025         for(user = block->use; user; user = user->next) {
16026                 vertex = print_pfrontiers(state, fp, user->member, vertex);
16027         }
16028         return vertex;
16029 }
16030 static void print_ipdominance_frontiers(struct compile_state *state,
16031         FILE *fp, struct basic_blocks *bb)
16032 {
16033         fprintf(fp, "\nipdominance frontiers\n");
16034         print_pfrontiers(state, fp, bb->last_block, 0);
16035         
16036 }
16037
16038 static void analyze_ipdominators(struct compile_state *state,
16039         struct basic_blocks *bb)
16040 {
16041         /* Find the post dominators */
16042         find_post_dominators(state, bb);
16043         /* Find the control dependencies (post dominance frontiers) */
16044         find_block_ipdomf(state, bb->last_block);
16045         /* If debuging print the print what I have just found */
16046         if (state->compiler->debug & DEBUG_RDOMINATORS) {
16047                 print_ipdominators(state, state->dbgout, bb);
16048                 print_ipdominance_frontiers(state, state->dbgout, bb);
16049                 print_control_flow(state, state->dbgout, bb);
16050         }
16051 }
16052
16053 static int bdominates(struct compile_state *state,
16054         struct block *dom, struct block *sub)
16055 {
16056         while(sub && (sub != dom)) {
16057                 sub = sub->idom;
16058         }
16059         return sub == dom;
16060 }
16061
16062 static int tdominates(struct compile_state *state,
16063         struct triple *dom, struct triple *sub)
16064 {
16065         struct block *bdom, *bsub;
16066         int result;
16067         bdom = block_of_triple(state, dom);
16068         bsub = block_of_triple(state, sub);
16069         if (bdom != bsub) {
16070                 result = bdominates(state, bdom, bsub);
16071         } 
16072         else {
16073                 struct triple *ins;
16074                 if (!bdom || !bsub) {
16075                         internal_error(state, dom, "huh?");
16076                 }
16077                 ins = sub;
16078                 while((ins != bsub->first) && (ins != dom)) {
16079                         ins = ins->prev;
16080                 }
16081                 result = (ins == dom);
16082         }
16083         return result;
16084 }
16085
16086 static void analyze_basic_blocks(
16087         struct compile_state *state, struct basic_blocks *bb)
16088 {
16089         setup_basic_blocks(state, bb);
16090         analyze_idominators(state, bb);
16091         analyze_ipdominators(state, bb);
16092 }
16093
16094 static void insert_phi_operations(struct compile_state *state)
16095 {
16096         size_t size;
16097         struct triple *first;
16098         int *has_already, *work;
16099         struct block *work_list, **work_list_tail;
16100         int iter;
16101         struct triple *var, *vnext;
16102
16103         size = sizeof(int) * (state->bb.last_vertex + 1);
16104         has_already = xcmalloc(size, "has_already");
16105         work =        xcmalloc(size, "work");
16106         iter = 0;
16107
16108         first = state->first;
16109         for(var = first->next; var != first ; var = vnext) {
16110                 struct block *block;
16111                 struct triple_set *user, *unext;
16112                 vnext = var->next;
16113
16114                 if (!triple_is_auto_var(state, var) || !var->use) {
16115                         continue;
16116                 }
16117                         
16118                 iter += 1;
16119                 work_list = 0;
16120                 work_list_tail = &work_list;
16121                 for(user = var->use; user; user = unext) {
16122                         unext = user->next;
16123                         if (MISC(var, 0) == user->member) {
16124                                 continue;
16125                         }
16126                         if (user->member->op == OP_READ) {
16127                                 continue;
16128                         }
16129                         if (user->member->op != OP_WRITE) {
16130                                 internal_error(state, user->member, 
16131                                         "bad variable access");
16132                         }
16133                         block = user->member->u.block;
16134                         if (!block) {
16135                                 warning(state, user->member, "dead code");
16136                                 release_triple(state, user->member);
16137                                 continue;
16138                         }
16139                         if (work[block->vertex] >= iter) {
16140                                 continue;
16141                         }
16142                         work[block->vertex] = iter;
16143                         *work_list_tail = block;
16144                         block->work_next = 0;
16145                         work_list_tail = &block->work_next;
16146                 }
16147                 for(block = work_list; block; block = block->work_next) {
16148                         struct block_set *df;
16149                         for(df = block->domfrontier; df; df = df->next) {
16150                                 struct triple *phi;
16151                                 struct block *front;
16152                                 int in_edges;
16153                                 front = df->member;
16154
16155                                 if (has_already[front->vertex] >= iter) {
16156                                         continue;
16157                                 }
16158                                 /* Count how many edges flow into this block */
16159                                 in_edges = front->users;
16160                                 /* Insert a phi function for this variable */
16161                                 get_occurance(var->occurance);
16162                                 phi = alloc_triple(
16163                                         state, OP_PHI, var->type, -1, in_edges, 
16164                                         var->occurance);
16165                                 phi->u.block = front;
16166                                 MISC(phi, 0) = var;
16167                                 use_triple(var, phi);
16168 #if 1
16169                                 if (phi->rhs != in_edges) {
16170                                         internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16171                                                 phi->rhs, in_edges);
16172                                 }
16173 #endif
16174                                 /* Insert the phi functions immediately after the label */
16175                                 insert_triple(state, front->first->next, phi);
16176                                 if (front->first == front->last) {
16177                                         front->last = front->first->next;
16178                                 }
16179                                 has_already[front->vertex] = iter;
16180                                 transform_to_arch_instruction(state, phi);
16181
16182                                 /* If necessary plan to visit the basic block */
16183                                 if (work[front->vertex] >= iter) {
16184                                         continue;
16185                                 }
16186                                 work[front->vertex] = iter;
16187                                 *work_list_tail = front;
16188                                 front->work_next = 0;
16189                                 work_list_tail = &front->work_next;
16190                         }
16191                 }
16192         }
16193         xfree(has_already);
16194         xfree(work);
16195 }
16196
16197
16198 struct stack {
16199         struct triple_set *top;
16200         unsigned orig_id;
16201 };
16202
16203 static int count_auto_vars(struct compile_state *state)
16204 {
16205         struct triple *first, *ins;
16206         int auto_vars = 0;
16207         first = state->first;
16208         ins = first;
16209         do {
16210                 if (triple_is_auto_var(state, ins)) {
16211                         auto_vars += 1;
16212                 }
16213                 ins = ins->next;
16214         } while(ins != first);
16215         return auto_vars;
16216 }
16217
16218 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16219 {
16220         struct triple *first, *ins;
16221         int auto_vars = 0;
16222         first = state->first;
16223         ins = first;
16224         do {
16225                 if (triple_is_auto_var(state, ins)) {
16226                         auto_vars += 1;
16227                         stacks[auto_vars].orig_id = ins->id;
16228                         ins->id = auto_vars;
16229                 }
16230                 ins = ins->next;
16231         } while(ins != first);
16232 }
16233
16234 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16235 {
16236         struct triple *first, *ins;
16237         first = state->first;
16238         ins = first;
16239         do {
16240                 if (triple_is_auto_var(state, ins)) {
16241                         ins->id = stacks[ins->id].orig_id;
16242                 }
16243                 ins = ins->next;
16244         } while(ins != first);
16245 }
16246
16247 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16248 {
16249         struct triple_set *head;
16250         struct triple *top_val;
16251         top_val = 0;
16252         head = stacks[var->id].top;
16253         if (head) {
16254                 top_val = head->member;
16255         }
16256         return top_val;
16257 }
16258
16259 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16260 {
16261         struct triple_set *new;
16262         /* Append new to the head of the list,
16263          * it's the only sensible behavoir for a stack.
16264          */
16265         new = xcmalloc(sizeof(*new), "triple_set");
16266         new->member = val;
16267         new->next   = stacks[var->id].top;
16268         stacks[var->id].top = new;
16269 }
16270
16271 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16272 {
16273         struct triple_set *set, **ptr;
16274         ptr = &stacks[var->id].top;
16275         while(*ptr) {
16276                 set = *ptr;
16277                 if (set->member == oldval) {
16278                         *ptr = set->next;
16279                         xfree(set);
16280                         /* Only free one occurance from the stack */
16281                         return;
16282                 }
16283                 else {
16284                         ptr = &set->next;
16285                 }
16286         }
16287 }
16288
16289 /*
16290  * C(V)
16291  * S(V)
16292  */
16293 static void fixup_block_phi_variables(
16294         struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16295 {
16296         struct block_set *set;
16297         struct triple *ptr;
16298         int edge;
16299         if (!parent || !block)
16300                 return;
16301         /* Find the edge I am coming in on */
16302         edge = 0;
16303         for(set = block->use; set; set = set->next, edge++) {
16304                 if (set->member == parent) {
16305                         break;
16306                 }
16307         }
16308         if (!set) {
16309                 internal_error(state, 0, "phi input is not on a control predecessor");
16310         }
16311         for(ptr = block->first; ; ptr = ptr->next) {
16312                 if (ptr->op == OP_PHI) {
16313                         struct triple *var, *val, **slot;
16314                         var = MISC(ptr, 0);
16315                         if (!var) {
16316                                 internal_error(state, ptr, "no var???");
16317                         }
16318                         /* Find the current value of the variable */
16319                         val = peek_triple(stacks, var);
16320                         if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16321                                 internal_error(state, val, "bad value in phi");
16322                         }
16323                         if (edge >= ptr->rhs) {
16324                                 internal_error(state, ptr, "edges > phi rhs");
16325                         }
16326                         slot = &RHS(ptr, edge);
16327                         if ((*slot != 0) && (*slot != val)) {
16328                                 internal_error(state, ptr, "phi already bound on this edge");
16329                         }
16330                         *slot = val;
16331                         use_triple(val, ptr);
16332                 }
16333                 if (ptr == block->last) {
16334                         break;
16335                 }
16336         }
16337 }
16338
16339
16340 static void rename_block_variables(
16341         struct compile_state *state, struct stack *stacks, struct block *block)
16342 {
16343         struct block_set *user, *edge;
16344         struct triple *ptr, *next, *last;
16345         int done;
16346         if (!block)
16347                 return;
16348         last = block->first;
16349         done = 0;
16350         for(ptr = block->first; !done; ptr = next) {
16351                 next = ptr->next;
16352                 if (ptr == block->last) {
16353                         done = 1;
16354                 }
16355                 /* RHS(A) */
16356                 if (ptr->op == OP_READ) {
16357                         struct triple *var, *val;
16358                         var = RHS(ptr, 0);
16359                         if (!triple_is_auto_var(state, var)) {
16360                                 internal_error(state, ptr, "read of non auto var!");
16361                         }
16362                         unuse_triple(var, ptr);
16363                         /* Find the current value of the variable */
16364                         val = peek_triple(stacks, var);
16365                         if (!val) {
16366                                 /* Let the optimizer at variables that are not initially
16367                                  * set.  But give it a bogus value so things seem to
16368                                  * work by accident.  This is useful for bitfields because
16369                                  * setting them always involves a read-modify-write.
16370                                  */
16371                                 if (TYPE_ARITHMETIC(ptr->type->type)) {
16372                                         val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16373                                         val->u.cval = 0xdeadbeaf;
16374                                 } else {
16375                                         val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16376                                 }
16377                         }
16378                         if (!val) {
16379                                 error(state, ptr, "variable used without being set");
16380                         }
16381                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16382                                 internal_error(state, val, "bad value in read");
16383                         }
16384                         propogate_use(state, ptr, val);
16385                         release_triple(state, ptr);
16386                         continue;
16387                 }
16388                 /* LHS(A) */
16389                 if (ptr->op == OP_WRITE) {
16390                         struct triple *var, *val, *tval;
16391                         var = MISC(ptr, 0);
16392                         if (!triple_is_auto_var(state, var)) {
16393                                 internal_error(state, ptr, "write to non auto var!");
16394                         }
16395                         tval = val = RHS(ptr, 0);
16396                         if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16397                                 triple_is_auto_var(state, val)) {
16398                                 internal_error(state, ptr, "bad value in write");
16399                         }
16400                         /* Insert a cast if the types differ */
16401                         if (!is_subset_type(ptr->type, val->type)) {
16402                                 if (val->op == OP_INTCONST) {
16403                                         tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16404                                         tval->u.cval = val->u.cval;
16405                                 }
16406                                 else {
16407                                         tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16408                                         use_triple(val, tval);
16409                                 }
16410                                 transform_to_arch_instruction(state, tval);
16411                                 unuse_triple(val, ptr);
16412                                 RHS(ptr, 0) = tval;
16413                                 use_triple(tval, ptr);
16414                         }
16415                         propogate_use(state, ptr, tval);
16416                         unuse_triple(var, ptr);
16417                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
16418                         push_triple(stacks, var, tval);
16419                 }
16420                 if (ptr->op == OP_PHI) {
16421                         struct triple *var;
16422                         var = MISC(ptr, 0);
16423                         if (!triple_is_auto_var(state, var)) {
16424                                 internal_error(state, ptr, "phi references non auto var!");
16425                         }
16426                         /* Push OP_PHI onto a stack of variable uses */
16427                         push_triple(stacks, var, ptr);
16428                 }
16429                 last = ptr;
16430         }
16431         block->last = last;
16432
16433         /* Fixup PHI functions in the cf successors */
16434         for(edge = block->edges; edge; edge = edge->next) {
16435                 fixup_block_phi_variables(state, stacks, block, edge->member);
16436         }
16437         /* rename variables in the dominated nodes */
16438         for(user = block->idominates; user; user = user->next) {
16439                 rename_block_variables(state, stacks, user->member);
16440         }
16441         /* pop the renamed variable stack */
16442         last = block->first;
16443         done = 0;
16444         for(ptr = block->first; !done ; ptr = next) {
16445                 next = ptr->next;
16446                 if (ptr == block->last) {
16447                         done = 1;
16448                 }
16449                 if (ptr->op == OP_WRITE) {
16450                         struct triple *var;
16451                         var = MISC(ptr, 0);
16452                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
16453                         pop_triple(stacks, var, RHS(ptr, 0));
16454                         release_triple(state, ptr);
16455                         continue;
16456                 }
16457                 if (ptr->op == OP_PHI) {
16458                         struct triple *var;
16459                         var = MISC(ptr, 0);
16460                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
16461                         pop_triple(stacks, var, ptr);
16462                 }
16463                 last = ptr;
16464         }
16465         block->last = last;
16466 }
16467
16468 static void rename_variables(struct compile_state *state)
16469 {
16470         struct stack *stacks;
16471         int auto_vars;
16472
16473         /* Allocate stacks for the Variables */
16474         auto_vars = count_auto_vars(state);
16475         stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16476
16477         /* Give each auto_var a stack */
16478         number_auto_vars(state, stacks);
16479
16480         /* Rename the variables */
16481         rename_block_variables(state, stacks, state->bb.first_block);
16482
16483         /* Remove the stacks from the auto_vars */
16484         restore_auto_vars(state, stacks);
16485         xfree(stacks);
16486 }
16487
16488 static void prune_block_variables(struct compile_state *state,
16489         struct block *block)
16490 {
16491         struct block_set *user;
16492         struct triple *next, *ptr;
16493         int done;
16494
16495         done = 0;
16496         for(ptr = block->first; !done; ptr = next) {
16497                 /* Be extremely careful I am deleting the list
16498                  * as I walk trhough it.
16499                  */
16500                 next = ptr->next;
16501                 if (ptr == block->last) {
16502                         done = 1;
16503                 }
16504                 if (triple_is_auto_var(state, ptr)) {
16505                         struct triple_set *user, *next;
16506                         for(user = ptr->use; user; user = next) {
16507                                 struct triple *use;
16508                                 next = user->next;
16509                                 use = user->member;
16510                                 if (MISC(ptr, 0) == user->member) {
16511                                         continue;
16512                                 }
16513                                 if (use->op != OP_PHI) {
16514                                         internal_error(state, use, "decl still used");
16515                                 }
16516                                 if (MISC(use, 0) != ptr) {
16517                                         internal_error(state, use, "bad phi use of decl");
16518                                 }
16519                                 unuse_triple(ptr, use);
16520                                 MISC(use, 0) = 0;
16521                         }
16522                         if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16523                                 /* Delete the adecl */
16524                                 release_triple(state, MISC(ptr, 0));
16525                                 /* And the piece */
16526                                 release_triple(state, ptr);
16527                         }
16528                         continue;
16529                 }
16530         }
16531         for(user = block->idominates; user; user = user->next) {
16532                 prune_block_variables(state, user->member);
16533         }
16534 }
16535
16536 struct phi_triple {
16537         struct triple *phi;
16538         unsigned orig_id;
16539         int alive;
16540 };
16541
16542 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16543 {
16544         struct triple **slot;
16545         int zrhs, i;
16546         if (live[phi->id].alive) {
16547                 return;
16548         }
16549         live[phi->id].alive = 1;
16550         zrhs = phi->rhs;
16551         slot = &RHS(phi, 0);
16552         for(i = 0; i < zrhs; i++) {
16553                 struct triple *used;
16554                 used = slot[i];
16555                 if (used && (used->op == OP_PHI)) {
16556                         keep_phi(state, live, used);
16557                 }
16558         }
16559 }
16560
16561 static void prune_unused_phis(struct compile_state *state)
16562 {
16563         struct triple *first, *phi;
16564         struct phi_triple *live;
16565         int phis, i;
16566         
16567         /* Find the first instruction */
16568         first = state->first;
16569
16570         /* Count how many phi functions I need to process */
16571         phis = 0;
16572         for(phi = first->next; phi != first; phi = phi->next) {
16573                 if (phi->op == OP_PHI) {
16574                         phis += 1;
16575                 }
16576         }
16577         
16578         /* Mark them all dead */
16579         live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16580         phis = 0;
16581         for(phi = first->next; phi != first; phi = phi->next) {
16582                 if (phi->op != OP_PHI) {
16583                         continue;
16584                 }
16585                 live[phis].alive   = 0;
16586                 live[phis].orig_id = phi->id;
16587                 live[phis].phi     = phi;
16588                 phi->id = phis;
16589                 phis += 1;
16590         }
16591         
16592         /* Mark phis alive that are used by non phis */
16593         for(i = 0; i < phis; i++) {
16594                 struct triple_set *set;
16595                 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16596                         if (set->member->op != OP_PHI) {
16597                                 keep_phi(state, live, live[i].phi);
16598                                 break;
16599                         }
16600                 }
16601         }
16602
16603         /* Delete the extraneous phis */
16604         for(i = 0; i < phis; i++) {
16605                 struct triple **slot;
16606                 int zrhs, j;
16607                 if (!live[i].alive) {
16608                         release_triple(state, live[i].phi);
16609                         continue;
16610                 }
16611                 phi = live[i].phi;
16612                 slot = &RHS(phi, 0);
16613                 zrhs = phi->rhs;
16614                 for(j = 0; j < zrhs; j++) {
16615                         if(!slot[j]) {
16616                                 struct triple *unknown;
16617                                 get_occurance(phi->occurance);
16618                                 unknown = flatten(state, state->global_pool,
16619                                         alloc_triple(state, OP_UNKNOWNVAL,
16620                                                 phi->type, 0, 0, phi->occurance));
16621                                 slot[j] = unknown;
16622                                 use_triple(unknown, phi);
16623                                 transform_to_arch_instruction(state, unknown);
16624 #if 0                           
16625                                 warning(state, phi, "variable not set at index %d on all paths to use", j);
16626 #endif
16627                         }
16628                 }
16629         }
16630         xfree(live);
16631 }
16632
16633 static void transform_to_ssa_form(struct compile_state *state)
16634 {
16635         insert_phi_operations(state);
16636         rename_variables(state);
16637
16638         prune_block_variables(state, state->bb.first_block);
16639         prune_unused_phis(state);
16640
16641         print_blocks(state, __func__, state->dbgout);
16642 }
16643
16644
16645 static void clear_vertex(
16646         struct compile_state *state, struct block *block, void *arg)
16647 {
16648         /* Clear the current blocks vertex and the vertex of all
16649          * of the current blocks neighbors in case there are malformed
16650          * blocks with now instructions at this point.
16651          */
16652         struct block_set *user, *edge;
16653         block->vertex = 0;
16654         for(edge = block->edges; edge; edge = edge->next) {
16655                 edge->member->vertex = 0;
16656         }
16657         for(user = block->use; user; user = user->next) {
16658                 user->member->vertex = 0;
16659         }
16660 }
16661
16662 static void mark_live_block(
16663         struct compile_state *state, struct block *block, int *next_vertex)
16664 {
16665         /* See if this is a block that has not been marked */
16666         if (block->vertex != 0) {
16667                 return;
16668         }
16669         block->vertex = *next_vertex;
16670         *next_vertex += 1;
16671         if (triple_is_branch(state, block->last)) {
16672                 struct triple **targ;
16673                 targ = triple_edge_targ(state, block->last, 0);
16674                 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16675                         if (!*targ) {
16676                                 continue;
16677                         }
16678                         if (!triple_stores_block(state, *targ)) {
16679                                 internal_error(state, 0, "bad targ");
16680                         }
16681                         mark_live_block(state, (*targ)->u.block, next_vertex);
16682                 }
16683                 /* Ensure the last block of a function remains alive */
16684                 if (triple_is_call(state, block->last)) {
16685                         mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16686                 }
16687         }
16688         else if (block->last->next != state->first) {
16689                 struct triple *ins;
16690                 ins = block->last->next;
16691                 if (!triple_stores_block(state, ins)) {
16692                         internal_error(state, 0, "bad block start");
16693                 }
16694                 mark_live_block(state, ins->u.block, next_vertex);
16695         }
16696 }
16697
16698 static void transform_from_ssa_form(struct compile_state *state)
16699 {
16700         /* To get out of ssa form we insert moves on the incoming
16701          * edges to blocks containting phi functions.
16702          */
16703         struct triple *first;
16704         struct triple *phi, *var, *next;
16705         int next_vertex;
16706
16707         /* Walk the control flow to see which blocks remain alive */
16708         walk_blocks(state, &state->bb, clear_vertex, 0);
16709         next_vertex = 1;
16710         mark_live_block(state, state->bb.first_block, &next_vertex);
16711
16712         /* Walk all of the operations to find the phi functions */
16713         first = state->first;
16714         for(phi = first->next; phi != first ; phi = next) {
16715                 struct block_set *set;
16716                 struct block *block;
16717                 struct triple **slot;
16718                 struct triple *var;
16719                 struct triple_set *use, *use_next;
16720                 int edge, writers, readers;
16721                 next = phi->next;
16722                 if (phi->op != OP_PHI) {
16723                         continue;
16724                 }
16725
16726                 block = phi->u.block;
16727                 slot  = &RHS(phi, 0);
16728
16729                 /* If this phi is in a dead block just forget it */
16730                 if (block->vertex == 0) {
16731                         release_triple(state, phi);
16732                         continue;
16733                 }
16734
16735                 /* Forget uses from code in dead blocks */
16736                 for(use = phi->use; use; use = use_next) {
16737                         struct block *ublock;
16738                         struct triple **expr;
16739                         use_next = use->next;
16740                         ublock = block_of_triple(state, use->member);
16741                         if ((use->member == phi) || (ublock->vertex != 0)) {
16742                                 continue;
16743                         }
16744                         expr = triple_rhs(state, use->member, 0);
16745                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
16746                                 if (*expr == phi) {
16747                                         *expr = 0;
16748                                 }
16749                         }
16750                         unuse_triple(phi, use->member);
16751                 }
16752                 /* A variable to replace the phi function */
16753                 if (registers_of(state, phi->type) != 1) {
16754                         internal_error(state, phi, "phi->type does not fit in a single register!");
16755                 }
16756                 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16757                 var = var->next; /* point at the var */
16758                         
16759                 /* Replaces use of phi with var */
16760                 propogate_use(state, phi, var);
16761
16762                 /* Count the readers */
16763                 readers = 0;
16764                 for(use = var->use; use; use = use->next) {
16765                         if (use->member != MISC(var, 0)) {
16766                                 readers++;
16767                         }
16768                 }
16769
16770                 /* Walk all of the incoming edges/blocks and insert moves.
16771                  */
16772                 writers = 0;
16773                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16774                         struct block *eblock, *vblock;
16775                         struct triple *move;
16776                         struct triple *val, *base;
16777                         eblock = set->member;
16778                         val = slot[edge];
16779                         slot[edge] = 0;
16780                         unuse_triple(val, phi);
16781                         vblock = block_of_triple(state, val);
16782
16783                         /* If we don't have a value that belongs in an OP_WRITE
16784                          * continue on.
16785                          */
16786                         if (!val || (val == &unknown_triple) || (val == phi)
16787                                 || (vblock && (vblock->vertex == 0))) {
16788                                 continue;
16789                         }
16790                         /* If the value should never occur error */
16791                         if (!vblock) {
16792                                 internal_error(state, val, "no vblock?");
16793                                 continue;
16794                         }
16795
16796                         /* If the value occurs in a dead block see if a replacement
16797                          * block can be found.
16798                          */
16799                         while(eblock && (eblock->vertex == 0)) {
16800                                 eblock = eblock->idom;
16801                         }
16802                         /* If not continue on with the next value. */
16803                         if (!eblock || (eblock->vertex == 0)) {
16804                                 continue;
16805                         }
16806
16807                         /* If we have an empty incoming block ignore it. */
16808                         if (!eblock->first) {
16809                                 internal_error(state, 0, "empty block?");
16810                         }
16811                         
16812                         /* Make certain the write is placed in the edge block... */
16813                         /* Walk through the edge block backwards to find an
16814                          * appropriate location for the OP_WRITE.
16815                          */
16816                         for(base = eblock->last; base != eblock->first; base = base->prev) {
16817                                 struct triple **expr;
16818                                 if (base->op == OP_PIECE) {
16819                                         base = MISC(base, 0);
16820                                 }
16821                                 if ((base == var) || (base == val)) {
16822                                         goto out;
16823                                 }
16824                                 expr = triple_lhs(state, base, 0);
16825                                 for(; expr; expr = triple_lhs(state, base, expr)) {
16826                                         if ((*expr) == val) {
16827                                                 goto out;
16828                                         }
16829                                 }
16830                                 expr = triple_rhs(state, base, 0);
16831                                 for(; expr; expr = triple_rhs(state, base, expr)) {
16832                                         if ((*expr) == var) {
16833                                                 goto out;
16834                                         }
16835                                 }
16836                         }
16837                 out:
16838                         if (triple_is_branch(state, base)) {
16839                                 internal_error(state, base,
16840                                         "Could not insert write to phi");
16841                         }
16842                         move = post_triple(state, base, OP_WRITE, var->type, val, var);
16843                         use_triple(val, move);
16844                         use_triple(var, move);
16845                         writers++;
16846                 }
16847                 if (!writers && readers) {
16848                         internal_error(state, var, "no value written to in use phi?");
16849                 }
16850                 /* If var is not used free it */
16851                 if (!writers) {
16852                         release_triple(state, MISC(var, 0));
16853                         release_triple(state, var);
16854                 }
16855                 /* Release the phi function */
16856                 release_triple(state, phi);
16857         }
16858         
16859         /* Walk all of the operations to find the adecls */
16860         for(var = first->next; var != first ; var = var->next) {
16861                 struct triple_set *use, *use_next;
16862                 if (!triple_is_auto_var(state, var)) {
16863                         continue;
16864                 }
16865
16866                 /* Walk through all of the rhs uses of var and
16867                  * replace them with read of var.
16868                  */
16869                 for(use = var->use; use; use = use_next) {
16870                         struct triple *read, *user;
16871                         struct triple **slot;
16872                         int zrhs, i, used;
16873                         use_next = use->next;
16874                         user = use->member;
16875                         
16876                         /* Generate a read of var */
16877                         read = pre_triple(state, user, OP_READ, var->type, var, 0);
16878                         use_triple(var, read);
16879
16880                         /* Find the rhs uses and see if they need to be replaced */
16881                         used = 0;
16882                         zrhs = user->rhs;
16883                         slot = &RHS(user, 0);
16884                         for(i = 0; i < zrhs; i++) {
16885                                 if (slot[i] == var) {
16886                                         slot[i] = read;
16887                                         used = 1;
16888                                 }
16889                         }
16890                         /* If we did use it cleanup the uses */
16891                         if (used) {
16892                                 unuse_triple(var, user);
16893                                 use_triple(read, user);
16894                         } 
16895                         /* If we didn't use it release the extra triple */
16896                         else {
16897                                 release_triple(state, read);
16898                         }
16899                 }
16900         }
16901 }
16902
16903 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16904         FILE *fp = state->dbgout; \
16905         fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16906         } 
16907
16908 static void rebuild_ssa_form(struct compile_state *state)
16909 {
16910 HI();
16911         transform_from_ssa_form(state);
16912 HI();
16913         state->bb.first = state->first;
16914         free_basic_blocks(state, &state->bb);
16915         analyze_basic_blocks(state, &state->bb);
16916 HI();
16917         insert_phi_operations(state);
16918 HI();
16919         rename_variables(state);
16920 HI();
16921         
16922         prune_block_variables(state, state->bb.first_block);
16923 HI();
16924         prune_unused_phis(state);
16925 HI();
16926 }
16927 #undef HI
16928
16929 /* 
16930  * Register conflict resolution
16931  * =========================================================
16932  */
16933
16934 static struct reg_info find_def_color(
16935         struct compile_state *state, struct triple *def)
16936 {
16937         struct triple_set *set;
16938         struct reg_info info;
16939         info.reg = REG_UNSET;
16940         info.regcm = 0;
16941         if (!triple_is_def(state, def)) {
16942                 return info;
16943         }
16944         info = arch_reg_lhs(state, def, 0);
16945         if (info.reg >= MAX_REGISTERS) {
16946                 info.reg = REG_UNSET;
16947         }
16948         for(set = def->use; set; set = set->next) {
16949                 struct reg_info tinfo;
16950                 int i;
16951                 i = find_rhs_use(state, set->member, def);
16952                 if (i < 0) {
16953                         continue;
16954                 }
16955                 tinfo = arch_reg_rhs(state, set->member, i);
16956                 if (tinfo.reg >= MAX_REGISTERS) {
16957                         tinfo.reg = REG_UNSET;
16958                 }
16959                 if ((tinfo.reg != REG_UNSET) && 
16960                         (info.reg != REG_UNSET) &&
16961                         (tinfo.reg != info.reg)) {
16962                         internal_error(state, def, "register conflict");
16963                 }
16964                 if ((info.regcm & tinfo.regcm) == 0) {
16965                         internal_error(state, def, "regcm conflict %x & %x == 0",
16966                                 info.regcm, tinfo.regcm);
16967                 }
16968                 if (info.reg == REG_UNSET) {
16969                         info.reg = tinfo.reg;
16970                 }
16971                 info.regcm &= tinfo.regcm;
16972         }
16973         if (info.reg >= MAX_REGISTERS) {
16974                 internal_error(state, def, "register out of range");
16975         }
16976         return info;
16977 }
16978
16979 static struct reg_info find_lhs_pre_color(
16980         struct compile_state *state, struct triple *ins, int index)
16981 {
16982         struct reg_info info;
16983         int zlhs, zrhs, i;
16984         zrhs = ins->rhs;
16985         zlhs = ins->lhs;
16986         if (!zlhs && triple_is_def(state, ins)) {
16987                 zlhs = 1;
16988         }
16989         if (index >= zlhs) {
16990                 internal_error(state, ins, "Bad lhs %d", index);
16991         }
16992         info = arch_reg_lhs(state, ins, index);
16993         for(i = 0; i < zrhs; i++) {
16994                 struct reg_info rinfo;
16995                 rinfo = arch_reg_rhs(state, ins, i);
16996                 if ((info.reg == rinfo.reg) &&
16997                         (rinfo.reg >= MAX_REGISTERS)) {
16998                         struct reg_info tinfo;
16999                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
17000                         info.reg = tinfo.reg;
17001                         info.regcm &= tinfo.regcm;
17002                         break;
17003                 }
17004         }
17005         if (info.reg >= MAX_REGISTERS) {
17006                 info.reg = REG_UNSET;
17007         }
17008         return info;
17009 }
17010
17011 static struct reg_info find_rhs_post_color(
17012         struct compile_state *state, struct triple *ins, int index);
17013
17014 static struct reg_info find_lhs_post_color(
17015         struct compile_state *state, struct triple *ins, int index)
17016 {
17017         struct triple_set *set;
17018         struct reg_info info;
17019         struct triple *lhs;
17020 #if DEBUG_TRIPLE_COLOR
17021         fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
17022                 ins, index);
17023 #endif
17024         if ((index == 0) && triple_is_def(state, ins)) {
17025                 lhs = ins;
17026         }
17027         else if (index < ins->lhs) {
17028                 lhs = LHS(ins, index);
17029         }
17030         else {
17031                 internal_error(state, ins, "Bad lhs %d", index);
17032                 lhs = 0;
17033         }
17034         info = arch_reg_lhs(state, ins, index);
17035         if (info.reg >= MAX_REGISTERS) {
17036                 info.reg = REG_UNSET;
17037         }
17038         for(set = lhs->use; set; set = set->next) {
17039                 struct reg_info rinfo;
17040                 struct triple *user;
17041                 int zrhs, i;
17042                 user = set->member;
17043                 zrhs = user->rhs;
17044                 for(i = 0; i < zrhs; i++) {
17045                         if (RHS(user, i) != lhs) {
17046                                 continue;
17047                         }
17048                         rinfo = find_rhs_post_color(state, user, i);
17049                         if ((info.reg != REG_UNSET) &&
17050                                 (rinfo.reg != REG_UNSET) &&
17051                                 (info.reg != rinfo.reg)) {
17052                                 internal_error(state, ins, "register conflict");
17053                         }
17054                         if ((info.regcm & rinfo.regcm) == 0) {
17055                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
17056                                         info.regcm, rinfo.regcm);
17057                         }
17058                         if (info.reg == REG_UNSET) {
17059                                 info.reg = rinfo.reg;
17060                         }
17061                         info.regcm &= rinfo.regcm;
17062                 }
17063         }
17064 #if DEBUG_TRIPLE_COLOR
17065         fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17066                 ins, index, info.reg, info.regcm);
17067 #endif
17068         return info;
17069 }
17070
17071 static struct reg_info find_rhs_post_color(
17072         struct compile_state *state, struct triple *ins, int index)
17073 {
17074         struct reg_info info, rinfo;
17075         int zlhs, i;
17076 #if DEBUG_TRIPLE_COLOR
17077         fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17078                 ins, index);
17079 #endif
17080         rinfo = arch_reg_rhs(state, ins, index);
17081         zlhs = ins->lhs;
17082         if (!zlhs && triple_is_def(state, ins)) {
17083                 zlhs = 1;
17084         }
17085         info = rinfo;
17086         if (info.reg >= MAX_REGISTERS) {
17087                 info.reg = REG_UNSET;
17088         }
17089         for(i = 0; i < zlhs; i++) {
17090                 struct reg_info linfo;
17091                 linfo = arch_reg_lhs(state, ins, i);
17092                 if ((linfo.reg == rinfo.reg) &&
17093                         (linfo.reg >= MAX_REGISTERS)) {
17094                         struct reg_info tinfo;
17095                         tinfo = find_lhs_post_color(state, ins, i);
17096                         if (tinfo.reg >= MAX_REGISTERS) {
17097                                 tinfo.reg = REG_UNSET;
17098                         }
17099                         info.regcm &= linfo.regcm;
17100                         info.regcm &= tinfo.regcm;
17101                         if (info.reg != REG_UNSET) {
17102                                 internal_error(state, ins, "register conflict");
17103                         }
17104                         if (info.regcm == 0) {
17105                                 internal_error(state, ins, "regcm conflict");
17106                         }
17107                         info.reg = tinfo.reg;
17108                 }
17109         }
17110 #if DEBUG_TRIPLE_COLOR
17111         fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17112                 ins, index, info.reg, info.regcm);
17113 #endif
17114         return info;
17115 }
17116
17117 static struct reg_info find_lhs_color(
17118         struct compile_state *state, struct triple *ins, int index)
17119 {
17120         struct reg_info pre, post, info;
17121 #if DEBUG_TRIPLE_COLOR
17122         fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17123                 ins, index);
17124 #endif
17125         pre = find_lhs_pre_color(state, ins, index);
17126         post = find_lhs_post_color(state, ins, index);
17127         if ((pre.reg != post.reg) &&
17128                 (pre.reg != REG_UNSET) &&
17129                 (post.reg != REG_UNSET)) {
17130                 internal_error(state, ins, "register conflict");
17131         }
17132         info.regcm = pre.regcm & post.regcm;
17133         info.reg = pre.reg;
17134         if (info.reg == REG_UNSET) {
17135                 info.reg = post.reg;
17136         }
17137 #if DEBUG_TRIPLE_COLOR
17138         fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17139                 ins, index, info.reg, info.regcm,
17140                 pre.reg, pre.regcm, post.reg, post.regcm);
17141 #endif
17142         return info;
17143 }
17144
17145 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17146 {
17147         struct triple_set *entry, *next;
17148         struct triple *out;
17149         struct reg_info info, rinfo;
17150
17151         info = arch_reg_lhs(state, ins, 0);
17152         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17153         use_triple(RHS(out, 0), out);
17154         /* Get the users of ins to use out instead */
17155         for(entry = ins->use; entry; entry = next) {
17156                 int i;
17157                 next = entry->next;
17158                 if (entry->member == out) {
17159                         continue;
17160                 }
17161                 i = find_rhs_use(state, entry->member, ins);
17162                 if (i < 0) {
17163                         continue;
17164                 }
17165                 rinfo = arch_reg_rhs(state, entry->member, i);
17166                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17167                         continue;
17168                 }
17169                 replace_rhs_use(state, ins, out, entry->member);
17170         }
17171         transform_to_arch_instruction(state, out);
17172         return out;
17173 }
17174
17175 static struct triple *typed_pre_copy(
17176         struct compile_state *state, struct type *type, struct triple *ins, int index)
17177 {
17178         /* Carefully insert enough operations so that I can
17179          * enter any operation with a GPR32.
17180          */
17181         struct triple *in;
17182         struct triple **expr;
17183         unsigned classes;
17184         struct reg_info info;
17185         int op;
17186         if (ins->op == OP_PHI) {
17187                 internal_error(state, ins, "pre_copy on a phi?");
17188         }
17189         classes = arch_type_to_regcm(state, type);
17190         info = arch_reg_rhs(state, ins, index);
17191         expr = &RHS(ins, index);
17192         if ((info.regcm & classes) == 0) {
17193                 FILE *fp = state->errout;
17194                 fprintf(fp, "src_type: ");
17195                 name_of(fp, ins->type);
17196                 fprintf(fp, "\ndst_type: ");
17197                 name_of(fp, type);
17198                 fprintf(fp, "\n");
17199                 internal_error(state, ins, "pre_copy with no register classes");
17200         }
17201         op = OP_COPY;
17202         if (!equiv_types(type, (*expr)->type)) {
17203                 op = OP_CONVERT;
17204         }
17205         in = pre_triple(state, ins, op, type, *expr, 0);
17206         unuse_triple(*expr, ins);
17207         *expr = in;
17208         use_triple(RHS(in, 0), in);
17209         use_triple(in, ins);
17210         transform_to_arch_instruction(state, in);
17211         return in;
17212         
17213 }
17214 static struct triple *pre_copy(
17215         struct compile_state *state, struct triple *ins, int index)
17216 {
17217         return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17218 }
17219
17220
17221 static void insert_copies_to_phi(struct compile_state *state)
17222 {
17223         /* To get out of ssa form we insert moves on the incoming
17224          * edges to blocks containting phi functions.
17225          */
17226         struct triple *first;
17227         struct triple *phi;
17228
17229         /* Walk all of the operations to find the phi functions */
17230         first = state->first;
17231         for(phi = first->next; phi != first ; phi = phi->next) {
17232                 struct block_set *set;
17233                 struct block *block;
17234                 struct triple **slot, *copy;
17235                 int edge;
17236                 if (phi->op != OP_PHI) {
17237                         continue;
17238                 }
17239                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17240                 block = phi->u.block;
17241                 slot  = &RHS(phi, 0);
17242                 /* Phi's that feed into mandatory live range joins
17243                  * cause nasty complications.  Insert a copy of
17244                  * the phi value so I never have to deal with
17245                  * that in the rest of the code.
17246                  */
17247                 copy = post_copy(state, phi);
17248                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17249                 /* Walk all of the incoming edges/blocks and insert moves.
17250                  */
17251                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17252                         struct block *eblock;
17253                         struct triple *move;
17254                         struct triple *val;
17255                         struct triple *ptr;
17256                         eblock = set->member;
17257                         val = slot[edge];
17258
17259                         if (val == phi) {
17260                                 continue;
17261                         }
17262
17263                         get_occurance(val->occurance);
17264                         move = build_triple(state, OP_COPY, val->type, val, 0,
17265                                 val->occurance);
17266                         move->u.block = eblock;
17267                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
17268                         use_triple(val, move);
17269                         
17270                         slot[edge] = move;
17271                         unuse_triple(val, phi);
17272                         use_triple(move, phi);
17273
17274                         /* Walk up the dominator tree until I have found the appropriate block */
17275                         while(eblock && !tdominates(state, val, eblock->last)) {
17276                                 eblock = eblock->idom;
17277                         }
17278                         if (!eblock) {
17279                                 internal_error(state, phi, "Cannot find block dominated by %p",
17280                                         val);
17281                         }
17282
17283                         /* Walk through the block backwards to find
17284                          * an appropriate location for the OP_COPY.
17285                          */
17286                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17287                                 struct triple **expr;
17288                                 if (ptr->op == OP_PIECE) {
17289                                         ptr = MISC(ptr, 0);
17290                                 }
17291                                 if ((ptr == phi) || (ptr == val)) {
17292                                         goto out;
17293                                 }
17294                                 expr = triple_lhs(state, ptr, 0);
17295                                 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17296                                         if ((*expr) == val) {
17297                                                 goto out;
17298                                         }
17299                                 }
17300                                 expr = triple_rhs(state, ptr, 0);
17301                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17302                                         if ((*expr) == phi) {
17303                                                 goto out;
17304                                         }
17305                                 }
17306                         }
17307                 out:
17308                         if (triple_is_branch(state, ptr)) {
17309                                 internal_error(state, ptr,
17310                                         "Could not insert write to phi");
17311                         }
17312                         insert_triple(state, after_lhs(state, ptr), move);
17313                         if (eblock->last == after_lhs(state, ptr)->prev) {
17314                                 eblock->last = move;
17315                         }
17316                         transform_to_arch_instruction(state, move);
17317                 }
17318         }
17319         print_blocks(state, __func__, state->dbgout);
17320 }
17321
17322 struct triple_reg_set;
17323 struct reg_block;
17324
17325
17326 static int do_triple_set(struct triple_reg_set **head, 
17327         struct triple *member, struct triple *new_member)
17328 {
17329         struct triple_reg_set **ptr, *new;
17330         if (!member)
17331                 return 0;
17332         ptr = head;
17333         while(*ptr) {
17334                 if ((*ptr)->member == member) {
17335                         return 0;
17336                 }
17337                 ptr = &(*ptr)->next;
17338         }
17339         new = xcmalloc(sizeof(*new), "triple_set");
17340         new->member = member;
17341         new->new    = new_member;
17342         new->next   = *head;
17343         *head       = new;
17344         return 1;
17345 }
17346
17347 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17348 {
17349         struct triple_reg_set *entry, **ptr;
17350         ptr = head;
17351         while(*ptr) {
17352                 entry = *ptr;
17353                 if (entry->member == member) {
17354                         *ptr = entry->next;
17355                         xfree(entry);
17356                         return;
17357                 }
17358                 else {
17359                         ptr = &entry->next;
17360                 }
17361         }
17362 }
17363
17364 static int in_triple(struct reg_block *rb, struct triple *in)
17365 {
17366         return do_triple_set(&rb->in, in, 0);
17367 }
17368
17369 #if DEBUG_ROMCC_WARNING
17370 static void unin_triple(struct reg_block *rb, struct triple *unin)
17371 {
17372         do_triple_unset(&rb->in, unin);
17373 }
17374 #endif
17375
17376 static int out_triple(struct reg_block *rb, struct triple *out)
17377 {
17378         return do_triple_set(&rb->out, out, 0);
17379 }
17380 #if DEBUG_ROMCC_WARNING
17381 static void unout_triple(struct reg_block *rb, struct triple *unout)
17382 {
17383         do_triple_unset(&rb->out, unout);
17384 }
17385 #endif
17386
17387 static int initialize_regblock(struct reg_block *blocks,
17388         struct block *block, int vertex)
17389 {
17390         struct block_set *user;
17391         if (!block || (blocks[block->vertex].block == block)) {
17392                 return vertex;
17393         }
17394         vertex += 1;
17395         /* Renumber the blocks in a convinient fashion */
17396         block->vertex = vertex;
17397         blocks[vertex].block    = block;
17398         blocks[vertex].vertex   = vertex;
17399         for(user = block->use; user; user = user->next) {
17400                 vertex = initialize_regblock(blocks, user->member, vertex);
17401         }
17402         return vertex;
17403 }
17404
17405 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17406 {
17407 /* Part to piece is a best attempt and it cannot be correct all by
17408  * itself.  If various values are read as different sizes in different
17409  * parts of the code this function cannot work.  Or rather it cannot
17410  * work in conjunction with compute_variable_liftimes.  As the
17411  * analysis will get confused.
17412  */
17413         struct triple *base;
17414         unsigned reg;
17415         if (!is_lvalue(state, ins)) {
17416                 return ins;
17417         }
17418         base = 0;
17419         reg = 0;
17420         while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17421                 base = MISC(ins, 0);
17422                 switch(ins->op) {
17423                 case OP_INDEX:
17424                         reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17425                         break;
17426                 case OP_DOT:
17427                         reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17428                         break;
17429                 default:
17430                         internal_error(state, ins, "unhandled part");
17431                         break;
17432                 }
17433                 ins = base;
17434         }
17435         if (base) {
17436                 if (reg > base->lhs) {
17437                         internal_error(state, base, "part out of range?");
17438                 }
17439                 ins = LHS(base, reg);
17440         }
17441         return ins;
17442 }
17443
17444 static int this_def(struct compile_state *state, 
17445         struct triple *ins, struct triple *other)
17446 {
17447         if (ins == other) {
17448                 return 1;
17449         }
17450         if (ins->op == OP_WRITE) {
17451                 ins = part_to_piece(state, MISC(ins, 0));
17452         }
17453         return ins == other;
17454 }
17455
17456 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17457         struct reg_block *rb, struct block *suc)
17458 {
17459         /* Read the conditional input set of a successor block
17460          * (i.e. the input to the phi nodes) and place it in the
17461          * current blocks output set.
17462          */
17463         struct block_set *set;
17464         struct triple *ptr;
17465         int edge;
17466         int done, change;
17467         change = 0;
17468         /* Find the edge I am coming in on */
17469         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17470                 if (set->member == rb->block) {
17471                         break;
17472                 }
17473         }
17474         if (!set) {
17475                 internal_error(state, 0, "Not coming on a control edge?");
17476         }
17477         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17478                 struct triple **slot, *expr, *ptr2;
17479                 int out_change, done2;
17480                 done = (ptr == suc->last);
17481                 if (ptr->op != OP_PHI) {
17482                         continue;
17483                 }
17484                 slot = &RHS(ptr, 0);
17485                 expr = slot[edge];
17486                 out_change = out_triple(rb, expr);
17487                 if (!out_change) {
17488                         continue;
17489                 }
17490                 /* If we don't define the variable also plast it
17491                  * in the current blocks input set.
17492                  */
17493                 ptr2 = rb->block->first;
17494                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17495                         if (this_def(state, ptr2, expr)) {
17496                                 break;
17497                         }
17498                         done2 = (ptr2 == rb->block->last);
17499                 }
17500                 if (!done2) {
17501                         continue;
17502                 }
17503                 change |= in_triple(rb, expr);
17504         }
17505         return change;
17506 }
17507
17508 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17509         struct reg_block *rb, struct block *suc)
17510 {
17511         struct triple_reg_set *in_set;
17512         int change;
17513         change = 0;
17514         /* Read the input set of a successor block
17515          * and place it in the current blocks output set.
17516          */
17517         in_set = blocks[suc->vertex].in;
17518         for(; in_set; in_set = in_set->next) {
17519                 int out_change, done;
17520                 struct triple *first, *last, *ptr;
17521                 out_change = out_triple(rb, in_set->member);
17522                 if (!out_change) {
17523                         continue;
17524                 }
17525                 /* If we don't define the variable also place it
17526                  * in the current blocks input set.
17527                  */
17528                 first = rb->block->first;
17529                 last = rb->block->last;
17530                 done = 0;
17531                 for(ptr = first; !done; ptr = ptr->next) {
17532                         if (this_def(state, ptr, in_set->member)) {
17533                                 break;
17534                         }
17535                         done = (ptr == last);
17536                 }
17537                 if (!done) {
17538                         continue;
17539                 }
17540                 change |= in_triple(rb, in_set->member);
17541         }
17542         change |= phi_in(state, blocks, rb, suc);
17543         return change;
17544 }
17545
17546 static int use_in(struct compile_state *state, struct reg_block *rb)
17547 {
17548         /* Find the variables we use but don't define and add
17549          * it to the current blocks input set.
17550          */
17551 #if DEBUG_ROMCC_WARNINGS
17552 #warning "FIXME is this O(N^2) algorithm bad?"
17553 #endif
17554         struct block *block;
17555         struct triple *ptr;
17556         int done;
17557         int change;
17558         block = rb->block;
17559         change = 0;
17560         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17561                 struct triple **expr;
17562                 done = (ptr == block->first);
17563                 /* The variable a phi function uses depends on the
17564                  * control flow, and is handled in phi_in, not
17565                  * here.
17566                  */
17567                 if (ptr->op == OP_PHI) {
17568                         continue;
17569                 }
17570                 expr = triple_rhs(state, ptr, 0);
17571                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17572                         struct triple *rhs, *test;
17573                         int tdone;
17574                         rhs = part_to_piece(state, *expr);
17575                         if (!rhs) {
17576                                 continue;
17577                         }
17578
17579                         /* See if rhs is defined in this block.
17580                          * A write counts as a definition.
17581                          */
17582                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17583                                 tdone = (test == block->first);
17584                                 if (this_def(state, test, rhs)) {
17585                                         rhs = 0;
17586                                         break;
17587                                 }
17588                         }
17589                         /* If I still have a valid rhs add it to in */
17590                         change |= in_triple(rb, rhs);
17591                 }
17592         }
17593         return change;
17594 }
17595
17596 static struct reg_block *compute_variable_lifetimes(
17597         struct compile_state *state, struct basic_blocks *bb)
17598 {
17599         struct reg_block *blocks;
17600         int change;
17601         blocks = xcmalloc(
17602                 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17603         initialize_regblock(blocks, bb->last_block, 0);
17604         do {
17605                 int i;
17606                 change = 0;
17607                 for(i = 1; i <= bb->last_vertex; i++) {
17608                         struct block_set *edge;
17609                         struct reg_block *rb;
17610                         rb = &blocks[i];
17611                         /* Add the all successor's input set to in */
17612                         for(edge = rb->block->edges; edge; edge = edge->next) {
17613                                 change |= reg_in(state, blocks, rb, edge->member);
17614                         }
17615                         /* Add use to in... */
17616                         change |= use_in(state, rb);
17617                 }
17618         } while(change);
17619         return blocks;
17620 }
17621
17622 static void free_variable_lifetimes(struct compile_state *state, 
17623         struct basic_blocks *bb, struct reg_block *blocks)
17624 {
17625         int i;
17626         /* free in_set && out_set on each block */
17627         for(i = 1; i <= bb->last_vertex; i++) {
17628                 struct triple_reg_set *entry, *next;
17629                 struct reg_block *rb;
17630                 rb = &blocks[i];
17631                 for(entry = rb->in; entry ; entry = next) {
17632                         next = entry->next;
17633                         do_triple_unset(&rb->in, entry->member);
17634                 }
17635                 for(entry = rb->out; entry; entry = next) {
17636                         next = entry->next;
17637                         do_triple_unset(&rb->out, entry->member);
17638                 }
17639         }
17640         xfree(blocks);
17641
17642 }
17643
17644 typedef void (*wvl_cb_t)(
17645         struct compile_state *state, 
17646         struct reg_block *blocks, struct triple_reg_set *live, 
17647         struct reg_block *rb, struct triple *ins, void *arg);
17648
17649 static void walk_variable_lifetimes(struct compile_state *state,
17650         struct basic_blocks *bb, struct reg_block *blocks, 
17651         wvl_cb_t cb, void *arg)
17652 {
17653         int i;
17654         
17655         for(i = 1; i <= state->bb.last_vertex; i++) {
17656                 struct triple_reg_set *live;
17657                 struct triple_reg_set *entry, *next;
17658                 struct triple *ptr, *prev;
17659                 struct reg_block *rb;
17660                 struct block *block;
17661                 int done;
17662
17663                 /* Get the blocks */
17664                 rb = &blocks[i];
17665                 block = rb->block;
17666
17667                 /* Copy out into live */
17668                 live = 0;
17669                 for(entry = rb->out; entry; entry = next) {
17670                         next = entry->next;
17671                         do_triple_set(&live, entry->member, entry->new);
17672                 }
17673                 /* Walk through the basic block calculating live */
17674                 for(done = 0, ptr = block->last; !done; ptr = prev) {
17675                         struct triple **expr;
17676
17677                         prev = ptr->prev;
17678                         done = (ptr == block->first);
17679
17680                         /* Ensure the current definition is in live */
17681                         if (triple_is_def(state, ptr)) {
17682                                 do_triple_set(&live, ptr, 0);
17683                         }
17684
17685                         /* Inform the callback function of what is
17686                          * going on.
17687                          */
17688                          cb(state, blocks, live, rb, ptr, arg);
17689                         
17690                         /* Remove the current definition from live */
17691                         do_triple_unset(&live, ptr);
17692
17693                         /* Add the current uses to live.
17694                          *
17695                          * It is safe to skip phi functions because they do
17696                          * not have any block local uses, and the block
17697                          * output sets already properly account for what
17698                          * control flow depedent uses phi functions do have.
17699                          */
17700                         if (ptr->op == OP_PHI) {
17701                                 continue;
17702                         }
17703                         expr = triple_rhs(state, ptr, 0);
17704                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
17705                                 /* If the triple is not a definition skip it. */
17706                                 if (!*expr || !triple_is_def(state, *expr)) {
17707                                         continue;
17708                                 }
17709                                 do_triple_set(&live, *expr, 0);
17710                         }
17711                 }
17712                 /* Free live */
17713                 for(entry = live; entry; entry = next) {
17714                         next = entry->next;
17715                         do_triple_unset(&live, entry->member);
17716                 }
17717         }
17718 }
17719
17720 struct print_live_variable_info {
17721         struct reg_block *rb;
17722         FILE *fp;
17723 };
17724 #if DEBUG_EXPLICIT_CLOSURES
17725 static void print_live_variables_block(
17726         struct compile_state *state, struct block *block, void *arg)
17727
17728 {
17729         struct print_live_variable_info *info = arg;
17730         struct block_set *edge;
17731         FILE *fp = info->fp;
17732         struct reg_block *rb;
17733         struct triple *ptr;
17734         int phi_present;
17735         int done;
17736         rb = &info->rb[block->vertex];
17737
17738         fprintf(fp, "\nblock: %p (%d),",
17739                 block,  block->vertex);
17740         for(edge = block->edges; edge; edge = edge->next) {
17741                 fprintf(fp, " %p<-%p",
17742                         edge->member, 
17743                         edge->member && edge->member->use?edge->member->use->member : 0);
17744         }
17745         fprintf(fp, "\n");
17746         if (rb->in) {
17747                 struct triple_reg_set *in_set;
17748                 fprintf(fp, "        in:");
17749                 for(in_set = rb->in; in_set; in_set = in_set->next) {
17750                         fprintf(fp, " %-10p", in_set->member);
17751                 }
17752                 fprintf(fp, "\n");
17753         }
17754         phi_present = 0;
17755         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17756                 done = (ptr == block->last);
17757                 if (ptr->op == OP_PHI) {
17758                         phi_present = 1;
17759                         break;
17760                 }
17761         }
17762         if (phi_present) {
17763                 int edge;
17764                 for(edge = 0; edge < block->users; edge++) {
17765                         fprintf(fp, "     in(%d):", edge);
17766                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17767                                 struct triple **slot;
17768                                 done = (ptr == block->last);
17769                                 if (ptr->op != OP_PHI) {
17770                                         continue;
17771                                 }
17772                                 slot = &RHS(ptr, 0);
17773                                 fprintf(fp, " %-10p", slot[edge]);
17774                         }
17775                         fprintf(fp, "\n");
17776                 }
17777         }
17778         if (block->first->op == OP_LABEL) {
17779                 fprintf(fp, "%p:\n", block->first);
17780         }
17781         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17782                 done = (ptr == block->last);
17783                 display_triple(fp, ptr);
17784         }
17785         if (rb->out) {
17786                 struct triple_reg_set *out_set;
17787                 fprintf(fp, "       out:");
17788                 for(out_set = rb->out; out_set; out_set = out_set->next) {
17789                         fprintf(fp, " %-10p", out_set->member);
17790                 }
17791                 fprintf(fp, "\n");
17792         }
17793         fprintf(fp, "\n");
17794 }
17795
17796 static void print_live_variables(struct compile_state *state, 
17797         struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17798 {
17799         struct print_live_variable_info info;
17800         info.rb = rb;
17801         info.fp = fp;
17802         fprintf(fp, "\nlive variables by block\n");
17803         walk_blocks(state, bb, print_live_variables_block, &info);
17804
17805 }
17806 #endif
17807
17808 static int count_triples(struct compile_state *state)
17809 {
17810         struct triple *first, *ins;
17811         int triples = 0;
17812         first = state->first;
17813         ins = first;
17814         do {
17815                 triples++;
17816                 ins = ins->next;
17817         } while (ins != first);
17818         return triples;
17819 }
17820
17821
17822 struct dead_triple {
17823         struct triple *triple;
17824         struct dead_triple *work_next;
17825         struct block *block;
17826         int old_id;
17827         int flags;
17828 #define TRIPLE_FLAG_ALIVE 1
17829 #define TRIPLE_FLAG_FREE  1
17830 };
17831
17832 static void print_dead_triples(struct compile_state *state, 
17833         struct dead_triple *dtriple)
17834 {
17835         struct triple *first, *ins;
17836         struct dead_triple *dt;
17837         FILE *fp;
17838         if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17839                 return;
17840         }
17841         fp = state->dbgout;
17842         fprintf(fp, "--------------- dtriples ---------------\n");
17843         first = state->first;
17844         ins = first;
17845         do {
17846                 dt = &dtriple[ins->id];
17847                 if ((ins->op == OP_LABEL) && (ins->use)) {
17848                         fprintf(fp, "\n%p:\n", ins);
17849                 }
17850                 fprintf(fp, "%c", 
17851                         (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17852                 display_triple(fp, ins);
17853                 if (triple_is_branch(state, ins)) {
17854                         fprintf(fp, "\n");
17855                 }
17856                 ins = ins->next;
17857         } while(ins != first);
17858         fprintf(fp, "\n");
17859 }
17860
17861
17862 static void awaken(
17863         struct compile_state *state,
17864         struct dead_triple *dtriple, struct triple **expr,
17865         struct dead_triple ***work_list_tail)
17866 {
17867         struct triple *triple;
17868         struct dead_triple *dt;
17869         if (!expr) {
17870                 return;
17871         }
17872         triple = *expr;
17873         if (!triple) {
17874                 return;
17875         }
17876         if (triple->id <= 0)  {
17877                 internal_error(state, triple, "bad triple id: %d",
17878                         triple->id);
17879         }
17880         if (triple->op == OP_NOOP) {
17881                 internal_error(state, triple, "awakening noop?");
17882                 return;
17883         }
17884         dt = &dtriple[triple->id];
17885         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17886                 dt->flags |= TRIPLE_FLAG_ALIVE;
17887                 if (!dt->work_next) {
17888                         **work_list_tail = dt;
17889                         *work_list_tail = &dt->work_next;
17890                 }
17891         }
17892 }
17893
17894 static void eliminate_inefectual_code(struct compile_state *state)
17895 {
17896         struct block *block;
17897         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17898         int triples, i;
17899         struct triple *first, *final, *ins;
17900
17901         if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17902                 return;
17903         }
17904
17905         /* Setup the work list */
17906         work_list = 0;
17907         work_list_tail = &work_list;
17908
17909         first = state->first;
17910         final = state->first->prev;
17911
17912         /* Count how many triples I have */
17913         triples = count_triples(state);
17914
17915         /* Now put then in an array and mark all of the triples dead */
17916         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17917         
17918         ins = first;
17919         i = 1;
17920         block = 0;
17921         do {
17922                 dtriple[i].triple = ins;
17923                 dtriple[i].block  = block_of_triple(state, ins);
17924                 dtriple[i].flags  = 0;
17925                 dtriple[i].old_id = ins->id;
17926                 ins->id = i;
17927                 /* See if it is an operation we always keep */
17928                 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17929                         awaken(state, dtriple, &ins, &work_list_tail);
17930                 }
17931                 i++;
17932                 ins = ins->next;
17933         } while(ins != first);
17934         while(work_list) {
17935                 struct block *block;
17936                 struct dead_triple *dt;
17937                 struct block_set *user;
17938                 struct triple **expr;
17939                 dt = work_list;
17940                 work_list = dt->work_next;
17941                 if (!work_list) {
17942                         work_list_tail = &work_list;
17943                 }
17944                 /* Make certain the block the current instruction is in lives */
17945                 block = block_of_triple(state, dt->triple);
17946                 awaken(state, dtriple, &block->first, &work_list_tail);
17947                 if (triple_is_branch(state, block->last)) {
17948                         awaken(state, dtriple, &block->last, &work_list_tail);
17949                 } else {
17950                         awaken(state, dtriple, &block->last->next, &work_list_tail);
17951                 }
17952
17953                 /* Wake up the data depencencies of this triple */
17954                 expr = 0;
17955                 do {
17956                         expr = triple_rhs(state, dt->triple, expr);
17957                         awaken(state, dtriple, expr, &work_list_tail);
17958                 } while(expr);
17959                 do {
17960                         expr = triple_lhs(state, dt->triple, expr);
17961                         awaken(state, dtriple, expr, &work_list_tail);
17962                 } while(expr);
17963                 do {
17964                         expr = triple_misc(state, dt->triple, expr);
17965                         awaken(state, dtriple, expr, &work_list_tail);
17966                 } while(expr);
17967                 /* Wake up the forward control dependencies */
17968                 do {
17969                         expr = triple_targ(state, dt->triple, expr);
17970                         awaken(state, dtriple, expr, &work_list_tail);
17971                 } while(expr);
17972                 /* Wake up the reverse control dependencies of this triple */
17973                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17974                         struct triple *last;
17975                         last = user->member->last;
17976                         while((last->op == OP_NOOP) && (last != user->member->first)) {
17977 #if DEBUG_ROMCC_WARNINGS
17978 #warning "Should we bring the awakening noops back?"
17979 #endif
17980                                 // internal_warning(state, last, "awakening noop?");
17981                                 last = last->prev;
17982                         }
17983                         awaken(state, dtriple, &last, &work_list_tail);
17984                 }
17985         }
17986         print_dead_triples(state, dtriple);
17987         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17988                 if ((dt->triple->op == OP_NOOP) && 
17989                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
17990                         internal_error(state, dt->triple, "noop effective?");
17991                 }
17992                 dt->triple->id = dt->old_id;    /* Restore the color */
17993                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17994                         release_triple(state, dt->triple);
17995                 }
17996         }
17997         xfree(dtriple);
17998
17999         rebuild_ssa_form(state);
18000
18001         print_blocks(state, __func__, state->dbgout);
18002 }
18003
18004
18005 static void insert_mandatory_copies(struct compile_state *state)
18006 {
18007         struct triple *ins, *first;
18008
18009         /* The object is with a minimum of inserted copies,
18010          * to resolve in fundamental register conflicts between
18011          * register value producers and consumers.
18012          * Theoretically we may be greater than minimal when we
18013          * are inserting copies before instructions but that
18014          * case should be rare.
18015          */
18016         first = state->first;
18017         ins = first;
18018         do {
18019                 struct triple_set *entry, *next;
18020                 struct triple *tmp;
18021                 struct reg_info info;
18022                 unsigned reg, regcm;
18023                 int do_post_copy, do_pre_copy;
18024                 tmp = 0;
18025                 if (!triple_is_def(state, ins)) {
18026                         goto next;
18027                 }
18028                 /* Find the architecture specific color information */
18029                 info = find_lhs_pre_color(state, ins, 0);
18030                 if (info.reg >= MAX_REGISTERS) {
18031                         info.reg = REG_UNSET;
18032                 }
18033
18034                 reg = REG_UNSET;
18035                 regcm = arch_type_to_regcm(state, ins->type);
18036                 do_post_copy = do_pre_copy = 0;
18037
18038                 /* Walk through the uses of ins and check for conflicts */
18039                 for(entry = ins->use; entry; entry = next) {
18040                         struct reg_info rinfo;
18041                         int i;
18042                         next = entry->next;
18043                         i = find_rhs_use(state, entry->member, ins);
18044                         if (i < 0) {
18045                                 continue;
18046                         }
18047                         
18048                         /* Find the users color requirements */
18049                         rinfo = arch_reg_rhs(state, entry->member, i);
18050                         if (rinfo.reg >= MAX_REGISTERS) {
18051                                 rinfo.reg = REG_UNSET;
18052                         }
18053                         
18054                         /* See if I need a pre_copy */
18055                         if (rinfo.reg != REG_UNSET) {
18056                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
18057                                         do_pre_copy = 1;
18058                                 }
18059                                 reg = rinfo.reg;
18060                         }
18061                         regcm &= rinfo.regcm;
18062                         regcm = arch_regcm_normalize(state, regcm);
18063                         if (regcm == 0) {
18064                                 do_pre_copy = 1;
18065                         }
18066                         /* Always use pre_copies for constants.
18067                          * They do not take up any registers until a
18068                          * copy places them in one.
18069                          */
18070                         if ((info.reg == REG_UNNEEDED) && 
18071                                 (rinfo.reg != REG_UNNEEDED)) {
18072                                 do_pre_copy = 1;
18073                         }
18074                 }
18075                 do_post_copy =
18076                         !do_pre_copy &&
18077                         (((info.reg != REG_UNSET) && 
18078                                 (reg != REG_UNSET) &&
18079                                 (info.reg != reg)) ||
18080                         ((info.regcm & regcm) == 0));
18081
18082                 reg = info.reg;
18083                 regcm = info.regcm;
18084                 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18085                 for(entry = ins->use; entry; entry = next) {
18086                         struct reg_info rinfo;
18087                         int i;
18088                         next = entry->next;
18089                         i = find_rhs_use(state, entry->member, ins);
18090                         if (i < 0) {
18091                                 continue;
18092                         }
18093                         
18094                         /* Find the users color requirements */
18095                         rinfo = arch_reg_rhs(state, entry->member, i);
18096                         if (rinfo.reg >= MAX_REGISTERS) {
18097                                 rinfo.reg = REG_UNSET;
18098                         }
18099
18100                         /* Now see if it is time to do the pre_copy */
18101                         if (rinfo.reg != REG_UNSET) {
18102                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18103                                         ((regcm & rinfo.regcm) == 0) ||
18104                                         /* Don't let a mandatory coalesce sneak
18105                                          * into a operation that is marked to prevent
18106                                          * coalescing.
18107                                          */
18108                                         ((reg != REG_UNNEEDED) &&
18109                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18110                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18111                                         ) {
18112                                         if (do_pre_copy) {
18113                                                 struct triple *user;
18114                                                 user = entry->member;
18115                                                 if (RHS(user, i) != ins) {
18116                                                         internal_error(state, user, "bad rhs");
18117                                                 }
18118                                                 tmp = pre_copy(state, user, i);
18119                                                 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18120                                                 continue;
18121                                         } else {
18122                                                 do_post_copy = 1;
18123                                         }
18124                                 }
18125                                 reg = rinfo.reg;
18126                         }
18127                         if ((regcm & rinfo.regcm) == 0) {
18128                                 if (do_pre_copy) {
18129                                         struct triple *user;
18130                                         user = entry->member;
18131                                         if (RHS(user, i) != ins) {
18132                                                 internal_error(state, user, "bad rhs");
18133                                         }
18134                                         tmp = pre_copy(state, user, i);
18135                                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18136                                         continue;
18137                                 } else {
18138                                         do_post_copy = 1;
18139                                 }
18140                         }
18141                         regcm &= rinfo.regcm;
18142                         
18143                 }
18144                 if (do_post_copy) {
18145                         struct reg_info pre, post;
18146                         tmp = post_copy(state, ins);
18147                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18148                         pre = arch_reg_lhs(state, ins, 0);
18149                         post = arch_reg_lhs(state, tmp, 0);
18150                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18151                                 internal_error(state, tmp, "useless copy");
18152                         }
18153                 }
18154         next:
18155                 ins = ins->next;
18156         } while(ins != first);
18157
18158         print_blocks(state, __func__, state->dbgout);
18159 }
18160
18161
18162 struct live_range_edge;
18163 struct live_range_def;
18164 struct live_range {
18165         struct live_range_edge *edges;
18166         struct live_range_def *defs;
18167 /* Note. The list pointed to by defs is kept in order.
18168  * That is baring splits in the flow control
18169  * defs dominates defs->next wich dominates defs->next->next
18170  * etc.
18171  */
18172         unsigned color;
18173         unsigned classes;
18174         unsigned degree;
18175         unsigned length;
18176         struct live_range *group_next, **group_prev;
18177 };
18178
18179 struct live_range_edge {
18180         struct live_range_edge *next;
18181         struct live_range *node;
18182 };
18183
18184 struct live_range_def {
18185         struct live_range_def *next;
18186         struct live_range_def *prev;
18187         struct live_range *lr;
18188         struct triple *def;
18189         unsigned orig_id;
18190 };
18191
18192 #define LRE_HASH_SIZE 2048
18193 struct lre_hash {
18194         struct lre_hash *next;
18195         struct live_range *left;
18196         struct live_range *right;
18197 };
18198
18199
18200 struct reg_state {
18201         struct lre_hash *hash[LRE_HASH_SIZE];
18202         struct reg_block *blocks;
18203         struct live_range_def *lrd;
18204         struct live_range *lr;
18205         struct live_range *low, **low_tail;
18206         struct live_range *high, **high_tail;
18207         unsigned defs;
18208         unsigned ranges;
18209         int passes, max_passes;
18210 };
18211
18212
18213 struct print_interference_block_info {
18214         struct reg_state *rstate;
18215         FILE *fp;
18216         int need_edges;
18217 };
18218 static void print_interference_block(
18219         struct compile_state *state, struct block *block, void *arg)
18220
18221 {
18222         struct print_interference_block_info *info = arg;
18223         struct reg_state *rstate = info->rstate;
18224         struct block_set *edge;
18225         FILE *fp = info->fp;
18226         struct reg_block *rb;
18227         struct triple *ptr;
18228         int phi_present;
18229         int done;
18230         rb = &rstate->blocks[block->vertex];
18231
18232         fprintf(fp, "\nblock: %p (%d),",
18233                 block,  block->vertex);
18234         for(edge = block->edges; edge; edge = edge->next) {
18235                 fprintf(fp, " %p<-%p",
18236                         edge->member, 
18237                         edge->member && edge->member->use?edge->member->use->member : 0);
18238         }
18239         fprintf(fp, "\n");
18240         if (rb->in) {
18241                 struct triple_reg_set *in_set;
18242                 fprintf(fp, "        in:");
18243                 for(in_set = rb->in; in_set; in_set = in_set->next) {
18244                         fprintf(fp, " %-10p", in_set->member);
18245                 }
18246                 fprintf(fp, "\n");
18247         }
18248         phi_present = 0;
18249         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18250                 done = (ptr == block->last);
18251                 if (ptr->op == OP_PHI) {
18252                         phi_present = 1;
18253                         break;
18254                 }
18255         }
18256         if (phi_present) {
18257                 int edge;
18258                 for(edge = 0; edge < block->users; edge++) {
18259                         fprintf(fp, "     in(%d):", edge);
18260                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18261                                 struct triple **slot;
18262                                 done = (ptr == block->last);
18263                                 if (ptr->op != OP_PHI) {
18264                                         continue;
18265                                 }
18266                                 slot = &RHS(ptr, 0);
18267                                 fprintf(fp, " %-10p", slot[edge]);
18268                         }
18269                         fprintf(fp, "\n");
18270                 }
18271         }
18272         if (block->first->op == OP_LABEL) {
18273                 fprintf(fp, "%p:\n", block->first);
18274         }
18275         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18276                 struct live_range *lr;
18277                 unsigned id;
18278                 int op;
18279                 op = ptr->op;
18280                 done = (ptr == block->last);
18281                 lr = rstate->lrd[ptr->id].lr;
18282                 
18283                 id = ptr->id;
18284                 ptr->id = rstate->lrd[id].orig_id;
18285                 SET_REG(ptr->id, lr->color);
18286                 display_triple(fp, ptr);
18287                 ptr->id = id;
18288
18289                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18290                         internal_error(state, ptr, "lr has no defs!");
18291                 }
18292                 if (info->need_edges) {
18293                         if (lr->defs) {
18294                                 struct live_range_def *lrd;
18295                                 fprintf(fp, "       range:");
18296                                 lrd = lr->defs;
18297                                 do {
18298                                         fprintf(fp, " %-10p", lrd->def);
18299                                         lrd = lrd->next;
18300                                 } while(lrd != lr->defs);
18301                                 fprintf(fp, "\n");
18302                         }
18303                         if (lr->edges > 0) {
18304                                 struct live_range_edge *edge;
18305                                 fprintf(fp, "       edges:");
18306                                 for(edge = lr->edges; edge; edge = edge->next) {
18307                                         struct live_range_def *lrd;
18308                                         lrd = edge->node->defs;
18309                                         do {
18310                                                 fprintf(fp, " %-10p", lrd->def);
18311                                                 lrd = lrd->next;
18312                                         } while(lrd != edge->node->defs);
18313                                         fprintf(fp, "|");
18314                                 }
18315                                 fprintf(fp, "\n");
18316                         }
18317                 }
18318                 /* Do a bunch of sanity checks */
18319                 valid_ins(state, ptr);
18320                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18321                         internal_error(state, ptr, "Invalid triple id: %d",
18322                                 ptr->id);
18323                 }
18324         }
18325         if (rb->out) {
18326                 struct triple_reg_set *out_set;
18327                 fprintf(fp, "       out:");
18328                 for(out_set = rb->out; out_set; out_set = out_set->next) {
18329                         fprintf(fp, " %-10p", out_set->member);
18330                 }
18331                 fprintf(fp, "\n");
18332         }
18333         fprintf(fp, "\n");
18334 }
18335
18336 static void print_interference_blocks(
18337         struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18338 {
18339         struct print_interference_block_info info;
18340         info.rstate = rstate;
18341         info.fp = fp;
18342         info.need_edges = need_edges;
18343         fprintf(fp, "\nlive variables by block\n");
18344         walk_blocks(state, &state->bb, print_interference_block, &info);
18345
18346 }
18347
18348 static unsigned regc_max_size(struct compile_state *state, int classes)
18349 {
18350         unsigned max_size;
18351         int i;
18352         max_size = 0;
18353         for(i = 0; i < MAX_REGC; i++) {
18354                 if (classes & (1 << i)) {
18355                         unsigned size;
18356                         size = arch_regc_size(state, i);
18357                         if (size > max_size) {
18358                                 max_size = size;
18359                         }
18360                 }
18361         }
18362         return max_size;
18363 }
18364
18365 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18366 {
18367         unsigned equivs[MAX_REG_EQUIVS];
18368         int i;
18369         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18370                 internal_error(state, 0, "invalid register");
18371         }
18372         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18373                 internal_error(state, 0, "invalid register");
18374         }
18375         arch_reg_equivs(state, equivs, reg1);
18376         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18377                 if (equivs[i] == reg2) {
18378                         return 1;
18379                 }
18380         }
18381         return 0;
18382 }
18383
18384 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18385 {
18386         unsigned equivs[MAX_REG_EQUIVS];
18387         int i;
18388         if (reg == REG_UNNEEDED) {
18389                 return;
18390         }
18391         arch_reg_equivs(state, equivs, reg);
18392         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18393                 used[equivs[i]] = 1;
18394         }
18395         return;
18396 }
18397
18398 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18399 {
18400         unsigned equivs[MAX_REG_EQUIVS];
18401         int i;
18402         if (reg == REG_UNNEEDED) {
18403                 return;
18404         }
18405         arch_reg_equivs(state, equivs, reg);
18406         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18407                 used[equivs[i]] += 1;
18408         }
18409         return;
18410 }
18411
18412 static unsigned int hash_live_edge(
18413         struct live_range *left, struct live_range *right)
18414 {
18415         unsigned int hash, val;
18416         unsigned long lval, rval;
18417         lval = ((unsigned long)left)/sizeof(struct live_range);
18418         rval = ((unsigned long)right)/sizeof(struct live_range);
18419         hash = 0;
18420         while(lval) {
18421                 val = lval & 0xff;
18422                 lval >>= 8;
18423                 hash = (hash *263) + val;
18424         }
18425         while(rval) {
18426                 val = rval & 0xff;
18427                 rval >>= 8;
18428                 hash = (hash *263) + val;
18429         }
18430         hash = hash & (LRE_HASH_SIZE - 1);
18431         return hash;
18432 }
18433
18434 static struct lre_hash **lre_probe(struct reg_state *rstate,
18435         struct live_range *left, struct live_range *right)
18436 {
18437         struct lre_hash **ptr;
18438         unsigned int index;
18439         /* Ensure left <= right */
18440         if (left > right) {
18441                 struct live_range *tmp;
18442                 tmp = left;
18443                 left = right;
18444                 right = tmp;
18445         }
18446         index = hash_live_edge(left, right);
18447         
18448         ptr = &rstate->hash[index];
18449         while(*ptr) {
18450                 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18451                         break;
18452                 }
18453                 ptr = &(*ptr)->next;
18454         }
18455         return ptr;
18456 }
18457
18458 static int interfere(struct reg_state *rstate,
18459         struct live_range *left, struct live_range *right)
18460 {
18461         struct lre_hash **ptr;
18462         ptr = lre_probe(rstate, left, right);
18463         return ptr && *ptr;
18464 }
18465
18466 static void add_live_edge(struct reg_state *rstate, 
18467         struct live_range *left, struct live_range *right)
18468 {
18469         /* FIXME the memory allocation overhead is noticeable here... */
18470         struct lre_hash **ptr, *new_hash;
18471         struct live_range_edge *edge;
18472
18473         if (left == right) {
18474                 return;
18475         }
18476         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18477                 return;
18478         }
18479         /* Ensure left <= right */
18480         if (left > right) {
18481                 struct live_range *tmp;
18482                 tmp = left;
18483                 left = right;
18484                 right = tmp;
18485         }
18486         ptr = lre_probe(rstate, left, right);
18487         if (*ptr) {
18488                 return;
18489         }
18490 #if 0
18491         fprintf(state->errout, "new_live_edge(%p, %p)\n",
18492                 left, right);
18493 #endif
18494         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18495         new_hash->next  = *ptr;
18496         new_hash->left  = left;
18497         new_hash->right = right;
18498         *ptr = new_hash;
18499
18500         edge = xmalloc(sizeof(*edge), "live_range_edge");
18501         edge->next   = left->edges;
18502         edge->node   = right;
18503         left->edges  = edge;
18504         left->degree += 1;
18505         
18506         edge = xmalloc(sizeof(*edge), "live_range_edge");
18507         edge->next    = right->edges;
18508         edge->node    = left;
18509         right->edges  = edge;
18510         right->degree += 1;
18511 }
18512
18513 static void remove_live_edge(struct reg_state *rstate,
18514         struct live_range *left, struct live_range *right)
18515 {
18516         struct live_range_edge *edge, **ptr;
18517         struct lre_hash **hptr, *entry;
18518         hptr = lre_probe(rstate, left, right);
18519         if (!hptr || !*hptr) {
18520                 return;
18521         }
18522         entry = *hptr;
18523         *hptr = entry->next;
18524         xfree(entry);
18525
18526         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18527                 edge = *ptr;
18528                 if (edge->node == right) {
18529                         *ptr = edge->next;
18530                         memset(edge, 0, sizeof(*edge));
18531                         xfree(edge);
18532                         right->degree--;
18533                         break;
18534                 }
18535         }
18536         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18537                 edge = *ptr;
18538                 if (edge->node == left) {
18539                         *ptr = edge->next;
18540                         memset(edge, 0, sizeof(*edge));
18541                         xfree(edge);
18542                         left->degree--;
18543                         break;
18544                 }
18545         }
18546 }
18547
18548 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18549 {
18550         struct live_range_edge *edge, *next;
18551         for(edge = range->edges; edge; edge = next) {
18552                 next = edge->next;
18553                 remove_live_edge(rstate, range, edge->node);
18554         }
18555 }
18556
18557 static void transfer_live_edges(struct reg_state *rstate, 
18558         struct live_range *dest, struct live_range *src)
18559 {
18560         struct live_range_edge *edge, *next;
18561         for(edge = src->edges; edge; edge = next) {
18562                 struct live_range *other;
18563                 next = edge->next;
18564                 other = edge->node;
18565                 remove_live_edge(rstate, src, other);
18566                 add_live_edge(rstate, dest, other);
18567         }
18568 }
18569
18570
18571 /* Interference graph...
18572  * 
18573  * new(n) --- Return a graph with n nodes but no edges.
18574  * add(g,x,y) --- Return a graph including g with an between x and y
18575  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18576  *                x and y in the graph g
18577  * degree(g, x) --- Return the degree of the node x in the graph g
18578  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18579  *
18580  * Implement with a hash table && a set of adjcency vectors.
18581  * The hash table supports constant time implementations of add and interfere.
18582  * The adjacency vectors support an efficient implementation of neighbors.
18583  */
18584
18585 /* 
18586  *     +---------------------------------------------------+
18587  *     |         +--------------+                          |
18588  *     v         v              |                          |
18589  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select 
18590  *
18591  * -- In simplify implment optimistic coloring... (No backtracking)
18592  * -- Implement Rematerialization it is the only form of spilling we can perform
18593  *    Essentially this means dropping a constant from a register because
18594  *    we can regenerate it later.
18595  *
18596  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18597  *     coalesce at phi points...
18598  * --- Bias coloring if at all possible do the coalesing a compile time.
18599  *
18600  *
18601  */
18602
18603 #if DEBUG_ROMCC_WARNING
18604 static void different_colored(
18605         struct compile_state *state, struct reg_state *rstate, 
18606         struct triple *parent, struct triple *ins)
18607 {
18608         struct live_range *lr;
18609         struct triple **expr;
18610         lr = rstate->lrd[ins->id].lr;
18611         expr = triple_rhs(state, ins, 0);
18612         for(;expr; expr = triple_rhs(state, ins, expr)) {
18613                 struct live_range *lr2;
18614                 if (!*expr || (*expr == parent) || (*expr == ins)) {
18615                         continue;
18616                 }
18617                 lr2 = rstate->lrd[(*expr)->id].lr;
18618                 if (lr->color == lr2->color) {
18619                         internal_error(state, ins, "live range too big");
18620                 }
18621         }
18622 }
18623 #endif
18624
18625 static struct live_range *coalesce_ranges(
18626         struct compile_state *state, struct reg_state *rstate,
18627         struct live_range *lr1, struct live_range *lr2)
18628 {
18629         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18630         unsigned color;
18631         unsigned classes;
18632         if (lr1 == lr2) {
18633                 return lr1;
18634         }
18635         if (!lr1->defs || !lr2->defs) {
18636                 internal_error(state, 0,
18637                         "cannot coalese dead live ranges");
18638         }
18639         if ((lr1->color == REG_UNNEEDED) ||
18640                 (lr2->color == REG_UNNEEDED)) {
18641                 internal_error(state, 0, 
18642                         "cannot coalesce live ranges without a possible color");
18643         }
18644         if ((lr1->color != lr2->color) &&
18645                 (lr1->color != REG_UNSET) &&
18646                 (lr2->color != REG_UNSET)) {
18647                 internal_error(state, lr1->defs->def, 
18648                         "cannot coalesce live ranges of different colors");
18649         }
18650         color = lr1->color;
18651         if (color == REG_UNSET) {
18652                 color = lr2->color;
18653         }
18654         classes = lr1->classes & lr2->classes;
18655         if (!classes) {
18656                 internal_error(state, lr1->defs->def,
18657                         "cannot coalesce live ranges with dissimilar register classes");
18658         }
18659         if (state->compiler->debug & DEBUG_COALESCING) {
18660                 FILE *fp = state->errout;
18661                 fprintf(fp, "coalescing:");
18662                 lrd = lr1->defs;
18663                 do {
18664                         fprintf(fp, " %p", lrd->def);
18665                         lrd = lrd->next;
18666                 } while(lrd != lr1->defs);
18667                 fprintf(fp, " |");
18668                 lrd = lr2->defs;
18669                 do {
18670                         fprintf(fp, " %p", lrd->def);
18671                         lrd = lrd->next;
18672                 } while(lrd != lr2->defs);
18673                 fprintf(fp, "\n");
18674         }
18675         /* If there is a clear dominate live range put it in lr1,
18676          * For purposes of this test phi functions are
18677          * considered dominated by the definitions that feed into
18678          * them. 
18679          */
18680         if ((lr1->defs->prev->def->op == OP_PHI) ||
18681                 ((lr2->defs->prev->def->op != OP_PHI) &&
18682                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18683                 struct live_range *tmp;
18684                 tmp = lr1;
18685                 lr1 = lr2;
18686                 lr2 = tmp;
18687         }
18688 #if 0
18689         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
18690                 fprintf(state->errout, "lr1 post\n");
18691         }
18692         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18693                 fprintf(state->errout, "lr1 pre\n");
18694         }
18695         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
18696                 fprintf(state->errout, "lr2 post\n");
18697         }
18698         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18699                 fprintf(state->errout, "lr2 pre\n");
18700         }
18701 #endif
18702 #if 0
18703         fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18704                 lr1->defs->def,
18705                 lr1->color,
18706                 lr2->defs->def,
18707                 lr2->color);
18708 #endif
18709         
18710         /* Append lr2 onto lr1 */
18711 #if DEBUG_ROMCC_WARNINGS
18712 #warning "FIXME should this be a merge instead of a splice?"
18713 #endif
18714         /* This FIXME item applies to the correctness of live_range_end 
18715          * and to the necessity of making multiple passes of coalesce_live_ranges.
18716          * A failure to find some coalesce opportunities in coaleace_live_ranges
18717          * does not impact the correct of the compiler just the efficiency with
18718          * which registers are allocated.
18719          */
18720         head = lr1->defs;
18721         mid1 = lr1->defs->prev;
18722         mid2 = lr2->defs;
18723         end  = lr2->defs->prev;
18724         
18725         head->prev = end;
18726         end->next  = head;
18727
18728         mid1->next = mid2;
18729         mid2->prev = mid1;
18730
18731         /* Fixup the live range in the added live range defs */
18732         lrd = head;
18733         do {
18734                 lrd->lr = lr1;
18735                 lrd = lrd->next;
18736         } while(lrd != head);
18737
18738         /* Mark lr2 as free. */
18739         lr2->defs = 0;
18740         lr2->color = REG_UNNEEDED;
18741         lr2->classes = 0;
18742
18743         if (!lr1->defs) {
18744                 internal_error(state, 0, "lr1->defs == 0 ?");
18745         }
18746
18747         lr1->color   = color;
18748         lr1->classes = classes;
18749
18750         /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18751         transfer_live_edges(rstate, lr1, lr2);
18752
18753         return lr1;
18754 }
18755
18756 static struct live_range_def *live_range_head(
18757         struct compile_state *state, struct live_range *lr,
18758         struct live_range_def *last)
18759 {
18760         struct live_range_def *result;
18761         result = 0;
18762         if (last == 0) {
18763                 result = lr->defs;
18764         }
18765         else if (!tdominates(state, lr->defs->def, last->next->def)) {
18766                 result = last->next;
18767         }
18768         return result;
18769 }
18770
18771 static struct live_range_def *live_range_end(
18772         struct compile_state *state, struct live_range *lr,
18773         struct live_range_def *last)
18774 {
18775         struct live_range_def *result;
18776         result = 0;
18777         if (last == 0) {
18778                 result = lr->defs->prev;
18779         }
18780         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18781                 result = last->prev;
18782         }
18783         return result;
18784 }
18785
18786
18787 static void initialize_live_ranges(
18788         struct compile_state *state, struct reg_state *rstate)
18789 {
18790         struct triple *ins, *first;
18791         size_t count, size;
18792         int i, j;
18793
18794         first = state->first;
18795         /* First count how many instructions I have.
18796          */
18797         count = count_triples(state);
18798         /* Potentially I need one live range definitions for each
18799          * instruction.
18800          */
18801         rstate->defs = count;
18802         /* Potentially I need one live range for each instruction
18803          * plus an extra for the dummy live range.
18804          */
18805         rstate->ranges = count + 1;
18806         size = sizeof(rstate->lrd[0]) * rstate->defs;
18807         rstate->lrd = xcmalloc(size, "live_range_def");
18808         size = sizeof(rstate->lr[0]) * rstate->ranges;
18809         rstate->lr  = xcmalloc(size, "live_range");
18810
18811         /* Setup the dummy live range */
18812         rstate->lr[0].classes = 0;
18813         rstate->lr[0].color = REG_UNSET;
18814         rstate->lr[0].defs = 0;
18815         i = j = 0;
18816         ins = first;
18817         do {
18818                 /* If the triple is a variable give it a live range */
18819                 if (triple_is_def(state, ins)) {
18820                         struct reg_info info;
18821                         /* Find the architecture specific color information */
18822                         info = find_def_color(state, ins);
18823                         i++;
18824                         rstate->lr[i].defs    = &rstate->lrd[j];
18825                         rstate->lr[i].color   = info.reg;
18826                         rstate->lr[i].classes = info.regcm;
18827                         rstate->lr[i].degree  = 0;
18828                         rstate->lrd[j].lr = &rstate->lr[i];
18829                 } 
18830                 /* Otherwise give the triple the dummy live range. */
18831                 else {
18832                         rstate->lrd[j].lr = &rstate->lr[0];
18833                 }
18834
18835                 /* Initalize the live_range_def */
18836                 rstate->lrd[j].next    = &rstate->lrd[j];
18837                 rstate->lrd[j].prev    = &rstate->lrd[j];
18838                 rstate->lrd[j].def     = ins;
18839                 rstate->lrd[j].orig_id = ins->id;
18840                 ins->id = j;
18841
18842                 j++;
18843                 ins = ins->next;
18844         } while(ins != first);
18845         rstate->ranges = i;
18846
18847         /* Make a second pass to handle achitecture specific register
18848          * constraints.
18849          */
18850         ins = first;
18851         do {
18852                 int zlhs, zrhs, i, j;
18853                 if (ins->id > rstate->defs) {
18854                         internal_error(state, ins, "bad id");
18855                 }
18856                 
18857                 /* Walk through the template of ins and coalesce live ranges */
18858                 zlhs = ins->lhs;
18859                 if ((zlhs == 0) && triple_is_def(state, ins)) {
18860                         zlhs = 1;
18861                 }
18862                 zrhs = ins->rhs;
18863
18864                 if (state->compiler->debug & DEBUG_COALESCING2) {
18865                         fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18866                                 ins, zlhs, zrhs);
18867                 }
18868
18869                 for(i = 0; i < zlhs; i++) {
18870                         struct reg_info linfo;
18871                         struct live_range_def *lhs;
18872                         linfo = arch_reg_lhs(state, ins, i);
18873                         if (linfo.reg < MAX_REGISTERS) {
18874                                 continue;
18875                         }
18876                         if (triple_is_def(state, ins)) {
18877                                 lhs = &rstate->lrd[ins->id];
18878                         } else {
18879                                 lhs = &rstate->lrd[LHS(ins, i)->id];
18880                         }
18881
18882                         if (state->compiler->debug & DEBUG_COALESCING2) {
18883                                 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18884                                         i, lhs, linfo.reg);
18885                         }
18886
18887                         for(j = 0; j < zrhs; j++) {
18888                                 struct reg_info rinfo;
18889                                 struct live_range_def *rhs;
18890                                 rinfo = arch_reg_rhs(state, ins, j);
18891                                 if (rinfo.reg < MAX_REGISTERS) {
18892                                         continue;
18893                                 }
18894                                 rhs = &rstate->lrd[RHS(ins, j)->id];
18895
18896                                 if (state->compiler->debug & DEBUG_COALESCING2) {
18897                                         fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18898                                                 j, rhs, rinfo.reg);
18899                                 }
18900
18901                                 if (rinfo.reg == linfo.reg) {
18902                                         coalesce_ranges(state, rstate, 
18903                                                 lhs->lr, rhs->lr);
18904                                 }
18905                         }
18906                 }
18907                 ins = ins->next;
18908         } while(ins != first);
18909 }
18910
18911 static void graph_ins(
18912         struct compile_state *state, 
18913         struct reg_block *blocks, struct triple_reg_set *live, 
18914         struct reg_block *rb, struct triple *ins, void *arg)
18915 {
18916         struct reg_state *rstate = arg;
18917         struct live_range *def;
18918         struct triple_reg_set *entry;
18919
18920         /* If the triple is not a definition
18921          * we do not have a definition to add to
18922          * the interference graph.
18923          */
18924         if (!triple_is_def(state, ins)) {
18925                 return;
18926         }
18927         def = rstate->lrd[ins->id].lr;
18928         
18929         /* Create an edge between ins and everything that is
18930          * alive, unless the live_range cannot share
18931          * a physical register with ins.
18932          */
18933         for(entry = live; entry; entry = entry->next) {
18934                 struct live_range *lr;
18935                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18936                         internal_error(state, 0, "bad entry?");
18937                 }
18938                 lr = rstate->lrd[entry->member->id].lr;
18939                 if (def == lr) {
18940                         continue;
18941                 }
18942                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18943                         continue;
18944                 }
18945                 add_live_edge(rstate, def, lr);
18946         }
18947         return;
18948 }
18949
18950 #if DEBUG_CONSISTENCY > 1
18951 static struct live_range *get_verify_live_range(
18952         struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18953 {
18954         struct live_range *lr;
18955         struct live_range_def *lrd;
18956         int ins_found;
18957         if ((ins->id < 0) || (ins->id > rstate->defs)) {
18958                 internal_error(state, ins, "bad ins?");
18959         }
18960         lr = rstate->lrd[ins->id].lr;
18961         ins_found = 0;
18962         lrd = lr->defs;
18963         do {
18964                 if (lrd->def == ins) {
18965                         ins_found = 1;
18966                 }
18967                 lrd = lrd->next;
18968         } while(lrd != lr->defs);
18969         if (!ins_found) {
18970                 internal_error(state, ins, "ins not in live range");
18971         }
18972         return lr;
18973 }
18974
18975 static void verify_graph_ins(
18976         struct compile_state *state, 
18977         struct reg_block *blocks, struct triple_reg_set *live, 
18978         struct reg_block *rb, struct triple *ins, void *arg)
18979 {
18980         struct reg_state *rstate = arg;
18981         struct triple_reg_set *entry1, *entry2;
18982
18983
18984         /* Compare live against edges and make certain the code is working */
18985         for(entry1 = live; entry1; entry1 = entry1->next) {
18986                 struct live_range *lr1;
18987                 lr1 = get_verify_live_range(state, rstate, entry1->member);
18988                 for(entry2 = live; entry2; entry2 = entry2->next) {
18989                         struct live_range *lr2;
18990                         struct live_range_edge *edge2;
18991                         int lr1_found;
18992                         int lr2_degree;
18993                         if (entry2 == entry1) {
18994                                 continue;
18995                         }
18996                         lr2 = get_verify_live_range(state, rstate, entry2->member);
18997                         if (lr1 == lr2) {
18998                                 internal_error(state, entry2->member, 
18999                                         "live range with 2 values simultaneously alive");
19000                         }
19001                         if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
19002                                 continue;
19003                         }
19004                         if (!interfere(rstate, lr1, lr2)) {
19005                                 internal_error(state, entry2->member, 
19006                                         "edges don't interfere?");
19007                         }
19008                                 
19009                         lr1_found = 0;
19010                         lr2_degree = 0;
19011                         for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
19012                                 lr2_degree++;
19013                                 if (edge2->node == lr1) {
19014                                         lr1_found = 1;
19015                                 }
19016                         }
19017                         if (lr2_degree != lr2->degree) {
19018                                 internal_error(state, entry2->member,
19019                                         "computed degree: %d does not match reported degree: %d\n",
19020                                         lr2_degree, lr2->degree);
19021                         }
19022                         if (!lr1_found) {
19023                                 internal_error(state, entry2->member, "missing edge");
19024                         }
19025                 }
19026         }
19027         return;
19028 }
19029 #endif
19030
19031 static void print_interference_ins(
19032         struct compile_state *state, 
19033         struct reg_block *blocks, struct triple_reg_set *live, 
19034         struct reg_block *rb, struct triple *ins, void *arg)
19035 {
19036         struct reg_state *rstate = arg;
19037         struct live_range *lr;
19038         unsigned id;
19039         FILE *fp = state->dbgout;
19040
19041         lr = rstate->lrd[ins->id].lr;
19042         id = ins->id;
19043         ins->id = rstate->lrd[id].orig_id;
19044         SET_REG(ins->id, lr->color);
19045         display_triple(state->dbgout, ins);
19046         ins->id = id;
19047
19048         if (lr->defs) {
19049                 struct live_range_def *lrd;
19050                 fprintf(fp, "       range:");
19051                 lrd = lr->defs;
19052                 do {
19053                         fprintf(fp, " %-10p", lrd->def);
19054                         lrd = lrd->next;
19055                 } while(lrd != lr->defs);
19056                 fprintf(fp, "\n");
19057         }
19058         if (live) {
19059                 struct triple_reg_set *entry;
19060                 fprintf(fp, "        live:");
19061                 for(entry = live; entry; entry = entry->next) {
19062                         fprintf(fp, " %-10p", entry->member);
19063                 }
19064                 fprintf(fp, "\n");
19065         }
19066         if (lr->edges) {
19067                 struct live_range_edge *entry;
19068                 fprintf(fp, "       edges:");
19069                 for(entry = lr->edges; entry; entry = entry->next) {
19070                         struct live_range_def *lrd;
19071                         lrd = entry->node->defs;
19072                         do {
19073                                 fprintf(fp, " %-10p", lrd->def);
19074                                 lrd = lrd->next;
19075                         } while(lrd != entry->node->defs);
19076                         fprintf(fp, "|");
19077                 }
19078                 fprintf(fp, "\n");
19079         }
19080         if (triple_is_branch(state, ins)) {
19081                 fprintf(fp, "\n");
19082         }
19083         return;
19084 }
19085
19086 static int coalesce_live_ranges(
19087         struct compile_state *state, struct reg_state *rstate)
19088 {
19089         /* At the point where a value is moved from one
19090          * register to another that value requires two
19091          * registers, thus increasing register pressure.
19092          * Live range coaleescing reduces the register
19093          * pressure by keeping a value in one register
19094          * longer.
19095          *
19096          * In the case of a phi function all paths leading
19097          * into it must be allocated to the same register
19098          * otherwise the phi function may not be removed.
19099          *
19100          * Forcing a value to stay in a single register
19101          * for an extended period of time does have
19102          * limitations when applied to non homogenous
19103          * register pool.  
19104          *
19105          * The two cases I have identified are:
19106          * 1) Two forced register assignments may
19107          *    collide.
19108          * 2) Registers may go unused because they
19109          *    are only good for storing the value
19110          *    and not manipulating it.
19111          *
19112          * Because of this I need to split live ranges,
19113          * even outside of the context of coalesced live
19114          * ranges.  The need to split live ranges does
19115          * impose some constraints on live range coalescing.
19116          *
19117          * - Live ranges may not be coalesced across phi
19118          *   functions.  This creates a 2 headed live
19119          *   range that cannot be sanely split.
19120          *
19121          * - phi functions (coalesced in initialize_live_ranges) 
19122          *   are handled as pre split live ranges so we will
19123          *   never attempt to split them.
19124          */
19125         int coalesced;
19126         int i;
19127
19128         coalesced = 0;
19129         for(i = 0; i <= rstate->ranges; i++) {
19130                 struct live_range *lr1;
19131                 struct live_range_def *lrd1;
19132                 lr1 = &rstate->lr[i];
19133                 if (!lr1->defs) {
19134                         continue;
19135                 }
19136                 lrd1 = live_range_end(state, lr1, 0);
19137                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19138                         struct triple_set *set;
19139                         if (lrd1->def->op != OP_COPY) {
19140                                 continue;
19141                         }
19142                         /* Skip copies that are the result of a live range split. */
19143                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19144                                 continue;
19145                         }
19146                         for(set = lrd1->def->use; set; set = set->next) {
19147                                 struct live_range_def *lrd2;
19148                                 struct live_range *lr2, *res;
19149
19150                                 lrd2 = &rstate->lrd[set->member->id];
19151
19152                                 /* Don't coalesce with instructions
19153                                  * that are the result of a live range
19154                                  * split.
19155                                  */
19156                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19157                                         continue;
19158                                 }
19159                                 lr2 = rstate->lrd[set->member->id].lr;
19160                                 if (lr1 == lr2) {
19161                                         continue;
19162                                 }
19163                                 if ((lr1->color != lr2->color) &&
19164                                         (lr1->color != REG_UNSET) &&
19165                                         (lr2->color != REG_UNSET)) {
19166                                         continue;
19167                                 }
19168                                 if ((lr1->classes & lr2->classes) == 0) {
19169                                         continue;
19170                                 }
19171                                 
19172                                 if (interfere(rstate, lr1, lr2)) {
19173                                         continue;
19174                                 }
19175
19176                                 res = coalesce_ranges(state, rstate, lr1, lr2);
19177                                 coalesced += 1;
19178                                 if (res != lr1) {
19179                                         goto next;
19180                                 }
19181                         }
19182                 }
19183         next:
19184                 ;
19185         }
19186         return coalesced;
19187 }
19188
19189
19190 static void fix_coalesce_conflicts(struct compile_state *state,
19191         struct reg_block *blocks, struct triple_reg_set *live,
19192         struct reg_block *rb, struct triple *ins, void *arg)
19193 {
19194         int *conflicts = arg;
19195         int zlhs, zrhs, i, j;
19196
19197         /* See if we have a mandatory coalesce operation between
19198          * a lhs and a rhs value.  If so and the rhs value is also
19199          * alive then this triple needs to be pre copied.  Otherwise
19200          * we would have two definitions in the same live range simultaneously
19201          * alive.
19202          */
19203         zlhs = ins->lhs;
19204         if ((zlhs == 0) && triple_is_def(state, ins)) {
19205                 zlhs = 1;
19206         }
19207         zrhs = ins->rhs;
19208         for(i = 0; i < zlhs; i++) {
19209                 struct reg_info linfo;
19210                 linfo = arch_reg_lhs(state, ins, i);
19211                 if (linfo.reg < MAX_REGISTERS) {
19212                         continue;
19213                 }
19214                 for(j = 0; j < zrhs; j++) {
19215                         struct reg_info rinfo;
19216                         struct triple *rhs;
19217                         struct triple_reg_set *set;
19218                         int found;
19219                         found = 0;
19220                         rinfo = arch_reg_rhs(state, ins, j);
19221                         if (rinfo.reg != linfo.reg) {
19222                                 continue;
19223                         }
19224                         rhs = RHS(ins, j);
19225                         for(set = live; set && !found; set = set->next) {
19226                                 if (set->member == rhs) {
19227                                         found = 1;
19228                                 }
19229                         }
19230                         if (found) {
19231                                 struct triple *copy;
19232                                 copy = pre_copy(state, ins, j);
19233                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19234                                 (*conflicts)++;
19235                         }
19236                 }
19237         }
19238         return;
19239 }
19240
19241 static int correct_coalesce_conflicts(
19242         struct compile_state *state, struct reg_block *blocks)
19243 {
19244         int conflicts;
19245         conflicts = 0;
19246         walk_variable_lifetimes(state, &state->bb, blocks, 
19247                 fix_coalesce_conflicts, &conflicts);
19248         return conflicts;
19249 }
19250
19251 static void replace_set_use(struct compile_state *state,
19252         struct triple_reg_set *head, struct triple *orig, struct triple *new)
19253 {
19254         struct triple_reg_set *set;
19255         for(set = head; set; set = set->next) {
19256                 if (set->member == orig) {
19257                         set->member = new;
19258                 }
19259         }
19260 }
19261
19262 static void replace_block_use(struct compile_state *state, 
19263         struct reg_block *blocks, struct triple *orig, struct triple *new)
19264 {
19265         int i;
19266 #if DEBUG_ROMCC_WARNINGS
19267 #warning "WISHLIST visit just those blocks that need it *"
19268 #endif
19269         for(i = 1; i <= state->bb.last_vertex; i++) {
19270                 struct reg_block *rb;
19271                 rb = &blocks[i];
19272                 replace_set_use(state, rb->in, orig, new);
19273                 replace_set_use(state, rb->out, orig, new);
19274         }
19275 }
19276
19277 static void color_instructions(struct compile_state *state)
19278 {
19279         struct triple *ins, *first;
19280         first = state->first;
19281         ins = first;
19282         do {
19283                 if (triple_is_def(state, ins)) {
19284                         struct reg_info info;
19285                         info = find_lhs_color(state, ins, 0);
19286                         if (info.reg >= MAX_REGISTERS) {
19287                                 info.reg = REG_UNSET;
19288                         }
19289                         SET_INFO(ins->id, info);
19290                 }
19291                 ins = ins->next;
19292         } while(ins != first);
19293 }
19294
19295 static struct reg_info read_lhs_color(
19296         struct compile_state *state, struct triple *ins, int index)
19297 {
19298         struct reg_info info;
19299         if ((index == 0) && triple_is_def(state, ins)) {
19300                 info.reg   = ID_REG(ins->id);
19301                 info.regcm = ID_REGCM(ins->id);
19302         }
19303         else if (index < ins->lhs) {
19304                 info = read_lhs_color(state, LHS(ins, index), 0);
19305         }
19306         else {
19307                 internal_error(state, ins, "Bad lhs %d", index);
19308                 info.reg = REG_UNSET;
19309                 info.regcm = 0;
19310         }
19311         return info;
19312 }
19313
19314 static struct triple *resolve_tangle(
19315         struct compile_state *state, struct triple *tangle)
19316 {
19317         struct reg_info info, uinfo;
19318         struct triple_set *set, *next;
19319         struct triple *copy;
19320
19321 #if DEBUG_ROMCC_WARNINGS
19322 #warning "WISHLIST recalculate all affected instructions colors"
19323 #endif
19324         info = find_lhs_color(state, tangle, 0);
19325         for(set = tangle->use; set; set = next) {
19326                 struct triple *user;
19327                 int i, zrhs;
19328                 next = set->next;
19329                 user = set->member;
19330                 zrhs = user->rhs;
19331                 for(i = 0; i < zrhs; i++) {
19332                         if (RHS(user, i) != tangle) {
19333                                 continue;
19334                         }
19335                         uinfo = find_rhs_post_color(state, user, i);
19336                         if (uinfo.reg == info.reg) {
19337                                 copy = pre_copy(state, user, i);
19338                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19339                                 SET_INFO(copy->id, uinfo);
19340                         }
19341                 }
19342         }
19343         copy = 0;
19344         uinfo = find_lhs_pre_color(state, tangle, 0);
19345         if (uinfo.reg == info.reg) {
19346                 struct reg_info linfo;
19347                 copy = post_copy(state, tangle);
19348                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19349                 linfo = find_lhs_color(state, copy, 0);
19350                 SET_INFO(copy->id, linfo);
19351         }
19352         info = find_lhs_color(state, tangle, 0);
19353         SET_INFO(tangle->id, info);
19354         
19355         return copy;
19356 }
19357
19358
19359 static void fix_tangles(struct compile_state *state,
19360         struct reg_block *blocks, struct triple_reg_set *live,
19361         struct reg_block *rb, struct triple *ins, void *arg)
19362 {
19363         int *tangles = arg;
19364         struct triple *tangle;
19365         do {
19366                 char used[MAX_REGISTERS];
19367                 struct triple_reg_set *set;
19368                 tangle = 0;
19369
19370                 /* Find out which registers have multiple uses at this point */
19371                 memset(used, 0, sizeof(used));
19372                 for(set = live; set; set = set->next) {
19373                         struct reg_info info;
19374                         info = read_lhs_color(state, set->member, 0);
19375                         if (info.reg == REG_UNSET) {
19376                                 continue;
19377                         }
19378                         reg_inc_used(state, used, info.reg);
19379                 }
19380                 
19381                 /* Now find the least dominated definition of a register in
19382                  * conflict I have seen so far.
19383                  */
19384                 for(set = live; set; set = set->next) {
19385                         struct reg_info info;
19386                         info = read_lhs_color(state, set->member, 0);
19387                         if (used[info.reg] < 2) {
19388                                 continue;
19389                         }
19390                         /* Changing copies that feed into phi functions
19391                          * is incorrect.
19392                          */
19393                         if (set->member->use && 
19394                                 (set->member->use->member->op == OP_PHI)) {
19395                                 continue;
19396                         }
19397                         if (!tangle || tdominates(state, set->member, tangle)) {
19398                                 tangle = set->member;
19399                         }
19400                 }
19401                 /* If I have found a tangle resolve it */
19402                 if (tangle) {
19403                         struct triple *post_copy;
19404                         (*tangles)++;
19405                         post_copy = resolve_tangle(state, tangle);
19406                         if (post_copy) {
19407                                 replace_block_use(state, blocks, tangle, post_copy);
19408                         }
19409                         if (post_copy && (tangle != ins)) {
19410                                 replace_set_use(state, live, tangle, post_copy);
19411                         }
19412                 }
19413         } while(tangle);
19414         return;
19415 }
19416
19417 static int correct_tangles(
19418         struct compile_state *state, struct reg_block *blocks)
19419 {
19420         int tangles;
19421         tangles = 0;
19422         color_instructions(state);
19423         walk_variable_lifetimes(state, &state->bb, blocks, 
19424                 fix_tangles, &tangles);
19425         return tangles;
19426 }
19427
19428
19429 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19430 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19431
19432 struct triple *find_constrained_def(
19433         struct compile_state *state, struct live_range *range, struct triple *constrained)
19434 {
19435         struct live_range_def *lrd, *lrd_next;
19436         lrd_next = range->defs;
19437         do {
19438                 struct reg_info info;
19439                 unsigned regcm;
19440
19441                 lrd = lrd_next;
19442                 lrd_next = lrd->next;
19443
19444                 regcm = arch_type_to_regcm(state, lrd->def->type);
19445                 info = find_lhs_color(state, lrd->def, 0);
19446                 regcm      = arch_regcm_reg_normalize(state, regcm);
19447                 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19448                 /* If the 2 register class masks are equal then
19449                  * the current register class is not constrained.
19450                  */
19451                 if (regcm == info.regcm) {
19452                         continue;
19453                 }
19454                 
19455                 /* If there is just one use.
19456                  * That use cannot accept a larger register class.
19457                  * There are no intervening definitions except
19458                  * definitions that feed into that use.
19459                  * Then a triple is not constrained.
19460                  * FIXME handle this case!
19461                  */
19462 #if DEBUG_ROMCC_WARNINGS
19463 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19464 #endif
19465                 
19466
19467                 /* Of the constrained live ranges deal with the
19468                  * least dominated one first.
19469                  */
19470                 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19471                         fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19472                                 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19473                 }
19474                 if (!constrained || 
19475                         tdominates(state, lrd->def, constrained))
19476                 {
19477                         constrained = lrd->def;
19478                 }
19479         } while(lrd_next != range->defs);
19480         return constrained;
19481 }
19482
19483 static int split_constrained_ranges(
19484         struct compile_state *state, struct reg_state *rstate, 
19485         struct live_range *range)
19486 {
19487         /* Walk through the edges in conflict and our current live
19488          * range, and find definitions that are more severly constrained
19489          * than they type of data they contain require.
19490          * 
19491          * Then pick one of those ranges and relax the constraints.
19492          */
19493         struct live_range_edge *edge;
19494         struct triple *constrained;
19495
19496         constrained = 0;
19497         for(edge = range->edges; edge; edge = edge->next) {
19498                 constrained = find_constrained_def(state, edge->node, constrained);
19499         }
19500 #if DEBUG_ROMCC_WARNINGS
19501 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19502 #endif
19503         if (!constrained) {
19504                 constrained = find_constrained_def(state, range, constrained);
19505         }
19506
19507         if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19508                 fprintf(state->errout, "constrained: ");
19509                 display_triple(state->errout, constrained);
19510         }
19511         if (constrained) {
19512                 ids_from_rstate(state, rstate);
19513                 cleanup_rstate(state, rstate);
19514                 resolve_tangle(state, constrained);
19515         }
19516         return !!constrained;
19517 }
19518         
19519 static int split_ranges(
19520         struct compile_state *state, struct reg_state *rstate,
19521         char *used, struct live_range *range)
19522 {
19523         int split;
19524         if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19525                 fprintf(state->errout, "split_ranges %d %s %p\n", 
19526                         rstate->passes, tops(range->defs->def->op), range->defs->def);
19527         }
19528         if ((range->color == REG_UNNEEDED) ||
19529                 (rstate->passes >= rstate->max_passes)) {
19530                 return 0;
19531         }
19532         split = split_constrained_ranges(state, rstate, range);
19533
19534         /* Ideally I would split the live range that will not be used
19535          * for the longest period of time in hopes that this will 
19536          * (a) allow me to spill a register or
19537          * (b) allow me to place a value in another register.
19538          *
19539          * So far I don't have a test case for this, the resolving
19540          * of mandatory constraints has solved all of my
19541          * know issues.  So I have choosen not to write any
19542          * code until I cat get a better feel for cases where
19543          * it would be useful to have.
19544          *
19545          */
19546 #if DEBUG_ROMCC_WARNINGS
19547 #warning "WISHLIST implement live range splitting..."
19548 #endif
19549         
19550         if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19551                 FILE *fp = state->errout;
19552                 print_interference_blocks(state, rstate, fp, 0);
19553                 print_dominators(state, fp, &state->bb);
19554         }
19555         return split;
19556 }
19557
19558 static FILE *cgdebug_fp(struct compile_state *state)
19559 {
19560         FILE *fp;
19561         fp = 0;
19562         if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19563                 fp = state->errout;
19564         }
19565         if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19566                 fp = state->dbgout;
19567         }
19568         return fp;
19569 }
19570
19571 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19572 {
19573         FILE *fp;
19574         fp = cgdebug_fp(state);
19575         if (fp) {
19576                 va_list args;
19577                 va_start(args, fmt);
19578                 vfprintf(fp, fmt, args);
19579                 va_end(args);
19580         }
19581 }
19582
19583 static void cgdebug_flush(struct compile_state *state)
19584 {
19585         FILE *fp;
19586         fp = cgdebug_fp(state);
19587         if (fp) {
19588                 fflush(fp);
19589         }
19590 }
19591
19592 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19593 {
19594         FILE *fp;
19595         fp = cgdebug_fp(state);
19596         if (fp) {
19597                 loc(fp, state, ins);
19598         }
19599 }
19600
19601 static int select_free_color(struct compile_state *state, 
19602         struct reg_state *rstate, struct live_range *range)
19603 {
19604         struct triple_set *entry;
19605         struct live_range_def *lrd;
19606         struct live_range_def *phi;
19607         struct live_range_edge *edge;
19608         char used[MAX_REGISTERS];
19609         struct triple **expr;
19610
19611         /* Instead of doing just the trivial color select here I try
19612          * a few extra things because a good color selection will help reduce
19613          * copies.
19614          */
19615
19616         /* Find the registers currently in use */
19617         memset(used, 0, sizeof(used));
19618         for(edge = range->edges; edge; edge = edge->next) {
19619                 if (edge->node->color == REG_UNSET) {
19620                         continue;
19621                 }
19622                 reg_fill_used(state, used, edge->node->color);
19623         }
19624
19625         if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19626                 int i;
19627                 i = 0;
19628                 for(edge = range->edges; edge; edge = edge->next) {
19629                         i++;
19630                 }
19631                 cgdebug_printf(state, "\n%s edges: %d", 
19632                         tops(range->defs->def->op), i);
19633                 cgdebug_loc(state, range->defs->def);
19634                 cgdebug_printf(state, "\n");
19635                 for(i = 0; i < MAX_REGISTERS; i++) {
19636                         if (used[i]) {
19637                                 cgdebug_printf(state, "used: %s\n",
19638                                         arch_reg_str(i));
19639                         }
19640                 }
19641         }       
19642
19643         /* If a color is already assigned see if it will work */
19644         if (range->color != REG_UNSET) {
19645                 struct live_range_def *lrd;
19646                 if (!used[range->color]) {
19647                         return 1;
19648                 }
19649                 for(edge = range->edges; edge; edge = edge->next) {
19650                         if (edge->node->color != range->color) {
19651                                 continue;
19652                         }
19653                         warning(state, edge->node->defs->def, "edge: ");
19654                         lrd = edge->node->defs;
19655                         do {
19656                                 warning(state, lrd->def, " %p %s",
19657                                         lrd->def, tops(lrd->def->op));
19658                                 lrd = lrd->next;
19659                         } while(lrd != edge->node->defs);
19660                 }
19661                 lrd = range->defs;
19662                 warning(state, range->defs->def, "def: ");
19663                 do {
19664                         warning(state, lrd->def, " %p %s",
19665                                 lrd->def, tops(lrd->def->op));
19666                         lrd = lrd->next;
19667                 } while(lrd != range->defs);
19668                 internal_error(state, range->defs->def,
19669                         "live range with already used color %s",
19670                         arch_reg_str(range->color));
19671         }
19672
19673         /* If I feed into an expression reuse it's color.
19674          * This should help remove copies in the case of 2 register instructions
19675          * and phi functions.
19676          */
19677         phi = 0;
19678         lrd = live_range_end(state, range, 0);
19679         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19680                 entry = lrd->def->use;
19681                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19682                         struct live_range_def *insd;
19683                         unsigned regcm;
19684                         insd = &rstate->lrd[entry->member->id];
19685                         if (insd->lr->defs == 0) {
19686                                 continue;
19687                         }
19688                         if (!phi && (insd->def->op == OP_PHI) &&
19689                                 !interfere(rstate, range, insd->lr)) {
19690                                 phi = insd;
19691                         }
19692                         if (insd->lr->color == REG_UNSET) {
19693                                 continue;
19694                         }
19695                         regcm = insd->lr->classes;
19696                         if (((regcm & range->classes) == 0) ||
19697                                 (used[insd->lr->color])) {
19698                                 continue;
19699                         }
19700                         if (interfere(rstate, range, insd->lr)) {
19701                                 continue;
19702                         }
19703                         range->color = insd->lr->color;
19704                 }
19705         }
19706         /* If I feed into a phi function reuse it's color or the color
19707          * of something else that feeds into the phi function.
19708          */
19709         if (phi) {
19710                 if (phi->lr->color != REG_UNSET) {
19711                         if (used[phi->lr->color]) {
19712                                 range->color = phi->lr->color;
19713                         }
19714                 }
19715                 else {
19716                         expr = triple_rhs(state, phi->def, 0);
19717                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19718                                 struct live_range *lr;
19719                                 unsigned regcm;
19720                                 if (!*expr) {
19721                                         continue;
19722                                 }
19723                                 lr = rstate->lrd[(*expr)->id].lr;
19724                                 if (lr->color == REG_UNSET) {
19725                                         continue;
19726                                 }
19727                                 regcm = lr->classes;
19728                                 if (((regcm & range->classes) == 0) ||
19729                                         (used[lr->color])) {
19730                                         continue;
19731                                 }
19732                                 if (interfere(rstate, range, lr)) {
19733                                         continue;
19734                                 }
19735                                 range->color = lr->color;
19736                         }
19737                 }
19738         }
19739         /* If I don't interfere with a rhs node reuse it's color */
19740         lrd = live_range_head(state, range, 0);
19741         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19742                 expr = triple_rhs(state, lrd->def, 0);
19743                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19744                         struct live_range *lr;
19745                         unsigned regcm;
19746                         if (!*expr) {
19747                                 continue;
19748                         }
19749                         lr = rstate->lrd[(*expr)->id].lr;
19750                         if (lr->color == REG_UNSET) {
19751                                 continue;
19752                         }
19753                         regcm = lr->classes;
19754                         if (((regcm & range->classes) == 0) ||
19755                                 (used[lr->color])) {
19756                                 continue;
19757                         }
19758                         if (interfere(rstate, range, lr)) {
19759                                 continue;
19760                         }
19761                         range->color = lr->color;
19762                         break;
19763                 }
19764         }
19765         /* If I have not opportunitically picked a useful color
19766          * pick the first color that is free.
19767          */
19768         if (range->color == REG_UNSET) {
19769                 range->color = 
19770                         arch_select_free_register(state, used, range->classes);
19771         }
19772         if (range->color == REG_UNSET) {
19773                 struct live_range_def *lrd;
19774                 int i;
19775                 if (split_ranges(state, rstate, used, range)) {
19776                         return 0;
19777                 }
19778                 for(edge = range->edges; edge; edge = edge->next) {
19779                         warning(state, edge->node->defs->def, "edge reg %s",
19780                                 arch_reg_str(edge->node->color));
19781                         lrd = edge->node->defs;
19782                         do {
19783                                 warning(state, lrd->def, " %s %p",
19784                                         tops(lrd->def->op), lrd->def);
19785                                 lrd = lrd->next;
19786                         } while(lrd != edge->node->defs);
19787                 }
19788                 warning(state, range->defs->def, "range: ");
19789                 lrd = range->defs;
19790                 do {
19791                         warning(state, lrd->def, " %s %p",
19792                                 tops(lrd->def->op), lrd->def);
19793                         lrd = lrd->next;
19794                 } while(lrd != range->defs);
19795                         
19796                 warning(state, range->defs->def, "classes: %x",
19797                         range->classes);
19798                 for(i = 0; i < MAX_REGISTERS; i++) {
19799                         if (used[i]) {
19800                                 warning(state, range->defs->def, "used: %s",
19801                                         arch_reg_str(i));
19802                         }
19803                 }
19804                 error(state, range->defs->def, "too few registers");
19805         }
19806         range->classes &= arch_reg_regcm(state, range->color);
19807         if ((range->color == REG_UNSET) || (range->classes == 0)) {
19808                 internal_error(state, range->defs->def, "select_free_color did not?");
19809         }
19810         return 1;
19811 }
19812
19813 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19814 {
19815         int colored;
19816         struct live_range_edge *edge;
19817         struct live_range *range;
19818         if (rstate->low) {
19819                 cgdebug_printf(state, "Lo: ");
19820                 range = rstate->low;
19821                 if (*range->group_prev != range) {
19822                         internal_error(state, 0, "lo: *prev != range?");
19823                 }
19824                 *range->group_prev = range->group_next;
19825                 if (range->group_next) {
19826                         range->group_next->group_prev = range->group_prev;
19827                 }
19828                 if (&range->group_next == rstate->low_tail) {
19829                         rstate->low_tail = range->group_prev;
19830                 }
19831                 if (rstate->low == range) {
19832                         internal_error(state, 0, "low: next != prev?");
19833                 }
19834         }
19835         else if (rstate->high) {
19836                 cgdebug_printf(state, "Hi: ");
19837                 range = rstate->high;
19838                 if (*range->group_prev != range) {
19839                         internal_error(state, 0, "hi: *prev != range?");
19840                 }
19841                 *range->group_prev = range->group_next;
19842                 if (range->group_next) {
19843                         range->group_next->group_prev = range->group_prev;
19844                 }
19845                 if (&range->group_next == rstate->high_tail) {
19846                         rstate->high_tail = range->group_prev;
19847                 }
19848                 if (rstate->high == range) {
19849                         internal_error(state, 0, "high: next != prev?");
19850                 }
19851         }
19852         else {
19853                 return 1;
19854         }
19855         cgdebug_printf(state, " %d\n", range - rstate->lr);
19856         range->group_prev = 0;
19857         for(edge = range->edges; edge; edge = edge->next) {
19858                 struct live_range *node;
19859                 node = edge->node;
19860                 /* Move nodes from the high to the low list */
19861                 if (node->group_prev && (node->color == REG_UNSET) &&
19862                         (node->degree == regc_max_size(state, node->classes))) {
19863                         if (*node->group_prev != node) {
19864                                 internal_error(state, 0, "move: *prev != node?");
19865                         }
19866                         *node->group_prev = node->group_next;
19867                         if (node->group_next) {
19868                                 node->group_next->group_prev = node->group_prev;
19869                         }
19870                         if (&node->group_next == rstate->high_tail) {
19871                                 rstate->high_tail = node->group_prev;
19872                         }
19873                         cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19874                         node->group_prev  = rstate->low_tail;
19875                         node->group_next  = 0;
19876                         *rstate->low_tail = node;
19877                         rstate->low_tail  = &node->group_next;
19878                         if (*node->group_prev != node) {
19879                                 internal_error(state, 0, "move2: *prev != node?");
19880                         }
19881                 }
19882                 node->degree -= 1;
19883         }
19884         colored = color_graph(state, rstate);
19885         if (colored) {
19886                 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19887                 cgdebug_loc(state, range->defs->def);
19888                 cgdebug_flush(state);
19889                 colored = select_free_color(state, rstate, range);
19890                 if (colored) {
19891                         cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19892                 }
19893         }
19894         return colored;
19895 }
19896
19897 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19898 {
19899         struct live_range *lr;
19900         struct live_range_edge *edge;
19901         struct triple *ins, *first;
19902         char used[MAX_REGISTERS];
19903         first = state->first;
19904         ins = first;
19905         do {
19906                 if (triple_is_def(state, ins)) {
19907                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
19908                                 internal_error(state, ins, 
19909                                         "triple without a live range def");
19910                         }
19911                         lr = rstate->lrd[ins->id].lr;
19912                         if (lr->color == REG_UNSET) {
19913                                 internal_error(state, ins,
19914                                         "triple without a color");
19915                         }
19916                         /* Find the registers used by the edges */
19917                         memset(used, 0, sizeof(used));
19918                         for(edge = lr->edges; edge; edge = edge->next) {
19919                                 if (edge->node->color == REG_UNSET) {
19920                                         internal_error(state, 0,
19921                                                 "live range without a color");
19922                         }
19923                                 reg_fill_used(state, used, edge->node->color);
19924                         }
19925                         if (used[lr->color]) {
19926                                 internal_error(state, ins,
19927                                         "triple with already used color");
19928                         }
19929                 }
19930                 ins = ins->next;
19931         } while(ins != first);
19932 }
19933
19934 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19935 {
19936         struct live_range_def *lrd;
19937         struct live_range *lr;
19938         struct triple *first, *ins;
19939         first = state->first;
19940         ins = first;
19941         do {
19942                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19943                         internal_error(state, ins, 
19944                                 "triple without a live range");
19945                 }
19946                 lrd = &rstate->lrd[ins->id];
19947                 lr = lrd->lr;
19948                 ins->id = lrd->orig_id;
19949                 SET_REG(ins->id, lr->color);
19950                 ins = ins->next;
19951         } while (ins != first);
19952 }
19953
19954 static struct live_range *merge_sort_lr(
19955         struct live_range *first, struct live_range *last)
19956 {
19957         struct live_range *mid, *join, **join_tail, *pick;
19958         size_t size;
19959         size = (last - first) + 1;
19960         if (size >= 2) {
19961                 mid = first + size/2;
19962                 first = merge_sort_lr(first, mid -1);
19963                 mid   = merge_sort_lr(mid, last);
19964                 
19965                 join = 0;
19966                 join_tail = &join;
19967                 /* merge the two lists */
19968                 while(first && mid) {
19969                         if ((first->degree < mid->degree) ||
19970                                 ((first->degree == mid->degree) &&
19971                                         (first->length < mid->length))) {
19972                                 pick = first;
19973                                 first = first->group_next;
19974                                 if (first) {
19975                                         first->group_prev = 0;
19976                                 }
19977                         }
19978                         else {
19979                                 pick = mid;
19980                                 mid = mid->group_next;
19981                                 if (mid) {
19982                                         mid->group_prev = 0;
19983                                 }
19984                         }
19985                         pick->group_next = 0;
19986                         pick->group_prev = join_tail;
19987                         *join_tail = pick;
19988                         join_tail = &pick->group_next;
19989                 }
19990                 /* Splice the remaining list */
19991                 pick = (first)? first : mid;
19992                 *join_tail = pick;
19993                 if (pick) { 
19994                         pick->group_prev = join_tail;
19995                 }
19996         }
19997         else {
19998                 if (!first->defs) {
19999                         first = 0;
20000                 }
20001                 join = first;
20002         }
20003         return join;
20004 }
20005
20006 static void ids_from_rstate(struct compile_state *state, 
20007         struct reg_state *rstate)
20008 {
20009         struct triple *ins, *first;
20010         if (!rstate->defs) {
20011                 return;
20012         }
20013         /* Display the graph if desired */
20014         if (state->compiler->debug & DEBUG_INTERFERENCE) {
20015                 FILE *fp = state->dbgout;
20016                 print_interference_blocks(state, rstate, fp, 0);
20017                 print_control_flow(state, fp, &state->bb);
20018                 fflush(fp);
20019         }
20020         first = state->first;
20021         ins = first;
20022         do {
20023                 if (ins->id) {
20024                         struct live_range_def *lrd;
20025                         lrd = &rstate->lrd[ins->id];
20026                         ins->id = lrd->orig_id;
20027                 }
20028                 ins = ins->next;
20029         } while(ins != first);
20030 }
20031
20032 static void cleanup_live_edges(struct reg_state *rstate)
20033 {
20034         int i;
20035         /* Free the edges on each node */
20036         for(i = 1; i <= rstate->ranges; i++) {
20037                 remove_live_edges(rstate, &rstate->lr[i]);
20038         }
20039 }
20040
20041 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
20042 {
20043         cleanup_live_edges(rstate);
20044         xfree(rstate->lrd);
20045         xfree(rstate->lr);
20046
20047         /* Free the variable lifetime information */
20048         if (rstate->blocks) {
20049                 free_variable_lifetimes(state, &state->bb, rstate->blocks);
20050         }
20051         rstate->defs = 0;
20052         rstate->ranges = 0;
20053         rstate->lrd = 0;
20054         rstate->lr = 0;
20055         rstate->blocks = 0;
20056 }
20057
20058 static void verify_consistency(struct compile_state *state);
20059 static void allocate_registers(struct compile_state *state)
20060 {
20061         struct reg_state rstate;
20062         int colored;
20063
20064         /* Clear out the reg_state */
20065         memset(&rstate, 0, sizeof(rstate));
20066         rstate.max_passes = state->compiler->max_allocation_passes;
20067
20068         do {
20069                 struct live_range **point, **next;
20070                 int conflicts;
20071                 int tangles;
20072                 int coalesced;
20073
20074                 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
20075                         FILE *fp = state->errout;
20076                         fprintf(fp, "pass: %d\n", rstate.passes);
20077                         fflush(fp);
20078                 }
20079
20080                 /* Restore ids */
20081                 ids_from_rstate(state, &rstate);
20082
20083                 /* Cleanup the temporary data structures */
20084                 cleanup_rstate(state, &rstate);
20085
20086                 /* Compute the variable lifetimes */
20087                 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20088
20089                 /* Fix invalid mandatory live range coalesce conflicts */
20090                 conflicts = correct_coalesce_conflicts(state, rstate.blocks);
20091
20092                 /* Fix two simultaneous uses of the same register.
20093                  * In a few pathlogical cases a partial untangle moves
20094                  * the tangle to a part of the graph we won't revisit.
20095                  * So we keep looping until we have no more tangle fixes
20096                  * to apply.
20097                  */
20098                 do {
20099                         tangles = correct_tangles(state, rstate.blocks);
20100                 } while(tangles);
20101
20102                 
20103                 print_blocks(state, "resolve_tangles", state->dbgout);
20104                 verify_consistency(state);
20105                 
20106                 /* Allocate and initialize the live ranges */
20107                 initialize_live_ranges(state, &rstate);
20108
20109                 /* Note currently doing coalescing in a loop appears to 
20110                  * buys me nothing.  The code is left this way in case
20111                  * there is some value in it.  Or if a future bugfix
20112                  * yields some benefit.
20113                  */
20114                 do {
20115                         if (state->compiler->debug & DEBUG_COALESCING) {
20116                                 fprintf(state->errout, "coalescing\n");
20117                         }
20118
20119                         /* Remove any previous live edge calculations */
20120                         cleanup_live_edges(&rstate);
20121
20122                         /* Compute the interference graph */
20123                         walk_variable_lifetimes(
20124                                 state, &state->bb, rstate.blocks, 
20125                                 graph_ins, &rstate);
20126                         
20127                         /* Display the interference graph if desired */
20128                         if (state->compiler->debug & DEBUG_INTERFERENCE) {
20129                                 print_interference_blocks(state, &rstate, state->dbgout, 1);
20130                                 fprintf(state->dbgout, "\nlive variables by instruction\n");
20131                                 walk_variable_lifetimes(
20132                                         state, &state->bb, rstate.blocks, 
20133                                         print_interference_ins, &rstate);
20134                         }
20135                         
20136                         coalesced = coalesce_live_ranges(state, &rstate);
20137
20138                         if (state->compiler->debug & DEBUG_COALESCING) {
20139                                 fprintf(state->errout, "coalesced: %d\n", coalesced);
20140                         }
20141                 } while(coalesced);
20142
20143 #if DEBUG_CONSISTENCY > 1
20144 # if 0
20145                 fprintf(state->errout, "verify_graph_ins...\n");
20146 # endif
20147                 /* Verify the interference graph */
20148                 walk_variable_lifetimes(
20149                         state, &state->bb, rstate.blocks, 
20150                         verify_graph_ins, &rstate);
20151 # if 0
20152                 fprintf(state->errout, "verify_graph_ins done\n");
20153 #endif
20154 #endif
20155                         
20156                 /* Build the groups low and high.  But with the nodes
20157                  * first sorted by degree order.
20158                  */
20159                 rstate.low_tail  = &rstate.low;
20160                 rstate.high_tail = &rstate.high;
20161                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20162                 if (rstate.high) {
20163                         rstate.high->group_prev = &rstate.high;
20164                 }
20165                 for(point = &rstate.high; *point; point = &(*point)->group_next)
20166                         ;
20167                 rstate.high_tail = point;
20168                 /* Walk through the high list and move everything that needs
20169                  * to be onto low.
20170                  */
20171                 for(point = &rstate.high; *point; point = next) {
20172                         struct live_range *range;
20173                         next = &(*point)->group_next;
20174                         range = *point;
20175                         
20176                         /* If it has a low degree or it already has a color
20177                          * place the node in low.
20178                          */
20179                         if ((range->degree < regc_max_size(state, range->classes)) ||
20180                                 (range->color != REG_UNSET)) {
20181                                 cgdebug_printf(state, "Lo: %5d degree %5d%s\n", 
20182                                         range - rstate.lr, range->degree,
20183                                         (range->color != REG_UNSET) ? " (colored)": "");
20184                                 *range->group_prev = range->group_next;
20185                                 if (range->group_next) {
20186                                         range->group_next->group_prev = range->group_prev;
20187                                 }
20188                                 if (&range->group_next == rstate.high_tail) {
20189                                         rstate.high_tail = range->group_prev;
20190                                 }
20191                                 range->group_prev  = rstate.low_tail;
20192                                 range->group_next  = 0;
20193                                 *rstate.low_tail   = range;
20194                                 rstate.low_tail    = &range->group_next;
20195                                 next = point;
20196                         }
20197                         else {
20198                                 cgdebug_printf(state, "hi: %5d degree %5d%s\n", 
20199                                         range - rstate.lr, range->degree,
20200                                         (range->color != REG_UNSET) ? " (colored)": "");
20201                         }
20202                 }
20203                 /* Color the live_ranges */
20204                 colored = color_graph(state, &rstate);
20205                 rstate.passes++;
20206         } while (!colored);
20207
20208         /* Verify the graph was properly colored */
20209         verify_colors(state, &rstate);
20210
20211         /* Move the colors from the graph to the triples */
20212         color_triples(state, &rstate);
20213
20214         /* Cleanup the temporary data structures */
20215         cleanup_rstate(state, &rstate);
20216
20217         /* Display the new graph */
20218         print_blocks(state, __func__, state->dbgout);
20219 }
20220
20221 /* Sparce Conditional Constant Propogation
20222  * =========================================
20223  */
20224 struct ssa_edge;
20225 struct flow_block;
20226 struct lattice_node {
20227         unsigned old_id;
20228         struct triple *def;
20229         struct ssa_edge *out;
20230         struct flow_block *fblock;
20231         struct triple *val;
20232         /* lattice high   val == def
20233          * lattice const  is_const(val)
20234          * lattice low    other
20235          */
20236 };
20237 struct ssa_edge {
20238         struct lattice_node *src;
20239         struct lattice_node *dst;
20240         struct ssa_edge *work_next;
20241         struct ssa_edge *work_prev;
20242         struct ssa_edge *out_next;
20243 };
20244 struct flow_edge {
20245         struct flow_block *src;
20246         struct flow_block *dst;
20247         struct flow_edge *work_next;
20248         struct flow_edge *work_prev;
20249         struct flow_edge *in_next;
20250         struct flow_edge *out_next;
20251         int executable;
20252 };
20253 #define MAX_FLOW_BLOCK_EDGES 3
20254 struct flow_block {
20255         struct block *block;
20256         struct flow_edge *in;
20257         struct flow_edge *out;
20258         struct flow_edge *edges;
20259 };
20260
20261 struct scc_state {
20262         int ins_count;
20263         struct lattice_node *lattice;
20264         struct ssa_edge     *ssa_edges;
20265         struct flow_block   *flow_blocks;
20266         struct flow_edge    *flow_work_list;
20267         struct ssa_edge     *ssa_work_list;
20268 };
20269
20270
20271 static int is_scc_const(struct compile_state *state, struct triple *ins)
20272 {
20273         return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20274 }
20275
20276 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20277 {
20278         return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20279 }
20280
20281 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20282 {
20283         return is_scc_const(state, lnode->val);
20284 }
20285
20286 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20287 {
20288         return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20289 }
20290
20291 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc, 
20292         struct flow_edge *fedge)
20293 {
20294         if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20295                 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20296                         fedge,
20297                         fedge->src->block?fedge->src->block->last->id: 0,
20298                         fedge->dst->block?fedge->dst->block->first->id: 0);
20299         }
20300         if ((fedge == scc->flow_work_list) ||
20301                 (fedge->work_next != fedge) ||
20302                 (fedge->work_prev != fedge)) {
20303
20304                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20305                         fprintf(state->errout, "dupped fedge: %p\n",
20306                                 fedge);
20307                 }
20308                 return;
20309         }
20310         if (!scc->flow_work_list) {
20311                 scc->flow_work_list = fedge;
20312                 fedge->work_next = fedge->work_prev = fedge;
20313         }
20314         else {
20315                 struct flow_edge *ftail;
20316                 ftail = scc->flow_work_list->work_prev;
20317                 fedge->work_next = ftail->work_next;
20318                 fedge->work_prev = ftail;
20319                 fedge->work_next->work_prev = fedge;
20320                 fedge->work_prev->work_next = fedge;
20321         }
20322 }
20323
20324 static struct flow_edge *scc_next_fedge(
20325         struct compile_state *state, struct scc_state *scc)
20326 {
20327         struct flow_edge *fedge;
20328         fedge = scc->flow_work_list;
20329         if (fedge) {
20330                 fedge->work_next->work_prev = fedge->work_prev;
20331                 fedge->work_prev->work_next = fedge->work_next;
20332                 if (fedge->work_next != fedge) {
20333                         scc->flow_work_list = fedge->work_next;
20334                 } else {
20335                         scc->flow_work_list = 0;
20336                 }
20337                 fedge->work_next = fedge->work_prev = fedge;
20338         }
20339         return fedge;
20340 }
20341
20342 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20343         struct ssa_edge *sedge)
20344 {
20345         if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20346                 fprintf(state->errout, "adding sedge: %5ld (%4d -> %5d)\n",
20347                         (long)(sedge - scc->ssa_edges),
20348                         sedge->src->def->id,
20349                         sedge->dst->def->id);
20350         }
20351         if ((sedge == scc->ssa_work_list) ||
20352                 (sedge->work_next != sedge) ||
20353                 (sedge->work_prev != sedge)) {
20354
20355                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20356                         fprintf(state->errout, "dupped sedge: %5ld\n",
20357                                 (long)(sedge - scc->ssa_edges));
20358                 }
20359                 return;
20360         }
20361         if (!scc->ssa_work_list) {
20362                 scc->ssa_work_list = sedge;
20363                 sedge->work_next = sedge->work_prev = sedge;
20364         }
20365         else {
20366                 struct ssa_edge *stail;
20367                 stail = scc->ssa_work_list->work_prev;
20368                 sedge->work_next = stail->work_next;
20369                 sedge->work_prev = stail;
20370                 sedge->work_next->work_prev = sedge;
20371                 sedge->work_prev->work_next = sedge;
20372         }
20373 }
20374
20375 static struct ssa_edge *scc_next_sedge(
20376         struct compile_state *state, struct scc_state *scc)
20377 {
20378         struct ssa_edge *sedge;
20379         sedge = scc->ssa_work_list;
20380         if (sedge) {
20381                 sedge->work_next->work_prev = sedge->work_prev;
20382                 sedge->work_prev->work_next = sedge->work_next;
20383                 if (sedge->work_next != sedge) {
20384                         scc->ssa_work_list = sedge->work_next;
20385                 } else {
20386                         scc->ssa_work_list = 0;
20387                 }
20388                 sedge->work_next = sedge->work_prev = sedge;
20389         }
20390         return sedge;
20391 }
20392
20393 static void initialize_scc_state(
20394         struct compile_state *state, struct scc_state *scc)
20395 {
20396         int ins_count, ssa_edge_count;
20397         int ins_index, ssa_edge_index, fblock_index;
20398         struct triple *first, *ins;
20399         struct block *block;
20400         struct flow_block *fblock;
20401
20402         memset(scc, 0, sizeof(*scc));
20403
20404         /* Inialize pass zero find out how much memory we need */
20405         first = state->first;
20406         ins = first;
20407         ins_count = ssa_edge_count = 0;
20408         do {
20409                 struct triple_set *edge;
20410                 ins_count += 1;
20411                 for(edge = ins->use; edge; edge = edge->next) {
20412                         ssa_edge_count++;
20413                 }
20414                 ins = ins->next;
20415         } while(ins != first);
20416         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20417                 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20418                         ins_count, ssa_edge_count, state->bb.last_vertex);
20419         }
20420         scc->ins_count   = ins_count;
20421         scc->lattice     = 
20422                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20423         scc->ssa_edges   = 
20424                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20425         scc->flow_blocks = 
20426                 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1), 
20427                         "flow_blocks");
20428
20429         /* Initialize pass one collect up the nodes */
20430         fblock = 0;
20431         block = 0;
20432         ins_index = ssa_edge_index = fblock_index = 0;
20433         ins = first;
20434         do {
20435                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20436                         block = ins->u.block;
20437                         if (!block) {
20438                                 internal_error(state, ins, "label without block");
20439                         }
20440                         fblock_index += 1;
20441                         block->vertex = fblock_index;
20442                         fblock = &scc->flow_blocks[fblock_index];
20443                         fblock->block = block;
20444                         fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20445                                 "flow_edges");
20446                 }
20447                 {
20448                         struct lattice_node *lnode;
20449                         ins_index += 1;
20450                         lnode = &scc->lattice[ins_index];
20451                         lnode->def = ins;
20452                         lnode->out = 0;
20453                         lnode->fblock = fblock;
20454                         lnode->val = ins; /* LATTICE HIGH */
20455                         if (lnode->val->op == OP_UNKNOWNVAL) {
20456                                 lnode->val = 0; /* LATTICE LOW by definition */
20457                         }
20458                         lnode->old_id = ins->id;
20459                         ins->id = ins_index;
20460                 }
20461                 ins = ins->next;
20462         } while(ins != first);
20463         /* Initialize pass two collect up the edges */
20464         block = 0;
20465         fblock = 0;
20466         ins = first;
20467         do {
20468                 {
20469                         struct triple_set *edge;
20470                         struct ssa_edge **stail;
20471                         struct lattice_node *lnode;
20472                         lnode = &scc->lattice[ins->id];
20473                         lnode->out = 0;
20474                         stail = &lnode->out;
20475                         for(edge = ins->use; edge; edge = edge->next) {
20476                                 struct ssa_edge *sedge;
20477                                 ssa_edge_index += 1;
20478                                 sedge = &scc->ssa_edges[ssa_edge_index];
20479                                 *stail = sedge;
20480                                 stail = &sedge->out_next;
20481                                 sedge->src = lnode;
20482                                 sedge->dst = &scc->lattice[edge->member->id];
20483                                 sedge->work_next = sedge->work_prev = sedge;
20484                                 sedge->out_next = 0;
20485                         }
20486                 }
20487                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20488                         struct flow_edge *fedge, **ftail;
20489                         struct block_set *bedge;
20490                         block = ins->u.block;
20491                         fblock = &scc->flow_blocks[block->vertex];
20492                         fblock->in = 0;
20493                         fblock->out = 0;
20494                         ftail = &fblock->out;
20495
20496                         fedge = fblock->edges;
20497                         bedge = block->edges;
20498                         for(; bedge; bedge = bedge->next, fedge++) {
20499                                 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20500                                 if (fedge->dst->block != bedge->member) {
20501                                         internal_error(state, 0, "block mismatch");
20502                                 }
20503                                 *ftail = fedge;
20504                                 ftail = &fedge->out_next;
20505                                 fedge->out_next = 0;
20506                         }
20507                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20508                                 fedge->src = fblock;
20509                                 fedge->work_next = fedge->work_prev = fedge;
20510                                 fedge->executable = 0;
20511                         }
20512                 }
20513                 ins = ins->next;
20514         } while (ins != first);
20515         block = 0;
20516         fblock = 0;
20517         ins = first;
20518         do {
20519                 if ((ins->op  == OP_LABEL) && (block != ins->u.block)) {
20520                         struct flow_edge **ftail;
20521                         struct block_set *bedge;
20522                         block = ins->u.block;
20523                         fblock = &scc->flow_blocks[block->vertex];
20524                         ftail = &fblock->in;
20525                         for(bedge = block->use; bedge; bedge = bedge->next) {
20526                                 struct block *src_block;
20527                                 struct flow_block *sfblock;
20528                                 struct flow_edge *sfedge;
20529                                 src_block = bedge->member;
20530                                 sfblock = &scc->flow_blocks[src_block->vertex];
20531                                 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20532                                         if (sfedge->dst == fblock) {
20533                                                 break;
20534                                         }
20535                                 }
20536                                 if (!sfedge) {
20537                                         internal_error(state, 0, "edge mismatch");
20538                                 }
20539                                 *ftail = sfedge;
20540                                 ftail = &sfedge->in_next;
20541                                 sfedge->in_next = 0;
20542                         }
20543                 }
20544                 ins = ins->next;
20545         } while(ins != first);
20546         /* Setup a dummy block 0 as a node above the start node */
20547         {
20548                 struct flow_block *fblock, *dst;
20549                 struct flow_edge *fedge;
20550                 fblock = &scc->flow_blocks[0];
20551                 fblock->block = 0;
20552                 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20553                 fblock->in = 0;
20554                 fblock->out = fblock->edges;
20555                 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20556                 fedge = fblock->edges;
20557                 fedge->src        = fblock;
20558                 fedge->dst        = dst;
20559                 fedge->work_next  = fedge;
20560                 fedge->work_prev  = fedge;
20561                 fedge->in_next    = fedge->dst->in;
20562                 fedge->out_next   = 0;
20563                 fedge->executable = 0;
20564                 fedge->dst->in = fedge;
20565                 
20566                 /* Initialize the work lists */
20567                 scc->flow_work_list = 0;
20568                 scc->ssa_work_list  = 0;
20569                 scc_add_fedge(state, scc, fedge);
20570         }
20571         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20572                 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20573                         ins_index, ssa_edge_index, fblock_index);
20574         }
20575 }
20576
20577         
20578 static void free_scc_state(
20579         struct compile_state *state, struct scc_state *scc)
20580 {
20581         int i;
20582         for(i = 0; i < state->bb.last_vertex + 1; i++) {
20583                 struct flow_block *fblock;
20584                 fblock = &scc->flow_blocks[i];
20585                 if (fblock->edges) {
20586                         xfree(fblock->edges);
20587                         fblock->edges = 0;
20588                 }
20589         }
20590         xfree(scc->flow_blocks);
20591         xfree(scc->ssa_edges);
20592         xfree(scc->lattice);
20593         
20594 }
20595
20596 static struct lattice_node *triple_to_lattice(
20597         struct compile_state *state, struct scc_state *scc, struct triple *ins)
20598 {
20599         if (ins->id <= 0) {
20600                 internal_error(state, ins, "bad id");
20601         }
20602         return &scc->lattice[ins->id];
20603 }
20604
20605 static struct triple *preserve_lval(
20606         struct compile_state *state, struct lattice_node *lnode)
20607 {
20608         struct triple *old;
20609         /* Preserve the original value */
20610         if (lnode->val) {
20611                 old = dup_triple(state, lnode->val);
20612                 if (lnode->val != lnode->def) {
20613                         xfree(lnode->val);
20614                 }
20615                 lnode->val = 0;
20616         } else {
20617                 old = 0;
20618         }
20619         return old;
20620 }
20621
20622 static int lval_changed(struct compile_state *state, 
20623         struct triple *old, struct lattice_node *lnode)
20624 {
20625         int changed;
20626         /* See if the lattice value has changed */
20627         changed = 1;
20628         if (!old && !lnode->val) {
20629                 changed = 0;
20630         }
20631         if (changed &&
20632                 lnode->val && old &&
20633                 (memcmp(lnode->val->param, old->param,
20634                         TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20635                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20636                 changed = 0;
20637         }
20638         if (old) {
20639                 xfree(old);
20640         }
20641         return changed;
20642
20643 }
20644
20645 static void scc_debug_lnode(
20646         struct compile_state *state, struct scc_state *scc,
20647         struct lattice_node *lnode, int changed)
20648 {
20649         if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20650                 display_triple_changes(state->errout, lnode->val, lnode->def);
20651         }
20652         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20653                 FILE *fp = state->errout;
20654                 struct triple *val, **expr;
20655                 val = lnode->val? lnode->val : lnode->def;
20656                 fprintf(fp, "%p %s %3d %10s (",
20657                         lnode->def, 
20658                         ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20659                         lnode->def->id,
20660                         tops(lnode->def->op));
20661                 expr = triple_rhs(state, lnode->def, 0);
20662                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20663                         if (*expr) {
20664                                 fprintf(fp, " %d", (*expr)->id);
20665                         }
20666                 }
20667                 if (val->op == OP_INTCONST) {
20668                         fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20669                 }
20670                 fprintf(fp, " ) -> %s %s\n",
20671                         (is_lattice_hi(state, lnode)? "hi":
20672                                 is_lattice_const(state, lnode)? "const" : "lo"),
20673                         changed? "changed" : ""
20674                         );
20675         }
20676 }
20677
20678 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20679         struct lattice_node *lnode)
20680 {
20681         int changed;
20682         struct triple *old, *scratch;
20683         struct triple **dexpr, **vexpr;
20684         int count, i;
20685         
20686         /* Store the original value */
20687         old = preserve_lval(state, lnode);
20688
20689         /* Reinitialize the value */
20690         lnode->val = scratch = dup_triple(state, lnode->def);
20691         scratch->id = lnode->old_id;
20692         scratch->next     = scratch;
20693         scratch->prev     = scratch;
20694         scratch->use      = 0;
20695
20696         count = TRIPLE_SIZE(scratch);
20697         for(i = 0; i < count; i++) {
20698                 dexpr = &lnode->def->param[i];
20699                 vexpr = &scratch->param[i];
20700                 *vexpr = *dexpr;
20701                 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20702                         (i >= TRIPLE_TARG_OFF(scratch))) &&
20703                         *dexpr) {
20704                         struct lattice_node *tmp;
20705                         tmp = triple_to_lattice(state, scc, *dexpr);
20706                         *vexpr = (tmp->val)? tmp->val : tmp->def;
20707                 }
20708         }
20709         if (triple_is_branch(state, scratch)) {
20710                 scratch->next = lnode->def->next;
20711         }
20712         /* Recompute the value */
20713 #if DEBUG_ROMCC_WARNINGS
20714 #warning "FIXME see if simplify does anything bad"
20715 #endif
20716         /* So far it looks like only the strength reduction
20717          * optimization are things I need to worry about.
20718          */
20719         simplify(state, scratch);
20720         /* Cleanup my value */
20721         if (scratch->use) {
20722                 internal_error(state, lnode->def, "scratch used?");
20723         }
20724         if ((scratch->prev != scratch) ||
20725                 ((scratch->next != scratch) &&
20726                         (!triple_is_branch(state, lnode->def) ||
20727                                 (scratch->next != lnode->def->next)))) {
20728                 internal_error(state, lnode->def, "scratch in list?");
20729         }
20730         /* undo any uses... */
20731         count = TRIPLE_SIZE(scratch);
20732         for(i = 0; i < count; i++) {
20733                 vexpr = &scratch->param[i];
20734                 if (*vexpr) {
20735                         unuse_triple(*vexpr, scratch);
20736                 }
20737         }
20738         if (lnode->val->op == OP_UNKNOWNVAL) {
20739                 lnode->val = 0; /* Lattice low by definition */
20740         }
20741         /* Find the case when I am lattice high */
20742         if (lnode->val && 
20743                 (lnode->val->op == lnode->def->op) &&
20744                 (memcmp(lnode->val->param, lnode->def->param, 
20745                         count * sizeof(lnode->val->param[0])) == 0) &&
20746                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20747                 lnode->val = lnode->def;
20748         }
20749         /* Only allow lattice high when all of my inputs
20750          * are also lattice high.  Occassionally I can
20751          * have constants with a lattice low input, so
20752          * I do not need to check that case.
20753          */
20754         if (is_lattice_hi(state, lnode)) {
20755                 struct lattice_node *tmp;
20756                 int rhs;
20757                 rhs = lnode->val->rhs;
20758                 for(i = 0; i < rhs; i++) {
20759                         tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20760                         if (!is_lattice_hi(state, tmp)) {
20761                                 lnode->val = 0;
20762                                 break;
20763                         }
20764                 }
20765         }
20766         /* Find the cases that are always lattice lo */
20767         if (lnode->val && 
20768                 triple_is_def(state, lnode->val) &&
20769                 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20770                 lnode->val = 0;
20771         }
20772         /* See if the lattice value has changed */
20773         changed = lval_changed(state, old, lnode);
20774         /* See if this value should not change */
20775         if ((lnode->val != lnode->def) && 
20776                 ((      !triple_is_def(state, lnode->def)  &&
20777                         !triple_is_cbranch(state, lnode->def)) ||
20778                         (lnode->def->op == OP_PIECE))) {
20779 #if DEBUG_ROMCC_WARNINGS
20780 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20781 #endif
20782                 if (changed) {
20783                         internal_warning(state, lnode->def, "non def changes value?");
20784                 }
20785                 lnode->val = 0;
20786         }
20787
20788         /* See if we need to free the scratch value */
20789         if (lnode->val != scratch) {
20790                 xfree(scratch);
20791         }
20792         
20793         return changed;
20794 }
20795
20796
20797 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20798         struct lattice_node *lnode)
20799 {
20800         struct lattice_node *cond;
20801         struct flow_edge *left, *right;
20802         int changed;
20803
20804         /* Update the branch value */
20805         changed = compute_lnode_val(state, scc, lnode);
20806         scc_debug_lnode(state, scc, lnode, changed);
20807
20808         /* This only applies to conditional branches */
20809         if (!triple_is_cbranch(state, lnode->def)) {
20810                 internal_error(state, lnode->def, "not a conditional branch");
20811         }
20812
20813         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20814                 struct flow_edge *fedge;
20815                 FILE *fp = state->errout;
20816                 fprintf(fp, "%s: %d (",
20817                         tops(lnode->def->op),
20818                         lnode->def->id);
20819                 
20820                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20821                         fprintf(fp, " %d", fedge->dst->block->vertex);
20822                 }
20823                 fprintf(fp, " )");
20824                 if (lnode->def->rhs > 0) {
20825                         fprintf(fp, " <- %d",
20826                                 RHS(lnode->def, 0)->id);
20827                 }
20828                 fprintf(fp, "\n");
20829         }
20830         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20831         for(left = cond->fblock->out; left; left = left->out_next) {
20832                 if (left->dst->block->first == lnode->def->next) {
20833                         break;
20834                 }
20835         }
20836         if (!left) {
20837                 internal_error(state, lnode->def, "Cannot find left branch edge");
20838         }
20839         for(right = cond->fblock->out; right; right = right->out_next) {
20840                 if (right->dst->block->first == TARG(lnode->def, 0)) {
20841                         break;
20842                 }
20843         }
20844         if (!right) {
20845                 internal_error(state, lnode->def, "Cannot find right branch edge");
20846         }
20847         /* I should only come here if the controlling expressions value
20848          * has changed, which means it must be either a constant or lo.
20849          */
20850         if (is_lattice_hi(state, cond)) {
20851                 internal_error(state, cond->def, "condition high?");
20852                 return;
20853         }
20854         if (is_lattice_lo(state, cond)) {
20855                 scc_add_fedge(state, scc, left);
20856                 scc_add_fedge(state, scc, right);
20857         }
20858         else if (cond->val->u.cval) {
20859                 scc_add_fedge(state, scc, right);
20860         } else {
20861                 scc_add_fedge(state, scc, left);
20862         }
20863
20864 }
20865
20866
20867 static void scc_add_sedge_dst(struct compile_state *state, 
20868         struct scc_state *scc, struct ssa_edge *sedge)
20869 {
20870         if (triple_is_cbranch(state, sedge->dst->def)) {
20871                 scc_visit_cbranch(state, scc, sedge->dst);
20872         }
20873         else if (triple_is_def(state, sedge->dst->def)) {
20874                 scc_add_sedge(state, scc, sedge);
20875         }
20876 }
20877
20878 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc, 
20879         struct lattice_node *lnode)
20880 {
20881         struct lattice_node *tmp;
20882         struct triple **slot, *old;
20883         struct flow_edge *fedge;
20884         int changed;
20885         int index;
20886         if (lnode->def->op != OP_PHI) {
20887                 internal_error(state, lnode->def, "not phi");
20888         }
20889         /* Store the original value */
20890         old = preserve_lval(state, lnode);
20891
20892         /* default to lattice high */
20893         lnode->val = lnode->def;
20894         slot = &RHS(lnode->def, 0);
20895         index = 0;
20896         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20897                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20898                         fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n", 
20899                                 index,
20900                                 fedge->dst->block->vertex,
20901                                 fedge->executable
20902                                 );
20903                 }
20904                 if (!fedge->executable) {
20905                         continue;
20906                 }
20907                 if (!slot[index]) {
20908                         internal_error(state, lnode->def, "no phi value");
20909                 }
20910                 tmp = triple_to_lattice(state, scc, slot[index]);
20911                 /* meet(X, lattice low) = lattice low */
20912                 if (is_lattice_lo(state, tmp)) {
20913                         lnode->val = 0;
20914                 }
20915                 /* meet(X, lattice high) = X */
20916                 else if (is_lattice_hi(state, tmp)) {
20917                         lnode->val = lnode->val;
20918                 }
20919                 /* meet(lattice high, X) = X */
20920                 else if (is_lattice_hi(state, lnode)) {
20921                         lnode->val = dup_triple(state, tmp->val);
20922                         /* Only change the type if necessary */
20923                         if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20924                                 lnode->val->type = lnode->def->type;
20925                         }
20926                 }
20927                 /* meet(const, const) = const or lattice low */
20928                 else if (!constants_equal(state, lnode->val, tmp->val)) {
20929                         lnode->val = 0;
20930                 }
20931
20932                 /* meet(lattice low, X) = lattice low */
20933                 if (is_lattice_lo(state, lnode)) {
20934                         lnode->val = 0;
20935                         break;
20936                 }
20937         }
20938         changed = lval_changed(state, old, lnode);
20939         scc_debug_lnode(state, scc, lnode, changed);
20940
20941         /* If the lattice value has changed update the work lists. */
20942         if (changed) {
20943                 struct ssa_edge *sedge;
20944                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20945                         scc_add_sedge_dst(state, scc, sedge);
20946                 }
20947         }
20948 }
20949
20950
20951 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20952         struct lattice_node *lnode)
20953 {
20954         int changed;
20955
20956         if (!triple_is_def(state, lnode->def)) {
20957                 internal_warning(state, lnode->def, "not visiting an expression?");
20958         }
20959         changed = compute_lnode_val(state, scc, lnode);
20960         scc_debug_lnode(state, scc, lnode, changed);
20961
20962         if (changed) {
20963                 struct ssa_edge *sedge;
20964                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20965                         scc_add_sedge_dst(state, scc, sedge);
20966                 }
20967         }
20968 }
20969
20970 static void scc_writeback_values(
20971         struct compile_state *state, struct scc_state *scc)
20972 {
20973         struct triple *first, *ins;
20974         first = state->first;
20975         ins = first;
20976         do {
20977                 struct lattice_node *lnode;
20978                 lnode = triple_to_lattice(state, scc, ins);
20979                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20980                         if (is_lattice_hi(state, lnode) &&
20981                                 (lnode->val->op != OP_NOOP))
20982                         {
20983                                 struct flow_edge *fedge;
20984                                 int executable;
20985                                 executable = 0;
20986                                 for(fedge = lnode->fblock->in; 
20987                                     !executable && fedge; fedge = fedge->in_next) {
20988                                         executable |= fedge->executable;
20989                                 }
20990                                 if (executable) {
20991                                         internal_warning(state, lnode->def,
20992                                                 "lattice node %d %s->%s still high?",
20993                                                 ins->id, 
20994                                                 tops(lnode->def->op),
20995                                                 tops(lnode->val->op));
20996                                 }
20997                         }
20998                 }
20999
21000                 /* Restore id */
21001                 ins->id = lnode->old_id;
21002                 if (lnode->val && (lnode->val != ins)) {
21003                         /* See if it something I know how to write back */
21004                         switch(lnode->val->op) {
21005                         case OP_INTCONST:
21006                                 mkconst(state, ins, lnode->val->u.cval);
21007                                 break;
21008                         case OP_ADDRCONST:
21009                                 mkaddr_const(state, ins, 
21010                                         MISC(lnode->val, 0), lnode->val->u.cval);
21011                                 break;
21012                         default:
21013                                 /* By default don't copy the changes,
21014                                  * recompute them in place instead.
21015                                  */
21016                                 simplify(state, ins);
21017                                 break;
21018                         }
21019                         if (is_const(lnode->val) &&
21020                                 !constants_equal(state, lnode->val, ins)) {
21021                                 internal_error(state, 0, "constants not equal");
21022                         }
21023                         /* Free the lattice nodes */
21024                         xfree(lnode->val);
21025                         lnode->val = 0;
21026                 }
21027                 ins = ins->next;
21028         } while(ins != first);
21029 }
21030
21031 static void scc_transform(struct compile_state *state)
21032 {
21033         struct scc_state scc;
21034         if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
21035                 return;
21036         }
21037
21038         initialize_scc_state(state, &scc);
21039
21040         while(scc.flow_work_list || scc.ssa_work_list) {
21041                 struct flow_edge *fedge;
21042                 struct ssa_edge *sedge;
21043                 struct flow_edge *fptr;
21044                 while((fedge = scc_next_fedge(state, &scc))) {
21045                         struct block *block;
21046                         struct triple *ptr;
21047                         struct flow_block *fblock;
21048                         int reps;
21049                         int done;
21050                         if (fedge->executable) {
21051                                 continue;
21052                         }
21053                         if (!fedge->dst) {
21054                                 internal_error(state, 0, "fedge without dst");
21055                         }
21056                         if (!fedge->src) {
21057                                 internal_error(state, 0, "fedge without src");
21058                         }
21059                         fedge->executable = 1;
21060                         fblock = fedge->dst;
21061                         block = fblock->block;
21062                         reps = 0;
21063                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21064                                 if (fptr->executable) {
21065                                         reps++;
21066                                 }
21067                         }
21068                         
21069                         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21070                                 fprintf(state->errout, "vertex: %d reps: %d\n", 
21071                                         block->vertex, reps);
21072                         }
21073
21074                         done = 0;
21075                         for(ptr = block->first; !done; ptr = ptr->next) {
21076                                 struct lattice_node *lnode;
21077                                 done = (ptr == block->last);
21078                                 lnode = &scc.lattice[ptr->id];
21079                                 if (ptr->op == OP_PHI) {
21080                                         scc_visit_phi(state, &scc, lnode);
21081                                 }
21082                                 else if ((reps == 1) && triple_is_def(state, ptr))
21083                                 {
21084                                         scc_visit_expr(state, &scc, lnode);
21085                                 }
21086                         }
21087                         /* Add unconditional branch edges */
21088                         if (!triple_is_cbranch(state, fblock->block->last)) {
21089                                 struct flow_edge *out;
21090                                 for(out = fblock->out; out; out = out->out_next) {
21091                                         scc_add_fedge(state, &scc, out);
21092                                 }
21093                         }
21094                 }
21095                 while((sedge = scc_next_sedge(state, &scc))) {
21096                         struct lattice_node *lnode;
21097                         struct flow_block *fblock;
21098                         lnode = sedge->dst;
21099                         fblock = lnode->fblock;
21100
21101                         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21102                                 fprintf(state->errout, "sedge: %5ld (%5d -> %5d)\n",
21103                                         sedge - scc.ssa_edges,
21104                                         sedge->src->def->id,
21105                                         sedge->dst->def->id);
21106                         }
21107
21108                         if (lnode->def->op == OP_PHI) {
21109                                 scc_visit_phi(state, &scc, lnode);
21110                         }
21111                         else {
21112                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21113                                         if (fptr->executable) {
21114                                                 break;
21115                                         }
21116                                 }
21117                                 if (fptr) {
21118                                         scc_visit_expr(state, &scc, lnode);
21119                                 }
21120                         }
21121                 }
21122         }
21123         
21124         scc_writeback_values(state, &scc);
21125         free_scc_state(state, &scc);
21126         rebuild_ssa_form(state);
21127         
21128         print_blocks(state, __func__, state->dbgout);
21129 }
21130
21131
21132 static void transform_to_arch_instructions(struct compile_state *state)
21133 {
21134         struct triple *ins, *first;
21135         first = state->first;
21136         ins = first;
21137         do {
21138                 ins = transform_to_arch_instruction(state, ins);
21139         } while(ins != first);
21140         
21141         print_blocks(state, __func__, state->dbgout);
21142 }
21143
21144 #if DEBUG_CONSISTENCY
21145 static void verify_uses(struct compile_state *state)
21146 {
21147         struct triple *first, *ins;
21148         struct triple_set *set;
21149         first = state->first;
21150         ins = first;
21151         do {
21152                 struct triple **expr;
21153                 expr = triple_rhs(state, ins, 0);
21154                 for(; expr; expr = triple_rhs(state, ins, expr)) {
21155                         struct triple *rhs;
21156                         rhs = *expr;
21157                         for(set = rhs?rhs->use:0; set; set = set->next) {
21158                                 if (set->member == ins) {
21159                                         break;
21160                                 }
21161                         }
21162                         if (!set) {
21163                                 internal_error(state, ins, "rhs not used");
21164                         }
21165                 }
21166                 expr = triple_lhs(state, ins, 0);
21167                 for(; expr; expr = triple_lhs(state, ins, expr)) {
21168                         struct triple *lhs;
21169                         lhs = *expr;
21170                         for(set =  lhs?lhs->use:0; set; set = set->next) {
21171                                 if (set->member == ins) {
21172                                         break;
21173                                 }
21174                         }
21175                         if (!set) {
21176                                 internal_error(state, ins, "lhs not used");
21177                         }
21178                 }
21179                 expr = triple_misc(state, ins, 0);
21180                 if (ins->op != OP_PHI) {
21181                         for(; expr; expr = triple_targ(state, ins, expr)) {
21182                                 struct triple *misc;
21183                                 misc = *expr;
21184                                 for(set = misc?misc->use:0; set; set = set->next) {
21185                                         if (set->member == ins) {
21186                                                 break;
21187                                         }
21188                                 }
21189                                 if (!set) {
21190                                         internal_error(state, ins, "misc not used");
21191                                 }
21192                         }
21193                 }
21194                 if (!triple_is_ret(state, ins)) {
21195                         expr = triple_targ(state, ins, 0);
21196                         for(; expr; expr = triple_targ(state, ins, expr)) {
21197                                 struct triple *targ;
21198                                 targ = *expr;
21199                                 for(set = targ?targ->use:0; set; set = set->next) {
21200                                         if (set->member == ins) {
21201                                                 break;
21202                                         }
21203                                 }
21204                                 if (!set) {
21205                                         internal_error(state, ins, "targ not used");
21206                                 }
21207                         }
21208                 }
21209                 ins = ins->next;
21210         } while(ins != first);
21211         
21212 }
21213 static void verify_blocks_present(struct compile_state *state)
21214 {
21215         struct triple *first, *ins;
21216         if (!state->bb.first_block) {
21217                 return;
21218         }
21219         first = state->first;
21220         ins = first;
21221         do {
21222                 valid_ins(state, ins);
21223                 if (triple_stores_block(state, ins)) {
21224                         if (!ins->u.block) {
21225                                 internal_error(state, ins, 
21226                                         "%p not in a block?", ins);
21227                         }
21228                 }
21229                 ins = ins->next;
21230         } while(ins != first);
21231         
21232         
21233 }
21234
21235 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21236 {
21237         struct block_set *bedge;
21238         struct block *targ;
21239         targ = block_of_triple(state, edge);
21240         for(bedge = block->edges; bedge; bedge = bedge->next) {
21241                 if (bedge->member == targ) {
21242                         return 1;
21243                 }
21244         }
21245         return 0;
21246 }
21247
21248 static void verify_blocks(struct compile_state *state)
21249 {
21250         struct triple *ins;
21251         struct block *block;
21252         int blocks;
21253         block = state->bb.first_block;
21254         if (!block) {
21255                 return;
21256         }
21257         blocks = 0;
21258         do {
21259                 int users;
21260                 struct block_set *user, *edge;
21261                 blocks++;
21262                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21263                         if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21264                                 internal_error(state, ins, "inconsitent block specified");
21265                         }
21266                         valid_ins(state, ins);
21267                 }
21268                 users = 0;
21269                 for(user = block->use; user; user = user->next) {
21270                         users++;
21271                         if (!user->member->first) {
21272                                 internal_error(state, block->first, "user is empty");
21273                         }
21274                         if ((block == state->bb.last_block) &&
21275                                 (user->member == state->bb.first_block)) {
21276                                 continue;
21277                         }
21278                         for(edge = user->member->edges; edge; edge = edge->next) {
21279                                 if (edge->member == block) {
21280                                         break;
21281                                 }
21282                         }
21283                         if (!edge) {
21284                                 internal_error(state, user->member->first,
21285                                         "user does not use block");
21286                         }
21287                 }
21288                 if (triple_is_branch(state, block->last)) {
21289                         struct triple **expr;
21290                         expr = triple_edge_targ(state, block->last, 0);
21291                         for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21292                                 if (*expr && !edge_present(state, block, *expr)) {
21293                                         internal_error(state, block->last, "no edge to targ");
21294                                 }
21295                         }
21296                 }
21297                 if (!triple_is_ubranch(state, block->last) &&
21298                         (block != state->bb.last_block) &&
21299                         !edge_present(state, block, block->last->next)) {
21300                         internal_error(state, block->last, "no edge to block->last->next");
21301                 }
21302                 for(edge = block->edges; edge; edge = edge->next) {
21303                         for(user = edge->member->use; user; user = user->next) {
21304                                 if (user->member == block) {
21305                                         break;
21306                                 }
21307                         }
21308                         if (!user || user->member != block) {
21309                                 internal_error(state, block->first,
21310                                         "block does not use edge");
21311                         }
21312                         if (!edge->member->first) {
21313                                 internal_error(state, block->first, "edge block is empty");
21314                         }
21315                 }
21316                 if (block->users != users) {
21317                         internal_error(state, block->first, 
21318                                 "computed users %d != stored users %d",
21319                                 users, block->users);
21320                 }
21321                 if (!triple_stores_block(state, block->last->next)) {
21322                         internal_error(state, block->last->next, 
21323                                 "cannot find next block");
21324                 }
21325                 block = block->last->next->u.block;
21326                 if (!block) {
21327                         internal_error(state, block->last->next,
21328                                 "bad next block");
21329                 }
21330         } while(block != state->bb.first_block);
21331         if (blocks != state->bb.last_vertex) {
21332                 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21333                         blocks, state->bb.last_vertex);
21334         }
21335 }
21336
21337 static void verify_domination(struct compile_state *state)
21338 {
21339         struct triple *first, *ins;
21340         struct triple_set *set;
21341         if (!state->bb.first_block) {
21342                 return;
21343         }
21344         
21345         first = state->first;
21346         ins = first;
21347         do {
21348                 for(set = ins->use; set; set = set->next) {
21349                         struct triple **slot;
21350                         struct triple *use_point;
21351                         int i, zrhs;
21352                         use_point = 0;
21353                         zrhs = set->member->rhs;
21354                         slot = &RHS(set->member, 0);
21355                         /* See if the use is on the right hand side */
21356                         for(i = 0; i < zrhs; i++) {
21357                                 if (slot[i] == ins) {
21358                                         break;
21359                                 }
21360                         }
21361                         if (i < zrhs) {
21362                                 use_point = set->member;
21363                                 if (set->member->op == OP_PHI) {
21364                                         struct block_set *bset;
21365                                         int edge;
21366                                         bset = set->member->u.block->use;
21367                                         for(edge = 0; bset && (edge < i); edge++) {
21368                                                 bset = bset->next;
21369                                         }
21370                                         if (!bset) {
21371                                                 internal_error(state, set->member, 
21372                                                         "no edge for phi rhs %d", i);
21373                                         }
21374                                         use_point = bset->member->last;
21375                                 }
21376                         }
21377                         if (use_point &&
21378                                 !tdominates(state, ins, use_point)) {
21379                                 if (is_const(ins)) {
21380                                         internal_warning(state, ins, 
21381                                         "non dominated rhs use point %p?", use_point);
21382                                 }
21383                                 else {
21384                                         internal_error(state, ins, 
21385                                                 "non dominated rhs use point %p?", use_point);
21386                                 }
21387                         }
21388                 }
21389                 ins = ins->next;
21390         } while(ins != first);
21391 }
21392
21393 static void verify_rhs(struct compile_state *state)
21394 {
21395         struct triple *first, *ins;
21396         first = state->first;
21397         ins = first;
21398         do {
21399                 struct triple **slot;
21400                 int zrhs, i;
21401                 zrhs = ins->rhs;
21402                 slot = &RHS(ins, 0);
21403                 for(i = 0; i < zrhs; i++) {
21404                         if (slot[i] == 0) {
21405                                 internal_error(state, ins,
21406                                         "missing rhs %d on %s",
21407                                         i, tops(ins->op));
21408                         }
21409                         if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21410                                 internal_error(state, ins,
21411                                         "ins == rhs[%d] on %s",
21412                                         i, tops(ins->op));
21413                         }
21414                 }
21415                 ins = ins->next;
21416         } while(ins != first);
21417 }
21418
21419 static void verify_piece(struct compile_state *state)
21420 {
21421         struct triple *first, *ins;
21422         first = state->first;
21423         ins = first;
21424         do {
21425                 struct triple *ptr;
21426                 int lhs, i;
21427                 lhs = ins->lhs;
21428                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21429                         if (ptr != LHS(ins, i)) {
21430                                 internal_error(state, ins, "malformed lhs on %s",
21431                                         tops(ins->op));
21432                         }
21433                         if (ptr->op != OP_PIECE) {
21434                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
21435                                         tops(ptr->op), i, tops(ins->op));
21436                         }
21437                         if (ptr->u.cval != i) {
21438                                 internal_error(state, ins, "bad u.cval of %d %d expected",
21439                                         ptr->u.cval, i);
21440                         }
21441                 }
21442                 ins = ins->next;
21443         } while(ins != first);
21444 }
21445
21446 static void verify_ins_colors(struct compile_state *state)
21447 {
21448         struct triple *first, *ins;
21449         
21450         first = state->first;
21451         ins = first;
21452         do {
21453                 ins = ins->next;
21454         } while(ins != first);
21455 }
21456
21457 static void verify_unknown(struct compile_state *state)
21458 {
21459         struct triple *first, *ins;
21460         if (    (unknown_triple.next != &unknown_triple) ||
21461                 (unknown_triple.prev != &unknown_triple) ||
21462 #if 0
21463                 (unknown_triple.use != 0) ||
21464 #endif
21465                 (unknown_triple.op != OP_UNKNOWNVAL) ||
21466                 (unknown_triple.lhs != 0) ||
21467                 (unknown_triple.rhs != 0) ||
21468                 (unknown_triple.misc != 0) ||
21469                 (unknown_triple.targ != 0) ||
21470                 (unknown_triple.template_id != 0) ||
21471                 (unknown_triple.id != -1) ||
21472                 (unknown_triple.type != &unknown_type) ||
21473                 (unknown_triple.occurance != &dummy_occurance) ||
21474                 (unknown_triple.param[0] != 0) ||
21475                 (unknown_triple.param[1] != 0)) {
21476                 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21477         }
21478         if (    (dummy_occurance.count != 2) ||
21479                 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21480                 (strcmp(dummy_occurance.function, "") != 0) ||
21481                 (dummy_occurance.col != 0) ||
21482                 (dummy_occurance.parent != 0)) {
21483                 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21484         }
21485         if (    (unknown_type.type != TYPE_UNKNOWN)) {
21486                 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21487         }
21488         first = state->first;
21489         ins = first;
21490         do {
21491                 int params, i;
21492                 if (ins == &unknown_triple) {
21493                         internal_error(state, ins, "unknown triple in list");
21494                 }
21495                 params = TRIPLE_SIZE(ins);
21496                 for(i = 0; i < params; i++) {
21497                         if (ins->param[i] == &unknown_triple) {
21498                                 internal_error(state, ins, "unknown triple used!");
21499                         }
21500                 }
21501                 ins = ins->next;
21502         } while(ins != first);
21503 }
21504
21505 static void verify_types(struct compile_state *state)
21506 {
21507         struct triple *first, *ins;
21508         first = state->first;
21509         ins = first;
21510         do {
21511                 struct type *invalid;
21512                 invalid = invalid_type(state, ins->type);
21513                 if (invalid) {
21514                         FILE *fp = state->errout;
21515                         fprintf(fp, "type: ");
21516                         name_of(fp, ins->type);
21517                         fprintf(fp, "\n");
21518                         fprintf(fp, "invalid type: ");
21519                         name_of(fp, invalid);
21520                         fprintf(fp, "\n");
21521                         internal_error(state, ins, "invalid ins type");
21522                 }
21523         } while(ins != first);
21524 }
21525
21526 static void verify_copy(struct compile_state *state)
21527 {
21528         struct triple *first, *ins, *next;
21529         first = state->first;
21530         next = ins = first;
21531         do {
21532                 ins = next;
21533                 next = ins->next;
21534                 if (ins->op != OP_COPY) {
21535                         continue;
21536                 }
21537                 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21538                         FILE *fp = state->errout;
21539                         fprintf(fp, "src type: ");
21540                         name_of(fp, RHS(ins, 0)->type);
21541                         fprintf(fp, "\n");
21542                         fprintf(fp, "dst type: ");
21543                         name_of(fp, ins->type);
21544                         fprintf(fp, "\n");
21545                         internal_error(state, ins, "type mismatch in copy");
21546                 }
21547         } while(next != first);
21548 }
21549
21550 static void verify_consistency(struct compile_state *state)
21551 {
21552         verify_unknown(state);
21553         verify_uses(state);
21554         verify_blocks_present(state);
21555         verify_blocks(state);
21556         verify_domination(state);
21557         verify_rhs(state);
21558         verify_piece(state);
21559         verify_ins_colors(state);
21560         verify_types(state);
21561         verify_copy(state);
21562         if (state->compiler->debug & DEBUG_VERIFICATION) {
21563                 fprintf(state->dbgout, "consistency verified\n");
21564         }
21565 }
21566 #else 
21567 static void verify_consistency(struct compile_state *state) {}
21568 #endif /* DEBUG_CONSISTENCY */
21569
21570 static void optimize(struct compile_state *state)
21571 {
21572         /* Join all of the functions into one giant function */
21573         join_functions(state);
21574
21575         /* Dump what the instruction graph intially looks like */
21576         print_triples(state);
21577
21578         /* Replace structures with simpler data types */
21579         decompose_compound_types(state);
21580         print_triples(state);
21581
21582         verify_consistency(state);
21583         /* Analyze the intermediate code */
21584         state->bb.first = state->first;
21585         analyze_basic_blocks(state, &state->bb);
21586
21587         /* Transform the code to ssa form. */
21588         /*
21589          * The transformation to ssa form puts a phi function
21590          * on each of edge of a dominance frontier where that
21591          * phi function might be needed.  At -O2 if we don't
21592          * eleminate the excess phi functions we can get an
21593          * exponential code size growth.  So I kill the extra
21594          * phi functions early and I kill them often.
21595          */
21596         transform_to_ssa_form(state);
21597         verify_consistency(state);
21598
21599         /* Remove dead code */
21600         eliminate_inefectual_code(state);
21601         verify_consistency(state);
21602
21603         /* Do strength reduction and simple constant optimizations */
21604         simplify_all(state);
21605         verify_consistency(state);
21606         /* Propogate constants throughout the code */
21607         scc_transform(state);
21608         verify_consistency(state);
21609 #if DEBUG_ROMCC_WARNINGS
21610 #warning "WISHLIST implement single use constants (least possible register pressure)"
21611 #warning "WISHLIST implement induction variable elimination"
21612 #endif
21613         /* Select architecture instructions and an initial partial
21614          * coloring based on architecture constraints.
21615          */
21616         transform_to_arch_instructions(state);
21617         verify_consistency(state);
21618
21619         /* Remove dead code */
21620         eliminate_inefectual_code(state);
21621         verify_consistency(state);
21622
21623         /* Color all of the variables to see if they will fit in registers */
21624         insert_copies_to_phi(state);
21625         verify_consistency(state);
21626
21627         insert_mandatory_copies(state);
21628         verify_consistency(state);
21629
21630         allocate_registers(state);
21631         verify_consistency(state);
21632
21633         /* Remove the optimization information.
21634          * This is more to check for memory consistency than to free memory.
21635          */
21636         free_basic_blocks(state, &state->bb);
21637 }
21638
21639 static void print_op_asm(struct compile_state *state,
21640         struct triple *ins, FILE *fp)
21641 {
21642         struct asm_info *info;
21643         const char *ptr;
21644         unsigned lhs, rhs, i;
21645         info = ins->u.ainfo;
21646         lhs = ins->lhs;
21647         rhs = ins->rhs;
21648         /* Don't count the clobbers in lhs */
21649         for(i = 0; i < lhs; i++) {
21650                 if (LHS(ins, i)->type == &void_type) {
21651                         break;
21652                 }
21653         }
21654         lhs = i;
21655         fprintf(fp, "#ASM\n");
21656         fputc('\t', fp);
21657         for(ptr = info->str; *ptr; ptr++) {
21658                 char *next;
21659                 unsigned long param;
21660                 struct triple *piece;
21661                 if (*ptr != '%') {
21662                         fputc(*ptr, fp);
21663                         continue;
21664                 }
21665                 ptr++;
21666                 if (*ptr == '%') {
21667                         fputc('%', fp);
21668                         continue;
21669                 }
21670                 param = strtoul(ptr, &next, 10);
21671                 if (ptr == next) {
21672                         error(state, ins, "Invalid asm template");
21673                 }
21674                 if (param >= (lhs + rhs)) {
21675                         error(state, ins, "Invalid param %%%u in asm template",
21676                                 param);
21677                 }
21678                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21679                 fprintf(fp, "%s", 
21680                         arch_reg_str(ID_REG(piece->id)));
21681                 ptr = next -1;
21682         }
21683         fprintf(fp, "\n#NOT ASM\n");
21684 }
21685
21686
21687 /* Only use the low x86 byte registers.  This allows me
21688  * allocate the entire register when a byte register is used.
21689  */
21690 #define X86_4_8BIT_GPRS 1
21691
21692 /* x86 featrues */
21693 #define X86_MMX_REGS  (1<<0)
21694 #define X86_XMM_REGS  (1<<1)
21695 #define X86_NOOP_COPY (1<<2)
21696
21697 /* The x86 register classes */
21698 #define REGC_FLAGS       0
21699 #define REGC_GPR8        1
21700 #define REGC_GPR16       2
21701 #define REGC_GPR32       3
21702 #define REGC_DIVIDEND64  4
21703 #define REGC_DIVIDEND32  5
21704 #define REGC_MMX         6
21705 #define REGC_XMM         7
21706 #define REGC_GPR32_8     8
21707 #define REGC_GPR16_8     9
21708 #define REGC_GPR8_LO    10
21709 #define REGC_IMM32      11
21710 #define REGC_IMM16      12
21711 #define REGC_IMM8       13
21712 #define LAST_REGC  REGC_IMM8
21713 #if LAST_REGC >= MAX_REGC
21714 #error "MAX_REGC is to low"
21715 #endif
21716
21717 /* Register class masks */
21718 #define REGCM_FLAGS      (1 << REGC_FLAGS)
21719 #define REGCM_GPR8       (1 << REGC_GPR8)
21720 #define REGCM_GPR16      (1 << REGC_GPR16)
21721 #define REGCM_GPR32      (1 << REGC_GPR32)
21722 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21723 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21724 #define REGCM_MMX        (1 << REGC_MMX)
21725 #define REGCM_XMM        (1 << REGC_XMM)
21726 #define REGCM_GPR32_8    (1 << REGC_GPR32_8)
21727 #define REGCM_GPR16_8    (1 << REGC_GPR16_8)
21728 #define REGCM_GPR8_LO    (1 << REGC_GPR8_LO)
21729 #define REGCM_IMM32      (1 << REGC_IMM32)
21730 #define REGCM_IMM16      (1 << REGC_IMM16)
21731 #define REGCM_IMM8       (1 << REGC_IMM8)
21732 #define REGCM_ALL        ((1 << (LAST_REGC + 1)) - 1)
21733 #define REGCM_IMMALL    (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21734
21735 /* The x86 registers */
21736 #define REG_EFLAGS  2
21737 #define REGC_FLAGS_FIRST REG_EFLAGS
21738 #define REGC_FLAGS_LAST  REG_EFLAGS
21739 #define REG_AL      3
21740 #define REG_BL      4
21741 #define REG_CL      5
21742 #define REG_DL      6
21743 #define REG_AH      7
21744 #define REG_BH      8
21745 #define REG_CH      9
21746 #define REG_DH      10
21747 #define REGC_GPR8_LO_FIRST REG_AL
21748 #define REGC_GPR8_LO_LAST  REG_DL
21749 #define REGC_GPR8_FIRST  REG_AL
21750 #define REGC_GPR8_LAST   REG_DH
21751 #define REG_AX     11
21752 #define REG_BX     12
21753 #define REG_CX     13
21754 #define REG_DX     14
21755 #define REG_SI     15
21756 #define REG_DI     16
21757 #define REG_BP     17
21758 #define REG_SP     18
21759 #define REGC_GPR16_FIRST REG_AX
21760 #define REGC_GPR16_LAST  REG_SP
21761 #define REG_EAX    19
21762 #define REG_EBX    20
21763 #define REG_ECX    21
21764 #define REG_EDX    22
21765 #define REG_ESI    23
21766 #define REG_EDI    24
21767 #define REG_EBP    25
21768 #define REG_ESP    26
21769 #define REGC_GPR32_FIRST REG_EAX
21770 #define REGC_GPR32_LAST  REG_ESP
21771 #define REG_EDXEAX 27
21772 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21773 #define REGC_DIVIDEND64_LAST  REG_EDXEAX
21774 #define REG_DXAX   28
21775 #define REGC_DIVIDEND32_FIRST REG_DXAX
21776 #define REGC_DIVIDEND32_LAST  REG_DXAX
21777 #define REG_MMX0   29
21778 #define REG_MMX1   30
21779 #define REG_MMX2   31
21780 #define REG_MMX3   32
21781 #define REG_MMX4   33
21782 #define REG_MMX5   34
21783 #define REG_MMX6   35
21784 #define REG_MMX7   36
21785 #define REGC_MMX_FIRST REG_MMX0
21786 #define REGC_MMX_LAST  REG_MMX7
21787 #define REG_XMM0   37
21788 #define REG_XMM1   38
21789 #define REG_XMM2   39
21790 #define REG_XMM3   40
21791 #define REG_XMM4   41
21792 #define REG_XMM5   42
21793 #define REG_XMM6   43
21794 #define REG_XMM7   44
21795 #define REGC_XMM_FIRST REG_XMM0
21796 #define REGC_XMM_LAST  REG_XMM7
21797
21798 #if DEBUG_ROMCC_WARNINGS
21799 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21800 #endif
21801
21802 #define LAST_REG   REG_XMM7
21803
21804 #define REGC_GPR32_8_FIRST REG_EAX
21805 #define REGC_GPR32_8_LAST  REG_EDX
21806 #define REGC_GPR16_8_FIRST REG_AX
21807 #define REGC_GPR16_8_LAST  REG_DX
21808
21809 #define REGC_IMM8_FIRST    -1
21810 #define REGC_IMM8_LAST     -1
21811 #define REGC_IMM16_FIRST   -2
21812 #define REGC_IMM16_LAST    -1
21813 #define REGC_IMM32_FIRST   -4
21814 #define REGC_IMM32_LAST    -1
21815
21816 #if LAST_REG >= MAX_REGISTERS
21817 #error "MAX_REGISTERS to low"
21818 #endif
21819
21820
21821 static unsigned regc_size[LAST_REGC +1] = {
21822         [REGC_FLAGS]      = REGC_FLAGS_LAST      - REGC_FLAGS_FIRST + 1,
21823         [REGC_GPR8]       = REGC_GPR8_LAST       - REGC_GPR8_FIRST + 1,
21824         [REGC_GPR16]      = REGC_GPR16_LAST      - REGC_GPR16_FIRST + 1,
21825         [REGC_GPR32]      = REGC_GPR32_LAST      - REGC_GPR32_FIRST + 1,
21826         [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21827         [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21828         [REGC_MMX]        = REGC_MMX_LAST        - REGC_MMX_FIRST + 1,
21829         [REGC_XMM]        = REGC_XMM_LAST        - REGC_XMM_FIRST + 1,
21830         [REGC_GPR32_8]    = REGC_GPR32_8_LAST    - REGC_GPR32_8_FIRST + 1,
21831         [REGC_GPR16_8]    = REGC_GPR16_8_LAST    - REGC_GPR16_8_FIRST + 1,
21832         [REGC_GPR8_LO]    = REGC_GPR8_LO_LAST    - REGC_GPR8_LO_FIRST + 1,
21833         [REGC_IMM32]      = 0,
21834         [REGC_IMM16]      = 0,
21835         [REGC_IMM8]       = 0,
21836 };
21837
21838 static const struct {
21839         int first, last;
21840 } regcm_bound[LAST_REGC + 1] = {
21841         [REGC_FLAGS]      = { REGC_FLAGS_FIRST,      REGC_FLAGS_LAST },
21842         [REGC_GPR8]       = { REGC_GPR8_FIRST,       REGC_GPR8_LAST },
21843         [REGC_GPR16]      = { REGC_GPR16_FIRST,      REGC_GPR16_LAST },
21844         [REGC_GPR32]      = { REGC_GPR32_FIRST,      REGC_GPR32_LAST },
21845         [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21846         [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21847         [REGC_MMX]        = { REGC_MMX_FIRST,        REGC_MMX_LAST },
21848         [REGC_XMM]        = { REGC_XMM_FIRST,        REGC_XMM_LAST },
21849         [REGC_GPR32_8]    = { REGC_GPR32_8_FIRST,    REGC_GPR32_8_LAST },
21850         [REGC_GPR16_8]    = { REGC_GPR16_8_FIRST,    REGC_GPR16_8_LAST },
21851         [REGC_GPR8_LO]    = { REGC_GPR8_LO_FIRST,    REGC_GPR8_LO_LAST },
21852         [REGC_IMM32]      = { REGC_IMM32_FIRST,      REGC_IMM32_LAST },
21853         [REGC_IMM16]      = { REGC_IMM16_FIRST,      REGC_IMM16_LAST },
21854         [REGC_IMM8]       = { REGC_IMM8_FIRST,       REGC_IMM8_LAST },
21855 };
21856
21857 #if ARCH_INPUT_REGS != 4
21858 #error ARCH_INPUT_REGS size mismatch
21859 #endif
21860 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21861         { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21862         { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21863         { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21864         { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21865 };
21866
21867 #if ARCH_OUTPUT_REGS != 4
21868 #error ARCH_INPUT_REGS size mismatch
21869 #endif
21870 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21871         { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21872         { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21873         { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21874         { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21875 };
21876
21877 static void init_arch_state(struct arch_state *arch)
21878 {
21879         memset(arch, 0, sizeof(*arch));
21880         arch->features = 0;
21881 }
21882
21883 static const struct compiler_flag arch_flags[] = {
21884         { "mmx",       X86_MMX_REGS },
21885         { "sse",       X86_XMM_REGS },
21886         { "noop-copy", X86_NOOP_COPY },
21887         { 0,     0 },
21888 };
21889 static const struct compiler_flag arch_cpus[] = {
21890         { "i386", 0 },
21891         { "p2",   X86_MMX_REGS },
21892         { "p3",   X86_MMX_REGS | X86_XMM_REGS },
21893         { "p4",   X86_MMX_REGS | X86_XMM_REGS },
21894         { "k7",   X86_MMX_REGS },
21895         { "k8",   X86_MMX_REGS | X86_XMM_REGS },
21896         { "c3",   X86_MMX_REGS },
21897         { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21898         {  0,     0 }
21899 };
21900 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21901 {
21902         int result;
21903         int act;
21904
21905         act = 1;
21906         result = -1;
21907         if (strncmp(flag, "no-", 3) == 0) {
21908                 flag += 3;
21909                 act = 0;
21910         }
21911         if (act && strncmp(flag, "cpu=", 4) == 0) {
21912                 flag += 4;
21913                 result = set_flag(arch_cpus, &arch->features, 1, flag);
21914         }
21915         else {
21916                 result = set_flag(arch_flags, &arch->features, act, flag);
21917         }
21918         return result;
21919 }
21920
21921 static void arch_usage(FILE *fp)
21922 {
21923         flag_usage(fp, arch_flags, "-m", "-mno-");
21924         flag_usage(fp, arch_cpus, "-mcpu=", 0);
21925 }
21926
21927 static unsigned arch_regc_size(struct compile_state *state, int class)
21928 {
21929         if ((class < 0) || (class > LAST_REGC)) {
21930                 return 0;
21931         }
21932         return regc_size[class];
21933 }
21934
21935 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21936 {
21937         /* See if two register classes may have overlapping registers */
21938         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21939                 REGCM_GPR32_8 | REGCM_GPR32 | 
21940                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21941
21942         /* Special case for the immediates */
21943         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21944                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21945                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21946                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) { 
21947                 return 0;
21948         }
21949         return (regcm1 & regcm2) ||
21950                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21951 }
21952
21953 static void arch_reg_equivs(
21954         struct compile_state *state, unsigned *equiv, int reg)
21955 {
21956         if ((reg < 0) || (reg > LAST_REG)) {
21957                 internal_error(state, 0, "invalid register");
21958         }
21959         *equiv++ = reg;
21960         switch(reg) {
21961         case REG_AL:
21962 #if X86_4_8BIT_GPRS
21963                 *equiv++ = REG_AH;
21964 #endif
21965                 *equiv++ = REG_AX;
21966                 *equiv++ = REG_EAX;
21967                 *equiv++ = REG_DXAX;
21968                 *equiv++ = REG_EDXEAX;
21969                 break;
21970         case REG_AH:
21971 #if X86_4_8BIT_GPRS
21972                 *equiv++ = REG_AL;
21973 #endif
21974                 *equiv++ = REG_AX;
21975                 *equiv++ = REG_EAX;
21976                 *equiv++ = REG_DXAX;
21977                 *equiv++ = REG_EDXEAX;
21978                 break;
21979         case REG_BL:  
21980 #if X86_4_8BIT_GPRS
21981                 *equiv++ = REG_BH;
21982 #endif
21983                 *equiv++ = REG_BX;
21984                 *equiv++ = REG_EBX;
21985                 break;
21986
21987         case REG_BH:
21988 #if X86_4_8BIT_GPRS
21989                 *equiv++ = REG_BL;
21990 #endif
21991                 *equiv++ = REG_BX;
21992                 *equiv++ = REG_EBX;
21993                 break;
21994         case REG_CL:
21995 #if X86_4_8BIT_GPRS
21996                 *equiv++ = REG_CH;
21997 #endif
21998                 *equiv++ = REG_CX;
21999                 *equiv++ = REG_ECX;
22000                 break;
22001
22002         case REG_CH:
22003 #if X86_4_8BIT_GPRS
22004                 *equiv++ = REG_CL;
22005 #endif
22006                 *equiv++ = REG_CX;
22007                 *equiv++ = REG_ECX;
22008                 break;
22009         case REG_DL:
22010 #if X86_4_8BIT_GPRS
22011                 *equiv++ = REG_DH;
22012 #endif
22013                 *equiv++ = REG_DX;
22014                 *equiv++ = REG_EDX;
22015                 *equiv++ = REG_DXAX;
22016                 *equiv++ = REG_EDXEAX;
22017                 break;
22018         case REG_DH:
22019 #if X86_4_8BIT_GPRS
22020                 *equiv++ = REG_DL;
22021 #endif
22022                 *equiv++ = REG_DX;
22023                 *equiv++ = REG_EDX;
22024                 *equiv++ = REG_DXAX;
22025                 *equiv++ = REG_EDXEAX;
22026                 break;
22027         case REG_AX:
22028                 *equiv++ = REG_AL;
22029                 *equiv++ = REG_AH;
22030                 *equiv++ = REG_EAX;
22031                 *equiv++ = REG_DXAX;
22032                 *equiv++ = REG_EDXEAX;
22033                 break;
22034         case REG_BX:
22035                 *equiv++ = REG_BL;
22036                 *equiv++ = REG_BH;
22037                 *equiv++ = REG_EBX;
22038                 break;
22039         case REG_CX:  
22040                 *equiv++ = REG_CL;
22041                 *equiv++ = REG_CH;
22042                 *equiv++ = REG_ECX;
22043                 break;
22044         case REG_DX:  
22045                 *equiv++ = REG_DL;
22046                 *equiv++ = REG_DH;
22047                 *equiv++ = REG_EDX;
22048                 *equiv++ = REG_DXAX;
22049                 *equiv++ = REG_EDXEAX;
22050                 break;
22051         case REG_SI:  
22052                 *equiv++ = REG_ESI;
22053                 break;
22054         case REG_DI:
22055                 *equiv++ = REG_EDI;
22056                 break;
22057         case REG_BP:
22058                 *equiv++ = REG_EBP;
22059                 break;
22060         case REG_SP:
22061                 *equiv++ = REG_ESP;
22062                 break;
22063         case REG_EAX:
22064                 *equiv++ = REG_AL;
22065                 *equiv++ = REG_AH;
22066                 *equiv++ = REG_AX;
22067                 *equiv++ = REG_DXAX;
22068                 *equiv++ = REG_EDXEAX;
22069                 break;
22070         case REG_EBX:
22071                 *equiv++ = REG_BL;
22072                 *equiv++ = REG_BH;
22073                 *equiv++ = REG_BX;
22074                 break;
22075         case REG_ECX:
22076                 *equiv++ = REG_CL;
22077                 *equiv++ = REG_CH;
22078                 *equiv++ = REG_CX;
22079                 break;
22080         case REG_EDX:
22081                 *equiv++ = REG_DL;
22082                 *equiv++ = REG_DH;
22083                 *equiv++ = REG_DX;
22084                 *equiv++ = REG_DXAX;
22085                 *equiv++ = REG_EDXEAX;
22086                 break;
22087         case REG_ESI: 
22088                 *equiv++ = REG_SI;
22089                 break;
22090         case REG_EDI: 
22091                 *equiv++ = REG_DI;
22092                 break;
22093         case REG_EBP: 
22094                 *equiv++ = REG_BP;
22095                 break;
22096         case REG_ESP: 
22097                 *equiv++ = REG_SP;
22098                 break;
22099         case REG_DXAX: 
22100                 *equiv++ = REG_AL;
22101                 *equiv++ = REG_AH;
22102                 *equiv++ = REG_DL;
22103                 *equiv++ = REG_DH;
22104                 *equiv++ = REG_AX;
22105                 *equiv++ = REG_DX;
22106                 *equiv++ = REG_EAX;
22107                 *equiv++ = REG_EDX;
22108                 *equiv++ = REG_EDXEAX;
22109                 break;
22110         case REG_EDXEAX: 
22111                 *equiv++ = REG_AL;
22112                 *equiv++ = REG_AH;
22113                 *equiv++ = REG_DL;
22114                 *equiv++ = REG_DH;
22115                 *equiv++ = REG_AX;
22116                 *equiv++ = REG_DX;
22117                 *equiv++ = REG_EAX;
22118                 *equiv++ = REG_EDX;
22119                 *equiv++ = REG_DXAX;
22120                 break;
22121         }
22122         *equiv++ = REG_UNSET; 
22123 }
22124
22125 static unsigned arch_avail_mask(struct compile_state *state)
22126 {
22127         unsigned avail_mask;
22128         /* REGCM_GPR8 is not available */
22129         avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 | 
22130                 REGCM_GPR32 | REGCM_GPR32_8 | 
22131                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22132                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22133         if (state->arch->features & X86_MMX_REGS) {
22134                 avail_mask |= REGCM_MMX;
22135         }
22136         if (state->arch->features & X86_XMM_REGS) {
22137                 avail_mask |= REGCM_XMM;
22138         }
22139         return avail_mask;
22140 }
22141
22142 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22143 {
22144         unsigned mask, result;
22145         int class, class2;
22146         result = regcm;
22147
22148         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22149                 if ((result & mask) == 0) {
22150                         continue;
22151                 }
22152                 if (class > LAST_REGC) {
22153                         result &= ~mask;
22154                 }
22155                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22156                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22157                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22158                                 result |= (1 << class2);
22159                         }
22160                 }
22161         }
22162         result &= arch_avail_mask(state);
22163         return result;
22164 }
22165
22166 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22167 {
22168         /* Like arch_regcm_normalize except immediate register classes are excluded */
22169         regcm = arch_regcm_normalize(state, regcm);
22170         /* Remove the immediate register classes */
22171         regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22172         return regcm;
22173         
22174 }
22175
22176 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22177 {
22178         unsigned mask;
22179         int class;
22180         mask = 0;
22181         for(class = 0; class <= LAST_REGC; class++) {
22182                 if ((reg >= regcm_bound[class].first) &&
22183                         (reg <= regcm_bound[class].last)) {
22184                         mask |= (1 << class);
22185                 }
22186         }
22187         if (!mask) {
22188                 internal_error(state, 0, "reg %d not in any class", reg);
22189         }
22190         return mask;
22191 }
22192
22193 static struct reg_info arch_reg_constraint(
22194         struct compile_state *state, struct type *type, const char *constraint)
22195 {
22196         static const struct {
22197                 char class;
22198                 unsigned int mask;
22199                 unsigned int reg;
22200         } constraints[] = {
22201                 { 'r', REGCM_GPR32,   REG_UNSET },
22202                 { 'g', REGCM_GPR32,   REG_UNSET },
22203                 { 'p', REGCM_GPR32,   REG_UNSET },
22204                 { 'q', REGCM_GPR8_LO, REG_UNSET },
22205                 { 'Q', REGCM_GPR32_8, REG_UNSET },
22206                 { 'x', REGCM_XMM,     REG_UNSET },
22207                 { 'y', REGCM_MMX,     REG_UNSET },
22208                 { 'a', REGCM_GPR32,   REG_EAX },
22209                 { 'b', REGCM_GPR32,   REG_EBX },
22210                 { 'c', REGCM_GPR32,   REG_ECX },
22211                 { 'd', REGCM_GPR32,   REG_EDX },
22212                 { 'D', REGCM_GPR32,   REG_EDI },
22213                 { 'S', REGCM_GPR32,   REG_ESI },
22214                 { '\0', 0, REG_UNSET },
22215         };
22216         unsigned int regcm;
22217         unsigned int mask, reg;
22218         struct reg_info result;
22219         const char *ptr;
22220         regcm = arch_type_to_regcm(state, type);
22221         reg = REG_UNSET;
22222         mask = 0;
22223         for(ptr = constraint; *ptr; ptr++) {
22224                 int i;
22225                 if (*ptr ==  ' ') {
22226                         continue;
22227                 }
22228                 for(i = 0; constraints[i].class != '\0'; i++) {
22229                         if (constraints[i].class == *ptr) {
22230                                 break;
22231                         }
22232                 }
22233                 if (constraints[i].class == '\0') {
22234                         error(state, 0, "invalid register constraint ``%c''", *ptr);
22235                         break;
22236                 }
22237                 if ((constraints[i].mask & regcm) == 0) {
22238                         error(state, 0, "invalid register class %c specified",
22239                                 *ptr);
22240                 }
22241                 mask |= constraints[i].mask;
22242                 if (constraints[i].reg != REG_UNSET) {
22243                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22244                                 error(state, 0, "Only one register may be specified");
22245                         }
22246                         reg = constraints[i].reg;
22247                 }
22248         }
22249         result.reg = reg;
22250         result.regcm = mask;
22251         return result;
22252 }
22253
22254 static struct reg_info arch_reg_clobber(
22255         struct compile_state *state, const char *clobber)
22256 {
22257         struct reg_info result;
22258         if (strcmp(clobber, "memory") == 0) {
22259                 result.reg = REG_UNSET;
22260                 result.regcm = 0;
22261         }
22262         else if (strcmp(clobber, "eax") == 0) {
22263                 result.reg = REG_EAX;
22264                 result.regcm = REGCM_GPR32;
22265         }
22266         else if (strcmp(clobber, "ebx") == 0) {
22267                 result.reg = REG_EBX;
22268                 result.regcm = REGCM_GPR32;
22269         }
22270         else if (strcmp(clobber, "ecx") == 0) {
22271                 result.reg = REG_ECX;
22272                 result.regcm = REGCM_GPR32;
22273         }
22274         else if (strcmp(clobber, "edx") == 0) {
22275                 result.reg = REG_EDX;
22276                 result.regcm = REGCM_GPR32;
22277         }
22278         else if (strcmp(clobber, "esi") == 0) {
22279                 result.reg = REG_ESI;
22280                 result.regcm = REGCM_GPR32;
22281         }
22282         else if (strcmp(clobber, "edi") == 0) {
22283                 result.reg = REG_EDI;
22284                 result.regcm = REGCM_GPR32;
22285         }
22286         else if (strcmp(clobber, "ebp") == 0) {
22287                 result.reg = REG_EBP;
22288                 result.regcm = REGCM_GPR32;
22289         }
22290         else if (strcmp(clobber, "esp") == 0) {
22291                 result.reg = REG_ESP;
22292                 result.regcm = REGCM_GPR32;
22293         }
22294         else if (strcmp(clobber, "cc") == 0) {
22295                 result.reg = REG_EFLAGS;
22296                 result.regcm = REGCM_FLAGS;
22297         }
22298         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
22299                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22300                 result.reg = REG_XMM0 + octdigval(clobber[3]);
22301                 result.regcm = REGCM_XMM;
22302         }
22303         else if ((strncmp(clobber, "mm", 2) == 0) &&
22304                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22305                 result.reg = REG_MMX0 + octdigval(clobber[3]);
22306                 result.regcm = REGCM_MMX;
22307         }
22308         else {
22309                 error(state, 0, "unknown register name `%s' in asm",
22310                         clobber);
22311                 result.reg = REG_UNSET;
22312                 result.regcm = 0;
22313         }
22314         return result;
22315 }
22316
22317 static int do_select_reg(struct compile_state *state, 
22318         char *used, int reg, unsigned classes)
22319 {
22320         unsigned mask;
22321         if (used[reg]) {
22322                 return REG_UNSET;
22323         }
22324         mask = arch_reg_regcm(state, reg);
22325         return (classes & mask) ? reg : REG_UNSET;
22326 }
22327
22328 static int arch_select_free_register(
22329         struct compile_state *state, char *used, int classes)
22330 {
22331         /* Live ranges with the most neighbors are colored first.
22332          *
22333          * Generally it does not matter which colors are given
22334          * as the register allocator attempts to color live ranges
22335          * in an order where you are guaranteed not to run out of colors.
22336          *
22337          * Occasionally the register allocator cannot find an order
22338          * of register selection that will find a free color.  To
22339          * increase the odds the register allocator will work when
22340          * it guesses first give out registers from register classes
22341          * least likely to run out of registers.
22342          * 
22343          */
22344         int i, reg;
22345         reg = REG_UNSET;
22346         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22347                 reg = do_select_reg(state, used, i, classes);
22348         }
22349         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22350                 reg = do_select_reg(state, used, i, classes);
22351         }
22352         for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22353                 reg = do_select_reg(state, used, i, classes);
22354         }
22355         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22356                 reg = do_select_reg(state, used, i, classes);
22357         }
22358         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22359                 reg = do_select_reg(state, used, i, classes);
22360         }
22361         for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22362                 reg = do_select_reg(state, used, i, classes);
22363         }
22364         for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22365                 reg = do_select_reg(state, used, i, classes);
22366         }
22367         for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22368                 reg = do_select_reg(state, used, i, classes);
22369         }
22370         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22371                 reg = do_select_reg(state, used, i, classes);
22372         }
22373         return reg;
22374 }
22375
22376
22377 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type) 
22378 {
22379
22380 #if DEBUG_ROMCC_WARNINGS
22381 #warning "FIXME force types smaller (if legal) before I get here"
22382 #endif
22383         unsigned mask;
22384         mask = 0;
22385         switch(type->type & TYPE_MASK) {
22386         case TYPE_ARRAY:
22387         case TYPE_VOID: 
22388                 mask = 0; 
22389                 break;
22390         case TYPE_CHAR:
22391         case TYPE_UCHAR:
22392                 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22393                         REGCM_GPR16 | REGCM_GPR16_8 | 
22394                         REGCM_GPR32 | REGCM_GPR32_8 |
22395                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22396                         REGCM_MMX | REGCM_XMM |
22397                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22398                 break;
22399         case TYPE_SHORT:
22400         case TYPE_USHORT:
22401                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
22402                         REGCM_GPR32 | REGCM_GPR32_8 |
22403                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22404                         REGCM_MMX | REGCM_XMM |
22405                         REGCM_IMM32 | REGCM_IMM16;
22406                 break;
22407         case TYPE_ENUM:
22408         case TYPE_INT:
22409         case TYPE_UINT:
22410         case TYPE_LONG:
22411         case TYPE_ULONG:
22412         case TYPE_POINTER:
22413                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
22414                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22415                         REGCM_MMX | REGCM_XMM |
22416                         REGCM_IMM32;
22417                 break;
22418         case TYPE_JOIN:
22419         case TYPE_UNION:
22420                 mask = arch_type_to_regcm(state, type->left);
22421                 break;
22422         case TYPE_OVERLAP:
22423                 mask = arch_type_to_regcm(state, type->left) &
22424                         arch_type_to_regcm(state, type->right);
22425                 break;
22426         case TYPE_BITFIELD:
22427                 mask = arch_type_to_regcm(state, type->left);
22428                 break;
22429         default:
22430                 fprintf(state->errout, "type: ");
22431                 name_of(state->errout, type);
22432                 fprintf(state->errout, "\n");
22433                 internal_error(state, 0, "no register class for type");
22434                 break;
22435         }
22436         mask = arch_regcm_normalize(state, mask);
22437         return mask;
22438 }
22439
22440 static int is_imm32(struct triple *imm)
22441 {
22442         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffffffffUL)) ||
22443                 (imm->op == OP_ADDRCONST);
22444         
22445 }
22446 static int is_imm16(struct triple *imm)
22447 {
22448         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22449 }
22450 static int is_imm8(struct triple *imm)
22451 {
22452         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22453 }
22454
22455 static int get_imm32(struct triple *ins, struct triple **expr)
22456 {
22457         struct triple *imm;
22458         imm = *expr;
22459         while(imm->op == OP_COPY) {
22460                 imm = RHS(imm, 0);
22461         }
22462         if (!is_imm32(imm)) {
22463                 return 0;
22464         }
22465         unuse_triple(*expr, ins);
22466         use_triple(imm, ins);
22467         *expr = imm;
22468         return 1;
22469 }
22470
22471 static int get_imm8(struct triple *ins, struct triple **expr)
22472 {
22473         struct triple *imm;
22474         imm = *expr;
22475         while(imm->op == OP_COPY) {
22476                 imm = RHS(imm, 0);
22477         }
22478         if (!is_imm8(imm)) {
22479                 return 0;
22480         }
22481         unuse_triple(*expr, ins);
22482         use_triple(imm, ins);
22483         *expr = imm;
22484         return 1;
22485 }
22486
22487 #define TEMPLATE_NOP           0
22488 #define TEMPLATE_INTCONST8     1
22489 #define TEMPLATE_INTCONST32    2
22490 #define TEMPLATE_UNKNOWNVAL    3
22491 #define TEMPLATE_COPY8_REG     5
22492 #define TEMPLATE_COPY16_REG    6
22493 #define TEMPLATE_COPY32_REG    7
22494 #define TEMPLATE_COPY_IMM8     8
22495 #define TEMPLATE_COPY_IMM16    9
22496 #define TEMPLATE_COPY_IMM32   10
22497 #define TEMPLATE_PHI8         11
22498 #define TEMPLATE_PHI16        12
22499 #define TEMPLATE_PHI32        13
22500 #define TEMPLATE_STORE8       14
22501 #define TEMPLATE_STORE16      15
22502 #define TEMPLATE_STORE32      16
22503 #define TEMPLATE_LOAD8        17
22504 #define TEMPLATE_LOAD16       18
22505 #define TEMPLATE_LOAD32       19
22506 #define TEMPLATE_BINARY8_REG  20
22507 #define TEMPLATE_BINARY16_REG 21
22508 #define TEMPLATE_BINARY32_REG 22
22509 #define TEMPLATE_BINARY8_IMM  23
22510 #define TEMPLATE_BINARY16_IMM 24
22511 #define TEMPLATE_BINARY32_IMM 25
22512 #define TEMPLATE_SL8_CL       26
22513 #define TEMPLATE_SL16_CL      27
22514 #define TEMPLATE_SL32_CL      28
22515 #define TEMPLATE_SL8_IMM      29
22516 #define TEMPLATE_SL16_IMM     30
22517 #define TEMPLATE_SL32_IMM     31
22518 #define TEMPLATE_UNARY8       32
22519 #define TEMPLATE_UNARY16      33
22520 #define TEMPLATE_UNARY32      34
22521 #define TEMPLATE_CMP8_REG     35
22522 #define TEMPLATE_CMP16_REG    36
22523 #define TEMPLATE_CMP32_REG    37
22524 #define TEMPLATE_CMP8_IMM     38
22525 #define TEMPLATE_CMP16_IMM    39
22526 #define TEMPLATE_CMP32_IMM    40
22527 #define TEMPLATE_TEST8        41
22528 #define TEMPLATE_TEST16       42
22529 #define TEMPLATE_TEST32       43
22530 #define TEMPLATE_SET          44
22531 #define TEMPLATE_JMP          45
22532 #define TEMPLATE_RET          46
22533 #define TEMPLATE_INB_DX       47
22534 #define TEMPLATE_INB_IMM      48
22535 #define TEMPLATE_INW_DX       49
22536 #define TEMPLATE_INW_IMM      50
22537 #define TEMPLATE_INL_DX       51
22538 #define TEMPLATE_INL_IMM      52
22539 #define TEMPLATE_OUTB_DX      53
22540 #define TEMPLATE_OUTB_IMM     54
22541 #define TEMPLATE_OUTW_DX      55
22542 #define TEMPLATE_OUTW_IMM     56
22543 #define TEMPLATE_OUTL_DX      57
22544 #define TEMPLATE_OUTL_IMM     58
22545 #define TEMPLATE_BSF          59
22546 #define TEMPLATE_RDMSR        60
22547 #define TEMPLATE_WRMSR        61
22548 #define TEMPLATE_UMUL8        62
22549 #define TEMPLATE_UMUL16       63
22550 #define TEMPLATE_UMUL32       64
22551 #define TEMPLATE_DIV8         65
22552 #define TEMPLATE_DIV16        66
22553 #define TEMPLATE_DIV32        67
22554 #define LAST_TEMPLATE       TEMPLATE_DIV32
22555 #if LAST_TEMPLATE >= MAX_TEMPLATES
22556 #error "MAX_TEMPLATES to low"
22557 #endif
22558
22559 #define COPY8_REGCM     (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22560 #define COPY16_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)  
22561 #define COPY32_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22562
22563
22564 static struct ins_template templates[] = {
22565         [TEMPLATE_NOP]      = {
22566                 .lhs = { 
22567                         [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22568                         [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22569                         [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22570                         [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22571                         [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22572                         [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22573                         [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22574                         [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22575                         [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22576                         [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22577                         [10] = { REG_UNNEEDED, REGCM_IMMALL },
22578                         [11] = { REG_UNNEEDED, REGCM_IMMALL },
22579                         [12] = { REG_UNNEEDED, REGCM_IMMALL },
22580                         [13] = { REG_UNNEEDED, REGCM_IMMALL },
22581                         [14] = { REG_UNNEEDED, REGCM_IMMALL },
22582                         [15] = { REG_UNNEEDED, REGCM_IMMALL },
22583                         [16] = { REG_UNNEEDED, REGCM_IMMALL },
22584                         [17] = { REG_UNNEEDED, REGCM_IMMALL },
22585                         [18] = { REG_UNNEEDED, REGCM_IMMALL },
22586                         [19] = { REG_UNNEEDED, REGCM_IMMALL },
22587                         [20] = { REG_UNNEEDED, REGCM_IMMALL },
22588                         [21] = { REG_UNNEEDED, REGCM_IMMALL },
22589                         [22] = { REG_UNNEEDED, REGCM_IMMALL },
22590                         [23] = { REG_UNNEEDED, REGCM_IMMALL },
22591                         [24] = { REG_UNNEEDED, REGCM_IMMALL },
22592                         [25] = { REG_UNNEEDED, REGCM_IMMALL },
22593                         [26] = { REG_UNNEEDED, REGCM_IMMALL },
22594                         [27] = { REG_UNNEEDED, REGCM_IMMALL },
22595                         [28] = { REG_UNNEEDED, REGCM_IMMALL },
22596                         [29] = { REG_UNNEEDED, REGCM_IMMALL },
22597                         [30] = { REG_UNNEEDED, REGCM_IMMALL },
22598                         [31] = { REG_UNNEEDED, REGCM_IMMALL },
22599                         [32] = { REG_UNNEEDED, REGCM_IMMALL },
22600                         [33] = { REG_UNNEEDED, REGCM_IMMALL },
22601                         [34] = { REG_UNNEEDED, REGCM_IMMALL },
22602                         [35] = { REG_UNNEEDED, REGCM_IMMALL },
22603                         [36] = { REG_UNNEEDED, REGCM_IMMALL },
22604                         [37] = { REG_UNNEEDED, REGCM_IMMALL },
22605                         [38] = { REG_UNNEEDED, REGCM_IMMALL },
22606                         [39] = { REG_UNNEEDED, REGCM_IMMALL },
22607                         [40] = { REG_UNNEEDED, REGCM_IMMALL },
22608                         [41] = { REG_UNNEEDED, REGCM_IMMALL },
22609                         [42] = { REG_UNNEEDED, REGCM_IMMALL },
22610                         [43] = { REG_UNNEEDED, REGCM_IMMALL },
22611                         [44] = { REG_UNNEEDED, REGCM_IMMALL },
22612                         [45] = { REG_UNNEEDED, REGCM_IMMALL },
22613                         [46] = { REG_UNNEEDED, REGCM_IMMALL },
22614                         [47] = { REG_UNNEEDED, REGCM_IMMALL },
22615                         [48] = { REG_UNNEEDED, REGCM_IMMALL },
22616                         [49] = { REG_UNNEEDED, REGCM_IMMALL },
22617                         [50] = { REG_UNNEEDED, REGCM_IMMALL },
22618                         [51] = { REG_UNNEEDED, REGCM_IMMALL },
22619                         [52] = { REG_UNNEEDED, REGCM_IMMALL },
22620                         [53] = { REG_UNNEEDED, REGCM_IMMALL },
22621                         [54] = { REG_UNNEEDED, REGCM_IMMALL },
22622                         [55] = { REG_UNNEEDED, REGCM_IMMALL },
22623                         [56] = { REG_UNNEEDED, REGCM_IMMALL },
22624                         [57] = { REG_UNNEEDED, REGCM_IMMALL },
22625                         [58] = { REG_UNNEEDED, REGCM_IMMALL },
22626                         [59] = { REG_UNNEEDED, REGCM_IMMALL },
22627                         [60] = { REG_UNNEEDED, REGCM_IMMALL },
22628                         [61] = { REG_UNNEEDED, REGCM_IMMALL },
22629                         [62] = { REG_UNNEEDED, REGCM_IMMALL },
22630                         [63] = { REG_UNNEEDED, REGCM_IMMALL },
22631                 },
22632         },
22633         [TEMPLATE_INTCONST8] = { 
22634                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22635         },
22636         [TEMPLATE_INTCONST32] = { 
22637                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22638         },
22639         [TEMPLATE_UNKNOWNVAL] = {
22640                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22641         },
22642         [TEMPLATE_COPY8_REG] = {
22643                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22644                 .rhs = { [0] = { REG_UNSET, COPY8_REGCM }  },
22645         },
22646         [TEMPLATE_COPY16_REG] = {
22647                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22648                 .rhs = { [0] = { REG_UNSET, COPY16_REGCM }  },
22649         },
22650         [TEMPLATE_COPY32_REG] = {
22651                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22652                 .rhs = { [0] = { REG_UNSET, COPY32_REGCM }  },
22653         },
22654         [TEMPLATE_COPY_IMM8] = {
22655                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22656                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22657         },
22658         [TEMPLATE_COPY_IMM16] = {
22659                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22660                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22661         },
22662         [TEMPLATE_COPY_IMM32] = {
22663                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22664                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22665         },
22666         [TEMPLATE_PHI8] = { 
22667                 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22668                 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22669         },
22670         [TEMPLATE_PHI16] = { 
22671                 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22672                 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } }, 
22673         },
22674         [TEMPLATE_PHI32] = { 
22675                 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22676                 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } }, 
22677         },
22678         [TEMPLATE_STORE8] = {
22679                 .rhs = { 
22680                         [0] = { REG_UNSET, REGCM_GPR32 },
22681                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22682                 },
22683         },
22684         [TEMPLATE_STORE16] = {
22685                 .rhs = { 
22686                         [0] = { REG_UNSET, REGCM_GPR32 },
22687                         [1] = { REG_UNSET, REGCM_GPR16 },
22688                 },
22689         },
22690         [TEMPLATE_STORE32] = {
22691                 .rhs = { 
22692                         [0] = { REG_UNSET, REGCM_GPR32 },
22693                         [1] = { REG_UNSET, REGCM_GPR32 },
22694                 },
22695         },
22696         [TEMPLATE_LOAD8] = {
22697                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22698                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22699         },
22700         [TEMPLATE_LOAD16] = {
22701                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22702                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22703         },
22704         [TEMPLATE_LOAD32] = {
22705                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22706                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22707         },
22708         [TEMPLATE_BINARY8_REG] = {
22709                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22710                 .rhs = { 
22711                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
22712                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22713                 },
22714         },
22715         [TEMPLATE_BINARY16_REG] = {
22716                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22717                 .rhs = { 
22718                         [0] = { REG_VIRT0, REGCM_GPR16 },
22719                         [1] = { REG_UNSET, REGCM_GPR16 },
22720                 },
22721         },
22722         [TEMPLATE_BINARY32_REG] = {
22723                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22724                 .rhs = { 
22725                         [0] = { REG_VIRT0, REGCM_GPR32 },
22726                         [1] = { REG_UNSET, REGCM_GPR32 },
22727                 },
22728         },
22729         [TEMPLATE_BINARY8_IMM] = {
22730                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22731                 .rhs = { 
22732                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
22733                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22734                 },
22735         },
22736         [TEMPLATE_BINARY16_IMM] = {
22737                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22738                 .rhs = { 
22739                         [0] = { REG_VIRT0,    REGCM_GPR16 },
22740                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
22741                 },
22742         },
22743         [TEMPLATE_BINARY32_IMM] = {
22744                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22745                 .rhs = { 
22746                         [0] = { REG_VIRT0,    REGCM_GPR32 },
22747                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
22748                 },
22749         },
22750         [TEMPLATE_SL8_CL] = {
22751                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22752                 .rhs = { 
22753                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
22754                         [1] = { REG_CL, REGCM_GPR8_LO },
22755                 },
22756         },
22757         [TEMPLATE_SL16_CL] = {
22758                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22759                 .rhs = { 
22760                         [0] = { REG_VIRT0, REGCM_GPR16 },
22761                         [1] = { REG_CL, REGCM_GPR8_LO },
22762                 },
22763         },
22764         [TEMPLATE_SL32_CL] = {
22765                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22766                 .rhs = { 
22767                         [0] = { REG_VIRT0, REGCM_GPR32 },
22768                         [1] = { REG_CL, REGCM_GPR8_LO },
22769                 },
22770         },
22771         [TEMPLATE_SL8_IMM] = {
22772                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22773                 .rhs = { 
22774                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
22775                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22776                 },
22777         },
22778         [TEMPLATE_SL16_IMM] = {
22779                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22780                 .rhs = { 
22781                         [0] = { REG_VIRT0,    REGCM_GPR16 },
22782                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22783                 },
22784         },
22785         [TEMPLATE_SL32_IMM] = {
22786                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22787                 .rhs = { 
22788                         [0] = { REG_VIRT0,    REGCM_GPR32 },
22789                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22790                 },
22791         },
22792         [TEMPLATE_UNARY8] = {
22793                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22794                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22795         },
22796         [TEMPLATE_UNARY16] = {
22797                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22798                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22799         },
22800         [TEMPLATE_UNARY32] = {
22801                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22802                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22803         },
22804         [TEMPLATE_CMP8_REG] = {
22805                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22806                 .rhs = {
22807                         [0] = { REG_UNSET, REGCM_GPR8_LO },
22808                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22809                 },
22810         },
22811         [TEMPLATE_CMP16_REG] = {
22812                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22813                 .rhs = {
22814                         [0] = { REG_UNSET, REGCM_GPR16 },
22815                         [1] = { REG_UNSET, REGCM_GPR16 },
22816                 },
22817         },
22818         [TEMPLATE_CMP32_REG] = {
22819                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22820                 .rhs = {
22821                         [0] = { REG_UNSET, REGCM_GPR32 },
22822                         [1] = { REG_UNSET, REGCM_GPR32 },
22823                 },
22824         },
22825         [TEMPLATE_CMP8_IMM] = {
22826                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22827                 .rhs = {
22828                         [0] = { REG_UNSET, REGCM_GPR8_LO },
22829                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22830                 },
22831         },
22832         [TEMPLATE_CMP16_IMM] = {
22833                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22834                 .rhs = {
22835                         [0] = { REG_UNSET, REGCM_GPR16 },
22836                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
22837                 },
22838         },
22839         [TEMPLATE_CMP32_IMM] = {
22840                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22841                 .rhs = {
22842                         [0] = { REG_UNSET, REGCM_GPR32 },
22843                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
22844                 },
22845         },
22846         [TEMPLATE_TEST8] = {
22847                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22848                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22849         },
22850         [TEMPLATE_TEST16] = {
22851                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22852                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22853         },
22854         [TEMPLATE_TEST32] = {
22855                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22856                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22857         },
22858         [TEMPLATE_SET] = {
22859                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22860                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22861         },
22862         [TEMPLATE_JMP] = {
22863                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22864         },
22865         [TEMPLATE_RET] = {
22866                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22867         },
22868         [TEMPLATE_INB_DX] = {
22869                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },  
22870                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22871         },
22872         [TEMPLATE_INB_IMM] = {
22873                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },  
22874                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22875         },
22876         [TEMPLATE_INW_DX]  = { 
22877                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
22878                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22879         },
22880         [TEMPLATE_INW_IMM] = { 
22881                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } }, 
22882                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22883         },
22884         [TEMPLATE_INL_DX]  = {
22885                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22886                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22887         },
22888         [TEMPLATE_INL_IMM] = {
22889                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22890                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22891         },
22892         [TEMPLATE_OUTB_DX] = { 
22893                 .rhs = {
22894                         [0] = { REG_AL,  REGCM_GPR8_LO },
22895                         [1] = { REG_DX, REGCM_GPR16 },
22896                 },
22897         },
22898         [TEMPLATE_OUTB_IMM] = { 
22899                 .rhs = {
22900                         [0] = { REG_AL,  REGCM_GPR8_LO },  
22901                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22902                 },
22903         },
22904         [TEMPLATE_OUTW_DX] = { 
22905                 .rhs = {
22906                         [0] = { REG_AX,  REGCM_GPR16 },
22907                         [1] = { REG_DX, REGCM_GPR16 },
22908                 },
22909         },
22910         [TEMPLATE_OUTW_IMM] = {
22911                 .rhs = {
22912                         [0] = { REG_AX,  REGCM_GPR16 }, 
22913                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22914                 },
22915         },
22916         [TEMPLATE_OUTL_DX] = { 
22917                 .rhs = {
22918                         [0] = { REG_EAX, REGCM_GPR32 },
22919                         [1] = { REG_DX, REGCM_GPR16 },
22920                 },
22921         },
22922         [TEMPLATE_OUTL_IMM] = { 
22923                 .rhs = {
22924                         [0] = { REG_EAX, REGCM_GPR32 }, 
22925                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22926                 },
22927         },
22928         [TEMPLATE_BSF] = {
22929                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22930                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22931         },
22932         [TEMPLATE_RDMSR] = {
22933                 .lhs = { 
22934                         [0] = { REG_EAX, REGCM_GPR32 },
22935                         [1] = { REG_EDX, REGCM_GPR32 },
22936                 },
22937                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22938         },
22939         [TEMPLATE_WRMSR] = {
22940                 .rhs = {
22941                         [0] = { REG_ECX, REGCM_GPR32 },
22942                         [1] = { REG_EAX, REGCM_GPR32 },
22943                         [2] = { REG_EDX, REGCM_GPR32 },
22944                 },
22945         },
22946         [TEMPLATE_UMUL8] = {
22947                 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22948                 .rhs = { 
22949                         [0] = { REG_AL, REGCM_GPR8_LO },
22950                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22951                 },
22952         },
22953         [TEMPLATE_UMUL16] = {
22954                 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22955                 .rhs = { 
22956                         [0] = { REG_AX, REGCM_GPR16 },
22957                         [1] = { REG_UNSET, REGCM_GPR16 },
22958                 },
22959         },
22960         [TEMPLATE_UMUL32] = {
22961                 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22962                 .rhs = { 
22963                         [0] = { REG_EAX, REGCM_GPR32 },
22964                         [1] = { REG_UNSET, REGCM_GPR32 },
22965                 },
22966         },
22967         [TEMPLATE_DIV8] = {
22968                 .lhs = { 
22969                         [0] = { REG_AL, REGCM_GPR8_LO },
22970                         [1] = { REG_AH, REGCM_GPR8 },
22971                 },
22972                 .rhs = {
22973                         [0] = { REG_AX, REGCM_GPR16 },
22974                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22975                 },
22976         },
22977         [TEMPLATE_DIV16] = {
22978                 .lhs = { 
22979                         [0] = { REG_AX, REGCM_GPR16 },
22980                         [1] = { REG_DX, REGCM_GPR16 },
22981                 },
22982                 .rhs = {
22983                         [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22984                         [1] = { REG_UNSET, REGCM_GPR16 },
22985                 },
22986         },
22987         [TEMPLATE_DIV32] = {
22988                 .lhs = { 
22989                         [0] = { REG_EAX, REGCM_GPR32 },
22990                         [1] = { REG_EDX, REGCM_GPR32 },
22991                 },
22992                 .rhs = {
22993                         [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
22994                         [1] = { REG_UNSET, REGCM_GPR32 },
22995                 },
22996         },
22997 };
22998
22999 static void fixup_branch(struct compile_state *state,
23000         struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
23001         struct triple *left, struct triple *right)
23002 {
23003         struct triple *test;
23004         if (!left) {
23005                 internal_error(state, branch, "no branch test?");
23006         }
23007         test = pre_triple(state, branch,
23008                 cmp_op, cmp_type, left, right);
23009         test->template_id = TEMPLATE_TEST32; 
23010         if (cmp_op == OP_CMP) {
23011                 test->template_id = TEMPLATE_CMP32_REG;
23012                 if (get_imm32(test, &RHS(test, 1))) {
23013                         test->template_id = TEMPLATE_CMP32_IMM;
23014                 }
23015         }
23016         use_triple(RHS(test, 0), test);
23017         use_triple(RHS(test, 1), test);
23018         unuse_triple(RHS(branch, 0), branch);
23019         RHS(branch, 0) = test;
23020         branch->op = jmp_op;
23021         branch->template_id = TEMPLATE_JMP;
23022         use_triple(RHS(branch, 0), branch);
23023 }
23024
23025 static void fixup_branches(struct compile_state *state,
23026         struct triple *cmp, struct triple *use, int jmp_op)
23027 {
23028         struct triple_set *entry, *next;
23029         for(entry = use->use; entry; entry = next) {
23030                 next = entry->next;
23031                 if (entry->member->op == OP_COPY) {
23032                         fixup_branches(state, cmp, entry->member, jmp_op);
23033                 }
23034                 else if (entry->member->op == OP_CBRANCH) {
23035                         struct triple *branch;
23036                         struct triple *left, *right;
23037                         left = right = 0;
23038                         left = RHS(cmp, 0);
23039                         if (cmp->rhs > 1) {
23040                                 right = RHS(cmp, 1);
23041                         }
23042                         branch = entry->member;
23043                         fixup_branch(state, branch, jmp_op, 
23044                                 cmp->op, cmp->type, left, right);
23045                 }
23046         }
23047 }
23048
23049 static void bool_cmp(struct compile_state *state, 
23050         struct triple *ins, int cmp_op, int jmp_op, int set_op)
23051 {
23052         struct triple_set *entry, *next;
23053         struct triple *set, *convert;
23054
23055         /* Put a barrier up before the cmp which preceeds the
23056          * copy instruction.  If a set actually occurs this gives
23057          * us a chance to move variables in registers out of the way.
23058          */
23059
23060         /* Modify the comparison operator */
23061         ins->op = cmp_op;
23062         ins->template_id = TEMPLATE_TEST32;
23063         if (cmp_op == OP_CMP) {
23064                 ins->template_id = TEMPLATE_CMP32_REG;
23065                 if (get_imm32(ins, &RHS(ins, 1))) {
23066                         ins->template_id =  TEMPLATE_CMP32_IMM;
23067                 }
23068         }
23069         /* Generate the instruction sequence that will transform the
23070          * result of the comparison into a logical value.
23071          */
23072         set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
23073         use_triple(ins, set);
23074         set->template_id = TEMPLATE_SET;
23075
23076         convert = set;
23077         if (!equiv_types(ins->type, set->type)) {
23078                 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
23079                 use_triple(set, convert);
23080                 convert->template_id = TEMPLATE_COPY32_REG;
23081         }
23082
23083         for(entry = ins->use; entry; entry = next) {
23084                 next = entry->next;
23085                 if (entry->member == set) {
23086                         continue;
23087                 }
23088                 replace_rhs_use(state, ins, convert, entry->member);
23089         }
23090         fixup_branches(state, ins, convert, jmp_op);
23091 }
23092
23093 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23094 {
23095         struct ins_template *template;
23096         struct reg_info result;
23097         int zlhs;
23098         if (ins->op == OP_PIECE) {
23099                 index = ins->u.cval;
23100                 ins = MISC(ins, 0);
23101         }
23102         zlhs = ins->lhs;
23103         if (triple_is_def(state, ins)) {
23104                 zlhs = 1;
23105         }
23106         if (index >= zlhs) {
23107                 internal_error(state, ins, "index %d out of range for %s",
23108                         index, tops(ins->op));
23109         }
23110         switch(ins->op) {
23111         case OP_ASM:
23112                 template = &ins->u.ainfo->tmpl;
23113                 break;
23114         default:
23115                 if (ins->template_id > LAST_TEMPLATE) {
23116                         internal_error(state, ins, "bad template number %d", 
23117                                 ins->template_id);
23118                 }
23119                 template = &templates[ins->template_id];
23120                 break;
23121         }
23122         result = template->lhs[index];
23123         result.regcm = arch_regcm_normalize(state, result.regcm);
23124         if (result.reg != REG_UNNEEDED) {
23125                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23126         }
23127         if (result.regcm == 0) {
23128                 internal_error(state, ins, "lhs %d regcm == 0", index);
23129         }
23130         return result;
23131 }
23132
23133 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23134 {
23135         struct reg_info result;
23136         struct ins_template *template;
23137         if ((index > ins->rhs) ||
23138                 (ins->op == OP_PIECE)) {
23139                 internal_error(state, ins, "index %d out of range for %s\n",
23140                         index, tops(ins->op));
23141         }
23142         switch(ins->op) {
23143         case OP_ASM:
23144                 template = &ins->u.ainfo->tmpl;
23145                 break;
23146         case OP_PHI:
23147                 index = 0;
23148                 /* Fall through */
23149         default:
23150                 if (ins->template_id > LAST_TEMPLATE) {
23151                         internal_error(state, ins, "bad template number %d", 
23152                                 ins->template_id);
23153                 }
23154                 template = &templates[ins->template_id];
23155                 break;
23156         }
23157         result = template->rhs[index];
23158         result.regcm = arch_regcm_normalize(state, result.regcm);
23159         if (result.regcm == 0) {
23160                 internal_error(state, ins, "rhs %d regcm == 0", index);
23161         }
23162         return result;
23163 }
23164
23165 static struct triple *mod_div(struct compile_state *state,
23166         struct triple *ins, int div_op, int index)
23167 {
23168         struct triple *div, *piece0, *piece1;
23169         
23170         /* Generate the appropriate division instruction */
23171         div = post_triple(state, ins, div_op, ins->type, 0, 0);
23172         RHS(div, 0) = RHS(ins, 0);
23173         RHS(div, 1) = RHS(ins, 1);
23174         piece0 = LHS(div, 0);
23175         piece1 = LHS(div, 1);
23176         div->template_id  = TEMPLATE_DIV32;
23177         use_triple(RHS(div, 0), div);
23178         use_triple(RHS(div, 1), div);
23179         use_triple(LHS(div, 0), div);
23180         use_triple(LHS(div, 1), div);
23181
23182         /* Replate uses of ins with the appropriate piece of the div */
23183         propogate_use(state, ins, LHS(div, index));
23184         release_triple(state, ins);
23185
23186         /* Return the address of the next instruction */
23187         return piece1->next;
23188 }
23189
23190 static int noop_adecl(struct triple *adecl)
23191 {
23192         struct triple_set *use;
23193         /* It's a noop if it doesn't specify stoorage */
23194         if (adecl->lhs == 0) {
23195                 return 1;
23196         }
23197         /* Is the adecl used? If not it's a noop */
23198         for(use = adecl->use; use ; use = use->next) {
23199                 if ((use->member->op != OP_PIECE) ||
23200                         (MISC(use->member, 0) != adecl)) {
23201                         return 0;
23202                 }
23203         }
23204         return 1;
23205 }
23206
23207 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23208 {
23209         struct triple *mask, *nmask, *shift;
23210         struct triple *val, *val_mask, *val_shift;
23211         struct triple *targ, *targ_mask;
23212         struct triple *new;
23213         ulong_t the_mask, the_nmask;
23214
23215         targ = RHS(ins, 0);
23216         val = RHS(ins, 1);
23217
23218         /* Get constant for the mask value */
23219         the_mask = 1;
23220         the_mask <<= ins->u.bitfield.size;
23221         the_mask -= 1;
23222         the_mask <<= ins->u.bitfield.offset;
23223         mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23224         mask->u.cval = the_mask;
23225
23226         /* Get the inverted mask value */
23227         the_nmask = ~the_mask;
23228         nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23229         nmask->u.cval = the_nmask;
23230
23231         /* Get constant for the shift value */
23232         shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23233         shift->u.cval = ins->u.bitfield.offset;
23234
23235         /* Shift and mask the source value */
23236         val_shift = val;
23237         if (shift->u.cval != 0) {
23238                 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23239                 use_triple(val, val_shift);
23240                 use_triple(shift, val_shift);
23241         }
23242         val_mask = val_shift;
23243         if (is_signed(val->type)) {
23244                 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23245                 use_triple(val_shift, val_mask);
23246                 use_triple(mask, val_mask);
23247         }
23248
23249         /* Mask the target value */
23250         targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23251         use_triple(targ, targ_mask);
23252         use_triple(nmask, targ_mask);
23253
23254         /* Now combined them together */
23255         new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23256         use_triple(targ_mask, new);
23257         use_triple(val_mask, new);
23258
23259         /* Move all of the users over to the new expression */
23260         propogate_use(state, ins, new);
23261
23262         /* Delete the original triple */
23263         release_triple(state, ins);
23264
23265         /* Restart the transformation at mask */
23266         return mask;
23267 }
23268
23269 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23270 {
23271         struct triple *mask, *shift;
23272         struct triple *val, *val_mask, *val_shift;
23273         ulong_t the_mask;
23274
23275         val = RHS(ins, 0);
23276
23277         /* Get constant for the mask value */
23278         the_mask = 1;
23279         the_mask <<= ins->u.bitfield.size;
23280         the_mask -= 1;
23281         mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23282         mask->u.cval = the_mask;
23283
23284         /* Get constant for the right shift value */
23285         shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23286         shift->u.cval = ins->u.bitfield.offset;
23287
23288         /* Shift arithmetic right, to correct the sign */
23289         val_shift = val;
23290         if (shift->u.cval != 0) {
23291                 int op;
23292                 if (ins->op == OP_SEXTRACT) {
23293                         op = OP_SSR;
23294                 } else {
23295                         op = OP_USR;
23296                 }
23297                 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23298                 use_triple(val, val_shift);
23299                 use_triple(shift, val_shift);
23300         }
23301
23302         /* Finally mask the value */
23303         val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23304         use_triple(val_shift, val_mask);
23305         use_triple(mask,      val_mask);
23306
23307         /* Move all of the users over to the new expression */
23308         propogate_use(state, ins, val_mask);
23309
23310         /* Release the original instruction */
23311         release_triple(state, ins);
23312
23313         return mask;
23314
23315 }
23316
23317 static struct triple *transform_to_arch_instruction(
23318         struct compile_state *state, struct triple *ins)
23319 {
23320         /* Transform from generic 3 address instructions
23321          * to archtecture specific instructions.
23322          * And apply architecture specific constraints to instructions.
23323          * Copies are inserted to preserve the register flexibility
23324          * of 3 address instructions.
23325          */
23326         struct triple *next, *value;
23327         size_t size;
23328         next = ins->next;
23329         switch(ins->op) {
23330         case OP_INTCONST:
23331                 ins->template_id = TEMPLATE_INTCONST32;
23332                 if (ins->u.cval < 256) {
23333                         ins->template_id = TEMPLATE_INTCONST8;
23334                 }
23335                 break;
23336         case OP_ADDRCONST:
23337                 ins->template_id = TEMPLATE_INTCONST32;
23338                 break;
23339         case OP_UNKNOWNVAL:
23340                 ins->template_id = TEMPLATE_UNKNOWNVAL;
23341                 break;
23342         case OP_NOOP:
23343         case OP_SDECL:
23344         case OP_BLOBCONST:
23345         case OP_LABEL:
23346                 ins->template_id = TEMPLATE_NOP;
23347                 break;
23348         case OP_COPY:
23349         case OP_CONVERT:
23350                 size = size_of(state, ins->type);
23351                 value = RHS(ins, 0);
23352                 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23353                         ins->template_id = TEMPLATE_COPY_IMM8;
23354                 }
23355                 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23356                         ins->template_id = TEMPLATE_COPY_IMM16;
23357                 }
23358                 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23359                         ins->template_id = TEMPLATE_COPY_IMM32;
23360                 }
23361                 else if (is_const(value)) {
23362                         internal_error(state, ins, "bad constant passed to copy");
23363                 }
23364                 else if (size <= SIZEOF_I8) {
23365                         ins->template_id = TEMPLATE_COPY8_REG;
23366                 }
23367                 else if (size <= SIZEOF_I16) {
23368                         ins->template_id = TEMPLATE_COPY16_REG;
23369                 }
23370                 else if (size <= SIZEOF_I32) {
23371                         ins->template_id = TEMPLATE_COPY32_REG;
23372                 }
23373                 else {
23374                         internal_error(state, ins, "bad type passed to copy");
23375                 }
23376                 break;
23377         case OP_PHI:
23378                 size = size_of(state, ins->type);
23379                 if (size <= SIZEOF_I8) {
23380                         ins->template_id = TEMPLATE_PHI8;
23381                 }
23382                 else if (size <= SIZEOF_I16) {
23383                         ins->template_id = TEMPLATE_PHI16;
23384                 }
23385                 else if (size <= SIZEOF_I32) {
23386                         ins->template_id = TEMPLATE_PHI32;
23387                 }
23388                 else {
23389                         internal_error(state, ins, "bad type passed to phi");
23390                 }
23391                 break;
23392         case OP_ADECL:
23393                 /* Adecls should always be treated as dead code and
23394                  * removed.  If we are not optimizing they may linger.
23395                  */
23396                 if (!noop_adecl(ins)) {
23397                         internal_error(state, ins, "adecl remains?");
23398                 }
23399                 ins->template_id = TEMPLATE_NOP;
23400                 next = after_lhs(state, ins);
23401                 break;
23402         case OP_STORE:
23403                 switch(ins->type->type & TYPE_MASK) {
23404                 case TYPE_CHAR:    case TYPE_UCHAR:
23405                         ins->template_id = TEMPLATE_STORE8;
23406                         break;
23407                 case TYPE_SHORT:   case TYPE_USHORT:
23408                         ins->template_id = TEMPLATE_STORE16;
23409                         break;
23410                 case TYPE_INT:     case TYPE_UINT:
23411                 case TYPE_LONG:    case TYPE_ULONG:
23412                 case TYPE_POINTER:
23413                         ins->template_id = TEMPLATE_STORE32;
23414                         break;
23415                 default:
23416                         internal_error(state, ins, "unknown type in store");
23417                         break;
23418                 }
23419                 break;
23420         case OP_LOAD:
23421                 switch(ins->type->type & TYPE_MASK) {
23422                 case TYPE_CHAR:   case TYPE_UCHAR:
23423                 case TYPE_SHORT:  case TYPE_USHORT:
23424                 case TYPE_INT:    case TYPE_UINT:
23425                 case TYPE_LONG:   case TYPE_ULONG:
23426                 case TYPE_POINTER:
23427                         break;
23428                 default:
23429                         internal_error(state, ins, "unknown type in load");
23430                         break;
23431                 }
23432                 ins->template_id = TEMPLATE_LOAD32;
23433                 break;
23434         case OP_ADD:
23435         case OP_SUB:
23436         case OP_AND:
23437         case OP_XOR:
23438         case OP_OR:
23439         case OP_SMUL:
23440                 ins->template_id = TEMPLATE_BINARY32_REG;
23441                 if (get_imm32(ins, &RHS(ins, 1))) {
23442                         ins->template_id = TEMPLATE_BINARY32_IMM;
23443                 }
23444                 break;
23445         case OP_SDIVT:
23446         case OP_UDIVT:
23447                 ins->template_id = TEMPLATE_DIV32;
23448                 next = after_lhs(state, ins);
23449                 break;
23450         case OP_UMUL:
23451                 ins->template_id = TEMPLATE_UMUL32;
23452                 break;
23453         case OP_UDIV:
23454                 next = mod_div(state, ins, OP_UDIVT, 0);
23455                 break;
23456         case OP_SDIV:
23457                 next = mod_div(state, ins, OP_SDIVT, 0);
23458                 break;
23459         case OP_UMOD:
23460                 next = mod_div(state, ins, OP_UDIVT, 1);
23461                 break;
23462         case OP_SMOD:
23463                 next = mod_div(state, ins, OP_SDIVT, 1);
23464                 break;
23465         case OP_SL:
23466         case OP_SSR:
23467         case OP_USR:
23468                 ins->template_id = TEMPLATE_SL32_CL;
23469                 if (get_imm8(ins, &RHS(ins, 1))) {
23470                         ins->template_id = TEMPLATE_SL32_IMM;
23471                 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23472                         typed_pre_copy(state, &uchar_type, ins, 1);
23473                 }
23474                 break;
23475         case OP_INVERT:
23476         case OP_NEG:
23477                 ins->template_id = TEMPLATE_UNARY32;
23478                 break;
23479         case OP_EQ: 
23480                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ); 
23481                 break;
23482         case OP_NOTEQ:
23483                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23484                 break;
23485         case OP_SLESS:
23486                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23487                 break;
23488         case OP_ULESS:
23489                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23490                 break;
23491         case OP_SMORE:
23492                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23493                 break;
23494         case OP_UMORE:
23495                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23496                 break;
23497         case OP_SLESSEQ:
23498                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23499                 break;
23500         case OP_ULESSEQ:
23501                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23502                 break;
23503         case OP_SMOREEQ:
23504                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23505                 break;
23506         case OP_UMOREEQ:
23507                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23508                 break;
23509         case OP_LTRUE:
23510                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23511                 break;
23512         case OP_LFALSE:
23513                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23514                 break;
23515         case OP_BRANCH:
23516                 ins->op = OP_JMP;
23517                 ins->template_id = TEMPLATE_NOP;
23518                 break;
23519         case OP_CBRANCH:
23520                 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST, 
23521                         RHS(ins, 0)->type, RHS(ins, 0), 0);
23522                 break;
23523         case OP_CALL:
23524                 ins->template_id = TEMPLATE_NOP;
23525                 break;
23526         case OP_RET:
23527                 ins->template_id = TEMPLATE_RET;
23528                 break;
23529         case OP_INB:
23530         case OP_INW:
23531         case OP_INL:
23532                 switch(ins->op) {
23533                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23534                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23535                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23536                 }
23537                 if (get_imm8(ins, &RHS(ins, 0))) {
23538                         ins->template_id += 1;
23539                 }
23540                 break;
23541         case OP_OUTB:
23542         case OP_OUTW:
23543         case OP_OUTL:
23544                 switch(ins->op) {
23545                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23546                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23547                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23548                 }
23549                 if (get_imm8(ins, &RHS(ins, 1))) {
23550                         ins->template_id += 1;
23551                 }
23552                 break;
23553         case OP_BSF:
23554         case OP_BSR:
23555                 ins->template_id = TEMPLATE_BSF;
23556                 break;
23557         case OP_RDMSR:
23558                 ins->template_id = TEMPLATE_RDMSR;
23559                 next = after_lhs(state, ins);
23560                 break;
23561         case OP_WRMSR:
23562                 ins->template_id = TEMPLATE_WRMSR;
23563                 break;
23564         case OP_HLT:
23565                 ins->template_id = TEMPLATE_NOP;
23566                 break;
23567         case OP_ASM:
23568                 ins->template_id = TEMPLATE_NOP;
23569                 next = after_lhs(state, ins);
23570                 break;
23571                 /* Already transformed instructions */
23572         case OP_TEST:
23573                 ins->template_id = TEMPLATE_TEST32;
23574                 break;
23575         case OP_CMP:
23576                 ins->template_id = TEMPLATE_CMP32_REG;
23577                 if (get_imm32(ins, &RHS(ins, 1))) {
23578                         ins->template_id = TEMPLATE_CMP32_IMM;
23579                 }
23580                 break;
23581         case OP_JMP:
23582                 ins->template_id = TEMPLATE_NOP;
23583                 break;
23584         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
23585         case OP_JMP_SLESS:   case OP_JMP_ULESS:
23586         case OP_JMP_SMORE:   case OP_JMP_UMORE:
23587         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23588         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23589                 ins->template_id = TEMPLATE_JMP;
23590                 break;
23591         case OP_SET_EQ:      case OP_SET_NOTEQ:
23592         case OP_SET_SLESS:   case OP_SET_ULESS:
23593         case OP_SET_SMORE:   case OP_SET_UMORE:
23594         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23595         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23596                 ins->template_id = TEMPLATE_SET;
23597                 break;
23598         case OP_DEPOSIT:
23599                 next = x86_deposit(state, ins);
23600                 break;
23601         case OP_SEXTRACT:
23602         case OP_UEXTRACT:
23603                 next = x86_extract(state, ins);
23604                 break;
23605                 /* Unhandled instructions */
23606         case OP_PIECE:
23607         default:
23608                 internal_error(state, ins, "unhandled ins: %d %s",
23609                         ins->op, tops(ins->op));
23610                 break;
23611         }
23612         return next;
23613 }
23614
23615 static long next_label(struct compile_state *state)
23616 {
23617         static long label_counter = 1000;
23618         return ++label_counter;
23619 }
23620 static void generate_local_labels(struct compile_state *state)
23621 {
23622         struct triple *first, *label;
23623         first = state->first;
23624         label = first;
23625         do {
23626                 if ((label->op == OP_LABEL) || 
23627                         (label->op == OP_SDECL)) {
23628                         if (label->use) {
23629                                 label->u.cval = next_label(state);
23630                         } else {
23631                                 label->u.cval = 0;
23632                         }
23633                         
23634                 }
23635                 label = label->next;
23636         } while(label != first);
23637 }
23638
23639 static int check_reg(struct compile_state *state, 
23640         struct triple *triple, int classes)
23641 {
23642         unsigned mask;
23643         int reg;
23644         reg = ID_REG(triple->id);
23645         if (reg == REG_UNSET) {
23646                 internal_error(state, triple, "register not set");
23647         }
23648         mask = arch_reg_regcm(state, reg);
23649         if (!(classes & mask)) {
23650                 internal_error(state, triple, "reg %d in wrong class",
23651                         reg);
23652         }
23653         return reg;
23654 }
23655
23656
23657 #if REG_XMM7 != 44
23658 #error "Registers have renumberd fix arch_reg_str"
23659 #endif
23660 static const char *arch_regs[] = {
23661         "%unset",
23662         "%unneeded",
23663         "%eflags",
23664         "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23665         "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23666         "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23667         "%edx:%eax",
23668         "%dx:%ax",
23669         "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23670         "%xmm0", "%xmm1", "%xmm2", "%xmm3", 
23671         "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23672 };
23673 static const char *arch_reg_str(int reg)
23674 {
23675         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23676                 reg = 0;
23677         }
23678         return arch_regs[reg];
23679 }
23680
23681 static const char *reg(struct compile_state *state, struct triple *triple,
23682         int classes)
23683 {
23684         int reg;
23685         reg = check_reg(state, triple, classes);
23686         return arch_reg_str(reg);
23687 }
23688
23689 static int arch_reg_size(int reg)
23690 {
23691         int size;
23692         size = 0;
23693         if (reg == REG_EFLAGS) {
23694                 size = 32;
23695         }
23696         else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23697                 size = 8;
23698         }
23699         else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23700                 size = 16;
23701         }
23702         else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23703                 size = 32;
23704         }
23705         else if (reg == REG_EDXEAX) {
23706                 size = 64;
23707         }
23708         else if (reg == REG_DXAX) {
23709                 size = 32;
23710         }
23711         else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23712                 size = 64;
23713         }
23714         else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23715                 size = 128;
23716         }
23717         return size;
23718 }
23719
23720 static int reg_size(struct compile_state *state, struct triple *ins)
23721 {
23722         int reg;
23723         reg = ID_REG(ins->id);
23724         if (reg == REG_UNSET) {
23725                 internal_error(state, ins, "register not set");
23726         }
23727         return arch_reg_size(reg);
23728 }
23729         
23730
23731
23732 const char *type_suffix(struct compile_state *state, struct type *type)
23733 {
23734         const char *suffix;
23735         switch(size_of(state, type)) {
23736         case SIZEOF_I8:  suffix = "b"; break;
23737         case SIZEOF_I16: suffix = "w"; break;
23738         case SIZEOF_I32: suffix = "l"; break;
23739         default:
23740                 internal_error(state, 0, "unknown suffix");
23741                 suffix = 0;
23742                 break;
23743         }
23744         return suffix;
23745 }
23746
23747 static void print_const_val(
23748         struct compile_state *state, struct triple *ins, FILE *fp)
23749 {
23750         switch(ins->op) {
23751         case OP_INTCONST:
23752                 fprintf(fp, " $%ld ", 
23753                         (long)(ins->u.cval));
23754                 break;
23755         case OP_ADDRCONST:
23756                 if ((MISC(ins, 0)->op != OP_SDECL) &&
23757                         (MISC(ins, 0)->op != OP_LABEL))
23758                 {
23759                         internal_error(state, ins, "bad base for addrconst");
23760                 }
23761                 if (MISC(ins, 0)->u.cval <= 0) {
23762                         internal_error(state, ins, "unlabeled constant");
23763                 }
23764                 fprintf(fp, " $L%s%lu+%lu ",
23765                         state->compiler->label_prefix, 
23766                         (unsigned long)(MISC(ins, 0)->u.cval),
23767                         (unsigned long)(ins->u.cval));
23768                 break;
23769         default:
23770                 internal_error(state, ins, "unknown constant type");
23771                 break;
23772         }
23773 }
23774
23775 static void print_const(struct compile_state *state,
23776         struct triple *ins, FILE *fp)
23777 {
23778         switch(ins->op) {
23779         case OP_INTCONST:
23780                 switch(ins->type->type & TYPE_MASK) {
23781                 case TYPE_CHAR:
23782                 case TYPE_UCHAR:
23783                         fprintf(fp, ".byte 0x%02lx\n", 
23784                                 (unsigned long)(ins->u.cval));
23785                         break;
23786                 case TYPE_SHORT:
23787                 case TYPE_USHORT:
23788                         fprintf(fp, ".short 0x%04lx\n", 
23789                                 (unsigned long)(ins->u.cval));
23790                         break;
23791                 case TYPE_INT:
23792                 case TYPE_UINT:
23793                 case TYPE_LONG:
23794                 case TYPE_ULONG:
23795                 case TYPE_POINTER:
23796                         fprintf(fp, ".int %lu\n", 
23797                                 (unsigned long)(ins->u.cval));
23798                         break;
23799                 default:
23800                         fprintf(state->errout, "type: ");
23801                         name_of(state->errout, ins->type);
23802                         fprintf(state->errout, "\n");
23803                         internal_error(state, ins, "Unknown constant type. Val: %lu",
23804                                 (unsigned long)(ins->u.cval));
23805                 }
23806                 
23807                 break;
23808         case OP_ADDRCONST:
23809                 if ((MISC(ins, 0)->op != OP_SDECL) &&
23810                         (MISC(ins, 0)->op != OP_LABEL)) {
23811                         internal_error(state, ins, "bad base for addrconst");
23812                 }
23813                 if (MISC(ins, 0)->u.cval <= 0) {
23814                         internal_error(state, ins, "unlabeled constant");
23815                 }
23816                 fprintf(fp, ".int L%s%lu+%lu\n",
23817                         state->compiler->label_prefix,
23818                         (unsigned long)(MISC(ins, 0)->u.cval),
23819                         (unsigned long)(ins->u.cval));
23820                 break;
23821         case OP_BLOBCONST:
23822         {
23823                 unsigned char *blob;
23824                 size_t size, i;
23825                 size = size_of_in_bytes(state, ins->type);
23826                 blob = ins->u.blob;
23827                 for(i = 0; i < size; i++) {
23828                         fprintf(fp, ".byte 0x%02x\n",
23829                                 blob[i]);
23830                 }
23831                 break;
23832         }
23833         default:
23834                 internal_error(state, ins, "Unknown constant type");
23835                 break;
23836         }
23837 }
23838
23839 #define TEXT_SECTION ".rom.text"
23840 #define DATA_SECTION ".rom.data"
23841
23842 static long get_const_pool_ref(
23843         struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23844 {
23845         size_t fill_bytes;
23846         long ref;
23847         ref = next_label(state);
23848         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23849         fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
23850         fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23851         print_const(state, ins, fp);
23852         fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23853         if (fill_bytes) {
23854                 fprintf(fp, ".fill %ld, 1, 0\n", (long int)fill_bytes);
23855         }
23856         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23857         return ref;
23858 }
23859
23860 static long get_mask_pool_ref(
23861         struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23862 {
23863         long ref;
23864         if (mask == 0xff) {
23865                 ref = 1;
23866         }
23867         else if (mask == 0xffff) {
23868                 ref = 2;
23869         }
23870         else {
23871                 ref = 0;
23872                 internal_error(state, ins, "unhandled mask value");
23873         }
23874         return ref;
23875 }
23876
23877 static void print_binary_op(struct compile_state *state,
23878         const char *op, struct triple *ins, FILE *fp) 
23879 {
23880         unsigned mask;
23881         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23882         if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23883                 internal_error(state, ins, "invalid register assignment");
23884         }
23885         if (is_const(RHS(ins, 1))) {
23886                 fprintf(fp, "\t%s ", op);
23887                 print_const_val(state, RHS(ins, 1), fp);
23888                 fprintf(fp, ", %s\n",
23889                         reg(state, RHS(ins, 0), mask));
23890         }
23891         else {
23892                 unsigned lmask, rmask;
23893                 int lreg, rreg;
23894                 lreg = check_reg(state, RHS(ins, 0), mask);
23895                 rreg = check_reg(state, RHS(ins, 1), mask);
23896                 lmask = arch_reg_regcm(state, lreg);
23897                 rmask = arch_reg_regcm(state, rreg);
23898                 mask = lmask & rmask;
23899                 fprintf(fp, "\t%s %s, %s\n",
23900                         op,
23901                         reg(state, RHS(ins, 1), mask),
23902                         reg(state, RHS(ins, 0), mask));
23903         }
23904 }
23905 static void print_unary_op(struct compile_state *state, 
23906         const char *op, struct triple *ins, FILE *fp)
23907 {
23908         unsigned mask;
23909         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23910         fprintf(fp, "\t%s %s\n",
23911                 op,
23912                 reg(state, RHS(ins, 0), mask));
23913 }
23914
23915 static void print_op_shift(struct compile_state *state,
23916         const char *op, struct triple *ins, FILE *fp)
23917 {
23918         unsigned mask;
23919         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23920         if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23921                 internal_error(state, ins, "invalid register assignment");
23922         }
23923         if (is_const(RHS(ins, 1))) {
23924                 fprintf(fp, "\t%s ", op);
23925                 print_const_val(state, RHS(ins, 1), fp);
23926                 fprintf(fp, ", %s\n",
23927                         reg(state, RHS(ins, 0), mask));
23928         }
23929         else {
23930                 fprintf(fp, "\t%s %s, %s\n",
23931                         op,
23932                         reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23933                         reg(state, RHS(ins, 0), mask));
23934         }
23935 }
23936
23937 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23938 {
23939         const char *op;
23940         int mask;
23941         int dreg;
23942         mask = 0;
23943         switch(ins->op) {
23944         case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23945         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23946         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23947         default:
23948                 internal_error(state, ins, "not an in operation");
23949                 op = 0;
23950                 break;
23951         }
23952         dreg = check_reg(state, ins, mask);
23953         if (!reg_is_reg(state, dreg, REG_EAX)) {
23954                 internal_error(state, ins, "dst != %%eax");
23955         }
23956         if (is_const(RHS(ins, 0))) {
23957                 fprintf(fp, "\t%s ", op);
23958                 print_const_val(state, RHS(ins, 0), fp);
23959                 fprintf(fp, ", %s\n",
23960                         reg(state, ins, mask));
23961         }
23962         else {
23963                 int addr_reg;
23964                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23965                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23966                         internal_error(state, ins, "src != %%dx");
23967                 }
23968                 fprintf(fp, "\t%s %s, %s\n",
23969                         op, 
23970                         reg(state, RHS(ins, 0), REGCM_GPR16),
23971                         reg(state, ins, mask));
23972         }
23973 }
23974
23975 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23976 {
23977         const char *op;
23978         int mask;
23979         int lreg;
23980         mask = 0;
23981         switch(ins->op) {
23982         case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23983         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23984         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23985         default:
23986                 internal_error(state, ins, "not an out operation");
23987                 op = 0;
23988                 break;
23989         }
23990         lreg = check_reg(state, RHS(ins, 0), mask);
23991         if (!reg_is_reg(state, lreg, REG_EAX)) {
23992                 internal_error(state, ins, "src != %%eax");
23993         }
23994         if (is_const(RHS(ins, 1))) {
23995                 fprintf(fp, "\t%s %s,", 
23996                         op, reg(state, RHS(ins, 0), mask));
23997                 print_const_val(state, RHS(ins, 1), fp);
23998                 fprintf(fp, "\n");
23999         }
24000         else {
24001                 int addr_reg;
24002                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
24003                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
24004                         internal_error(state, ins, "dst != %%dx");
24005                 }
24006                 fprintf(fp, "\t%s %s, %s\n",
24007                         op, 
24008                         reg(state, RHS(ins, 0), mask),
24009                         reg(state, RHS(ins, 1), REGCM_GPR16));
24010         }
24011 }
24012
24013 static void print_op_move(struct compile_state *state,
24014         struct triple *ins, FILE *fp)
24015 {
24016         /* op_move is complex because there are many types
24017          * of registers we can move between.
24018          * Because OP_COPY will be introduced in arbitrary locations
24019          * OP_COPY must not affect flags.
24020          * OP_CONVERT can change the flags and it is the only operation
24021          * where it is expected the types in the registers can change.
24022          */
24023         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
24024         struct triple *dst, *src;
24025         if (state->arch->features & X86_NOOP_COPY) {
24026                 omit_copy = 0;
24027         }
24028         if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
24029                 src = RHS(ins, 0);
24030                 dst = ins;
24031         }
24032         else {
24033                 internal_error(state, ins, "unknown move operation");
24034                 src = dst = 0;
24035         }
24036         if (reg_size(state, dst) < size_of(state, dst->type)) {
24037                 internal_error(state, ins, "Invalid destination register");
24038         }
24039         if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
24040                 fprintf(state->errout, "src type: ");
24041                 name_of(state->errout, src->type);
24042                 fprintf(state->errout, "\n");
24043                 fprintf(state->errout, "dst type: ");
24044                 name_of(state->errout, dst->type);
24045                 fprintf(state->errout, "\n");
24046                 internal_error(state, ins, "Type mismatch for OP_COPY");
24047         }
24048
24049         if (!is_const(src)) {
24050                 int src_reg, dst_reg;
24051                 int src_regcm, dst_regcm;
24052                 src_reg   = ID_REG(src->id);
24053                 dst_reg   = ID_REG(dst->id);
24054                 src_regcm = arch_reg_regcm(state, src_reg);
24055                 dst_regcm = arch_reg_regcm(state, dst_reg);
24056                 /* If the class is the same just move the register */
24057                 if (src_regcm & dst_regcm & 
24058                         (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
24059                         if ((src_reg != dst_reg) || !omit_copy) {
24060                                 fprintf(fp, "\tmov %s, %s\n",
24061                                         reg(state, src, src_regcm),
24062                                         reg(state, dst, dst_regcm));
24063                         }
24064                 }
24065                 /* Move 32bit to 16bit */
24066                 else if ((src_regcm & REGCM_GPR32) &&
24067                         (dst_regcm & REGCM_GPR16)) {
24068                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
24069                         if ((src_reg != dst_reg) || !omit_copy) {
24070                                 fprintf(fp, "\tmovw %s, %s\n",
24071                                         arch_reg_str(src_reg), 
24072                                         arch_reg_str(dst_reg));
24073                         }
24074                 }
24075                 /* Move from 32bit gprs to 16bit gprs */
24076                 else if ((src_regcm & REGCM_GPR32) &&
24077                         (dst_regcm & REGCM_GPR16)) {
24078                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24079                         if ((src_reg != dst_reg) || !omit_copy) {
24080                                 fprintf(fp, "\tmov %s, %s\n",
24081                                         arch_reg_str(src_reg),
24082                                         arch_reg_str(dst_reg));
24083                         }
24084                 }
24085                 /* Move 32bit to 8bit */
24086                 else if ((src_regcm & REGCM_GPR32_8) &&
24087                         (dst_regcm & REGCM_GPR8_LO))
24088                 {
24089                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
24090                         if ((src_reg != dst_reg) || !omit_copy) {
24091                                 fprintf(fp, "\tmovb %s, %s\n",
24092                                         arch_reg_str(src_reg),
24093                                         arch_reg_str(dst_reg));
24094                         }
24095                 }
24096                 /* Move 16bit to 8bit */
24097                 else if ((src_regcm & REGCM_GPR16_8) &&
24098                         (dst_regcm & REGCM_GPR8_LO))
24099                 {
24100                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24101                         if ((src_reg != dst_reg) || !omit_copy) {
24102                                 fprintf(fp, "\tmovb %s, %s\n",
24103                                         arch_reg_str(src_reg),
24104                                         arch_reg_str(dst_reg));
24105                         }
24106                 }
24107                 /* Move 8/16bit to 16/32bit */
24108                 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) && 
24109                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24110                         const char *op;
24111                         op = is_signed(src->type)? "movsx": "movzx";
24112                         fprintf(fp, "\t%s %s, %s\n",
24113                                 op,
24114                                 reg(state, src, src_regcm),
24115                                 reg(state, dst, dst_regcm));
24116                 }
24117                 /* Move between sse registers */
24118                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24119                         if ((src_reg != dst_reg) || !omit_copy) {
24120                                 fprintf(fp, "\tmovdqa %s, %s\n",
24121                                         reg(state, src, src_regcm),
24122                                         reg(state, dst, dst_regcm));
24123                         }
24124                 }
24125                 /* Move between mmx registers */
24126                 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24127                         if ((src_reg != dst_reg) || !omit_copy) {
24128                                 fprintf(fp, "\tmovq %s, %s\n",
24129                                         reg(state, src, src_regcm),
24130                                         reg(state, dst, dst_regcm));
24131                         }
24132                 }
24133                 /* Move from sse to mmx registers */
24134                 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24135                         fprintf(fp, "\tmovdq2q %s, %s\n",
24136                                 reg(state, src, src_regcm),
24137                                 reg(state, dst, dst_regcm));
24138                 }
24139                 /* Move from mmx to sse registers */
24140                 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24141                         fprintf(fp, "\tmovq2dq %s, %s\n",
24142                                 reg(state, src, src_regcm),
24143                                 reg(state, dst, dst_regcm));
24144                 }
24145                 /* Move between 32bit gprs & mmx/sse registers */
24146                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24147                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24148                         fprintf(fp, "\tmovd %s, %s\n",
24149                                 reg(state, src, src_regcm),
24150                                 reg(state, dst, dst_regcm));
24151                 }
24152                 /* Move from 16bit gprs &  mmx/sse registers */
24153                 else if ((src_regcm & REGCM_GPR16) &&
24154                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24155                         const char *op;
24156                         int mid_reg;
24157                         op = is_signed(src->type)? "movsx":"movzx";
24158                         mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24159                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24160                                 op,
24161                                 arch_reg_str(src_reg),
24162                                 arch_reg_str(mid_reg),
24163                                 arch_reg_str(mid_reg),
24164                                 arch_reg_str(dst_reg));
24165                 }
24166                 /* Move from mmx/sse registers to 16bit gprs */
24167                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24168                         (dst_regcm & REGCM_GPR16)) {
24169                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24170                         fprintf(fp, "\tmovd %s, %s\n",
24171                                 arch_reg_str(src_reg),
24172                                 arch_reg_str(dst_reg));
24173                 }
24174                 /* Move from gpr to 64bit dividend */
24175                 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))  &&
24176                         (dst_regcm & REGCM_DIVIDEND64)) {
24177                         const char *extend;
24178                         extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24179                         fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24180                                 arch_reg_str(src_reg), 
24181                                 extend);
24182                 }
24183                 /* Move from 64bit gpr to gpr */
24184                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24185                         (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24186                         if (dst_regcm & REGCM_GPR32) {
24187                                 src_reg = REG_EAX;
24188                         } 
24189                         else if (dst_regcm & REGCM_GPR16) {
24190                                 src_reg = REG_AX;
24191                         }
24192                         else if (dst_regcm & REGCM_GPR8_LO) {
24193                                 src_reg = REG_AL;
24194                         }
24195                         fprintf(fp, "\tmov %s, %s\n",
24196                                 arch_reg_str(src_reg),
24197                                 arch_reg_str(dst_reg));
24198                 }
24199                 /* Move from mmx/sse registers to 64bit gpr */
24200                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24201                         (dst_regcm & REGCM_DIVIDEND64)) {
24202                         const char *extend;
24203                         extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24204                         fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24205                                 arch_reg_str(src_reg),
24206                                 extend);
24207                 }
24208                 /* Move from 64bit gpr to mmx/sse register */
24209                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24210                         (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24211                         fprintf(fp, "\tmovd %%eax, %s\n",
24212                                 arch_reg_str(dst_reg));
24213                 }
24214 #if X86_4_8BIT_GPRS
24215                 /* Move from 8bit gprs to  mmx/sse registers */
24216                 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24217                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24218                         const char *op;
24219                         int mid_reg;
24220                         op = is_signed(src->type)? "movsx":"movzx";
24221                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24222                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24223                                 op,
24224                                 reg(state, src, src_regcm),
24225                                 arch_reg_str(mid_reg),
24226                                 arch_reg_str(mid_reg),
24227                                 reg(state, dst, dst_regcm));
24228                 }
24229                 /* Move from mmx/sse registers and 8bit gprs */
24230                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24231                         (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24232                         int mid_reg;
24233                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24234                         fprintf(fp, "\tmovd %s, %s\n",
24235                                 reg(state, src, src_regcm),
24236                                 arch_reg_str(mid_reg));
24237                 }
24238                 /* Move from 32bit gprs to 8bit gprs */
24239                 else if ((src_regcm & REGCM_GPR32) &&
24240                         (dst_regcm & REGCM_GPR8_LO)) {
24241                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24242                         if ((src_reg != dst_reg) || !omit_copy) {
24243                                 fprintf(fp, "\tmov %s, %s\n",
24244                                         arch_reg_str(src_reg),
24245                                         arch_reg_str(dst_reg));
24246                         }
24247                 }
24248                 /* Move from 16bit gprs to 8bit gprs */
24249                 else if ((src_regcm & REGCM_GPR16) &&
24250                         (dst_regcm & REGCM_GPR8_LO)) {
24251                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24252                         if ((src_reg != dst_reg) || !omit_copy) {
24253                                 fprintf(fp, "\tmov %s, %s\n",
24254                                         arch_reg_str(src_reg),
24255                                         arch_reg_str(dst_reg));
24256                         }
24257                 }
24258 #endif /* X86_4_8BIT_GPRS */
24259                 /* Move from %eax:%edx to %eax:%edx */
24260                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24261                         (dst_regcm & REGCM_DIVIDEND64) &&
24262                         (src_reg == dst_reg)) {
24263                         if (!omit_copy) {
24264                                 fprintf(fp, "\t/*mov %s, %s*/\n",
24265                                         arch_reg_str(src_reg),
24266                                         arch_reg_str(dst_reg));
24267                         }
24268                 }
24269                 else {
24270                         if ((src_regcm & ~REGCM_FLAGS) == 0) {
24271                                 internal_error(state, ins, "attempt to copy from %%eflags!");
24272                         }
24273                         internal_error(state, ins, "unknown copy type");
24274                 }
24275         }
24276         else {
24277                 size_t dst_size;
24278                 int dst_reg;
24279                 int dst_regcm;
24280                 dst_size = size_of(state, dst->type);
24281                 dst_reg = ID_REG(dst->id);
24282                 dst_regcm = arch_reg_regcm(state, dst_reg);
24283                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24284                         fprintf(fp, "\tmov ");
24285                         print_const_val(state, src, fp);
24286                         fprintf(fp, ", %s\n",
24287                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24288                 }
24289                 else if (dst_regcm & REGCM_DIVIDEND64) {
24290                         if (dst_size > SIZEOF_I32) {
24291                                 internal_error(state, ins, "%dbit constant...", dst_size);
24292                         }
24293                         fprintf(fp, "\tmov $0, %%edx\n");
24294                         fprintf(fp, "\tmov ");
24295                         print_const_val(state, src, fp);
24296                         fprintf(fp, ", %%eax\n");
24297                 }
24298                 else if (dst_regcm & REGCM_DIVIDEND32) {
24299                         if (dst_size > SIZEOF_I16) {
24300                                 internal_error(state, ins, "%dbit constant...", dst_size);
24301                         }
24302                         fprintf(fp, "\tmov $0, %%dx\n");
24303                         fprintf(fp, "\tmov ");
24304                         print_const_val(state, src, fp);
24305                         fprintf(fp, ", %%ax");
24306                 }
24307                 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24308                         long ref;
24309                         if (dst_size > SIZEOF_I32) {
24310                                 internal_error(state, ins, "%d bit constant...", dst_size);
24311                         }
24312                         ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24313                         fprintf(fp, "\tmovd L%s%lu, %s\n",
24314                                 state->compiler->label_prefix, ref,
24315                                 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24316                 }
24317                 else {
24318                         internal_error(state, ins, "unknown copy immediate type");
24319                 }
24320         }
24321         /* Leave now if this is not a type conversion */
24322         if (ins->op != OP_CONVERT) {
24323                 return;
24324         }
24325         /* Now make certain I have not logically overflowed the destination */
24326         if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24327                 (size_of(state, dst->type) < reg_size(state, dst)))
24328         {
24329                 unsigned long mask;
24330                 int dst_reg;
24331                 int dst_regcm;
24332                 if (size_of(state, dst->type) >= 32) {
24333                         fprintf(state->errout, "dst type: ");
24334                         name_of(state->errout, dst->type);
24335                         fprintf(state->errout, "\n");
24336                         internal_error(state, dst, "unhandled dst type size");
24337                 }
24338                 mask = 1;
24339                 mask <<= size_of(state, dst->type);
24340                 mask -= 1;
24341
24342                 dst_reg = ID_REG(dst->id);
24343                 dst_regcm = arch_reg_regcm(state, dst_reg);
24344
24345                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24346                         fprintf(fp, "\tand $0x%lx, %s\n",
24347                                 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24348                 }
24349                 else if (dst_regcm & REGCM_MMX) {
24350                         long ref;
24351                         ref = get_mask_pool_ref(state, dst, mask, fp);
24352                         fprintf(fp, "\tpand L%s%lu, %s\n",
24353                                 state->compiler->label_prefix, ref,
24354                                 reg(state, dst, REGCM_MMX));
24355                 }
24356                 else if (dst_regcm & REGCM_XMM) {
24357                         long ref;
24358                         ref = get_mask_pool_ref(state, dst, mask, fp);
24359                         fprintf(fp, "\tpand L%s%lu, %s\n",
24360                                 state->compiler->label_prefix, ref,
24361                                 reg(state, dst, REGCM_XMM));
24362                 }
24363                 else {
24364                         fprintf(state->errout, "dst type: ");
24365                         name_of(state->errout, dst->type);
24366                         fprintf(state->errout, "\n");
24367                         fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24368                         internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24369                 }
24370         }
24371         /* Make certain I am properly sign extended */
24372         if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24373                 (is_signed(src->type)))
24374         {
24375                 int bits, reg_bits, shift_bits;
24376                 int dst_reg;
24377                 int dst_regcm;
24378
24379                 bits = size_of(state, src->type);
24380                 reg_bits = reg_size(state, dst);
24381                 if (reg_bits > 32) {
24382                         reg_bits = 32;
24383                 }
24384                 shift_bits = reg_bits - size_of(state, src->type);
24385                 dst_reg = ID_REG(dst->id);
24386                 dst_regcm = arch_reg_regcm(state, dst_reg);
24387
24388                 if (shift_bits < 0) {
24389                         internal_error(state, dst, "negative shift?");
24390                 }
24391
24392                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24393                         fprintf(fp, "\tshl $%d, %s\n", 
24394                                 shift_bits, 
24395                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24396                         fprintf(fp, "\tsar $%d, %s\n", 
24397                                 shift_bits, 
24398                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24399                 }
24400                 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24401                         fprintf(fp, "\tpslld $%d, %s\n",
24402                                 shift_bits, 
24403                                 reg(state, dst, REGCM_MMX | REGCM_XMM));
24404                         fprintf(fp, "\tpsrad $%d, %s\n",
24405                                 shift_bits, 
24406                                 reg(state, dst, REGCM_MMX | REGCM_XMM));
24407                 }
24408                 else {
24409                         fprintf(state->errout, "dst type: ");
24410                         name_of(state->errout, dst->type);
24411                         fprintf(state->errout, "\n");
24412                         fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24413                         internal_error(state, dst, "failed to signed extend value");
24414                 }
24415         }
24416 }
24417
24418 static void print_op_load(struct compile_state *state,
24419         struct triple *ins, FILE *fp)
24420 {
24421         struct triple *dst, *src;
24422         const char *op;
24423         dst = ins;
24424         src = RHS(ins, 0);
24425         if (is_const(src) || is_const(dst)) {
24426                 internal_error(state, ins, "unknown load operation");
24427         }
24428         switch(ins->type->type & TYPE_MASK) {
24429         case TYPE_CHAR:   op = "movsbl"; break;
24430         case TYPE_UCHAR:  op = "movzbl"; break;
24431         case TYPE_SHORT:  op = "movswl"; break;
24432         case TYPE_USHORT: op = "movzwl"; break;
24433         case TYPE_INT:    case TYPE_UINT:
24434         case TYPE_LONG:   case TYPE_ULONG:
24435         case TYPE_POINTER:
24436                 op = "movl"; 
24437                 break;
24438         default:
24439                 internal_error(state, ins, "unknown type in load");
24440                 op = "<invalid opcode>";
24441                 break;
24442         }
24443         fprintf(fp, "\t%s (%s), %s\n",
24444                 op, 
24445                 reg(state, src, REGCM_GPR32),
24446                 reg(state, dst, REGCM_GPR32));
24447 }
24448
24449
24450 static void print_op_store(struct compile_state *state,
24451         struct triple *ins, FILE *fp)
24452 {
24453         struct triple *dst, *src;
24454         dst = RHS(ins, 0);
24455         src = RHS(ins, 1);
24456         if (is_const(src) && (src->op == OP_INTCONST)) {
24457                 long_t value;
24458                 value = (long_t)(src->u.cval);
24459                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24460                         type_suffix(state, src->type),
24461                         (long)(value),
24462                         reg(state, dst, REGCM_GPR32));
24463         }
24464         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24465                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24466                         type_suffix(state, src->type),
24467                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24468                         (unsigned long)(dst->u.cval));
24469         }
24470         else {
24471                 if (is_const(src) || is_const(dst)) {
24472                         internal_error(state, ins, "unknown store operation");
24473                 }
24474                 fprintf(fp, "\tmov%s %s, (%s)\n",
24475                         type_suffix(state, src->type),
24476                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24477                         reg(state, dst, REGCM_GPR32));
24478         }
24479         
24480         
24481 }
24482
24483 static void print_op_smul(struct compile_state *state,
24484         struct triple *ins, FILE *fp)
24485 {
24486         if (!is_const(RHS(ins, 1))) {
24487                 fprintf(fp, "\timul %s, %s\n",
24488                         reg(state, RHS(ins, 1), REGCM_GPR32),
24489                         reg(state, RHS(ins, 0), REGCM_GPR32));
24490         }
24491         else {
24492                 fprintf(fp, "\timul ");
24493                 print_const_val(state, RHS(ins, 1), fp);
24494                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24495         }
24496 }
24497
24498 static void print_op_cmp(struct compile_state *state,
24499         struct triple *ins, FILE *fp)
24500 {
24501         unsigned mask;
24502         int dreg;
24503         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24504         dreg = check_reg(state, ins, REGCM_FLAGS);
24505         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24506                 internal_error(state, ins, "bad dest register for cmp");
24507         }
24508         if (is_const(RHS(ins, 1))) {
24509                 fprintf(fp, "\tcmp ");
24510                 print_const_val(state, RHS(ins, 1), fp);
24511                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24512         }
24513         else {
24514                 unsigned lmask, rmask;
24515                 int lreg, rreg;
24516                 lreg = check_reg(state, RHS(ins, 0), mask);
24517                 rreg = check_reg(state, RHS(ins, 1), mask);
24518                 lmask = arch_reg_regcm(state, lreg);
24519                 rmask = arch_reg_regcm(state, rreg);
24520                 mask = lmask & rmask;
24521                 fprintf(fp, "\tcmp %s, %s\n",
24522                         reg(state, RHS(ins, 1), mask),
24523                         reg(state, RHS(ins, 0), mask));
24524         }
24525 }
24526
24527 static void print_op_test(struct compile_state *state,
24528         struct triple *ins, FILE *fp)
24529 {
24530         unsigned mask;
24531         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24532         fprintf(fp, "\ttest %s, %s\n",
24533                 reg(state, RHS(ins, 0), mask),
24534                 reg(state, RHS(ins, 0), mask));
24535 }
24536
24537 static void print_op_branch(struct compile_state *state,
24538         struct triple *branch, FILE *fp)
24539 {
24540         const char *bop = "j";
24541         if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24542                 if (branch->rhs != 0) {
24543                         internal_error(state, branch, "jmp with condition?");
24544                 }
24545                 bop = "jmp";
24546         }
24547         else {
24548                 struct triple *ptr;
24549                 if (branch->rhs != 1) {
24550                         internal_error(state, branch, "jmpcc without condition?");
24551                 }
24552                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24553                 if ((RHS(branch, 0)->op != OP_CMP) &&
24554                         (RHS(branch, 0)->op != OP_TEST)) {
24555                         internal_error(state, branch, "bad branch test");
24556                 }
24557 #if DEBUG_ROMCC_WARNINGS
24558 #warning "FIXME I have observed instructions between the test and branch instructions"
24559 #endif
24560                 ptr = RHS(branch, 0);
24561                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24562                         if (ptr->op != OP_COPY) {
24563                                 internal_error(state, branch, "branch does not follow test");
24564                         }
24565                 }
24566                 switch(branch->op) {
24567                 case OP_JMP_EQ:       bop = "jz";  break;
24568                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
24569                 case OP_JMP_SLESS:    bop = "jl";  break;
24570                 case OP_JMP_ULESS:    bop = "jb";  break;
24571                 case OP_JMP_SMORE:    bop = "jg";  break;
24572                 case OP_JMP_UMORE:    bop = "ja";  break;
24573                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
24574                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
24575                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
24576                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
24577                 default:
24578                         internal_error(state, branch, "Invalid branch op");
24579                         break;
24580                 }
24581                 
24582         }
24583 #if 1
24584         if (branch->op == OP_CALL) {
24585                 fprintf(fp, "\t/* call */\n");
24586         }
24587 #endif
24588         fprintf(fp, "\t%s L%s%lu\n",
24589                 bop, 
24590                 state->compiler->label_prefix,
24591                 (unsigned long)(TARG(branch, 0)->u.cval));
24592 }
24593
24594 static void print_op_ret(struct compile_state *state,
24595         struct triple *branch, FILE *fp)
24596 {
24597         fprintf(fp, "\tjmp *%s\n",
24598                 reg(state, RHS(branch, 0), REGCM_GPR32));
24599 }
24600
24601 static void print_op_set(struct compile_state *state,
24602         struct triple *set, FILE *fp)
24603 {
24604         const char *sop = "set";
24605         if (set->rhs != 1) {
24606                 internal_error(state, set, "setcc without condition?");
24607         }
24608         check_reg(state, RHS(set, 0), REGCM_FLAGS);
24609         if ((RHS(set, 0)->op != OP_CMP) &&
24610                 (RHS(set, 0)->op != OP_TEST)) {
24611                 internal_error(state, set, "bad set test");
24612         }
24613         if (RHS(set, 0)->next != set) {
24614                 internal_error(state, set, "set does not follow test");
24615         }
24616         switch(set->op) {
24617         case OP_SET_EQ:       sop = "setz";  break;
24618         case OP_SET_NOTEQ:    sop = "setnz"; break;
24619         case OP_SET_SLESS:    sop = "setl";  break;
24620         case OP_SET_ULESS:    sop = "setb";  break;
24621         case OP_SET_SMORE:    sop = "setg";  break;
24622         case OP_SET_UMORE:    sop = "seta";  break;
24623         case OP_SET_SLESSEQ:  sop = "setle"; break;
24624         case OP_SET_ULESSEQ:  sop = "setbe"; break;
24625         case OP_SET_SMOREEQ:  sop = "setge"; break;
24626         case OP_SET_UMOREEQ:  sop = "setae"; break;
24627         default:
24628                 internal_error(state, set, "Invalid set op");
24629                 break;
24630         }
24631         fprintf(fp, "\t%s %s\n",
24632                 sop, reg(state, set, REGCM_GPR8_LO));
24633 }
24634
24635 static void print_op_bit_scan(struct compile_state *state, 
24636         struct triple *ins, FILE *fp) 
24637 {
24638         const char *op;
24639         switch(ins->op) {
24640         case OP_BSF: op = "bsf"; break;
24641         case OP_BSR: op = "bsr"; break;
24642         default: 
24643                 internal_error(state, ins, "unknown bit scan");
24644                 op = 0;
24645                 break;
24646         }
24647         fprintf(fp, 
24648                 "\t%s %s, %s\n"
24649                 "\tjnz 1f\n"
24650                 "\tmovl $-1, %s\n"
24651                 "1:\n",
24652                 op,
24653                 reg(state, RHS(ins, 0), REGCM_GPR32),
24654                 reg(state, ins, REGCM_GPR32),
24655                 reg(state, ins, REGCM_GPR32));
24656 }
24657
24658
24659 static void print_sdecl(struct compile_state *state,
24660         struct triple *ins, FILE *fp)
24661 {
24662         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24663         fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
24664         fprintf(fp, "L%s%lu:\n", 
24665                 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24666         print_const(state, MISC(ins, 0), fp);
24667         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24668                 
24669 }
24670
24671 static void print_instruction(struct compile_state *state,
24672         struct triple *ins, FILE *fp)
24673 {
24674         /* Assumption: after I have exted the register allocator
24675          * everything is in a valid register. 
24676          */
24677         switch(ins->op) {
24678         case OP_ASM:
24679                 print_op_asm(state, ins, fp);
24680                 break;
24681         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
24682         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
24683         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
24684         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
24685         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
24686         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
24687         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
24688         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
24689         case OP_POS:    break;
24690         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
24691         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24692         case OP_NOOP:
24693         case OP_INTCONST:
24694         case OP_ADDRCONST:
24695         case OP_BLOBCONST:
24696                 /* Don't generate anything here for constants */
24697         case OP_PHI:
24698                 /* Don't generate anything for variable declarations. */
24699                 break;
24700         case OP_UNKNOWNVAL:
24701                 fprintf(fp, " /* unknown %s */\n",
24702                         reg(state, ins, REGCM_ALL));
24703                 break;
24704         case OP_SDECL:
24705                 print_sdecl(state, ins, fp);
24706                 break;
24707         case OP_COPY:   
24708         case OP_CONVERT:
24709                 print_op_move(state, ins, fp);
24710                 break;
24711         case OP_LOAD:
24712                 print_op_load(state, ins, fp);
24713                 break;
24714         case OP_STORE:
24715                 print_op_store(state, ins, fp);
24716                 break;
24717         case OP_SMUL:
24718                 print_op_smul(state, ins, fp);
24719                 break;
24720         case OP_CMP:    print_op_cmp(state, ins, fp); break;
24721         case OP_TEST:   print_op_test(state, ins, fp); break;
24722         case OP_JMP:
24723         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
24724         case OP_JMP_SLESS:   case OP_JMP_ULESS:
24725         case OP_JMP_SMORE:   case OP_JMP_UMORE:
24726         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24727         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24728         case OP_CALL:
24729                 print_op_branch(state, ins, fp);
24730                 break;
24731         case OP_RET:
24732                 print_op_ret(state, ins, fp);
24733                 break;
24734         case OP_SET_EQ:      case OP_SET_NOTEQ:
24735         case OP_SET_SLESS:   case OP_SET_ULESS:
24736         case OP_SET_SMORE:   case OP_SET_UMORE:
24737         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24738         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24739                 print_op_set(state, ins, fp);
24740                 break;
24741         case OP_INB:  case OP_INW:  case OP_INL:
24742                 print_op_in(state, ins, fp); 
24743                 break;
24744         case OP_OUTB: case OP_OUTW: case OP_OUTL:
24745                 print_op_out(state, ins, fp); 
24746                 break;
24747         case OP_BSF:
24748         case OP_BSR:
24749                 print_op_bit_scan(state, ins, fp);
24750                 break;
24751         case OP_RDMSR:
24752                 after_lhs(state, ins);
24753                 fprintf(fp, "\trdmsr\n");
24754                 break;
24755         case OP_WRMSR:
24756                 fprintf(fp, "\twrmsr\n");
24757                 break;
24758         case OP_HLT:
24759                 fprintf(fp, "\thlt\n");
24760                 break;
24761         case OP_SDIVT:
24762                 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24763                 break;
24764         case OP_UDIVT:
24765                 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24766                 break;
24767         case OP_UMUL:
24768                 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24769                 break;
24770         case OP_LABEL:
24771                 if (!ins->use) {
24772                         return;
24773                 }
24774                 fprintf(fp, "L%s%lu:\n", 
24775                         state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24776                 break;
24777         case OP_ADECL:
24778                 /* Ignore adecls with no registers error otherwise */
24779                 if (!noop_adecl(ins)) {
24780                         internal_error(state, ins, "adecl remains?");
24781                 }
24782                 break;
24783                 /* Ignore OP_PIECE */
24784         case OP_PIECE:
24785                 break;
24786                 /* Operations that should never get here */
24787         case OP_SDIV: case OP_UDIV:
24788         case OP_SMOD: case OP_UMOD:
24789         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
24790         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
24791         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24792         default:
24793                 internal_error(state, ins, "unknown op: %d %s",
24794                         ins->op, tops(ins->op));
24795                 break;
24796         }
24797 }
24798
24799 static void print_instructions(struct compile_state *state)
24800 {
24801         struct triple *first, *ins;
24802         int print_location;
24803         struct occurance *last_occurance;
24804         FILE *fp;
24805         int max_inline_depth;
24806         max_inline_depth = 0;
24807         print_location = 1;
24808         last_occurance = 0;
24809         fp = state->output;
24810         /* Masks for common sizes */
24811         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24812         fprintf(fp, ".balign 16\n");
24813         fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24814         fprintf(fp, ".int 0xff, 0, 0, 0\n");
24815         fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24816         fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24817         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24818         first = state->first;
24819         ins = first;
24820         do {
24821                 if (print_location && 
24822                         last_occurance != ins->occurance) {
24823                         if (!ins->occurance->parent) {
24824                                 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24825                                         ins->occurance->function?ins->occurance->function:"(null)",
24826                                         ins->occurance->filename?ins->occurance->filename:"(null)",
24827                                         ins->occurance->line,
24828                                         ins->occurance->col);
24829                         }
24830                         else {
24831                                 struct occurance *ptr;
24832                                 int inline_depth;
24833                                 fprintf(fp, "\t/*\n");
24834                                 inline_depth = 0;
24835                                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24836                                         inline_depth++;
24837                                         fprintf(fp, "\t * %s,%s:%d.%d\n",
24838                                                 ptr->function,
24839                                                 ptr->filename,
24840                                                 ptr->line,
24841                                                 ptr->col);
24842                                 }
24843                                 fprintf(fp, "\t */\n");
24844                                 if (inline_depth > max_inline_depth) {
24845                                         max_inline_depth = inline_depth;
24846                                 }
24847                         }
24848                         if (last_occurance) {
24849                                 put_occurance(last_occurance);
24850                         }
24851                         get_occurance(ins->occurance);
24852                         last_occurance = ins->occurance;
24853                 }
24854
24855                 print_instruction(state, ins, fp);
24856                 ins = ins->next;
24857         } while(ins != first);
24858         if (print_location) {
24859                 fprintf(fp, "/* max inline depth %d */\n",
24860                         max_inline_depth);
24861         }
24862 }
24863
24864 static void generate_code(struct compile_state *state)
24865 {
24866         generate_local_labels(state);
24867         print_instructions(state);
24868         
24869 }
24870
24871 static void print_preprocessed_tokens(struct compile_state *state)
24872 {
24873         int tok;
24874         FILE *fp;
24875         int line;
24876         const char *filename;
24877         fp = state->output;
24878         filename = 0;
24879         line = 0;
24880         for(;;) {
24881                 struct file_state *file;
24882                 struct token *tk;
24883                 const char *token_str;
24884                 tok = peek(state);
24885                 if (tok == TOK_EOF) {
24886                         break;
24887                 }
24888                 tk = eat(state, tok);
24889                 token_str = 
24890                         tk->ident ? tk->ident->name :
24891                         tk->str_len ? tk->val.str :
24892                         tokens[tk->tok];
24893
24894                 file = state->file;
24895                 while(file->macro && file->prev) {
24896                         file = file->prev;
24897                 }
24898                 if (!file->macro && 
24899                         ((file->line != line) || (file->basename != filename))) 
24900                 {
24901                         int i, col;
24902                         if ((file->basename == filename) &&
24903                                 (line < file->line)) {
24904                                 while(line < file->line) {
24905                                         fprintf(fp, "\n");
24906                                         line++;
24907                                 }
24908                         }
24909                         else {
24910                                 fprintf(fp, "\n#line %d \"%s\"\n",
24911                                         file->line, file->basename);
24912                         }
24913                         line = file->line;
24914                         filename = file->basename;
24915                         col = get_col(file) - strlen(token_str);
24916                         for(i = 0; i < col; i++) {
24917                                 fprintf(fp, " ");
24918                         }
24919                 }
24920                 
24921                 fprintf(fp, "%s ", token_str);
24922                 
24923                 if (state->compiler->debug & DEBUG_TOKENS) {
24924                         loc(state->dbgout, state, 0);
24925                         fprintf(state->dbgout, "%s <- `%s'\n",
24926                                 tokens[tok], token_str);
24927                 }
24928         }
24929 }
24930
24931 static void compile(const char *filename, const char *includefile,
24932         struct compiler_state *compiler, struct arch_state *arch)
24933 {
24934         int i;
24935         struct compile_state state;
24936         struct triple *ptr;
24937         memset(&state, 0, sizeof(state));
24938         state.compiler = compiler;
24939         state.arch     = arch;
24940         state.file = 0;
24941         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24942                 memset(&state.token[i], 0, sizeof(state.token[i]));
24943                 state.token[i].tok = -1;
24944         }
24945         /* Remember the output descriptors */
24946         state.errout = stderr;
24947         state.dbgout = stdout;
24948         /* Remember the output filename */
24949         state.output    = fopen(state.compiler->ofilename, "w");
24950         if (!state.output) {
24951                 error(&state, 0, "Cannot open output file %s\n",
24952                         state.compiler->ofilename);
24953         }
24954         /* Make certain a good cleanup happens */
24955         exit_state = &state;
24956         atexit(exit_cleanup);
24957
24958         /* Prep the preprocessor */
24959         state.if_depth = 0;
24960         memset(state.if_bytes, 0, sizeof(state.if_bytes));
24961         /* register the C keywords */
24962         register_keywords(&state);
24963         /* register the keywords the macro preprocessor knows */
24964         register_macro_keywords(&state);
24965         /* generate some builtin macros */
24966         register_builtin_macros(&state);
24967         /* Memorize where some special keywords are. */
24968         state.i_switch        = lookup(&state, "switch", 6);
24969         state.i_case          = lookup(&state, "case", 4);
24970         state.i_continue      = lookup(&state, "continue", 8);
24971         state.i_break         = lookup(&state, "break", 5);
24972         state.i_default       = lookup(&state, "default", 7);
24973         state.i_return        = lookup(&state, "return", 6);
24974         /* Memorize where predefined macros are. */
24975         state.i___VA_ARGS__   = lookup(&state, "__VA_ARGS__", 11);
24976         state.i___FILE__      = lookup(&state, "__FILE__", 8);
24977         state.i___LINE__      = lookup(&state, "__LINE__", 8);
24978         /* Memorize where predefined identifiers are. */
24979         state.i___func__      = lookup(&state, "__func__", 8);
24980         /* Memorize where some attribute keywords are. */
24981         state.i_noinline      = lookup(&state, "noinline", 8);
24982         state.i_always_inline = lookup(&state, "always_inline", 13);
24983
24984         /* Process the command line macros */
24985         process_cmdline_macros(&state);
24986
24987         /* Allocate beginning bounding labels for the function list */
24988         state.first = label(&state);
24989         state.first->id |= TRIPLE_FLAG_VOLATILE;
24990         use_triple(state.first, state.first);
24991         ptr = label(&state);
24992         ptr->id |= TRIPLE_FLAG_VOLATILE;
24993         use_triple(ptr, ptr);
24994         flatten(&state, state.first, ptr);
24995
24996         /* Allocate a label for the pool of global variables */
24997         state.global_pool = label(&state);
24998         state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
24999         flatten(&state, state.first, state.global_pool);
25000
25001         /* Enter the globl definition scope */
25002         start_scope(&state);
25003         register_builtins(&state);
25004
25005         compile_file(&state, filename, 1);
25006         if (includefile)
25007                 compile_file(&state, includefile, 1);
25008
25009         /* Stop if all we want is preprocessor output */
25010         if (state.compiler->flags & COMPILER_PP_ONLY) {
25011                 print_preprocessed_tokens(&state);
25012                 return;
25013         }
25014
25015         decls(&state);
25016
25017         /* Exit the global definition scope */
25018         end_scope(&state);
25019
25020         /* Now that basic compilation has happened 
25021          * optimize the intermediate code 
25022          */
25023         optimize(&state);
25024
25025         generate_code(&state);
25026         if (state.compiler->debug) {
25027                 fprintf(state.errout, "done\n");
25028         }
25029         exit_state = 0;
25030 }
25031
25032 static void version(FILE *fp)
25033 {
25034         fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
25035 }
25036
25037 static void usage(void)
25038 {
25039         FILE *fp = stdout;
25040         version(fp);
25041         fprintf(fp,
25042                 "\nUsage: romcc [options] <source>.c\n"
25043                 "Compile a C source file generating a binary that does not implicilty use RAM\n"
25044                 "Options: \n"
25045                 "-o <output file name>\n"
25046                 "-f<option>            Specify a generic compiler option\n"
25047                 "-m<option>            Specify a arch dependent option\n"
25048                 "--                    Specify this is the last option\n"
25049                 "\nGeneric compiler options:\n"
25050         );
25051         compiler_usage(fp);
25052         fprintf(fp,
25053                 "\nArchitecture compiler options:\n"
25054         );
25055         arch_usage(fp);
25056         fprintf(fp,
25057                 "\n"
25058         );
25059 }
25060
25061 static void arg_error(char *fmt, ...)
25062 {
25063         va_list args;
25064         va_start(args, fmt);
25065         vfprintf(stderr, fmt, args);
25066         va_end(args);
25067         usage();
25068         exit(1);
25069 }
25070
25071 int main(int argc, char **argv)
25072 {
25073         const char *filename;
25074         const char *includefile = NULL;
25075         struct compiler_state compiler;
25076         struct arch_state arch;
25077         int all_opts;
25078         
25079         
25080         /* I don't want any surprises */
25081         setlocale(LC_ALL, "C");
25082
25083         init_compiler_state(&compiler);
25084         init_arch_state(&arch);
25085         filename = 0;
25086         all_opts = 0;
25087         while(argc > 1) {
25088                 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
25089                         compiler.ofilename = argv[2];
25090                         argv += 2;
25091                         argc -= 2;
25092                 }
25093                 else if (!all_opts && argv[1][0] == '-') {
25094                         int result;
25095                         result = -1;
25096                         if (strcmp(argv[1], "--") == 0) {
25097                                 result = 0;
25098                                 all_opts = 1;
25099                         }
25100                         else if (strncmp(argv[1], "-E", 2) == 0) {
25101                                 result = compiler_encode_flag(&compiler, argv[1]);
25102                         }
25103                         else if (strncmp(argv[1], "-O", 2) == 0) {
25104                                 result = compiler_encode_flag(&compiler, argv[1]);
25105                         }
25106                         else if (strncmp(argv[1], "-I", 2) == 0) {
25107                                 result = compiler_encode_flag(&compiler, argv[1]);
25108                         }
25109                         else if (strncmp(argv[1], "-D", 2) == 0) {
25110                                 result = compiler_encode_flag(&compiler, argv[1]);
25111                         }
25112                         else if (strncmp(argv[1], "-U", 2) == 0) {
25113                                 result = compiler_encode_flag(&compiler, argv[1]);
25114                         }
25115                         else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25116                                 result = compiler_encode_flag(&compiler, argv[1]+2);
25117                         }
25118                         else if (strncmp(argv[1], "-f", 2) == 0) {
25119                                 result = compiler_encode_flag(&compiler, argv[1]+2);
25120                         }
25121                         else if (strncmp(argv[1], "-m", 2) == 0) {
25122                                 result = arch_encode_flag(&arch, argv[1]+2);
25123                         }
25124                         else if (strncmp(argv[1], "-include", 10) == 0) {
25125                                 if (includefile) {
25126                                         arg_error("Only one -include option may be specified.\n");
25127                                 } else {
25128                                         argv++;
25129                                         argc--;
25130                                         includefile = argv[1];
25131                                         result = 0;
25132                                 }
25133                         }
25134                         if (result < 0) {
25135                                 arg_error("Invalid option specified: %s\n",
25136                                         argv[1]);
25137                         }
25138                         argv++;
25139                         argc--;
25140                 }
25141                 else {
25142                         if (filename) {
25143                                 arg_error("Only one filename may be specified\n");
25144                         }
25145                         filename = argv[1];
25146                         argv++;
25147                         argc--;
25148                 }
25149         }
25150         if (!filename) {
25151                 arg_error("No filename specified\n");
25152         }
25153         compile(filename, includefile, &compiler, &arch);
25154
25155         return 0;
25156 }