Enable -Werror for 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 "72"
7 #define RELEASE_DATE "10 February 2010"
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
131 struct filelist {
132         const char *filename;
133         struct filelist *next;
134 };
135
136 struct filelist *include_filelist = NULL;
137
138 static void __attribute__((noreturn)) die(char *fmt, ...)
139 {
140         va_list args;
141
142         va_start(args, fmt);
143         vfprintf(stderr, fmt, args);
144         va_end(args);
145         fflush(stdout);
146         fflush(stderr);
147         exit(1);
148 }
149
150 static void *xmalloc(size_t size, const char *name)
151 {
152         void *buf;
153         buf = malloc(size);
154         if (!buf) {
155                 die("Cannot malloc %ld bytes to hold %s: %s\n",
156                         size + 0UL, name, strerror(errno));
157         }
158         return buf;
159 }
160
161 static void *xcmalloc(size_t size, const char *name)
162 {
163         void *buf;
164         buf = xmalloc(size, name);
165         memset(buf, 0, size);
166         return buf;
167 }
168
169 static void *xrealloc(void *ptr, size_t size, const char *name)
170 {
171         void *buf;
172         buf = realloc(ptr, size);
173         if (!buf) {
174                 die("Cannot realloc %ld bytes to hold %s: %s\n",
175                         size + 0UL, name, strerror(errno));
176         }
177         return buf;
178 }
179
180 static void xfree(const void *ptr)
181 {
182         free((void *)ptr);
183 }
184
185 static char *xstrdup(const char *str)
186 {
187         char *new;
188         int len;
189         len = strlen(str);
190         new = xmalloc(len + 1, "xstrdup string");
191         memcpy(new, str, len);
192         new[len] = '\0';
193         return new;
194 }
195
196 static void xchdir(const char *path)
197 {
198         if (chdir(path) != 0) {
199                 die("chdir to `%s' failed: %s\n",
200                         path, strerror(errno));
201         }
202 }
203
204 static int exists(const char *dirname, const char *filename)
205 {
206         char cwd[MAX_CWD_SIZE];
207         int does_exist;
208
209         if (getcwd(cwd, sizeof(cwd)) == 0) {
210                 die("cwd buffer to small");
211         }
212
213         does_exist = 1;
214         if (chdir(dirname) != 0) {
215                 does_exist = 0;
216         }
217         if (does_exist && (access(filename, O_RDONLY) < 0)) {
218                 if ((errno != EACCES) && (errno != EROFS)) {
219                         does_exist = 0;
220                 }
221         }
222         xchdir(cwd);
223         return does_exist;
224 }
225
226
227 static char *slurp_file(const char *dirname, const char *filename, off_t *r_size)
228 {
229         char cwd[MAX_CWD_SIZE];
230         char *buf;
231         off_t size, progress;
232         ssize_t result;
233         FILE* file;
234
235         if (!filename) {
236                 *r_size = 0;
237                 return 0;
238         }
239         if (getcwd(cwd, sizeof(cwd)) == 0) {
240                 die("cwd buffer to small");
241         }
242         xchdir(dirname);
243         file = fopen(filename, "rb");
244         xchdir(cwd);
245         if (file == NULL) {
246                 die("Cannot open '%s' : %s\n",
247                         filename, strerror(errno));
248         }
249         fseek(file, 0, SEEK_END);
250         size = ftell(file);
251         fseek(file, 0, SEEK_SET);
252         *r_size = size +1;
253         buf = xmalloc(size +2, filename);
254         buf[size] = '\n'; /* Make certain the file is newline terminated */
255         buf[size+1] = '\0'; /* Null terminate the file for good measure */
256         progress = 0;
257         while(progress < size) {
258                 result = fread(buf + progress, 1, size - progress, file);
259                 if (result < 0) {
260                         if ((errno == EINTR) || (errno == EAGAIN))
261                                 continue;
262                         die("read on %s of %ld bytes failed: %s\n",
263                                 filename, (size - progress)+ 0UL, strerror(errno));
264                 }
265                 progress += result;
266         }
267         fclose(file);
268         return buf;
269 }
270
271 /* Types on the destination platform */
272 #if DEBUG_ROMCC_WARNINGS
273 #warning "FIXME this assumes 32bit x86 is the destination"
274 #endif
275 typedef int8_t   schar_t;
276 typedef uint8_t  uchar_t;
277 typedef int8_t   char_t;
278 typedef int16_t  short_t;
279 typedef uint16_t ushort_t;
280 typedef int32_t  int_t;
281 typedef uint32_t uint_t;
282 typedef int32_t  long_t;
283 #define ulong_t uint32_t
284
285 #define SCHAR_T_MIN (-128)
286 #define SCHAR_T_MAX 127
287 #define UCHAR_T_MAX 255
288 #define CHAR_T_MIN  SCHAR_T_MIN
289 #define CHAR_T_MAX  SCHAR_T_MAX
290 #define SHRT_T_MIN  (-32768)
291 #define SHRT_T_MAX  32767
292 #define USHRT_T_MAX 65535
293 #define INT_T_MIN   (-LONG_T_MAX - 1)
294 #define INT_T_MAX   2147483647
295 #define UINT_T_MAX  4294967295U
296 #define LONG_T_MIN  (-LONG_T_MAX - 1)
297 #define LONG_T_MAX  2147483647
298 #define ULONG_T_MAX 4294967295U
299
300 #define SIZEOF_I8    8
301 #define SIZEOF_I16   16
302 #define SIZEOF_I32   32
303 #define SIZEOF_I64   64
304
305 #define SIZEOF_CHAR    8
306 #define SIZEOF_SHORT   16
307 #define SIZEOF_INT     32
308 #define SIZEOF_LONG    (sizeof(long_t)*SIZEOF_CHAR)
309
310
311 #define ALIGNOF_CHAR    8
312 #define ALIGNOF_SHORT   16
313 #define ALIGNOF_INT     32
314 #define ALIGNOF_LONG    (sizeof(long_t)*SIZEOF_CHAR)
315
316 #define REG_SIZEOF_REG     32
317 #define REG_SIZEOF_CHAR    REG_SIZEOF_REG
318 #define REG_SIZEOF_SHORT   REG_SIZEOF_REG
319 #define REG_SIZEOF_INT     REG_SIZEOF_REG
320 #define REG_SIZEOF_LONG    REG_SIZEOF_REG
321
322 #define REG_ALIGNOF_REG     REG_SIZEOF_REG
323 #define REG_ALIGNOF_CHAR    REG_SIZEOF_REG
324 #define REG_ALIGNOF_SHORT   REG_SIZEOF_REG
325 #define REG_ALIGNOF_INT     REG_SIZEOF_REG
326 #define REG_ALIGNOF_LONG    REG_SIZEOF_REG
327
328 /* Additional definitions for clarity.
329  * I currently assume a long is the largest native
330  * machine word and that a pointer fits into it.
331  */
332 #define SIZEOF_WORD     SIZEOF_LONG
333 #define SIZEOF_POINTER  SIZEOF_LONG
334 #define ALIGNOF_WORD    ALIGNOF_LONG
335 #define ALIGNOF_POINTER ALIGNOF_LONG
336 #define REG_SIZEOF_POINTER  REG_SIZEOF_LONG
337 #define REG_ALIGNOF_POINTER REG_ALIGNOF_LONG
338
339 struct file_state {
340         struct file_state *prev;
341         const char *basename;
342         char *dirname;
343         const char *buf;
344         off_t size;
345         const char *pos;
346         int line;
347         const char *line_start;
348         int report_line;
349         const char *report_name;
350         const char *report_dir;
351         int macro      : 1;
352         int trigraphs  : 1;
353         int join_lines : 1;
354 };
355 struct hash_entry;
356 struct token {
357         int tok;
358         struct hash_entry *ident;
359         const char *pos;
360         int str_len;
361         union {
362                 ulong_t integer;
363                 const char *str;
364                 int notmacro;
365         } val;
366 };
367
368 /* I have two classes of types:
369  * Operational types.
370  * Logical types.  (The type the C standard says the operation is of)
371  *
372  * The operational types are:
373  * chars
374  * shorts
375  * ints
376  * longs
377  *
378  * floats
379  * doubles
380  * long doubles
381  *
382  * pointer
383  */
384
385
386 /* Machine model.
387  * No memory is useable by the compiler.
388  * There is no floating point support.
389  * All operations take place in general purpose registers.
390  * There is one type of general purpose register.
391  * Unsigned longs are stored in that general purpose register.
392  */
393
394 /* Operations on general purpose registers.
395  */
396
397 #define OP_SDIVT      0
398 #define OP_UDIVT      1
399 #define OP_SMUL       2
400 #define OP_UMUL       3
401 #define OP_SDIV       4
402 #define OP_UDIV       5
403 #define OP_SMOD       6
404 #define OP_UMOD       7
405 #define OP_ADD        8
406 #define OP_SUB        9
407 #define OP_SL        10
408 #define OP_USR       11
409 #define OP_SSR       12
410 #define OP_AND       13
411 #define OP_XOR       14
412 #define OP_OR        15
413 #define OP_POS       16 /* Dummy positive operator don't use it */
414 #define OP_NEG       17
415 #define OP_INVERT    18
416
417 #define OP_EQ        20
418 #define OP_NOTEQ     21
419 #define OP_SLESS     22
420 #define OP_ULESS     23
421 #define OP_SMORE     24
422 #define OP_UMORE     25
423 #define OP_SLESSEQ   26
424 #define OP_ULESSEQ   27
425 #define OP_SMOREEQ   28
426 #define OP_UMOREEQ   29
427
428 #define OP_LFALSE    30  /* Test if the expression is logically false */
429 #define OP_LTRUE     31  /* Test if the expression is logcially true */
430
431 #define OP_LOAD      32
432 #define OP_STORE     33
433 /* For OP_STORE ->type holds the type
434  * RHS(0) holds the destination address
435  * RHS(1) holds the value to store.
436  */
437
438 #define OP_UEXTRACT  34
439 /* OP_UEXTRACT extracts an unsigned bitfield from a pseudo register
440  * RHS(0) holds the psuedo register to extract from
441  * ->type holds the size of the bitfield.
442  * ->u.bitfield.size holds the size of the bitfield.
443  * ->u.bitfield.offset holds the offset to extract from
444  */
445 #define OP_SEXTRACT  35
446 /* OP_SEXTRACT extracts a signed bitfield from a pseudo register
447  * RHS(0) holds the psuedo register to extract from
448  * ->type holds the size of the bitfield.
449  * ->u.bitfield.size holds the size of the bitfield.
450  * ->u.bitfield.offset holds the offset to extract from
451  */
452 #define OP_DEPOSIT   36
453 /* OP_DEPOSIT replaces a bitfield with a new value.
454  * RHS(0) holds the value to replace a bitifield in.
455  * RHS(1) holds the replacement value
456  * ->u.bitfield.size holds the size of the bitfield.
457  * ->u.bitfield.offset holds the deposit into
458  */
459
460 #define OP_NOOP      37
461
462 #define OP_MIN_CONST 50
463 #define OP_MAX_CONST 58
464 #define IS_CONST_OP(X) (((X) >= OP_MIN_CONST) && ((X) <= OP_MAX_CONST))
465 #define OP_INTCONST  50
466 /* For OP_INTCONST ->type holds the type.
467  * ->u.cval holds the constant value.
468  */
469 #define OP_BLOBCONST 51
470 /* For OP_BLOBCONST ->type holds the layout and size
471  * information.  u.blob holds a pointer to the raw binary
472  * data for the constant initializer.
473  */
474 #define OP_ADDRCONST 52
475 /* For OP_ADDRCONST ->type holds the type.
476  * MISC(0) holds the reference to the static variable.
477  * ->u.cval holds an offset from that value.
478  */
479 #define OP_UNKNOWNVAL 59
480 /* For OP_UNKNOWNAL ->type holds the type.
481  * For some reason we don't know what value this type has.
482  * This allows for variables that have don't have values
483  * assigned yet, or variables whose value we simply do not know.
484  */
485
486 #define OP_WRITE     60
487 /* OP_WRITE moves one pseudo register to another.
488  * MISC(0) holds the destination pseudo register, which must be an OP_DECL.
489  * RHS(0) holds the psuedo to move.
490  */
491
492 #define OP_READ      61
493 /* OP_READ reads the value of a variable and makes
494  * it available for the pseudo operation.
495  * Useful for things like def-use chains.
496  * RHS(0) holds points to the triple to read from.
497  */
498 #define OP_COPY      62
499 /* OP_COPY makes a copy of the pseudo register or constant in RHS(0).
500  */
501 #define OP_CONVERT   63
502 /* OP_CONVERT makes a copy of the pseudo register or constant in RHS(0).
503  * And then the type is converted appropriately.
504  */
505 #define OP_PIECE     64
506 /* OP_PIECE returns one piece of a instruction that returns a structure.
507  * MISC(0) is the instruction
508  * u.cval is the LHS piece of the instruction to return.
509  */
510 #define OP_ASM       65
511 /* OP_ASM holds a sequence of assembly instructions, the result
512  * of a C asm directive.
513  * RHS(x) holds input value x to the assembly sequence.
514  * LHS(x) holds the output value x from the assembly sequence.
515  * u.blob holds the string of assembly instructions.
516  */
517
518 #define OP_DEREF     66
519 /* OP_DEREF generates an lvalue from a pointer.
520  * RHS(0) holds the pointer value.
521  * OP_DEREF serves as a place holder to indicate all necessary
522  * checks have been done to indicate a value is an lvalue.
523  */
524 #define OP_DOT       67
525 /* OP_DOT references a submember of a structure lvalue.
526  * MISC(0) holds the lvalue.
527  * ->u.field holds the name of the field we want.
528  *
529  * Not seen after structures are flattened.
530  */
531 #define OP_INDEX     68
532 /* OP_INDEX references a submember of a tuple or array lvalue.
533  * MISC(0) holds the lvalue.
534  * ->u.cval holds the index into the lvalue.
535  *
536  * Not seen after structures are flattened.
537  */
538 #define OP_VAL       69
539 /* OP_VAL returns the value of a subexpression of the current expression.
540  * Useful for operators that have side effects.
541  * RHS(0) holds the expression.
542  * MISC(0) holds the subexpression of RHS(0) that is the
543  * value of the expression.
544  *
545  * Not seen outside of expressions.
546  */
547
548 #define OP_TUPLE     70
549 /* OP_TUPLE is an array of triples that are either variable
550  * or values for a structure or an array.  It is used as
551  * a place holder when flattening compound types.
552  * The value represented by an OP_TUPLE is held in N registers.
553  * LHS(0..N-1) refer to those registers.
554  * ->use is a list of statements that use the value.
555  *
556  * Although OP_TUPLE always has register sized pieces they are not
557  * used until structures are flattened/decomposed into their register
558  * components.
559  * ???? registers ????
560  */
561
562 #define OP_BITREF    71
563 /* OP_BITREF describes a bitfield as an lvalue.
564  * RHS(0) holds the register value.
565  * ->type holds the type of the bitfield.
566  * ->u.bitfield.size holds the size of the bitfield.
567  * ->u.bitfield.offset holds the offset of the bitfield in the register
568  */
569
570
571 #define OP_FCALL     72
572 /* OP_FCALL performs a procedure call.
573  * MISC(0) holds a pointer to the OP_LIST of a function
574  * RHS(x) holds argument x of a function
575  *
576  * Currently not seen outside of expressions.
577  */
578 #define OP_PROG      73
579 /* OP_PROG is an expression that holds a list of statements, or
580  * expressions.  The final expression is the value of the expression.
581  * RHS(0) holds the start of the list.
582  */
583
584 /* statements */
585 #define OP_LIST      80
586 /* OP_LIST Holds a list of statements that compose a function, and a result value.
587  * RHS(0) holds the list of statements.
588  * A list of all functions is maintained.
589  */
590
591 #define OP_BRANCH    81 /* an unconditional branch */
592 /* For branch instructions
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_CBRANCH   82 /* a conditional branch */
599 /* For conditional branch instructions
600  * RHS(0) holds the branch condition.
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_CALL      83 /* an uncontional branch that will return */
607 /* For call instructions
608  * MISC(0) holds the OP_RET that returns from the branch
609  * TARG(0) holds the branch target.
610  * ->next holds where to branch to if the branch is not taken.
611  * The branch target can only be a label
612  */
613
614 #define OP_RET       84 /* an uncontinonal branch through a variable back to an OP_CALL */
615 /* For call instructions
616  * RHS(0) holds the variable with the return address
617  * The branch target can only be a label
618  */
619
620 #define OP_LABEL     86
621 /* OP_LABEL is a triple that establishes an target for branches.
622  * ->use is the list of all branches that use this label.
623  */
624
625 #define OP_ADECL     87
626 /* OP_ADECL is a triple that establishes an lvalue for assignments.
627  * A variable takes N registers to contain.
628  * LHS(0..N-1) refer to an OP_PIECE triple that represents
629  * the Xth register that the variable is stored in.
630  * ->use is a list of statements that use the variable.
631  *
632  * Although OP_ADECL always has register sized pieces they are not
633  * used until structures are flattened/decomposed into their register
634  * components.
635  */
636
637 #define OP_SDECL     88
638 /* OP_SDECL is a triple that establishes a variable of static
639  * storage duration.
640  * ->use is a list of statements that use the variable.
641  * MISC(0) holds the initializer expression.
642  */
643
644
645 #define OP_PHI       89
646 /* OP_PHI is a triple used in SSA form code.
647  * It is used when multiple code paths merge and a variable needs
648  * a single assignment from any of those code paths.
649  * The operation is a cross between OP_DECL and OP_WRITE, which
650  * is what OP_PHI is generated from.
651  *
652  * RHS(x) points to the value from code path x
653  * The number of RHS entries is the number of control paths into the block
654  * in which OP_PHI resides.  The elements of the array point to point
655  * to the variables OP_PHI is derived from.
656  *
657  * MISC(0) holds a pointer to the orginal OP_DECL node.
658  */
659
660 #if 0
661 /* continuation helpers
662  */
663 #define OP_CPS_BRANCH    90 /* an unconditional branch */
664 /* OP_CPS_BRANCH calls a continuation
665  * RHS(x) holds argument x of the function
666  * TARG(0) holds OP_CPS_START target
667  */
668 #define OP_CPS_CBRANCH   91  /* a conditional branch */
669 /* OP_CPS_CBRANCH conditionally calls one of two continuations
670  * RHS(0) holds the branch condition
671  * RHS(x + 1) holds argument x of the function
672  * TARG(0) holds the OP_CPS_START to jump to when true
673  * ->next holds the OP_CPS_START to jump to when false
674  */
675 #define OP_CPS_CALL      92  /* an uncontional branch that will return */
676 /* For OP_CPS_CALL instructions
677  * RHS(x) holds argument x of the function
678  * MISC(0) holds the OP_CPS_RET that returns from the branch
679  * TARG(0) holds the branch target.
680  * ->next holds where the OP_CPS_RET will return to.
681  */
682 #define OP_CPS_RET       93
683 /* OP_CPS_RET conditionally calls one of two continuations
684  * RHS(0) holds the variable with the return function address
685  * RHS(x + 1) holds argument x of the function
686  * The branch target may be any OP_CPS_START
687  */
688 #define OP_CPS_END       94
689 /* OP_CPS_END is the triple at the end of the program.
690  * For most practical purposes it is a branch.
691  */
692 #define OP_CPS_START     95
693 /* OP_CPS_START is a triple at the start of a continuation
694  * The arguments variables takes N registers to contain.
695  * LHS(0..N-1) refer to an OP_PIECE triple that represents
696  * the Xth register that the arguments are stored in.
697  */
698 #endif
699
700 /* Architecture specific instructions */
701 #define OP_CMP         100
702 #define OP_TEST        101
703 #define OP_SET_EQ      102
704 #define OP_SET_NOTEQ   103
705 #define OP_SET_SLESS   104
706 #define OP_SET_ULESS   105
707 #define OP_SET_SMORE   106
708 #define OP_SET_UMORE   107
709 #define OP_SET_SLESSEQ 108
710 #define OP_SET_ULESSEQ 109
711 #define OP_SET_SMOREEQ 110
712 #define OP_SET_UMOREEQ 111
713
714 #define OP_JMP         112
715 #define OP_JMP_EQ      113
716 #define OP_JMP_NOTEQ   114
717 #define OP_JMP_SLESS   115
718 #define OP_JMP_ULESS   116
719 #define OP_JMP_SMORE   117
720 #define OP_JMP_UMORE   118
721 #define OP_JMP_SLESSEQ 119
722 #define OP_JMP_ULESSEQ 120
723 #define OP_JMP_SMOREEQ 121
724 #define OP_JMP_UMOREEQ 122
725
726 /* Builtin operators that it is just simpler to use the compiler for */
727 #define OP_INB         130
728 #define OP_INW         131
729 #define OP_INL         132
730 #define OP_OUTB        133
731 #define OP_OUTW        134
732 #define OP_OUTL        135
733 #define OP_BSF         136
734 #define OP_BSR         137
735 #define OP_RDMSR       138
736 #define OP_WRMSR       139
737 #define OP_HLT         140
738
739 struct op_info {
740         const char *name;
741         unsigned flags;
742 #define PURE       0x001 /* Triple has no side effects */
743 #define IMPURE     0x002 /* Triple has side effects */
744 #define PURE_BITS(FLAGS) ((FLAGS) & 0x3)
745 #define DEF        0x004 /* Triple is a variable definition */
746 #define BLOCK      0x008 /* Triple stores the current block */
747 #define STRUCTURAL 0x010 /* Triple does not generate a machine instruction */
748 #define BRANCH_BITS(FLAGS) ((FLAGS) & 0xe0 )
749 #define UBRANCH    0x020 /* Triple is an unconditional branch instruction */
750 #define CBRANCH    0x040 /* Triple is a conditional branch instruction */
751 #define RETBRANCH  0x060 /* Triple is a return instruction */
752 #define CALLBRANCH 0x080 /* Triple is a call instruction */
753 #define ENDBRANCH  0x0a0 /* Triple is an end instruction */
754 #define PART       0x100 /* Triple is really part of another triple */
755 #define BITFIELD   0x200 /* Triple manipulates a bitfield */
756         signed char lhs, rhs, misc, targ;
757 };
758
759 #define OP(LHS, RHS, MISC, TARG, FLAGS, NAME) { \
760         .name = (NAME), \
761         .flags = (FLAGS), \
762         .lhs = (LHS), \
763         .rhs = (RHS), \
764         .misc = (MISC), \
765         .targ = (TARG), \
766          }
767 static const struct op_info table_ops[] = {
768 [OP_SDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "sdivt"),
769 [OP_UDIVT      ] = OP( 2,  2, 0, 0, PURE | BLOCK , "udivt"),
770 [OP_SMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smul"),
771 [OP_UMUL       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umul"),
772 [OP_SDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sdiv"),
773 [OP_UDIV       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "udiv"),
774 [OP_SMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smod"),
775 [OP_UMOD       ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umod"),
776 [OP_ADD        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "add"),
777 [OP_SUB        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sub"),
778 [OP_SL         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sl"),
779 [OP_USR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "usr"),
780 [OP_SSR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ssr"),
781 [OP_AND        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "and"),
782 [OP_XOR        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "xor"),
783 [OP_OR         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "or"),
784 [OP_POS        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "pos"),
785 [OP_NEG        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "neg"),
786 [OP_INVERT     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "invert"),
787
788 [OP_EQ         ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "eq"),
789 [OP_NOTEQ      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "noteq"),
790 [OP_SLESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "sless"),
791 [OP_ULESS      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "uless"),
792 [OP_SMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smore"),
793 [OP_UMORE      ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umore"),
794 [OP_SLESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "slesseq"),
795 [OP_ULESSEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "ulesseq"),
796 [OP_SMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "smoreeq"),
797 [OP_UMOREEQ    ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK , "umoreeq"),
798 [OP_LFALSE     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "lfalse"),
799 [OP_LTRUE      ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK , "ltrue"),
800
801 [OP_LOAD       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "load"),
802 [OP_STORE      ] = OP( 0,  2, 0, 0, PURE | BLOCK , "store"),
803
804 [OP_UEXTRACT   ] = OP( 0,  1, 0, 0, PURE | DEF | BITFIELD, "uextract"),
805 [OP_SEXTRACT   ] = OP( 0,  1, 0, 0, PURE | DEF | BITFIELD, "sextract"),
806 [OP_DEPOSIT    ] = OP( 0,  2, 0, 0, PURE | DEF | BITFIELD, "deposit"),
807
808 [OP_NOOP       ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "noop"),
809
810 [OP_INTCONST   ] = OP( 0,  0, 0, 0, PURE | DEF, "intconst"),
811 [OP_BLOBCONST  ] = OP( 0,  0, 0, 0, PURE , "blobconst"),
812 [OP_ADDRCONST  ] = OP( 0,  0, 1, 0, PURE | DEF, "addrconst"),
813 [OP_UNKNOWNVAL ] = OP( 0,  0, 0, 0, PURE | DEF, "unknown"),
814
815 #if DEBUG_ROMCC_WARNINGS
816 #warning "FIXME is it correct for OP_WRITE to be a def?  I currently use it as one..."
817 #endif
818 [OP_WRITE      ] = OP( 0,  1, 1, 0, PURE | DEF | BLOCK, "write"),
819 [OP_READ       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "read"),
820 [OP_COPY       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "copy"),
821 [OP_CONVERT    ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "convert"),
822 [OP_PIECE      ] = OP( 0,  0, 1, 0, PURE | DEF | STRUCTURAL | PART, "piece"),
823 [OP_ASM        ] = OP(-1, -1, 0, 0, PURE, "asm"),
824 [OP_DEREF      ] = OP( 0,  1, 0, 0, 0 | DEF | BLOCK, "deref"),
825 [OP_DOT        ] = OP( 0,  0, 1, 0, PURE | DEF | PART, "dot"),
826 [OP_INDEX      ] = OP( 0,  0, 1, 0, PURE | DEF | PART, "index"),
827
828 [OP_VAL        ] = OP( 0,  1, 1, 0, 0 | DEF | BLOCK, "val"),
829 [OP_TUPLE      ] = OP(-1,  0, 0, 0, 0 | PURE | BLOCK | STRUCTURAL, "tuple"),
830 [OP_BITREF     ] = OP( 0,  1, 0, 0, 0 | DEF | PURE | STRUCTURAL | BITFIELD, "bitref"),
831 /* Call is special most it can stand in for anything so it depends on context */
832 [OP_FCALL      ] = OP( 0, -1, 1, 0, 0 | BLOCK | CALLBRANCH, "fcall"),
833 [OP_PROG       ] = OP( 0,  1, 0, 0, 0 | IMPURE | BLOCK | STRUCTURAL, "prog"),
834 /* The sizes of OP_FCALL depends upon context */
835
836 [OP_LIST       ] = OP( 0,  1, 1, 0, 0 | DEF | STRUCTURAL, "list"),
837 [OP_BRANCH     ] = OP( 0,  0, 0, 1, PURE | BLOCK | UBRANCH, "branch"),
838 [OP_CBRANCH    ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "cbranch"),
839 [OP_CALL       ] = OP( 0,  0, 1, 1, PURE | BLOCK | CALLBRANCH, "call"),
840 [OP_RET        ] = OP( 0,  1, 0, 0, PURE | BLOCK | RETBRANCH, "ret"),
841 [OP_LABEL      ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "label"),
842 [OP_ADECL      ] = OP( 0,  0, 0, 0, PURE | BLOCK | STRUCTURAL, "adecl"),
843 [OP_SDECL      ] = OP( 0,  0, 1, 0, PURE | BLOCK | STRUCTURAL, "sdecl"),
844 /* The number of RHS elements of OP_PHI depend upon context */
845 [OP_PHI        ] = OP( 0, -1, 1, 0, PURE | DEF | BLOCK, "phi"),
846
847 #if 0
848 [OP_CPS_BRANCH ] = OP( 0, -1, 0, 1, PURE | BLOCK | UBRANCH,     "cps_branch"),
849 [OP_CPS_CBRANCH] = OP( 0, -1, 0, 1, PURE | BLOCK | CBRANCH,     "cps_cbranch"),
850 [OP_CPS_CALL   ] = OP( 0, -1, 1, 1, PURE | BLOCK | CALLBRANCH,  "cps_call"),
851 [OP_CPS_RET    ] = OP( 0, -1, 0, 0, PURE | BLOCK | RETBRANCH,   "cps_ret"),
852 [OP_CPS_END    ] = OP( 0, -1, 0, 0, IMPURE | BLOCK | ENDBRANCH, "cps_end"),
853 [OP_CPS_START  ] = OP( -1, 0, 0, 0, PURE | BLOCK | STRUCTURAL,  "cps_start"),
854 #endif
855
856 [OP_CMP        ] = OP( 0,  2, 0, 0, PURE | DEF | BLOCK, "cmp"),
857 [OP_TEST       ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "test"),
858 [OP_SET_EQ     ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_eq"),
859 [OP_SET_NOTEQ  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_noteq"),
860 [OP_SET_SLESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_sless"),
861 [OP_SET_ULESS  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_uless"),
862 [OP_SET_SMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smore"),
863 [OP_SET_UMORE  ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umore"),
864 [OP_SET_SLESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_slesseq"),
865 [OP_SET_ULESSEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_ulesseq"),
866 [OP_SET_SMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_smoreq"),
867 [OP_SET_UMOREEQ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "set_umoreq"),
868 [OP_JMP        ] = OP( 0,  0, 0, 1, PURE | BLOCK | UBRANCH, "jmp"),
869 [OP_JMP_EQ     ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_eq"),
870 [OP_JMP_NOTEQ  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_noteq"),
871 [OP_JMP_SLESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_sless"),
872 [OP_JMP_ULESS  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_uless"),
873 [OP_JMP_SMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smore"),
874 [OP_JMP_UMORE  ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umore"),
875 [OP_JMP_SLESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_slesseq"),
876 [OP_JMP_ULESSEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_ulesseq"),
877 [OP_JMP_SMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_smoreq"),
878 [OP_JMP_UMOREEQ] = OP( 0,  1, 0, 1, PURE | BLOCK | CBRANCH, "jmp_umoreq"),
879
880 [OP_INB        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inb"),
881 [OP_INW        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inw"),
882 [OP_INL        ] = OP( 0,  1, 0, 0, IMPURE | DEF | BLOCK, "__inl"),
883 [OP_OUTB       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outb"),
884 [OP_OUTW       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outw"),
885 [OP_OUTL       ] = OP( 0,  2, 0, 0, IMPURE| BLOCK, "__outl"),
886 [OP_BSF        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsf"),
887 [OP_BSR        ] = OP( 0,  1, 0, 0, PURE | DEF | BLOCK, "__bsr"),
888 [OP_RDMSR      ] = OP( 2,  1, 0, 0, IMPURE | BLOCK, "__rdmsr"),
889 [OP_WRMSR      ] = OP( 0,  3, 0, 0, IMPURE | BLOCK, "__wrmsr"),
890 [OP_HLT        ] = OP( 0,  0, 0, 0, IMPURE | BLOCK, "__hlt"),
891 };
892 #undef OP
893 #define OP_MAX      (sizeof(table_ops)/sizeof(table_ops[0]))
894
895 static const char *tops(int index)
896 {
897         static const char unknown[] = "unknown op";
898         if (index < 0) {
899                 return unknown;
900         }
901         if (index > OP_MAX) {
902                 return unknown;
903         }
904         return table_ops[index].name;
905 }
906
907 struct asm_info;
908 struct triple;
909 struct block;
910 struct triple_set {
911         struct triple_set *next;
912         struct triple *member;
913 };
914
915 #define MAX_LHS  63
916 #define MAX_RHS  127
917 #define MAX_MISC 3
918 #define MAX_TARG 1
919
920 struct occurance {
921         int count;
922         const char *filename;
923         const char *function;
924         int line;
925         int col;
926         struct occurance *parent;
927 };
928 struct bitfield {
929         ulong_t size : 8;
930         ulong_t offset : 24;
931 };
932 struct triple {
933         struct triple *next, *prev;
934         struct triple_set *use;
935         struct type *type;
936         unsigned int op : 8;
937         unsigned int template_id : 7;
938         unsigned int lhs  : 6;
939         unsigned int rhs  : 7;
940         unsigned int misc : 2;
941         unsigned int targ : 1;
942 #define TRIPLE_SIZE(TRIPLE) \
943         ((TRIPLE)->lhs + (TRIPLE)->rhs + (TRIPLE)->misc + (TRIPLE)->targ)
944 #define TRIPLE_LHS_OFF(PTR)  (0)
945 #define TRIPLE_RHS_OFF(PTR)  (TRIPLE_LHS_OFF(PTR) + (PTR)->lhs)
946 #define TRIPLE_MISC_OFF(PTR) (TRIPLE_RHS_OFF(PTR) + (PTR)->rhs)
947 #define TRIPLE_TARG_OFF(PTR) (TRIPLE_MISC_OFF(PTR) + (PTR)->misc)
948 #define LHS(PTR,INDEX) ((PTR)->param[TRIPLE_LHS_OFF(PTR) + (INDEX)])
949 #define RHS(PTR,INDEX) ((PTR)->param[TRIPLE_RHS_OFF(PTR) + (INDEX)])
950 #define TARG(PTR,INDEX) ((PTR)->param[TRIPLE_TARG_OFF(PTR) + (INDEX)])
951 #define MISC(PTR,INDEX) ((PTR)->param[TRIPLE_MISC_OFF(PTR) + (INDEX)])
952         unsigned id; /* A scratch value and finally the register */
953 #define TRIPLE_FLAG_FLATTENED   (1 << 31)
954 #define TRIPLE_FLAG_PRE_SPLIT   (1 << 30)
955 #define TRIPLE_FLAG_POST_SPLIT  (1 << 29)
956 #define TRIPLE_FLAG_VOLATILE    (1 << 28)
957 #define TRIPLE_FLAG_INLINE      (1 << 27) /* ???? */
958 #define TRIPLE_FLAG_LOCAL       (1 << 26)
959
960 #define TRIPLE_FLAG_COPY TRIPLE_FLAG_VOLATILE
961         struct occurance *occurance;
962         union {
963                 ulong_t cval;
964                 struct bitfield bitfield;
965                 struct block  *block;
966                 void *blob;
967                 struct hash_entry *field;
968                 struct asm_info *ainfo;
969                 struct triple *func;
970                 struct symbol *symbol;
971         } u;
972         struct triple *param[2];
973 };
974
975 struct reg_info {
976         unsigned reg;
977         unsigned regcm;
978 };
979 struct ins_template {
980         struct reg_info lhs[MAX_LHS + 1], rhs[MAX_RHS + 1];
981 };
982
983 struct asm_info {
984         struct ins_template tmpl;
985         char *str;
986 };
987
988 struct block_set {
989         struct block_set *next;
990         struct block *member;
991 };
992 struct block {
993         struct block *work_next;
994         struct triple *first, *last;
995         int edge_count;
996         struct block_set *edges;
997         int users;
998         struct block_set *use;
999         struct block_set *idominates;
1000         struct block_set *domfrontier;
1001         struct block *idom;
1002         struct block_set *ipdominates;
1003         struct block_set *ipdomfrontier;
1004         struct block *ipdom;
1005         int vertex;
1006
1007 };
1008
1009 struct symbol {
1010         struct symbol *next;
1011         struct hash_entry *ident;
1012         struct triple *def;
1013         struct type *type;
1014         int scope_depth;
1015 };
1016
1017 struct macro_arg {
1018         struct macro_arg *next;
1019         struct hash_entry *ident;
1020 };
1021 struct macro {
1022         struct hash_entry *ident;
1023         const char *buf;
1024         int buf_len;
1025         struct macro_arg *args;
1026         int argc;
1027 };
1028
1029 struct hash_entry {
1030         struct hash_entry *next;
1031         const char *name;
1032         int name_len;
1033         int tok;
1034         struct macro *sym_define;
1035         struct symbol *sym_label;
1036         struct symbol *sym_tag;
1037         struct symbol *sym_ident;
1038 };
1039
1040 #define HASH_TABLE_SIZE 2048
1041
1042 struct compiler_state {
1043         const char *label_prefix;
1044         const char *ofilename;
1045         unsigned long flags;
1046         unsigned long debug;
1047         unsigned long max_allocation_passes;
1048
1049         size_t include_path_count;
1050         const char **include_paths;
1051
1052         size_t define_count;
1053         const char **defines;
1054
1055         size_t undef_count;
1056         const char **undefs;
1057 };
1058 struct arch_state {
1059         unsigned long features;
1060 };
1061 struct basic_blocks {
1062         struct triple *func;
1063         struct triple *first;
1064         struct block *first_block, *last_block;
1065         int last_vertex;
1066 };
1067 #define MAX_PP_IF_DEPTH 63
1068 struct compile_state {
1069         struct compiler_state *compiler;
1070         struct arch_state *arch;
1071         FILE *output;
1072         FILE *errout;
1073         FILE *dbgout;
1074         struct file_state *file;
1075         struct occurance *last_occurance;
1076         const char *function;
1077         int    token_base;
1078         struct token token[6];
1079         struct hash_entry *hash_table[HASH_TABLE_SIZE];
1080         struct hash_entry *i_switch;
1081         struct hash_entry *i_case;
1082         struct hash_entry *i_continue;
1083         struct hash_entry *i_break;
1084         struct hash_entry *i_default;
1085         struct hash_entry *i_return;
1086         struct hash_entry *i_noreturn;
1087         /* Additional hash entries for predefined macros */
1088         struct hash_entry *i_defined;
1089         struct hash_entry *i___VA_ARGS__;
1090         struct hash_entry *i___FILE__;
1091         struct hash_entry *i___LINE__;
1092         /* Additional hash entries for predefined identifiers */
1093         struct hash_entry *i___func__;
1094         /* Additional hash entries for attributes */
1095         struct hash_entry *i_noinline;
1096         struct hash_entry *i_always_inline;
1097         int scope_depth;
1098         unsigned char if_bytes[(MAX_PP_IF_DEPTH + CHAR_BIT -1)/CHAR_BIT];
1099         int if_depth;
1100         int eat_depth, eat_targ;
1101         struct file_state *macro_file;
1102         struct triple *functions;
1103         struct triple *main_function;
1104         struct triple *first;
1105         struct triple *global_pool;
1106         struct basic_blocks bb;
1107         int functions_joined;
1108 };
1109
1110 /* visibility global/local */
1111 /* static/auto duration */
1112 /* typedef, register, inline */
1113 #define STOR_SHIFT         0
1114 #define STOR_MASK     0x001f
1115 /* Visibility */
1116 #define STOR_GLOBAL   0x0001
1117 /* Duration */
1118 #define STOR_PERM     0x0002
1119 /* Definition locality */
1120 #define STOR_NONLOCAL 0x0004  /* The definition is not in this translation unit */
1121 /* Storage specifiers */
1122 #define STOR_AUTO     0x0000
1123 #define STOR_STATIC   0x0002
1124 #define STOR_LOCAL    0x0003
1125 #define STOR_EXTERN   0x0007
1126 #define STOR_INLINE   0x0008
1127 #define STOR_REGISTER 0x0010
1128 #define STOR_TYPEDEF  0x0018
1129
1130 #define QUAL_SHIFT         5
1131 #define QUAL_MASK     0x00e0
1132 #define QUAL_NONE     0x0000
1133 #define QUAL_CONST    0x0020
1134 #define QUAL_VOLATILE 0x0040
1135 #define QUAL_RESTRICT 0x0080
1136
1137 #define TYPE_SHIFT         8
1138 #define TYPE_MASK     0x1f00
1139 #define TYPE_INTEGER(TYPE)    ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_ULLONG)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1140 #define TYPE_ARITHMETIC(TYPE) ((((TYPE) >= TYPE_CHAR) && ((TYPE) <= TYPE_LDOUBLE)) || ((TYPE) == TYPE_ENUM) || ((TYPE) == TYPE_BITFIELD))
1141 #define TYPE_UNSIGNED(TYPE)   ((TYPE) & 0x0100)
1142 #define TYPE_SIGNED(TYPE)     (!TYPE_UNSIGNED(TYPE))
1143 #define TYPE_MKUNSIGNED(TYPE) (((TYPE) & ~0xF000) | 0x0100)
1144 #define TYPE_RANK(TYPE)       ((TYPE) & ~0xF1FF)
1145 #define TYPE_PTR(TYPE)        (((TYPE) & TYPE_MASK) == TYPE_POINTER)
1146 #define TYPE_DEFAULT  0x0000
1147 #define TYPE_VOID     0x0100
1148 #define TYPE_CHAR     0x0200
1149 #define TYPE_UCHAR    0x0300
1150 #define TYPE_SHORT    0x0400
1151 #define TYPE_USHORT   0x0500
1152 #define TYPE_INT      0x0600
1153 #define TYPE_UINT     0x0700
1154 #define TYPE_LONG     0x0800
1155 #define TYPE_ULONG    0x0900
1156 #define TYPE_LLONG    0x0a00 /* long long */
1157 #define TYPE_ULLONG   0x0b00
1158 #define TYPE_FLOAT    0x0c00
1159 #define TYPE_DOUBLE   0x0d00
1160 #define TYPE_LDOUBLE  0x0e00 /* long double */
1161
1162 /* Note: TYPE_ENUM is chosen very carefully so TYPE_RANK works */
1163 #define TYPE_ENUM     0x1600
1164 #define TYPE_LIST     0x1700
1165 /* TYPE_LIST is a basic building block when defining enumerations
1166  * type->field_ident holds the name of this enumeration entry.
1167  * type->right holds the entry in the list.
1168  */
1169
1170 #define TYPE_STRUCT   0x1000
1171 /* For TYPE_STRUCT
1172  * type->left holds the link list of TYPE_PRODUCT entries that
1173  * make up the structure.
1174  * type->elements hold the length of the linked list
1175  */
1176 #define TYPE_UNION    0x1100
1177 /* For TYPE_UNION
1178  * type->left holds the link list of TYPE_OVERLAP entries that
1179  * make up the union.
1180  * type->elements hold the length of the linked list
1181  */
1182 #define TYPE_POINTER  0x1200
1183 /* For TYPE_POINTER:
1184  * type->left holds the type pointed to.
1185  */
1186 #define TYPE_FUNCTION 0x1300
1187 /* For TYPE_FUNCTION:
1188  * type->left holds the return type.
1189  * type->right holds the type of the arguments
1190  * type->elements holds the count of the arguments
1191  */
1192 #define TYPE_PRODUCT  0x1400
1193 /* TYPE_PRODUCT is a basic building block when defining structures
1194  * type->left holds the type that appears first in memory.
1195  * type->right holds the type that appears next in memory.
1196  */
1197 #define TYPE_OVERLAP  0x1500
1198 /* TYPE_OVERLAP is a basic building block when defining unions
1199  * type->left and type->right holds to types that overlap
1200  * each other in memory.
1201  */
1202 #define TYPE_ARRAY    0x1800
1203 /* TYPE_ARRAY is a basic building block when definitng arrays.
1204  * type->left holds the type we are an array of.
1205  * type->elements holds the number of elements.
1206  */
1207 #define TYPE_TUPLE    0x1900
1208 /* TYPE_TUPLE is a basic building block when defining
1209  * positionally reference type conglomerations. (i.e. closures)
1210  * In essence it is a wrapper for TYPE_PRODUCT, like TYPE_STRUCT
1211  * except it has no field names.
1212  * type->left holds the liked list of TYPE_PRODUCT entries that
1213  * make up the closure type.
1214  * type->elements hold the number of elements in the closure.
1215  */
1216 #define TYPE_JOIN     0x1a00
1217 /* TYPE_JOIN is a basic building block when defining
1218  * positionally reference type conglomerations. (i.e. closures)
1219  * In essence it is a wrapper for TYPE_OVERLAP, like TYPE_UNION
1220  * except it has no field names.
1221  * type->left holds the liked list of TYPE_OVERLAP entries that
1222  * make up the closure type.
1223  * type->elements hold the number of elements in the closure.
1224  */
1225 #define TYPE_BITFIELD 0x1b00
1226 /* TYPE_BITFIED is the type of a bitfield.
1227  * type->left holds the type basic type TYPE_BITFIELD is derived from.
1228  * type->elements holds the number of bits in the bitfield.
1229  */
1230 #define TYPE_UNKNOWN  0x1c00
1231 /* TYPE_UNKNOWN is the type of an unknown value.
1232  * Used on unknown consts and other places where I don't know the type.
1233  */
1234
1235 #define ATTRIB_SHIFT                 16
1236 #define ATTRIB_MASK          0xffff0000
1237 #define ATTRIB_NOINLINE      0x00010000
1238 #define ATTRIB_ALWAYS_INLINE 0x00020000
1239
1240 #define ELEMENT_COUNT_UNSPECIFIED ULONG_T_MAX
1241
1242 struct type {
1243         unsigned int type;
1244         struct type *left, *right;
1245         ulong_t elements;
1246         struct hash_entry *field_ident;
1247         struct hash_entry *type_ident;
1248 };
1249
1250 #define TEMPLATE_BITS      7
1251 #define MAX_TEMPLATES      (1<<TEMPLATE_BITS)
1252 #define MAX_REG_EQUIVS     16
1253 #define MAX_REGC           14
1254 #define MAX_REGISTERS      75
1255 #define REGISTER_BITS      7
1256 #define MAX_VIRT_REGISTERS (1<<REGISTER_BITS)
1257 #define REG_ERROR          0
1258 #define REG_UNSET          1
1259 #define REG_UNNEEDED       2
1260 #define REG_VIRT0          (MAX_REGISTERS + 0)
1261 #define REG_VIRT1          (MAX_REGISTERS + 1)
1262 #define REG_VIRT2          (MAX_REGISTERS + 2)
1263 #define REG_VIRT3          (MAX_REGISTERS + 3)
1264 #define REG_VIRT4          (MAX_REGISTERS + 4)
1265 #define REG_VIRT5          (MAX_REGISTERS + 5)
1266 #define REG_VIRT6          (MAX_REGISTERS + 6)
1267 #define REG_VIRT7          (MAX_REGISTERS + 7)
1268 #define REG_VIRT8          (MAX_REGISTERS + 8)
1269 #define REG_VIRT9          (MAX_REGISTERS + 9)
1270
1271 #if (MAX_REGISTERS + 9) > MAX_VIRT_REGISTERS
1272 #error "MAX_VIRT_REGISTERS to small"
1273 #endif
1274 #if (MAX_REGC + REGISTER_BITS) >= 26
1275 #error "Too many id bits used"
1276 #endif
1277
1278 /* Provision for 8 register classes */
1279 #define REG_SHIFT  0
1280 #define REGC_SHIFT REGISTER_BITS
1281 #define REGC_MASK (((1 << MAX_REGC) - 1) << REGISTER_BITS)
1282 #define REG_MASK (MAX_VIRT_REGISTERS -1)
1283 #define ID_REG(ID)              ((ID) & REG_MASK)
1284 #define SET_REG(ID, REG)        ((ID) = (((ID) & ~REG_MASK) | ((REG) & REG_MASK)))
1285 #define ID_REGCM(ID)            (((ID) & REGC_MASK) >> REGC_SHIFT)
1286 #define SET_REGCM(ID, REGCM)    ((ID) = (((ID) & ~REGC_MASK) | (((REGCM) << REGC_SHIFT) & REGC_MASK)))
1287 #define SET_INFO(ID, INFO)      ((ID) = (((ID) & ~(REG_MASK | REGC_MASK)) | \
1288                 (((INFO).reg) & REG_MASK) | ((((INFO).regcm) << REGC_SHIFT) & REGC_MASK)))
1289
1290 #define ARCH_INPUT_REGS 4
1291 #define ARCH_OUTPUT_REGS 4
1292
1293 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS];
1294 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS];
1295 static unsigned arch_reg_regcm(struct compile_state *state, int reg);
1296 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm);
1297 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm);
1298 static void arch_reg_equivs(
1299         struct compile_state *state, unsigned *equiv, int reg);
1300 static int arch_select_free_register(
1301         struct compile_state *state, char *used, int classes);
1302 static unsigned arch_regc_size(struct compile_state *state, int class);
1303 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2);
1304 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type);
1305 static const char *arch_reg_str(int reg);
1306 static struct reg_info arch_reg_constraint(
1307         struct compile_state *state, struct type *type, const char *constraint);
1308 static struct reg_info arch_reg_clobber(
1309         struct compile_state *state, const char *clobber);
1310 static struct reg_info arch_reg_lhs(struct compile_state *state,
1311         struct triple *ins, int index);
1312 static struct reg_info arch_reg_rhs(struct compile_state *state,
1313         struct triple *ins, int index);
1314 static int arch_reg_size(int reg);
1315 static struct triple *transform_to_arch_instruction(
1316         struct compile_state *state, struct triple *ins);
1317 static struct triple *flatten(
1318         struct compile_state *state, struct triple *first, struct triple *ptr);
1319 static void print_dominators(struct compile_state *state,
1320         FILE *fp, struct basic_blocks *bb);
1321 static void print_dominance_frontiers(struct compile_state *state,
1322         FILE *fp, struct basic_blocks *bb);
1323
1324
1325
1326 #define DEBUG_ABORT_ON_ERROR    0x00000001
1327 #define DEBUG_BASIC_BLOCKS      0x00000002
1328 #define DEBUG_FDOMINATORS       0x00000004
1329 #define DEBUG_RDOMINATORS       0x00000008
1330 #define DEBUG_TRIPLES           0x00000010
1331 #define DEBUG_INTERFERENCE      0x00000020
1332 #define DEBUG_SCC_TRANSFORM     0x00000040
1333 #define DEBUG_SCC_TRANSFORM2    0x00000080
1334 #define DEBUG_REBUILD_SSA_FORM  0x00000100
1335 #define DEBUG_INLINE            0x00000200
1336 #define DEBUG_RANGE_CONFLICTS   0x00000400
1337 #define DEBUG_RANGE_CONFLICTS2  0x00000800
1338 #define DEBUG_COLOR_GRAPH       0x00001000
1339 #define DEBUG_COLOR_GRAPH2      0x00002000
1340 #define DEBUG_COALESCING        0x00004000
1341 #define DEBUG_COALESCING2       0x00008000
1342 #define DEBUG_VERIFICATION      0x00010000
1343 #define DEBUG_CALLS             0x00020000
1344 #define DEBUG_CALLS2            0x00040000
1345 #define DEBUG_TOKENS            0x80000000
1346
1347 #define DEBUG_DEFAULT ( \
1348         DEBUG_ABORT_ON_ERROR | \
1349         DEBUG_BASIC_BLOCKS | \
1350         DEBUG_FDOMINATORS | \
1351         DEBUG_RDOMINATORS | \
1352         DEBUG_TRIPLES | \
1353         0 )
1354
1355 #define DEBUG_ALL ( \
1356         DEBUG_ABORT_ON_ERROR   | \
1357         DEBUG_BASIC_BLOCKS     | \
1358         DEBUG_FDOMINATORS      | \
1359         DEBUG_RDOMINATORS      | \
1360         DEBUG_TRIPLES          | \
1361         DEBUG_INTERFERENCE     | \
1362         DEBUG_SCC_TRANSFORM    | \
1363         DEBUG_SCC_TRANSFORM2   | \
1364         DEBUG_REBUILD_SSA_FORM | \
1365         DEBUG_INLINE           | \
1366         DEBUG_RANGE_CONFLICTS  | \
1367         DEBUG_RANGE_CONFLICTS2 | \
1368         DEBUG_COLOR_GRAPH      | \
1369         DEBUG_COLOR_GRAPH2     | \
1370         DEBUG_COALESCING       | \
1371         DEBUG_COALESCING2      | \
1372         DEBUG_VERIFICATION     | \
1373         DEBUG_CALLS            | \
1374         DEBUG_CALLS2           | \
1375         DEBUG_TOKENS           | \
1376         0 )
1377
1378 #define COMPILER_INLINE_MASK               0x00000007
1379 #define COMPILER_INLINE_ALWAYS             0x00000000
1380 #define COMPILER_INLINE_NEVER              0x00000001
1381 #define COMPILER_INLINE_DEFAULTON          0x00000002
1382 #define COMPILER_INLINE_DEFAULTOFF         0x00000003
1383 #define COMPILER_INLINE_NOPENALTY          0x00000004
1384 #define COMPILER_ELIMINATE_INEFECTUAL_CODE 0x00000008
1385 #define COMPILER_SIMPLIFY                  0x00000010
1386 #define COMPILER_SCC_TRANSFORM             0x00000020
1387 #define COMPILER_SIMPLIFY_OP               0x00000040
1388 #define COMPILER_SIMPLIFY_PHI              0x00000080
1389 #define COMPILER_SIMPLIFY_LABEL            0x00000100
1390 #define COMPILER_SIMPLIFY_BRANCH           0x00000200
1391 #define COMPILER_SIMPLIFY_COPY             0x00000400
1392 #define COMPILER_SIMPLIFY_ARITH            0x00000800
1393 #define COMPILER_SIMPLIFY_SHIFT            0x00001000
1394 #define COMPILER_SIMPLIFY_BITWISE          0x00002000
1395 #define COMPILER_SIMPLIFY_LOGICAL          0x00004000
1396 #define COMPILER_SIMPLIFY_BITFIELD         0x00008000
1397
1398 #define COMPILER_TRIGRAPHS                 0x40000000
1399 #define COMPILER_PP_ONLY                   0x80000000
1400
1401 #define COMPILER_DEFAULT_FLAGS ( \
1402         COMPILER_TRIGRAPHS | \
1403         COMPILER_ELIMINATE_INEFECTUAL_CODE | \
1404         COMPILER_INLINE_DEFAULTON | \
1405         COMPILER_SIMPLIFY_OP | \
1406         COMPILER_SIMPLIFY_PHI | \
1407         COMPILER_SIMPLIFY_LABEL | \
1408         COMPILER_SIMPLIFY_BRANCH | \
1409         COMPILER_SIMPLIFY_COPY | \
1410         COMPILER_SIMPLIFY_ARITH | \
1411         COMPILER_SIMPLIFY_SHIFT | \
1412         COMPILER_SIMPLIFY_BITWISE | \
1413         COMPILER_SIMPLIFY_LOGICAL | \
1414         COMPILER_SIMPLIFY_BITFIELD | \
1415         0 )
1416
1417 #define GLOBAL_SCOPE_DEPTH   1
1418 #define FUNCTION_SCOPE_DEPTH (GLOBAL_SCOPE_DEPTH + 1)
1419
1420 static void compile_file(struct compile_state *old_state, const char *filename, int local);
1421
1422
1423
1424 static void init_compiler_state(struct compiler_state *compiler)
1425 {
1426         memset(compiler, 0, sizeof(*compiler));
1427         compiler->label_prefix = "";
1428         compiler->ofilename = "auto.inc";
1429         compiler->flags = COMPILER_DEFAULT_FLAGS;
1430         compiler->debug = 0;
1431         compiler->max_allocation_passes = MAX_ALLOCATION_PASSES;
1432         compiler->include_path_count = 1;
1433         compiler->include_paths      = xcmalloc(sizeof(char *), "include_paths");
1434         compiler->define_count       = 1;
1435         compiler->defines            = xcmalloc(sizeof(char *), "defines");
1436         compiler->undef_count        = 1;
1437         compiler->undefs             = xcmalloc(sizeof(char *), "undefs");
1438 }
1439
1440 struct compiler_flag {
1441         const char *name;
1442         unsigned long flag;
1443 };
1444
1445 struct compiler_arg {
1446         const char *name;
1447         unsigned long mask;
1448         struct compiler_flag flags[16];
1449 };
1450
1451 static int set_flag(
1452         const struct compiler_flag *ptr, unsigned long *flags,
1453         int act, const char *flag)
1454 {
1455         int result = -1;
1456         for(; ptr->name; ptr++) {
1457                 if (strcmp(ptr->name, flag) == 0) {
1458                         break;
1459                 }
1460         }
1461         if (ptr->name) {
1462                 result = 0;
1463                 *flags &= ~(ptr->flag);
1464                 if (act) {
1465                         *flags |= ptr->flag;
1466                 }
1467         }
1468         return result;
1469 }
1470
1471 static int set_arg(
1472         const struct compiler_arg *ptr, unsigned long *flags, const char *arg)
1473 {
1474         const char *val;
1475         int result = -1;
1476         int len;
1477         val = strchr(arg, '=');
1478         if (val) {
1479                 len = val - arg;
1480                 val++;
1481                 for(; ptr->name; ptr++) {
1482                         if (strncmp(ptr->name, arg, len) == 0) {
1483                                 break;
1484                         }
1485                 }
1486                 if (ptr->name) {
1487                         *flags &= ~ptr->mask;
1488                         result = set_flag(&ptr->flags[0], flags, 1, val);
1489                 }
1490         }
1491         return result;
1492 }
1493
1494
1495 static void flag_usage(FILE *fp, const struct compiler_flag *ptr,
1496         const char *prefix, const char *invert_prefix)
1497 {
1498         for(;ptr->name; ptr++) {
1499                 fprintf(fp, "%s%s\n", prefix, ptr->name);
1500                 if (invert_prefix) {
1501                         fprintf(fp, "%s%s\n", invert_prefix, ptr->name);
1502                 }
1503         }
1504 }
1505
1506 static void arg_usage(FILE *fp, const struct compiler_arg *ptr,
1507         const char *prefix)
1508 {
1509         for(;ptr->name; ptr++) {
1510                 const struct compiler_flag *flag;
1511                 for(flag = &ptr->flags[0]; flag->name; flag++) {
1512                         fprintf(fp, "%s%s=%s\n",
1513                                 prefix, ptr->name, flag->name);
1514                 }
1515         }
1516 }
1517
1518 static int append_string(size_t *max, const char ***vec, const char *str,
1519         const char *name)
1520 {
1521         size_t count;
1522         count = ++(*max);
1523         *vec = xrealloc(*vec, sizeof(char *)*count, "name");
1524         (*vec)[count -1] = 0;
1525         (*vec)[count -2] = str;
1526         return 0;
1527 }
1528
1529 static void arg_error(char *fmt, ...);
1530 static const char *identifier(const char *str, const char *end);
1531
1532 static int append_include_path(struct compiler_state *compiler, const char *str)
1533 {
1534         int result;
1535         if (!exists(str, ".")) {
1536                 arg_error("Nonexistent include path: `%s'\n",
1537                         str);
1538         }
1539         result = append_string(&compiler->include_path_count,
1540                 &compiler->include_paths, str, "include_paths");
1541         return result;
1542 }
1543
1544 static int append_define(struct compiler_state *compiler, const char *str)
1545 {
1546         const char *end, *rest;
1547         int result;
1548
1549         end = strchr(str, '=');
1550         if (!end) {
1551                 end = str + strlen(str);
1552         }
1553         rest = identifier(str, end);
1554         if (rest != end) {
1555                 int len = end - str - 1;
1556                 arg_error("Invalid name cannot define macro: `%*.*s'\n",
1557                         len, len, str);
1558         }
1559         result = append_string(&compiler->define_count,
1560                 &compiler->defines, str, "defines");
1561         return result;
1562 }
1563
1564 static int append_undef(struct compiler_state *compiler, const char *str)
1565 {
1566         const char *end, *rest;
1567         int result;
1568
1569         end = str + strlen(str);
1570         rest = identifier(str, end);
1571         if (rest != end) {
1572                 int len = end - str - 1;
1573                 arg_error("Invalid name cannot undefine macro: `%*.*s'\n",
1574                         len, len, str);
1575         }
1576         result = append_string(&compiler->undef_count,
1577                 &compiler->undefs, str, "undefs");
1578         return result;
1579 }
1580
1581 static const struct compiler_flag romcc_flags[] = {
1582         { "trigraphs",                 COMPILER_TRIGRAPHS },
1583         { "pp-only",                   COMPILER_PP_ONLY },
1584         { "eliminate-inefectual-code", COMPILER_ELIMINATE_INEFECTUAL_CODE },
1585         { "simplify",                  COMPILER_SIMPLIFY },
1586         { "scc-transform",             COMPILER_SCC_TRANSFORM },
1587         { "simplify-op",               COMPILER_SIMPLIFY_OP },
1588         { "simplify-phi",              COMPILER_SIMPLIFY_PHI },
1589         { "simplify-label",            COMPILER_SIMPLIFY_LABEL },
1590         { "simplify-branch",           COMPILER_SIMPLIFY_BRANCH },
1591         { "simplify-copy",             COMPILER_SIMPLIFY_COPY },
1592         { "simplify-arith",            COMPILER_SIMPLIFY_ARITH },
1593         { "simplify-shift",            COMPILER_SIMPLIFY_SHIFT },
1594         { "simplify-bitwise",          COMPILER_SIMPLIFY_BITWISE },
1595         { "simplify-logical",          COMPILER_SIMPLIFY_LOGICAL },
1596         { "simplify-bitfield",         COMPILER_SIMPLIFY_BITFIELD },
1597         { 0, 0 },
1598 };
1599 static const struct compiler_arg romcc_args[] = {
1600         { "inline-policy",             COMPILER_INLINE_MASK,
1601                 {
1602                         { "always",      COMPILER_INLINE_ALWAYS, },
1603                         { "never",       COMPILER_INLINE_NEVER, },
1604                         { "defaulton",   COMPILER_INLINE_DEFAULTON, },
1605                         { "defaultoff",  COMPILER_INLINE_DEFAULTOFF, },
1606                         { "nopenalty",   COMPILER_INLINE_NOPENALTY, },
1607                         { 0, 0 },
1608                 },
1609         },
1610         { 0, 0 },
1611 };
1612 static const struct compiler_flag romcc_opt_flags[] = {
1613         { "-O",  COMPILER_SIMPLIFY },
1614         { "-O2", COMPILER_SIMPLIFY | COMPILER_SCC_TRANSFORM },
1615         { "-E",  COMPILER_PP_ONLY },
1616         { 0, 0, },
1617 };
1618 static const struct compiler_flag romcc_debug_flags[] = {
1619         { "all",                   DEBUG_ALL },
1620         { "abort-on-error",        DEBUG_ABORT_ON_ERROR },
1621         { "basic-blocks",          DEBUG_BASIC_BLOCKS },
1622         { "fdominators",           DEBUG_FDOMINATORS },
1623         { "rdominators",           DEBUG_RDOMINATORS },
1624         { "triples",               DEBUG_TRIPLES },
1625         { "interference",          DEBUG_INTERFERENCE },
1626         { "scc-transform",         DEBUG_SCC_TRANSFORM },
1627         { "scc-transform2",        DEBUG_SCC_TRANSFORM2 },
1628         { "rebuild-ssa-form",      DEBUG_REBUILD_SSA_FORM },
1629         { "inline",                DEBUG_INLINE },
1630         { "live-range-conflicts",  DEBUG_RANGE_CONFLICTS },
1631         { "live-range-conflicts2", DEBUG_RANGE_CONFLICTS2 },
1632         { "color-graph",           DEBUG_COLOR_GRAPH },
1633         { "color-graph2",          DEBUG_COLOR_GRAPH2 },
1634         { "coalescing",            DEBUG_COALESCING },
1635         { "coalescing2",           DEBUG_COALESCING2 },
1636         { "verification",          DEBUG_VERIFICATION },
1637         { "calls",                 DEBUG_CALLS },
1638         { "calls2",                DEBUG_CALLS2 },
1639         { "tokens",                DEBUG_TOKENS },
1640         { 0, 0 },
1641 };
1642
1643 static int compiler_encode_flag(
1644         struct compiler_state *compiler, const char *flag)
1645 {
1646         int act;
1647         int result;
1648
1649         act = 1;
1650         result = -1;
1651         if (strncmp(flag, "no-", 3) == 0) {
1652                 flag += 3;
1653                 act = 0;
1654         }
1655         if (strncmp(flag, "-O", 2) == 0) {
1656                 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1657         }
1658         else if (strncmp(flag, "-E", 2) == 0) {
1659                 result = set_flag(romcc_opt_flags, &compiler->flags, act, flag);
1660         }
1661         else if (strncmp(flag, "-I", 2) == 0) {
1662                 result = append_include_path(compiler, flag + 2);
1663         }
1664         else if (strncmp(flag, "-D", 2) == 0) {
1665                 result = append_define(compiler, flag + 2);
1666         }
1667         else if (strncmp(flag, "-U", 2) == 0) {
1668                 result = append_undef(compiler, flag + 2);
1669         }
1670         else if (act && strncmp(flag, "label-prefix=", 13) == 0) {
1671                 result = 0;
1672                 compiler->label_prefix = flag + 13;
1673         }
1674         else if (act && strncmp(flag, "max-allocation-passes=", 22) == 0) {
1675                 unsigned long max_passes;
1676                 char *end;
1677                 max_passes = strtoul(flag + 22, &end, 10);
1678                 if (end[0] == '\0') {
1679                         result = 0;
1680                         compiler->max_allocation_passes = max_passes;
1681                 }
1682         }
1683         else if (act && strcmp(flag, "debug") == 0) {
1684                 result = 0;
1685                 compiler->debug |= DEBUG_DEFAULT;
1686         }
1687         else if (strncmp(flag, "debug-", 6) == 0) {
1688                 flag += 6;
1689                 result = set_flag(romcc_debug_flags, &compiler->debug, act, flag);
1690         }
1691         else {
1692                 result = set_flag(romcc_flags, &compiler->flags, act, flag);
1693                 if (result < 0) {
1694                         result = set_arg(romcc_args, &compiler->flags, flag);
1695                 }
1696         }
1697         return result;
1698 }
1699
1700 static void compiler_usage(FILE *fp)
1701 {
1702         flag_usage(fp, romcc_opt_flags, "", 0);
1703         flag_usage(fp, romcc_flags, "-f", "-fno-");
1704         arg_usage(fp,  romcc_args, "-f");
1705         flag_usage(fp, romcc_debug_flags, "-fdebug-", "-fno-debug-");
1706         fprintf(fp, "-flabel-prefix=<prefix for assembly language labels>\n");
1707         fprintf(fp, "--label-prefix=<prefix for assembly language labels>\n");
1708         fprintf(fp, "-I<include path>\n");
1709         fprintf(fp, "-D<macro>[=defn]\n");
1710         fprintf(fp, "-U<macro>\n");
1711 }
1712
1713 static void do_cleanup(struct compile_state *state)
1714 {
1715         if (state->output) {
1716                 fclose(state->output);
1717                 unlink(state->compiler->ofilename);
1718                 state->output = 0;
1719         }
1720         if (state->dbgout) {
1721                 fflush(state->dbgout);
1722         }
1723         if (state->errout) {
1724                 fflush(state->errout);
1725         }
1726 }
1727
1728 static struct compile_state *exit_state;
1729 static void exit_cleanup(void)
1730 {
1731         if (exit_state) {
1732                 do_cleanup(exit_state);
1733         }
1734 }
1735
1736 static int get_col(struct file_state *file)
1737 {
1738         int col;
1739         const char *ptr, *end;
1740         ptr = file->line_start;
1741         end = file->pos;
1742         for(col = 0; ptr < end; ptr++) {
1743                 if (*ptr != '\t') {
1744                         col++;
1745                 }
1746                 else {
1747                         col = (col & ~7) + 8;
1748                 }
1749         }
1750         return col;
1751 }
1752
1753 static void loc(FILE *fp, struct compile_state *state, struct triple *triple)
1754 {
1755         int col;
1756         if (triple && triple->occurance) {
1757                 struct occurance *spot;
1758                 for(spot = triple->occurance; spot; spot = spot->parent) {
1759                         fprintf(fp, "%s:%d.%d: ",
1760                                 spot->filename, spot->line, spot->col);
1761                 }
1762                 return;
1763         }
1764         if (!state->file) {
1765                 return;
1766         }
1767         col = get_col(state->file);
1768         fprintf(fp, "%s:%d.%d: ",
1769                 state->file->report_name, state->file->report_line, col);
1770 }
1771
1772 static void __attribute__ ((noreturn)) internal_error(struct compile_state *state, struct triple *ptr,
1773         const char *fmt, ...)
1774 {
1775         FILE *fp = state->errout;
1776         va_list args;
1777         va_start(args, fmt);
1778         loc(fp, state, ptr);
1779         fputc('\n', fp);
1780         if (ptr) {
1781                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1782         }
1783         fprintf(fp, "Internal compiler error: ");
1784         vfprintf(fp, fmt, args);
1785         fprintf(fp, "\n");
1786         va_end(args);
1787         do_cleanup(state);
1788         abort();
1789 }
1790
1791
1792 static void internal_warning(struct compile_state *state, struct triple *ptr,
1793         const char *fmt, ...)
1794 {
1795         FILE *fp = state->errout;
1796         va_list args;
1797         va_start(args, fmt);
1798         loc(fp, state, ptr);
1799         if (ptr) {
1800                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1801         }
1802         fprintf(fp, "Internal compiler warning: ");
1803         vfprintf(fp, fmt, args);
1804         fprintf(fp, "\n");
1805         va_end(args);
1806 }
1807
1808
1809
1810 static void __attribute__ ((noreturn)) error(struct compile_state *state, struct triple *ptr,
1811         const char *fmt, ...)
1812 {
1813         FILE *fp = state->errout;
1814         va_list args;
1815         va_start(args, fmt);
1816         loc(fp, state, ptr);
1817         fputc('\n', fp);
1818         if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1819                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1820         }
1821         vfprintf(fp, fmt, args);
1822         va_end(args);
1823         fprintf(fp, "\n");
1824         do_cleanup(state);
1825         if (state->compiler->debug & DEBUG_ABORT_ON_ERROR) {
1826                 abort();
1827         }
1828         exit(1);
1829 }
1830
1831 static void warning(struct compile_state *state, struct triple *ptr,
1832         const char *fmt, ...)
1833 {
1834         FILE *fp = state->errout;
1835         va_list args;
1836         va_start(args, fmt);
1837         loc(fp, state, ptr);
1838         fprintf(fp, "warning: ");
1839         if (ptr && (state->compiler->debug & DEBUG_ABORT_ON_ERROR)) {
1840                 fprintf(fp, "%p %-10s ", ptr, tops(ptr->op));
1841         }
1842         vfprintf(fp, fmt, args);
1843         fprintf(fp, "\n");
1844         va_end(args);
1845 }
1846
1847 #define FINISHME() warning(state, 0, "FINISHME @ %s.%s:%d", __FILE__, __func__, __LINE__)
1848
1849 static void valid_op(struct compile_state *state, int op)
1850 {
1851         char *fmt = "invalid op: %d";
1852         if (op >= OP_MAX) {
1853                 internal_error(state, 0, fmt, op);
1854         }
1855         if (op < 0) {
1856                 internal_error(state, 0, fmt, op);
1857         }
1858 }
1859
1860 static void valid_ins(struct compile_state *state, struct triple *ptr)
1861 {
1862         valid_op(state, ptr->op);
1863 }
1864
1865 #if DEBUG_ROMCC_WARNING
1866 static void valid_param_count(struct compile_state *state, struct triple *ins)
1867 {
1868         int lhs, rhs, misc, targ;
1869         valid_ins(state, ins);
1870         lhs  = table_ops[ins->op].lhs;
1871         rhs  = table_ops[ins->op].rhs;
1872         misc = table_ops[ins->op].misc;
1873         targ = table_ops[ins->op].targ;
1874
1875         if ((lhs >= 0) && (ins->lhs != lhs)) {
1876                 internal_error(state, ins, "Bad lhs count");
1877         }
1878         if ((rhs >= 0) && (ins->rhs != rhs)) {
1879                 internal_error(state, ins, "Bad rhs count");
1880         }
1881         if ((misc >= 0) && (ins->misc != misc)) {
1882                 internal_error(state, ins, "Bad misc count");
1883         }
1884         if ((targ >= 0) && (ins->targ != targ)) {
1885                 internal_error(state, ins, "Bad targ count");
1886         }
1887 }
1888 #endif
1889
1890 static struct type void_type;
1891 static struct type unknown_type;
1892 static void use_triple(struct triple *used, struct triple *user)
1893 {
1894         struct triple_set **ptr, *new;
1895         if (!used)
1896                 return;
1897         if (!user)
1898                 return;
1899         ptr = &used->use;
1900         while(*ptr) {
1901                 if ((*ptr)->member == user) {
1902                         return;
1903                 }
1904                 ptr = &(*ptr)->next;
1905         }
1906         /* Append new to the head of the list,
1907          * copy_func and rename_block_variables
1908          * depends on this.
1909          */
1910         new = xcmalloc(sizeof(*new), "triple_set");
1911         new->member = user;
1912         new->next   = used->use;
1913         used->use   = new;
1914 }
1915
1916 static void unuse_triple(struct triple *used, struct triple *unuser)
1917 {
1918         struct triple_set *use, **ptr;
1919         if (!used) {
1920                 return;
1921         }
1922         ptr = &used->use;
1923         while(*ptr) {
1924                 use = *ptr;
1925                 if (use->member == unuser) {
1926                         *ptr = use->next;
1927                         xfree(use);
1928                 }
1929                 else {
1930                         ptr = &use->next;
1931                 }
1932         }
1933 }
1934
1935 static void put_occurance(struct occurance *occurance)
1936 {
1937         if (occurance) {
1938                 occurance->count -= 1;
1939                 if (occurance->count <= 0) {
1940                         if (occurance->parent) {
1941                                 put_occurance(occurance->parent);
1942                         }
1943                         xfree(occurance);
1944                 }
1945         }
1946 }
1947
1948 static void get_occurance(struct occurance *occurance)
1949 {
1950         if (occurance) {
1951                 occurance->count += 1;
1952         }
1953 }
1954
1955
1956 static struct occurance *new_occurance(struct compile_state *state)
1957 {
1958         struct occurance *result, *last;
1959         const char *filename;
1960         const char *function;
1961         int line, col;
1962
1963         function = "";
1964         filename = 0;
1965         line = 0;
1966         col  = 0;
1967         if (state->file) {
1968                 filename = state->file->report_name;
1969                 line     = state->file->report_line;
1970                 col      = get_col(state->file);
1971         }
1972         if (state->function) {
1973                 function = state->function;
1974         }
1975         last = state->last_occurance;
1976         if (last &&
1977                 (last->col == col) &&
1978                 (last->line == line) &&
1979                 (last->function == function) &&
1980                 ((last->filename == filename) ||
1981                         (strcmp(last->filename, filename) == 0)))
1982         {
1983                 get_occurance(last);
1984                 return last;
1985         }
1986         if (last) {
1987                 state->last_occurance = 0;
1988                 put_occurance(last);
1989         }
1990         result = xmalloc(sizeof(*result), "occurance");
1991         result->count    = 2;
1992         result->filename = filename;
1993         result->function = function;
1994         result->line     = line;
1995         result->col      = col;
1996         result->parent   = 0;
1997         state->last_occurance = result;
1998         return result;
1999 }
2000
2001 static struct occurance *inline_occurance(struct compile_state *state,
2002         struct occurance *base, struct occurance *top)
2003 {
2004         struct occurance *result, *last;
2005         if (top->parent) {
2006                 internal_error(state, 0, "inlining an already inlined function?");
2007         }
2008         /* If I have a null base treat it that way */
2009         if ((base->parent == 0) &&
2010                 (base->col == 0) &&
2011                 (base->line == 0) &&
2012                 (base->function[0] == '\0') &&
2013                 (base->filename[0] == '\0')) {
2014                 base = 0;
2015         }
2016         /* See if I can reuse the last occurance I had */
2017         last = state->last_occurance;
2018         if (last &&
2019                 (last->parent   == base) &&
2020                 (last->col      == top->col) &&
2021                 (last->line     == top->line) &&
2022                 (last->function == top->function) &&
2023                 (last->filename == top->filename)) {
2024                 get_occurance(last);
2025                 return last;
2026         }
2027         /* I can't reuse the last occurance so free it */
2028         if (last) {
2029                 state->last_occurance = 0;
2030                 put_occurance(last);
2031         }
2032         /* Generate a new occurance structure */
2033         get_occurance(base);
2034         result = xmalloc(sizeof(*result), "occurance");
2035         result->count    = 2;
2036         result->filename = top->filename;
2037         result->function = top->function;
2038         result->line     = top->line;
2039         result->col      = top->col;
2040         result->parent   = base;
2041         state->last_occurance = result;
2042         return result;
2043 }
2044
2045 static struct occurance dummy_occurance = {
2046         .count    = 2,
2047         .filename = __FILE__,
2048         .function = "",
2049         .line     = __LINE__,
2050         .col      = 0,
2051         .parent   = 0,
2052 };
2053
2054 /* The undef triple is used as a place holder when we are removing pointers
2055  * from a triple.  Having allows certain sanity checks to pass even
2056  * when the original triple that was pointed to is gone.
2057  */
2058 static struct triple unknown_triple = {
2059         .next      = &unknown_triple,
2060         .prev      = &unknown_triple,
2061         .use       = 0,
2062         .op        = OP_UNKNOWNVAL,
2063         .lhs       = 0,
2064         .rhs       = 0,
2065         .misc      = 0,
2066         .targ      = 0,
2067         .type      = &unknown_type,
2068         .id        = -1, /* An invalid id */
2069         .u = { .cval = 0, },
2070         .occurance = &dummy_occurance,
2071         .param = { [0] = 0, [1] = 0, },
2072 };
2073
2074
2075 static size_t registers_of(struct compile_state *state, struct type *type);
2076
2077 static struct triple *alloc_triple(struct compile_state *state,
2078         int op, struct type *type, int lhs_wanted, int rhs_wanted,
2079         struct occurance *occurance)
2080 {
2081         size_t size, extra_count, min_count;
2082         int lhs, rhs, misc, targ;
2083         struct triple *ret, dummy;
2084         dummy.op = op;
2085         dummy.occurance = occurance;
2086         valid_op(state, op);
2087         lhs = table_ops[op].lhs;
2088         rhs = table_ops[op].rhs;
2089         misc = table_ops[op].misc;
2090         targ = table_ops[op].targ;
2091
2092         switch(op) {
2093         case OP_FCALL:
2094                 rhs = rhs_wanted;
2095                 break;
2096         case OP_PHI:
2097                 rhs = rhs_wanted;
2098                 break;
2099         case OP_ADECL:
2100                 lhs = registers_of(state, type);
2101                 break;
2102         case OP_TUPLE:
2103                 lhs = registers_of(state, type);
2104                 break;
2105         case OP_ASM:
2106                 rhs = rhs_wanted;
2107                 lhs = lhs_wanted;
2108                 break;
2109         }
2110         if ((rhs < 0) || (rhs > MAX_RHS)) {
2111                 internal_error(state, &dummy, "bad rhs count %d", rhs);
2112         }
2113         if ((lhs < 0) || (lhs > MAX_LHS)) {
2114                 internal_error(state, &dummy, "bad lhs count %d", lhs);
2115         }
2116         if ((misc < 0) || (misc > MAX_MISC)) {
2117                 internal_error(state, &dummy, "bad misc count %d", misc);
2118         }
2119         if ((targ < 0) || (targ > MAX_TARG)) {
2120                 internal_error(state, &dummy, "bad targs count %d", targ);
2121         }
2122
2123         min_count = sizeof(ret->param)/sizeof(ret->param[0]);
2124         extra_count = lhs + rhs + misc + targ;
2125         extra_count = (extra_count < min_count)? 0 : extra_count - min_count;
2126
2127         size = sizeof(*ret) + sizeof(ret->param[0]) * extra_count;
2128         ret = xcmalloc(size, "tripple");
2129         ret->op        = op;
2130         ret->lhs       = lhs;
2131         ret->rhs       = rhs;
2132         ret->misc      = misc;
2133         ret->targ      = targ;
2134         ret->type      = type;
2135         ret->next      = ret;
2136         ret->prev      = ret;
2137         ret->occurance = occurance;
2138         /* A simple sanity check */
2139         if ((ret->op != op) ||
2140                 (ret->lhs != lhs) ||
2141                 (ret->rhs != rhs) ||
2142                 (ret->misc != misc) ||
2143                 (ret->targ != targ) ||
2144                 (ret->type != type) ||
2145                 (ret->next != ret) ||
2146                 (ret->prev != ret) ||
2147                 (ret->occurance != occurance)) {
2148                 internal_error(state, ret, "huh?");
2149         }
2150         return ret;
2151 }
2152
2153 struct triple *dup_triple(struct compile_state *state, struct triple *src)
2154 {
2155         struct triple *dup;
2156         int src_lhs, src_rhs, src_size;
2157         src_lhs = src->lhs;
2158         src_rhs = src->rhs;
2159         src_size = TRIPLE_SIZE(src);
2160         get_occurance(src->occurance);
2161         dup = alloc_triple(state, src->op, src->type, src_lhs, src_rhs,
2162                 src->occurance);
2163         memcpy(dup, src, sizeof(*src));
2164         memcpy(dup->param, src->param, src_size * sizeof(src->param[0]));
2165         return dup;
2166 }
2167
2168 static struct triple *copy_triple(struct compile_state *state, struct triple *src)
2169 {
2170         struct triple *copy;
2171         copy = dup_triple(state, src);
2172         copy->use = 0;
2173         copy->next = copy->prev = copy;
2174         return copy;
2175 }
2176
2177 static struct triple *new_triple(struct compile_state *state,
2178         int op, struct type *type, int lhs, int rhs)
2179 {
2180         struct triple *ret;
2181         struct occurance *occurance;
2182         occurance = new_occurance(state);
2183         ret = alloc_triple(state, op, type, lhs, rhs, occurance);
2184         return ret;
2185 }
2186
2187 static struct triple *build_triple(struct compile_state *state,
2188         int op, struct type *type, struct triple *left, struct triple *right,
2189         struct occurance *occurance)
2190 {
2191         struct triple *ret;
2192         size_t count;
2193         ret = alloc_triple(state, op, type, -1, -1, occurance);
2194         count = TRIPLE_SIZE(ret);
2195         if (count > 0) {
2196                 ret->param[0] = left;
2197         }
2198         if (count > 1) {
2199                 ret->param[1] = right;
2200         }
2201         return ret;
2202 }
2203
2204 static struct triple *triple(struct compile_state *state,
2205         int op, struct type *type, struct triple *left, struct triple *right)
2206 {
2207         struct triple *ret;
2208         size_t count;
2209         ret = new_triple(state, op, type, -1, -1);
2210         count = TRIPLE_SIZE(ret);
2211         if (count >= 1) {
2212                 ret->param[0] = left;
2213         }
2214         if (count >= 2) {
2215                 ret->param[1] = right;
2216         }
2217         return ret;
2218 }
2219
2220 static struct triple *branch(struct compile_state *state,
2221         struct triple *targ, struct triple *test)
2222 {
2223         struct triple *ret;
2224         if (test) {
2225                 ret = new_triple(state, OP_CBRANCH, &void_type, -1, 1);
2226                 RHS(ret, 0) = test;
2227         } else {
2228                 ret = new_triple(state, OP_BRANCH, &void_type, -1, 0);
2229         }
2230         TARG(ret, 0) = targ;
2231         /* record the branch target was used */
2232         if (!targ || (targ->op != OP_LABEL)) {
2233                 internal_error(state, 0, "branch not to label");
2234         }
2235         return ret;
2236 }
2237
2238 static int triple_is_label(struct compile_state *state, struct triple *ins);
2239 static int triple_is_call(struct compile_state *state, struct triple *ins);
2240 static int triple_is_cbranch(struct compile_state *state, struct triple *ins);
2241 static void insert_triple(struct compile_state *state,
2242         struct triple *first, struct triple *ptr)
2243 {
2244         if (ptr) {
2245                 if ((ptr->id & TRIPLE_FLAG_FLATTENED) || (ptr->next != ptr)) {
2246                         internal_error(state, ptr, "expression already used");
2247                 }
2248                 ptr->next       = first;
2249                 ptr->prev       = first->prev;
2250                 ptr->prev->next = ptr;
2251                 ptr->next->prev = ptr;
2252
2253                 if (triple_is_cbranch(state, ptr->prev) ||
2254                         triple_is_call(state, ptr->prev)) {
2255                         unuse_triple(first, ptr->prev);
2256                         use_triple(ptr, ptr->prev);
2257                 }
2258         }
2259 }
2260
2261 static int triple_stores_block(struct compile_state *state, struct triple *ins)
2262 {
2263         /* This function is used to determine if u.block
2264          * is utilized to store the current block number.
2265          */
2266         int stores_block;
2267         valid_ins(state, ins);
2268         stores_block = (table_ops[ins->op].flags & BLOCK) == BLOCK;
2269         return stores_block;
2270 }
2271
2272 static int triple_is_branch(struct compile_state *state, struct triple *ins);
2273 static struct block *block_of_triple(struct compile_state *state,
2274         struct triple *ins)
2275 {
2276         struct triple *first;
2277         if (!ins || ins == &unknown_triple) {
2278                 return 0;
2279         }
2280         first = state->first;
2281         while(ins != first && !triple_is_branch(state, ins->prev) &&
2282                 !triple_stores_block(state, ins))
2283         {
2284                 if (ins == ins->prev) {
2285                         internal_error(state, ins, "ins == ins->prev?");
2286                 }
2287                 ins = ins->prev;
2288         }
2289         return triple_stores_block(state, ins)? ins->u.block: 0;
2290 }
2291
2292 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins);
2293 static struct triple *pre_triple(struct compile_state *state,
2294         struct triple *base,
2295         int op, struct type *type, struct triple *left, struct triple *right)
2296 {
2297         struct block *block;
2298         struct triple *ret;
2299         int i;
2300         /* If I am an OP_PIECE jump to the real instruction */
2301         if (base->op == OP_PIECE) {
2302                 base = MISC(base, 0);
2303         }
2304         block = block_of_triple(state, base);
2305         get_occurance(base->occurance);
2306         ret = build_triple(state, op, type, left, right, base->occurance);
2307         generate_lhs_pieces(state, ret);
2308         if (triple_stores_block(state, ret)) {
2309                 ret->u.block = block;
2310         }
2311         insert_triple(state, base, ret);
2312         for(i = 0; i < ret->lhs; i++) {
2313                 struct triple *piece;
2314                 piece = LHS(ret, i);
2315                 insert_triple(state, base, piece);
2316                 use_triple(ret, piece);
2317                 use_triple(piece, ret);
2318         }
2319         if (block && (block->first == base)) {
2320                 block->first = ret;
2321         }
2322         return ret;
2323 }
2324
2325 static struct triple *post_triple(struct compile_state *state,
2326         struct triple *base,
2327         int op, struct type *type, struct triple *left, struct triple *right)
2328 {
2329         struct block *block;
2330         struct triple *ret, *next;
2331         int zlhs, i;
2332         /* If I am an OP_PIECE jump to the real instruction */
2333         if (base->op == OP_PIECE) {
2334                 base = MISC(base, 0);
2335         }
2336         /* If I have a left hand side skip over it */
2337         zlhs = base->lhs;
2338         if (zlhs) {
2339                 base = LHS(base, zlhs - 1);
2340         }
2341
2342         block = block_of_triple(state, base);
2343         get_occurance(base->occurance);
2344         ret = build_triple(state, op, type, left, right, base->occurance);
2345         generate_lhs_pieces(state, ret);
2346         if (triple_stores_block(state, ret)) {
2347                 ret->u.block = block;
2348         }
2349         next = base->next;
2350         insert_triple(state, next, ret);
2351         zlhs = ret->lhs;
2352         for(i = 0; i < zlhs; i++) {
2353                 struct triple *piece;
2354                 piece = LHS(ret, i);
2355                 insert_triple(state, next, piece);
2356                 use_triple(ret, piece);
2357                 use_triple(piece, ret);
2358         }
2359         if (block && (block->last == base)) {
2360                 block->last = ret;
2361                 if (zlhs) {
2362                         block->last = LHS(ret, zlhs - 1);
2363                 }
2364         }
2365         return ret;
2366 }
2367
2368 static struct type *reg_type(
2369         struct compile_state *state, struct type *type, int reg);
2370
2371 static void generate_lhs_piece(
2372         struct compile_state *state, struct triple *ins, int index)
2373 {
2374         struct type *piece_type;
2375         struct triple *piece;
2376         get_occurance(ins->occurance);
2377         piece_type = reg_type(state, ins->type, index * REG_SIZEOF_REG);
2378
2379         if ((piece_type->type & TYPE_MASK) == TYPE_BITFIELD) {
2380                 piece_type = piece_type->left;
2381         }
2382 #if 0
2383 {
2384         static void name_of(FILE *fp, struct type *type);
2385         FILE * fp = state->errout;
2386         fprintf(fp, "piece_type(%d): ", index);
2387         name_of(fp, piece_type);
2388         fprintf(fp, "\n");
2389 }
2390 #endif
2391         piece = alloc_triple(state, OP_PIECE, piece_type, -1, -1, ins->occurance);
2392         piece->u.cval  = index;
2393         LHS(ins, piece->u.cval) = piece;
2394         MISC(piece, 0) = ins;
2395 }
2396
2397 static void generate_lhs_pieces(struct compile_state *state, struct triple *ins)
2398 {
2399         int i, zlhs;
2400         zlhs = ins->lhs;
2401         for(i = 0; i < zlhs; i++) {
2402                 generate_lhs_piece(state, ins, i);
2403         }
2404 }
2405
2406 static struct triple *label(struct compile_state *state)
2407 {
2408         /* Labels don't get a type */
2409         struct triple *result;
2410         result = triple(state, OP_LABEL, &void_type, 0, 0);
2411         return result;
2412 }
2413
2414 static struct triple *mkprog(struct compile_state *state, ...)
2415 {
2416         struct triple *prog, *head, *arg;
2417         va_list args;
2418         int i;
2419
2420         head = label(state);
2421         prog = new_triple(state, OP_PROG, &void_type, -1, -1);
2422         RHS(prog, 0) = head;
2423         va_start(args, state);
2424         i = 0;
2425         while((arg = va_arg(args, struct triple *)) != 0) {
2426                 if (++i >= 100) {
2427                         internal_error(state, 0, "too many arguments to mkprog");
2428                 }
2429                 flatten(state, head, arg);
2430         }
2431         va_end(args);
2432         prog->type = head->prev->type;
2433         return prog;
2434 }
2435 static void name_of(FILE *fp, struct type *type);
2436 static void display_triple(FILE *fp, struct triple *ins)
2437 {
2438         struct occurance *ptr;
2439         const char *reg;
2440         char pre, post, vol;
2441         pre = post = vol = ' ';
2442         if (ins) {
2443                 if (ins->id & TRIPLE_FLAG_PRE_SPLIT) {
2444                         pre = '^';
2445                 }
2446                 if (ins->id & TRIPLE_FLAG_POST_SPLIT) {
2447                         post = ',';
2448                 }
2449                 if (ins->id & TRIPLE_FLAG_VOLATILE) {
2450                         vol = 'v';
2451                 }
2452                 reg = arch_reg_str(ID_REG(ins->id));
2453         }
2454         if (ins == 0) {
2455                 fprintf(fp, "(%p) <nothing> ", ins);
2456         }
2457         else if (ins->op == OP_INTCONST) {
2458                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s <0x%08lx>         ",
2459                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2460                         (unsigned long)(ins->u.cval));
2461         }
2462         else if (ins->op == OP_ADDRCONST) {
2463                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2464                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2465                         MISC(ins, 0), (unsigned long)(ins->u.cval));
2466         }
2467         else if (ins->op == OP_INDEX) {
2468                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2469                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2470                         RHS(ins, 0), (unsigned long)(ins->u.cval));
2471         }
2472         else if (ins->op == OP_PIECE) {
2473                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s %-10p <0x%08lx>",
2474                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op),
2475                         MISC(ins, 0), (unsigned long)(ins->u.cval));
2476         }
2477         else {
2478                 int i, count;
2479                 fprintf(fp, "(%p) %c%c%c %-7s %-2d %-10s",
2480                         ins, pre, post, vol, reg, ins->template_id, tops(ins->op));
2481                 if (table_ops[ins->op].flags & BITFIELD) {
2482                         fprintf(fp, " <%2d-%2d:%2d>",
2483                                 ins->u.bitfield.offset,
2484                                 ins->u.bitfield.offset + ins->u.bitfield.size,
2485                                 ins->u.bitfield.size);
2486                 }
2487                 count = TRIPLE_SIZE(ins);
2488                 for(i = 0; i < count; i++) {
2489                         fprintf(fp, " %-10p", ins->param[i]);
2490                 }
2491                 for(; i < 2; i++) {
2492                         fprintf(fp, "           ");
2493                 }
2494         }
2495         if (ins) {
2496                 struct triple_set *user;
2497 #if DEBUG_DISPLAY_TYPES
2498                 fprintf(fp, " <");
2499                 name_of(fp, ins->type);
2500                 fprintf(fp, "> ");
2501 #endif
2502 #if DEBUG_DISPLAY_USES
2503                 fprintf(fp, " [");
2504                 for(user = ins->use; user; user = user->next) {
2505                         fprintf(fp, " %-10p", user->member);
2506                 }
2507                 fprintf(fp, " ]");
2508 #endif
2509                 fprintf(fp, " @");
2510                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
2511                         fprintf(fp, " %s,%s:%d.%d",
2512                                 ptr->function,
2513                                 ptr->filename,
2514                                 ptr->line,
2515                                 ptr->col);
2516                 }
2517                 if (ins->op == OP_ASM) {
2518                         fprintf(fp, "\n\t%s", ins->u.ainfo->str);
2519                 }
2520         }
2521         fprintf(fp, "\n");
2522         fflush(fp);
2523 }
2524
2525 static int equiv_types(struct type *left, struct type *right);
2526 static void display_triple_changes(
2527         FILE *fp, const struct triple *new, const struct triple *orig)
2528 {
2529
2530         int new_count, orig_count;
2531         new_count = TRIPLE_SIZE(new);
2532         orig_count = TRIPLE_SIZE(orig);
2533         if ((new->op != orig->op) ||
2534                 (new_count != orig_count) ||
2535                 (memcmp(orig->param, new->param,
2536                         orig_count * sizeof(orig->param[0])) != 0) ||
2537                 (memcmp(&orig->u, &new->u, sizeof(orig->u)) != 0))
2538         {
2539                 struct occurance *ptr;
2540                 int i, min_count, indent;
2541                 fprintf(fp, "(%p %p)", new, orig);
2542                 if (orig->op == new->op) {
2543                         fprintf(fp, " %-11s", tops(orig->op));
2544                 } else {
2545                         fprintf(fp, " [%-10s %-10s]",
2546                                 tops(new->op), tops(orig->op));
2547                 }
2548                 min_count = new_count;
2549                 if (min_count > orig_count) {
2550                         min_count = orig_count;
2551                 }
2552                 for(indent = i = 0; i < min_count; i++) {
2553                         if (orig->param[i] == new->param[i]) {
2554                                 fprintf(fp, " %-11p",
2555                                         orig->param[i]);
2556                                 indent += 12;
2557                         } else {
2558                                 fprintf(fp, " [%-10p %-10p]",
2559                                         new->param[i],
2560                                         orig->param[i]);
2561                                 indent += 24;
2562                         }
2563                 }
2564                 for(; i < orig_count; i++) {
2565                         fprintf(fp, " [%-9p]", orig->param[i]);
2566                         indent += 12;
2567                 }
2568                 for(; i < new_count; i++) {
2569                         fprintf(fp, " [%-9p]", new->param[i]);
2570                         indent += 12;
2571                 }
2572                 if ((new->op == OP_INTCONST)||
2573                         (new->op == OP_ADDRCONST)) {
2574                         fprintf(fp, " <0x%08lx>",
2575                                 (unsigned long)(new->u.cval));
2576                         indent += 13;
2577                 }
2578                 for(;indent < 36; indent++) {
2579                         putc(' ', fp);
2580                 }
2581
2582 #if DEBUG_DISPLAY_TYPES
2583                 fprintf(fp, " <");
2584                 name_of(fp, new->type);
2585                 if (!equiv_types(new->type, orig->type)) {
2586                         fprintf(fp, " -- ");
2587                         name_of(fp, orig->type);
2588                 }
2589                 fprintf(fp, "> ");
2590 #endif
2591
2592                 fprintf(fp, " @");
2593                 for(ptr = orig->occurance; ptr; ptr = ptr->parent) {
2594                         fprintf(fp, " %s,%s:%d.%d",
2595                                 ptr->function,
2596                                 ptr->filename,
2597                                 ptr->line,
2598                                 ptr->col);
2599
2600                 }
2601                 fprintf(fp, "\n");
2602                 fflush(fp);
2603         }
2604 }
2605
2606 static int triple_is_pure(struct compile_state *state, struct triple *ins, unsigned id)
2607 {
2608         /* Does the triple have no side effects.
2609          * I.e. Rexecuting the triple with the same arguments
2610          * gives the same value.
2611          */
2612         unsigned pure;
2613         valid_ins(state, ins);
2614         pure = PURE_BITS(table_ops[ins->op].flags);
2615         if ((pure != PURE) && (pure != IMPURE)) {
2616                 internal_error(state, 0, "Purity of %s not known",
2617                         tops(ins->op));
2618         }
2619         return (pure == PURE) && !(id & TRIPLE_FLAG_VOLATILE);
2620 }
2621
2622 static int triple_is_branch_type(struct compile_state *state,
2623         struct triple *ins, unsigned type)
2624 {
2625         /* Is this one of the passed branch types? */
2626         valid_ins(state, ins);
2627         return (BRANCH_BITS(table_ops[ins->op].flags) == type);
2628 }
2629
2630 static int triple_is_branch(struct compile_state *state, struct triple *ins)
2631 {
2632         /* Is this triple a branch instruction? */
2633         valid_ins(state, ins);
2634         return (BRANCH_BITS(table_ops[ins->op].flags) != 0);
2635 }
2636
2637 static int triple_is_cbranch(struct compile_state *state, struct triple *ins)
2638 {
2639         /* Is this triple a conditional branch instruction? */
2640         return triple_is_branch_type(state, ins, CBRANCH);
2641 }
2642
2643 static int triple_is_ubranch(struct compile_state *state, struct triple *ins)
2644 {
2645         /* Is this triple a unconditional branch instruction? */
2646         unsigned type;
2647         valid_ins(state, ins);
2648         type = BRANCH_BITS(table_ops[ins->op].flags);
2649         return (type != 0) && (type != CBRANCH);
2650 }
2651
2652 static int triple_is_call(struct compile_state *state, struct triple *ins)
2653 {
2654         /* Is this triple a call instruction? */
2655         return triple_is_branch_type(state, ins, CALLBRANCH);
2656 }
2657
2658 static int triple_is_ret(struct compile_state *state, struct triple *ins)
2659 {
2660         /* Is this triple a return instruction? */
2661         return triple_is_branch_type(state, ins, RETBRANCH);
2662 }
2663
2664 #if DEBUG_ROMCC_WARNING
2665 static int triple_is_simple_ubranch(struct compile_state *state, struct triple *ins)
2666 {
2667         /* Is this triple an unconditional branch and not a call or a
2668          * return? */
2669         return triple_is_branch_type(state, ins, UBRANCH);
2670 }
2671 #endif
2672
2673 static int triple_is_end(struct compile_state *state, struct triple *ins)
2674 {
2675         return triple_is_branch_type(state, ins, ENDBRANCH);
2676 }
2677
2678 static int triple_is_label(struct compile_state *state, struct triple *ins)
2679 {
2680         valid_ins(state, ins);
2681         return (ins->op == OP_LABEL);
2682 }
2683
2684 static struct triple *triple_to_block_start(
2685         struct compile_state *state, struct triple *start)
2686 {
2687         while(!triple_is_branch(state, start->prev) &&
2688                 (!triple_is_label(state, start) || !start->use)) {
2689                 start = start->prev;
2690         }
2691         return start;
2692 }
2693
2694 static int triple_is_def(struct compile_state *state, struct triple *ins)
2695 {
2696         /* This function is used to determine which triples need
2697          * a register.
2698          */
2699         int is_def;
2700         valid_ins(state, ins);
2701         is_def = (table_ops[ins->op].flags & DEF) == DEF;
2702         if (ins->lhs >= 1) {
2703                 is_def = 0;
2704         }
2705         return is_def;
2706 }
2707
2708 static int triple_is_structural(struct compile_state *state, struct triple *ins)
2709 {
2710         int is_structural;
2711         valid_ins(state, ins);
2712         is_structural = (table_ops[ins->op].flags & STRUCTURAL) == STRUCTURAL;
2713         return is_structural;
2714 }
2715
2716 static int triple_is_part(struct compile_state *state, struct triple *ins)
2717 {
2718         int is_part;
2719         valid_ins(state, ins);
2720         is_part = (table_ops[ins->op].flags & PART) == PART;
2721         return is_part;
2722 }
2723
2724 static int triple_is_auto_var(struct compile_state *state, struct triple *ins)
2725 {
2726         return (ins->op == OP_PIECE) && (MISC(ins, 0)->op == OP_ADECL);
2727 }
2728
2729 static struct triple **triple_iter(struct compile_state *state,
2730         size_t count, struct triple **vector,
2731         struct triple *ins, struct triple **last)
2732 {
2733         struct triple **ret;
2734         ret = 0;
2735         if (count) {
2736                 if (!last) {
2737                         ret = vector;
2738                 }
2739                 else if ((last >= vector) && (last < (vector + count - 1))) {
2740                         ret = last + 1;
2741                 }
2742         }
2743         return ret;
2744
2745 }
2746
2747 static struct triple **triple_lhs(struct compile_state *state,
2748         struct triple *ins, struct triple **last)
2749 {
2750         return triple_iter(state, ins->lhs, &LHS(ins,0),
2751                 ins, last);
2752 }
2753
2754 static struct triple **triple_rhs(struct compile_state *state,
2755         struct triple *ins, struct triple **last)
2756 {
2757         return triple_iter(state, ins->rhs, &RHS(ins,0),
2758                 ins, last);
2759 }
2760
2761 static struct triple **triple_misc(struct compile_state *state,
2762         struct triple *ins, struct triple **last)
2763 {
2764         return triple_iter(state, ins->misc, &MISC(ins,0),
2765                 ins, last);
2766 }
2767
2768 static struct triple **do_triple_targ(struct compile_state *state,
2769         struct triple *ins, struct triple **last, int call_edges, int next_edges)
2770 {
2771         size_t count;
2772         struct triple **ret, **vector;
2773         int next_is_targ;
2774         ret = 0;
2775         count = ins->targ;
2776         next_is_targ = 0;
2777         if (triple_is_cbranch(state, ins)) {
2778                 next_is_targ = 1;
2779         }
2780         if (!call_edges && triple_is_call(state, ins)) {
2781                 count = 0;
2782         }
2783         if (next_edges && triple_is_call(state, ins)) {
2784                 next_is_targ = 1;
2785         }
2786         vector = &TARG(ins, 0);
2787         if (!ret && next_is_targ) {
2788                 if (!last) {
2789                         ret = &ins->next;
2790                 } else if (last == &ins->next) {
2791                         last = 0;
2792                 }
2793         }
2794         if (!ret && count) {
2795                 if (!last) {
2796                         ret = vector;
2797                 }
2798                 else if ((last >= vector) && (last < (vector + count - 1))) {
2799                         ret = last + 1;
2800                 }
2801                 else if (last == vector + count - 1) {
2802                         last = 0;
2803                 }
2804         }
2805         if (!ret && triple_is_ret(state, ins) && call_edges) {
2806                 struct triple_set *use;
2807                 for(use = ins->use; use; use = use->next) {
2808                         if (!triple_is_call(state, use->member)) {
2809                                 continue;
2810                         }
2811                         if (!last) {
2812                                 ret = &use->member->next;
2813                                 break;
2814                         }
2815                         else if (last == &use->member->next) {
2816                                 last = 0;
2817                         }
2818                 }
2819         }
2820         return ret;
2821 }
2822
2823 static struct triple **triple_targ(struct compile_state *state,
2824         struct triple *ins, struct triple **last)
2825 {
2826         return do_triple_targ(state, ins, last, 1, 1);
2827 }
2828
2829 static struct triple **triple_edge_targ(struct compile_state *state,
2830         struct triple *ins, struct triple **last)
2831 {
2832         return do_triple_targ(state, ins, last,
2833                 state->functions_joined, !state->functions_joined);
2834 }
2835
2836 static struct triple *after_lhs(struct compile_state *state, struct triple *ins)
2837 {
2838         struct triple *next;
2839         int lhs, i;
2840         lhs = ins->lhs;
2841         next = ins->next;
2842         for(i = 0; i < lhs; i++) {
2843                 struct triple *piece;
2844                 piece = LHS(ins, i);
2845                 if (next != piece) {
2846                         internal_error(state, ins, "malformed lhs on %s",
2847                                 tops(ins->op));
2848                 }
2849                 if (next->op != OP_PIECE) {
2850                         internal_error(state, ins, "bad lhs op %s at %d on %s",
2851                                 tops(next->op), i, tops(ins->op));
2852                 }
2853                 if (next->u.cval != i) {
2854                         internal_error(state, ins, "bad u.cval of %d %d expected",
2855                                 next->u.cval, i);
2856                 }
2857                 next = next->next;
2858         }
2859         return next;
2860 }
2861
2862 /* Function piece accessor functions */
2863 static struct triple *do_farg(struct compile_state *state,
2864         struct triple *func, unsigned index)
2865 {
2866         struct type *ftype;
2867         struct triple *first, *arg;
2868         unsigned i;
2869
2870         ftype = func->type;
2871         if((index < 0) || (index >= (ftype->elements + 2))) {
2872                 internal_error(state, func, "bad argument index: %d", index);
2873         }
2874         first = RHS(func, 0);
2875         arg = first->next;
2876         for(i = 0; i < index; i++, arg = after_lhs(state, arg)) {
2877                 /* do nothing */
2878         }
2879         if (arg->op != OP_ADECL) {
2880                 internal_error(state, 0, "arg not adecl?");
2881         }
2882         return arg;
2883 }
2884 static struct triple *fresult(struct compile_state *state, struct triple *func)
2885 {
2886         return do_farg(state, func, 0);
2887 }
2888 static struct triple *fretaddr(struct compile_state *state, struct triple *func)
2889 {
2890         return do_farg(state, func, 1);
2891 }
2892 static struct triple *farg(struct compile_state *state,
2893         struct triple *func, unsigned index)
2894 {
2895         return do_farg(state, func, index + 2);
2896 }
2897
2898
2899 static void display_func(struct compile_state *state, FILE *fp, struct triple *func)
2900 {
2901         struct triple *first, *ins;
2902         fprintf(fp, "display_func %s\n", func->type->type_ident->name);
2903         first = ins = RHS(func, 0);
2904         do {
2905                 if (triple_is_label(state, ins) && ins->use) {
2906                         fprintf(fp, "%p:\n", ins);
2907                 }
2908                 display_triple(fp, ins);
2909
2910                 if (triple_is_branch(state, ins)) {
2911                         fprintf(fp, "\n");
2912                 }
2913                 if (ins->next->prev != ins) {
2914                         internal_error(state, ins->next, "bad prev");
2915                 }
2916                 ins = ins->next;
2917         } while(ins != first);
2918 }
2919
2920 static void verify_use(struct compile_state *state,
2921         struct triple *user, struct triple *used)
2922 {
2923         int size, i;
2924         size = TRIPLE_SIZE(user);
2925         for(i = 0; i < size; i++) {
2926                 if (user->param[i] == used) {
2927                         break;
2928                 }
2929         }
2930         if (triple_is_branch(state, user)) {
2931                 if (user->next == used) {
2932                         i = -1;
2933                 }
2934         }
2935         if (i == size) {
2936                 internal_error(state, user, "%s(%p) does not use %s(%p)",
2937                         tops(user->op), user, tops(used->op), used);
2938         }
2939 }
2940
2941 static int find_rhs_use(struct compile_state *state,
2942         struct triple *user, struct triple *used)
2943 {
2944         struct triple **param;
2945         int size, i;
2946         verify_use(state, user, used);
2947
2948 #if DEBUG_ROMCC_WARNINGS
2949 #warning "AUDIT ME ->rhs"
2950 #endif
2951         size = user->rhs;
2952         param = &RHS(user, 0);
2953         for(i = 0; i < size; i++) {
2954                 if (param[i] == used) {
2955                         return i;
2956                 }
2957         }
2958         return -1;
2959 }
2960
2961 static void free_triple(struct compile_state *state, struct triple *ptr)
2962 {
2963         size_t size;
2964         size = sizeof(*ptr) - sizeof(ptr->param) +
2965                 (sizeof(ptr->param[0])*TRIPLE_SIZE(ptr));
2966         ptr->prev->next = ptr->next;
2967         ptr->next->prev = ptr->prev;
2968         if (ptr->use) {
2969                 internal_error(state, ptr, "ptr->use != 0");
2970         }
2971         put_occurance(ptr->occurance);
2972         memset(ptr, -1, size);
2973         xfree(ptr);
2974 }
2975
2976 static void release_triple(struct compile_state *state, struct triple *ptr)
2977 {
2978         struct triple_set *set, *next;
2979         struct triple **expr;
2980         struct block *block;
2981         if (ptr == &unknown_triple) {
2982                 return;
2983         }
2984         valid_ins(state, ptr);
2985         /* Make certain the we are not the first or last element of a block */
2986         block = block_of_triple(state, ptr);
2987         if (block) {
2988                 if ((block->last == ptr) && (block->first == ptr)) {
2989                         block->last = block->first = 0;
2990                 }
2991                 else if (block->last == ptr) {
2992                         block->last = ptr->prev;
2993                 }
2994                 else if (block->first == ptr) {
2995                         block->first = ptr->next;
2996                 }
2997         }
2998         /* Remove ptr from use chains where it is the user */
2999         expr = triple_rhs(state, ptr, 0);
3000         for(; expr; expr = triple_rhs(state, ptr, expr)) {
3001                 if (*expr) {
3002                         unuse_triple(*expr, ptr);
3003                 }
3004         }
3005         expr = triple_lhs(state, ptr, 0);
3006         for(; expr; expr = triple_lhs(state, ptr, expr)) {
3007                 if (*expr) {
3008                         unuse_triple(*expr, ptr);
3009                 }
3010         }
3011         expr = triple_misc(state, ptr, 0);
3012         for(; expr; expr = triple_misc(state, ptr, expr)) {
3013                 if (*expr) {
3014                         unuse_triple(*expr, ptr);
3015                 }
3016         }
3017         expr = triple_targ(state, ptr, 0);
3018         for(; expr; expr = triple_targ(state, ptr, expr)) {
3019                 if (*expr){
3020                         unuse_triple(*expr, ptr);
3021                 }
3022         }
3023         /* Reomve ptr from use chains where it is used */
3024         for(set = ptr->use; set; set = next) {
3025                 next = set->next;
3026                 valid_ins(state, set->member);
3027                 expr = triple_rhs(state, set->member, 0);
3028                 for(; expr; expr = triple_rhs(state, set->member, expr)) {
3029                         if (*expr == ptr) {
3030                                 *expr = &unknown_triple;
3031                         }
3032                 }
3033                 expr = triple_lhs(state, set->member, 0);
3034                 for(; expr; expr = triple_lhs(state, set->member, expr)) {
3035                         if (*expr == ptr) {
3036                                 *expr = &unknown_triple;
3037                         }
3038                 }
3039                 expr = triple_misc(state, set->member, 0);
3040                 for(; expr; expr = triple_misc(state, set->member, expr)) {
3041                         if (*expr == ptr) {
3042                                 *expr = &unknown_triple;
3043                         }
3044                 }
3045                 expr = triple_targ(state, set->member, 0);
3046                 for(; expr; expr = triple_targ(state, set->member, expr)) {
3047                         if (*expr == ptr) {
3048                                 *expr = &unknown_triple;
3049                         }
3050                 }
3051                 unuse_triple(ptr, set->member);
3052         }
3053         free_triple(state, ptr);
3054 }
3055
3056 static void print_triples(struct compile_state *state);
3057 static void print_blocks(struct compile_state *state, const char *func, FILE *fp);
3058
3059 #define TOK_UNKNOWN       0
3060 #define TOK_SPACE         1
3061 #define TOK_SEMI          2
3062 #define TOK_LBRACE        3
3063 #define TOK_RBRACE        4
3064 #define TOK_COMMA         5
3065 #define TOK_EQ            6
3066 #define TOK_COLON         7
3067 #define TOK_LBRACKET      8
3068 #define TOK_RBRACKET      9
3069 #define TOK_LPAREN        10
3070 #define TOK_RPAREN        11
3071 #define TOK_STAR          12
3072 #define TOK_DOTS          13
3073 #define TOK_MORE          14
3074 #define TOK_LESS          15
3075 #define TOK_TIMESEQ       16
3076 #define TOK_DIVEQ         17
3077 #define TOK_MODEQ         18
3078 #define TOK_PLUSEQ        19
3079 #define TOK_MINUSEQ       20
3080 #define TOK_SLEQ          21
3081 #define TOK_SREQ          22
3082 #define TOK_ANDEQ         23
3083 #define TOK_XOREQ         24
3084 #define TOK_OREQ          25
3085 #define TOK_EQEQ          26
3086 #define TOK_NOTEQ         27
3087 #define TOK_QUEST         28
3088 #define TOK_LOGOR         29
3089 #define TOK_LOGAND        30
3090 #define TOK_OR            31
3091 #define TOK_AND           32
3092 #define TOK_XOR           33
3093 #define TOK_LESSEQ        34
3094 #define TOK_MOREEQ        35
3095 #define TOK_SL            36
3096 #define TOK_SR            37
3097 #define TOK_PLUS          38
3098 #define TOK_MINUS         39
3099 #define TOK_DIV           40
3100 #define TOK_MOD           41
3101 #define TOK_PLUSPLUS      42
3102 #define TOK_MINUSMINUS    43
3103 #define TOK_BANG          44
3104 #define TOK_ARROW         45
3105 #define TOK_DOT           46
3106 #define TOK_TILDE         47
3107 #define TOK_LIT_STRING    48
3108 #define TOK_LIT_CHAR      49
3109 #define TOK_LIT_INT       50
3110 #define TOK_LIT_FLOAT     51
3111 #define TOK_MACRO         52
3112 #define TOK_CONCATENATE   53
3113
3114 #define TOK_IDENT         54
3115 #define TOK_STRUCT_NAME   55
3116 #define TOK_ENUM_CONST    56
3117 #define TOK_TYPE_NAME     57
3118
3119 #define TOK_AUTO          58
3120 #define TOK_BREAK         59
3121 #define TOK_CASE          60
3122 #define TOK_CHAR          61
3123 #define TOK_CONST         62
3124 #define TOK_CONTINUE      63
3125 #define TOK_DEFAULT       64
3126 #define TOK_DO            65
3127 #define TOK_DOUBLE        66
3128 #define TOK_ELSE          67
3129 #define TOK_ENUM          68
3130 #define TOK_EXTERN        69
3131 #define TOK_FLOAT         70
3132 #define TOK_FOR           71
3133 #define TOK_GOTO          72
3134 #define TOK_IF            73
3135 #define TOK_INLINE        74
3136 #define TOK_INT           75
3137 #define TOK_LONG          76
3138 #define TOK_REGISTER      77
3139 #define TOK_RESTRICT      78
3140 #define TOK_RETURN        79
3141 #define TOK_SHORT         80
3142 #define TOK_SIGNED        81
3143 #define TOK_SIZEOF        82
3144 #define TOK_STATIC        83
3145 #define TOK_STRUCT        84
3146 #define TOK_SWITCH        85
3147 #define TOK_TYPEDEF       86
3148 #define TOK_UNION         87
3149 #define TOK_UNSIGNED      88
3150 #define TOK_VOID          89
3151 #define TOK_VOLATILE      90
3152 #define TOK_WHILE         91
3153 #define TOK_ASM           92
3154 #define TOK_ATTRIBUTE     93
3155 #define TOK_ALIGNOF       94
3156 #define TOK_FIRST_KEYWORD TOK_AUTO
3157 #define TOK_LAST_KEYWORD  TOK_ALIGNOF
3158
3159 #define TOK_MDEFINE       100
3160 #define TOK_MDEFINED      101
3161 #define TOK_MUNDEF        102
3162 #define TOK_MINCLUDE      103
3163 #define TOK_MLINE         104
3164 #define TOK_MERROR        105
3165 #define TOK_MWARNING      106
3166 #define TOK_MPRAGMA       107
3167 #define TOK_MIFDEF        108
3168 #define TOK_MIFNDEF       109
3169 #define TOK_MELIF         110
3170 #define TOK_MENDIF        111
3171
3172 #define TOK_FIRST_MACRO   TOK_MDEFINE
3173 #define TOK_LAST_MACRO    TOK_MENDIF
3174
3175 #define TOK_MIF           112
3176 #define TOK_MELSE         113
3177 #define TOK_MIDENT        114
3178
3179 #define TOK_EOL           115
3180 #define TOK_EOF           116
3181
3182 static const char *tokens[] = {
3183 [TOK_UNKNOWN     ] = ":unknown:",
3184 [TOK_SPACE       ] = ":space:",
3185 [TOK_SEMI        ] = ";",
3186 [TOK_LBRACE      ] = "{",
3187 [TOK_RBRACE      ] = "}",
3188 [TOK_COMMA       ] = ",",
3189 [TOK_EQ          ] = "=",
3190 [TOK_COLON       ] = ":",
3191 [TOK_LBRACKET    ] = "[",
3192 [TOK_RBRACKET    ] = "]",
3193 [TOK_LPAREN      ] = "(",
3194 [TOK_RPAREN      ] = ")",
3195 [TOK_STAR        ] = "*",
3196 [TOK_DOTS        ] = "...",
3197 [TOK_MORE        ] = ">",
3198 [TOK_LESS        ] = "<",
3199 [TOK_TIMESEQ     ] = "*=",
3200 [TOK_DIVEQ       ] = "/=",
3201 [TOK_MODEQ       ] = "%=",
3202 [TOK_PLUSEQ      ] = "+=",
3203 [TOK_MINUSEQ     ] = "-=",
3204 [TOK_SLEQ        ] = "<<=",
3205 [TOK_SREQ        ] = ">>=",
3206 [TOK_ANDEQ       ] = "&=",
3207 [TOK_XOREQ       ] = "^=",
3208 [TOK_OREQ        ] = "|=",
3209 [TOK_EQEQ        ] = "==",
3210 [TOK_NOTEQ       ] = "!=",
3211 [TOK_QUEST       ] = "?",
3212 [TOK_LOGOR       ] = "||",
3213 [TOK_LOGAND      ] = "&&",
3214 [TOK_OR          ] = "|",
3215 [TOK_AND         ] = "&",
3216 [TOK_XOR         ] = "^",
3217 [TOK_LESSEQ      ] = "<=",
3218 [TOK_MOREEQ      ] = ">=",
3219 [TOK_SL          ] = "<<",
3220 [TOK_SR          ] = ">>",
3221 [TOK_PLUS        ] = "+",
3222 [TOK_MINUS       ] = "-",
3223 [TOK_DIV         ] = "/",
3224 [TOK_MOD         ] = "%",
3225 [TOK_PLUSPLUS    ] = "++",
3226 [TOK_MINUSMINUS  ] = "--",
3227 [TOK_BANG        ] = "!",
3228 [TOK_ARROW       ] = "->",
3229 [TOK_DOT         ] = ".",
3230 [TOK_TILDE       ] = "~",
3231 [TOK_LIT_STRING  ] = ":string:",
3232 [TOK_IDENT       ] = ":ident:",
3233 [TOK_TYPE_NAME   ] = ":typename:",
3234 [TOK_LIT_CHAR    ] = ":char:",
3235 [TOK_LIT_INT     ] = ":integer:",
3236 [TOK_LIT_FLOAT   ] = ":float:",
3237 [TOK_MACRO       ] = "#",
3238 [TOK_CONCATENATE ] = "##",
3239
3240 [TOK_AUTO        ] = "auto",
3241 [TOK_BREAK       ] = "break",
3242 [TOK_CASE        ] = "case",
3243 [TOK_CHAR        ] = "char",
3244 [TOK_CONST       ] = "const",
3245 [TOK_CONTINUE    ] = "continue",
3246 [TOK_DEFAULT     ] = "default",
3247 [TOK_DO          ] = "do",
3248 [TOK_DOUBLE      ] = "double",
3249 [TOK_ELSE        ] = "else",
3250 [TOK_ENUM        ] = "enum",
3251 [TOK_EXTERN      ] = "extern",
3252 [TOK_FLOAT       ] = "float",
3253 [TOK_FOR         ] = "for",
3254 [TOK_GOTO        ] = "goto",
3255 [TOK_IF          ] = "if",
3256 [TOK_INLINE      ] = "inline",
3257 [TOK_INT         ] = "int",
3258 [TOK_LONG        ] = "long",
3259 [TOK_REGISTER    ] = "register",
3260 [TOK_RESTRICT    ] = "restrict",
3261 [TOK_RETURN      ] = "return",
3262 [TOK_SHORT       ] = "short",
3263 [TOK_SIGNED      ] = "signed",
3264 [TOK_SIZEOF      ] = "sizeof",
3265 [TOK_STATIC      ] = "static",
3266 [TOK_STRUCT      ] = "struct",
3267 [TOK_SWITCH      ] = "switch",
3268 [TOK_TYPEDEF     ] = "typedef",
3269 [TOK_UNION       ] = "union",
3270 [TOK_UNSIGNED    ] = "unsigned",
3271 [TOK_VOID        ] = "void",
3272 [TOK_VOLATILE    ] = "volatile",
3273 [TOK_WHILE       ] = "while",
3274 [TOK_ASM         ] = "asm",
3275 [TOK_ATTRIBUTE   ] = "__attribute__",
3276 [TOK_ALIGNOF     ] = "__alignof__",
3277
3278 [TOK_MDEFINE     ] = "#define",
3279 [TOK_MDEFINED    ] = "#defined",
3280 [TOK_MUNDEF      ] = "#undef",
3281 [TOK_MINCLUDE    ] = "#include",
3282 [TOK_MLINE       ] = "#line",
3283 [TOK_MERROR      ] = "#error",
3284 [TOK_MWARNING    ] = "#warning",
3285 [TOK_MPRAGMA     ] = "#pragma",
3286 [TOK_MIFDEF      ] = "#ifdef",
3287 [TOK_MIFNDEF     ] = "#ifndef",
3288 [TOK_MELIF       ] = "#elif",
3289 [TOK_MENDIF      ] = "#endif",
3290
3291 [TOK_MIF         ] = "#if",
3292 [TOK_MELSE       ] = "#else",
3293 [TOK_MIDENT      ] = "#:ident:",
3294 [TOK_EOL         ] = "EOL",
3295 [TOK_EOF         ] = "EOF",
3296 };
3297
3298 static unsigned int hash(const char *str, int str_len)
3299 {
3300         unsigned int hash;
3301         const char *end;
3302         end = str + str_len;
3303         hash = 0;
3304         for(; str < end; str++) {
3305                 hash = (hash *263) + *str;
3306         }
3307         hash = hash & (HASH_TABLE_SIZE -1);
3308         return hash;
3309 }
3310
3311 static struct hash_entry *lookup(
3312         struct compile_state *state, const char *name, int name_len)
3313 {
3314         struct hash_entry *entry;
3315         unsigned int index;
3316         index = hash(name, name_len);
3317         entry = state->hash_table[index];
3318         while(entry &&
3319                 ((entry->name_len != name_len) ||
3320                         (memcmp(entry->name, name, name_len) != 0))) {
3321                 entry = entry->next;
3322         }
3323         if (!entry) {
3324                 char *new_name;
3325                 /* Get a private copy of the name */
3326                 new_name = xmalloc(name_len + 1, "hash_name");
3327                 memcpy(new_name, name, name_len);
3328                 new_name[name_len] = '\0';
3329
3330                 /* Create a new hash entry */
3331                 entry = xcmalloc(sizeof(*entry), "hash_entry");
3332                 entry->next = state->hash_table[index];
3333                 entry->name = new_name;
3334                 entry->name_len = name_len;
3335
3336                 /* Place the new entry in the hash table */
3337                 state->hash_table[index] = entry;
3338         }
3339         return entry;
3340 }
3341
3342 static void ident_to_keyword(struct compile_state *state, struct token *tk)
3343 {
3344         struct hash_entry *entry;
3345         entry = tk->ident;
3346         if (entry && ((entry->tok == TOK_TYPE_NAME) ||
3347                 (entry->tok == TOK_ENUM_CONST) ||
3348                 ((entry->tok >= TOK_FIRST_KEYWORD) &&
3349                         (entry->tok <= TOK_LAST_KEYWORD)))) {
3350                 tk->tok = entry->tok;
3351         }
3352 }
3353
3354 static void ident_to_macro(struct compile_state *state, struct token *tk)
3355 {
3356         struct hash_entry *entry;
3357         entry = tk->ident;
3358         if (!entry)
3359                 return;
3360         if ((entry->tok >= TOK_FIRST_MACRO) && (entry->tok <= TOK_LAST_MACRO)) {
3361                 tk->tok = entry->tok;
3362         }
3363         else if (entry->tok == TOK_IF) {
3364                 tk->tok = TOK_MIF;
3365         }
3366         else if (entry->tok == TOK_ELSE) {
3367                 tk->tok = TOK_MELSE;
3368         }
3369         else {
3370                 tk->tok = TOK_MIDENT;
3371         }
3372 }
3373
3374 static void hash_keyword(
3375         struct compile_state *state, const char *keyword, int tok)
3376 {
3377         struct hash_entry *entry;
3378         entry = lookup(state, keyword, strlen(keyword));
3379         if (entry && entry->tok != TOK_UNKNOWN) {
3380                 die("keyword %s already hashed", keyword);
3381         }
3382         entry->tok  = tok;
3383 }
3384
3385 static void romcc_symbol(
3386         struct compile_state *state, struct hash_entry *ident,
3387         struct symbol **chain, struct triple *def, struct type *type, int depth)
3388 {
3389         struct symbol *sym;
3390         if (*chain && ((*chain)->scope_depth >= depth)) {
3391                 error(state, 0, "%s already defined", ident->name);
3392         }
3393         sym = xcmalloc(sizeof(*sym), "symbol");
3394         sym->ident = ident;
3395         sym->def   = def;
3396         sym->type  = type;
3397         sym->scope_depth = depth;
3398         sym->next = *chain;
3399         *chain    = sym;
3400 }
3401
3402 static void symbol(
3403         struct compile_state *state, struct hash_entry *ident,
3404         struct symbol **chain, struct triple *def, struct type *type)
3405 {
3406         romcc_symbol(state, ident, chain, def, type, state->scope_depth);
3407 }
3408
3409 static void var_symbol(struct compile_state *state,
3410         struct hash_entry *ident, struct triple *def)
3411 {
3412         if ((def->type->type & TYPE_MASK) == TYPE_PRODUCT) {
3413                 internal_error(state, 0, "bad var type");
3414         }
3415         symbol(state, ident, &ident->sym_ident, def, def->type);
3416 }
3417
3418 static void label_symbol(struct compile_state *state,
3419         struct hash_entry *ident, struct triple *label, int depth)
3420 {
3421         romcc_symbol(state, ident, &ident->sym_label, label, &void_type, depth);
3422 }
3423
3424 static void start_scope(struct compile_state *state)
3425 {
3426         state->scope_depth++;
3427 }
3428
3429 static void end_scope_syms(struct compile_state *state,
3430         struct symbol **chain, int depth)
3431 {
3432         struct symbol *sym, *next;
3433         sym = *chain;
3434         while(sym && (sym->scope_depth == depth)) {
3435                 next = sym->next;
3436                 xfree(sym);
3437                 sym = next;
3438         }
3439         *chain = sym;
3440 }
3441
3442 static void end_scope(struct compile_state *state)
3443 {
3444         int i;
3445         int depth;
3446         /* Walk through the hash table and remove all symbols
3447          * in the current scope.
3448          */
3449         depth = state->scope_depth;
3450         for(i = 0; i < HASH_TABLE_SIZE; i++) {
3451                 struct hash_entry *entry;
3452                 entry = state->hash_table[i];
3453                 while(entry) {
3454                         end_scope_syms(state, &entry->sym_label, depth);
3455                         end_scope_syms(state, &entry->sym_tag,   depth);
3456                         end_scope_syms(state, &entry->sym_ident, depth);
3457                         entry = entry->next;
3458                 }
3459         }
3460         state->scope_depth = depth - 1;
3461 }
3462
3463 static void register_keywords(struct compile_state *state)
3464 {
3465         hash_keyword(state, "auto",          TOK_AUTO);
3466         hash_keyword(state, "break",         TOK_BREAK);
3467         hash_keyword(state, "case",          TOK_CASE);
3468         hash_keyword(state, "char",          TOK_CHAR);
3469         hash_keyword(state, "const",         TOK_CONST);
3470         hash_keyword(state, "continue",      TOK_CONTINUE);
3471         hash_keyword(state, "default",       TOK_DEFAULT);
3472         hash_keyword(state, "do",            TOK_DO);
3473         hash_keyword(state, "double",        TOK_DOUBLE);
3474         hash_keyword(state, "else",          TOK_ELSE);
3475         hash_keyword(state, "enum",          TOK_ENUM);
3476         hash_keyword(state, "extern",        TOK_EXTERN);
3477         hash_keyword(state, "float",         TOK_FLOAT);
3478         hash_keyword(state, "for",           TOK_FOR);
3479         hash_keyword(state, "goto",          TOK_GOTO);
3480         hash_keyword(state, "if",            TOK_IF);
3481         hash_keyword(state, "inline",        TOK_INLINE);
3482         hash_keyword(state, "int",           TOK_INT);
3483         hash_keyword(state, "long",          TOK_LONG);
3484         hash_keyword(state, "register",      TOK_REGISTER);
3485         hash_keyword(state, "restrict",      TOK_RESTRICT);
3486         hash_keyword(state, "return",        TOK_RETURN);
3487         hash_keyword(state, "short",         TOK_SHORT);
3488         hash_keyword(state, "signed",        TOK_SIGNED);
3489         hash_keyword(state, "sizeof",        TOK_SIZEOF);
3490         hash_keyword(state, "static",        TOK_STATIC);
3491         hash_keyword(state, "struct",        TOK_STRUCT);
3492         hash_keyword(state, "switch",        TOK_SWITCH);
3493         hash_keyword(state, "typedef",       TOK_TYPEDEF);
3494         hash_keyword(state, "union",         TOK_UNION);
3495         hash_keyword(state, "unsigned",      TOK_UNSIGNED);
3496         hash_keyword(state, "void",          TOK_VOID);
3497         hash_keyword(state, "volatile",      TOK_VOLATILE);
3498         hash_keyword(state, "__volatile__",  TOK_VOLATILE);
3499         hash_keyword(state, "while",         TOK_WHILE);
3500         hash_keyword(state, "asm",           TOK_ASM);
3501         hash_keyword(state, "__asm__",       TOK_ASM);
3502         hash_keyword(state, "__attribute__", TOK_ATTRIBUTE);
3503         hash_keyword(state, "__alignof__",   TOK_ALIGNOF);
3504 }
3505
3506 static void register_macro_keywords(struct compile_state *state)
3507 {
3508         hash_keyword(state, "define",        TOK_MDEFINE);
3509         hash_keyword(state, "defined",       TOK_MDEFINED);
3510         hash_keyword(state, "undef",         TOK_MUNDEF);
3511         hash_keyword(state, "include",       TOK_MINCLUDE);
3512         hash_keyword(state, "line",          TOK_MLINE);
3513         hash_keyword(state, "error",         TOK_MERROR);
3514         hash_keyword(state, "warning",       TOK_MWARNING);
3515         hash_keyword(state, "pragma",        TOK_MPRAGMA);
3516         hash_keyword(state, "ifdef",         TOK_MIFDEF);
3517         hash_keyword(state, "ifndef",        TOK_MIFNDEF);
3518         hash_keyword(state, "elif",          TOK_MELIF);
3519         hash_keyword(state, "endif",         TOK_MENDIF);
3520 }
3521
3522
3523 static void undef_macro(struct compile_state *state, struct hash_entry *ident)
3524 {
3525         if (ident->sym_define != 0) {
3526                 struct macro *macro;
3527                 struct macro_arg *arg, *anext;
3528                 macro = ident->sym_define;
3529                 ident->sym_define = 0;
3530
3531                 /* Free the macro arguments... */
3532                 anext = macro->args;
3533                 while(anext) {
3534                         arg = anext;
3535                         anext = arg->next;
3536                         xfree(arg);
3537                 }
3538
3539                 /* Free the macro buffer */
3540                 xfree(macro->buf);
3541
3542                 /* Now free the macro itself */
3543                 xfree(macro);
3544         }
3545 }
3546
3547 static void do_define_macro(struct compile_state *state,
3548         struct hash_entry *ident, const char *body,
3549         int argc, struct macro_arg *args)
3550 {
3551         struct macro *macro;
3552         struct macro_arg *arg;
3553         size_t body_len;
3554
3555         /* Find the length of the body */
3556         body_len = strlen(body);
3557         macro = ident->sym_define;
3558         if (macro != 0) {
3559                 int identical_bodies, identical_args;
3560                 struct macro_arg *oarg;
3561                 /* Explicitly allow identical redfinitions of the same macro */
3562                 identical_bodies =
3563                         (macro->buf_len == body_len) &&
3564                         (memcmp(macro->buf, body, body_len) == 0);
3565                 identical_args = macro->argc == argc;
3566                 oarg = macro->args;
3567                 arg = args;
3568                 while(identical_args && arg) {
3569                         identical_args = oarg->ident == arg->ident;
3570                         arg = arg->next;
3571                         oarg = oarg->next;
3572                 }
3573                 if (identical_bodies && identical_args) {
3574                         xfree(body);
3575                         return;
3576                 }
3577                 error(state, 0, "macro %s already defined\n", ident->name);
3578         }
3579 #if 0
3580         fprintf(state->errout, "#define %s: `%*.*s'\n",
3581                 ident->name, body_len, body_len, body);
3582 #endif
3583         macro = xmalloc(sizeof(*macro), "macro");
3584         macro->ident   = ident;
3585         macro->buf     = body;
3586         macro->buf_len = body_len;
3587         macro->args    = args;
3588         macro->argc    = argc;
3589
3590         ident->sym_define = macro;
3591 }
3592
3593 static void define_macro(
3594         struct compile_state *state,
3595         struct hash_entry *ident,
3596         const char *body, int body_len,
3597         int argc, struct macro_arg *args)
3598 {
3599         char *buf;
3600         buf = xmalloc(body_len + 1, "macro buf");
3601         memcpy(buf, body, body_len);
3602         buf[body_len] = '\0';
3603         do_define_macro(state, ident, buf, argc, args);
3604 }
3605
3606 static void register_builtin_macro(struct compile_state *state,
3607         const char *name, const char *value)
3608 {
3609         struct hash_entry *ident;
3610
3611         if (value[0] == '(') {
3612                 internal_error(state, 0, "Builtin macros with arguments not supported");
3613         }
3614         ident = lookup(state, name, strlen(name));
3615         define_macro(state, ident, value, strlen(value), -1, 0);
3616 }
3617
3618 static void register_builtin_macros(struct compile_state *state)
3619 {
3620         char buf[30];
3621         char scratch[30];
3622         time_t now;
3623         struct tm *tm;
3624         now = time(NULL);
3625         tm = localtime(&now);
3626
3627         register_builtin_macro(state, "__ROMCC__", VERSION_MAJOR);
3628         register_builtin_macro(state, "__ROMCC_MINOR__", VERSION_MINOR);
3629         register_builtin_macro(state, "__FILE__", "\"This should be the filename\"");
3630         register_builtin_macro(state, "__LINE__", "54321");
3631
3632         strftime(scratch, sizeof(scratch), "%b %e %Y", tm);
3633         sprintf(buf, "\"%s\"", scratch);
3634         register_builtin_macro(state, "__DATE__", buf);
3635
3636         strftime(scratch, sizeof(scratch), "%H:%M:%S", tm);
3637         sprintf(buf, "\"%s\"", scratch);
3638         register_builtin_macro(state, "__TIME__", buf);
3639
3640         /* I can't be a conforming implementation of C :( */
3641         register_builtin_macro(state, "__STDC__", "0");
3642         /* In particular I don't conform to C99 */
3643         register_builtin_macro(state, "__STDC_VERSION__", "199901L");
3644
3645 }
3646
3647 static void process_cmdline_macros(struct compile_state *state)
3648 {
3649         const char **macro, *name;
3650         struct hash_entry *ident;
3651         for(macro = state->compiler->defines; (name = *macro); macro++) {
3652                 const char *body;
3653                 size_t name_len;
3654
3655                 name_len = strlen(name);
3656                 body = strchr(name, '=');
3657                 if (!body) {
3658                         body = "\0";
3659                 } else {
3660                         name_len = body - name;
3661                         body++;
3662                 }
3663                 ident = lookup(state, name, name_len);
3664                 define_macro(state, ident, body, strlen(body), -1, 0);
3665         }
3666         for(macro = state->compiler->undefs; (name = *macro); macro++) {
3667                 ident = lookup(state, name, strlen(name));
3668                 undef_macro(state, ident);
3669         }
3670 }
3671
3672 static int spacep(int c)
3673 {
3674         int ret = 0;
3675         switch(c) {
3676         case ' ':
3677         case '\t':
3678         case '\f':
3679         case '\v':
3680         case '\r':
3681                 ret = 1;
3682                 break;
3683         }
3684         return ret;
3685 }
3686
3687 static int digitp(int c)
3688 {
3689         int ret = 0;
3690         switch(c) {
3691         case '0': case '1': case '2': case '3': case '4':
3692         case '5': case '6': case '7': case '8': case '9':
3693                 ret = 1;
3694                 break;
3695         }
3696         return ret;
3697 }
3698 static int digval(int c)
3699 {
3700         int val = -1;
3701         if ((c >= '0') && (c <= '9')) {
3702                 val = c - '0';
3703         }
3704         return val;
3705 }
3706
3707 static int hexdigitp(int c)
3708 {
3709         int ret = 0;
3710         switch(c) {
3711         case '0': case '1': case '2': case '3': case '4':
3712         case '5': case '6': case '7': case '8': case '9':
3713         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
3714         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
3715                 ret = 1;
3716                 break;
3717         }
3718         return ret;
3719 }
3720 static int hexdigval(int c)
3721 {
3722         int val = -1;
3723         if ((c >= '0') && (c <= '9')) {
3724                 val = c - '0';
3725         }
3726         else if ((c >= 'A') && (c <= 'F')) {
3727                 val = 10 + (c - 'A');
3728         }
3729         else if ((c >= 'a') && (c <= 'f')) {
3730                 val = 10 + (c - 'a');
3731         }
3732         return val;
3733 }
3734
3735 static int octdigitp(int c)
3736 {
3737         int ret = 0;
3738         switch(c) {
3739         case '0': case '1': case '2': case '3':
3740         case '4': case '5': case '6': case '7':
3741                 ret = 1;
3742                 break;
3743         }
3744         return ret;
3745 }
3746 static int octdigval(int c)
3747 {
3748         int val = -1;
3749         if ((c >= '0') && (c <= '7')) {
3750                 val = c - '0';
3751         }
3752         return val;
3753 }
3754
3755 static int letterp(int c)
3756 {
3757         int ret = 0;
3758         switch(c) {
3759         case 'a': case 'b': case 'c': case 'd': case 'e':
3760         case 'f': case 'g': case 'h': case 'i': case 'j':
3761         case 'k': case 'l': case 'm': case 'n': case 'o':
3762         case 'p': case 'q': case 'r': case 's': case 't':
3763         case 'u': case 'v': case 'w': case 'x': case 'y':
3764         case 'z':
3765         case 'A': case 'B': case 'C': case 'D': case 'E':
3766         case 'F': case 'G': case 'H': case 'I': case 'J':
3767         case 'K': case 'L': case 'M': case 'N': case 'O':
3768         case 'P': case 'Q': case 'R': case 'S': case 'T':
3769         case 'U': case 'V': case 'W': case 'X': case 'Y':
3770         case 'Z':
3771         case '_':
3772                 ret = 1;
3773                 break;
3774         }
3775         return ret;
3776 }
3777
3778 static const char *identifier(const char *str, const char *end)
3779 {
3780         if (letterp(*str)) {
3781                 for(; str < end; str++) {
3782                         int c;
3783                         c = *str;
3784                         if (!letterp(c) && !digitp(c)) {
3785                                 break;
3786                         }
3787                 }
3788         }
3789         return str;
3790 }
3791
3792 static int char_value(struct compile_state *state,
3793         const signed char **strp, const signed char *end)
3794 {
3795         const signed char *str;
3796         int c;
3797         str = *strp;
3798         c = *str++;
3799         if ((c == '\\') && (str < end)) {
3800                 switch(*str) {
3801                 case 'n':  c = '\n'; str++; break;
3802                 case 't':  c = '\t'; str++; break;
3803                 case 'v':  c = '\v'; str++; break;
3804                 case 'b':  c = '\b'; str++; break;
3805                 case 'r':  c = '\r'; str++; break;
3806                 case 'f':  c = '\f'; str++; break;
3807                 case 'a':  c = '\a'; str++; break;
3808                 case '\\': c = '\\'; str++; break;
3809                 case '?':  c = '?';  str++; break;
3810                 case '\'': c = '\''; str++; break;
3811                 case '"':  c = '"';  str++; break;
3812                 case 'x':
3813                         c = 0;
3814                         str++;
3815                         while((str < end) && hexdigitp(*str)) {
3816                                 c <<= 4;
3817                                 c += hexdigval(*str);
3818                                 str++;
3819                         }
3820                         break;
3821                 case '0': case '1': case '2': case '3':
3822                 case '4': case '5': case '6': case '7':
3823                         c = 0;
3824                         while((str < end) && octdigitp(*str)) {
3825                                 c <<= 3;
3826                                 c += octdigval(*str);
3827                                 str++;
3828                         }
3829                         break;
3830                 default:
3831                         error(state, 0, "Invalid character constant");
3832                         break;
3833                 }
3834         }
3835         *strp = str;
3836         return c;
3837 }
3838
3839 static const char *next_char(struct file_state *file, const char *pos, int index)
3840 {
3841         const char *end = file->buf + file->size;
3842         while(pos < end) {
3843                 /* Lookup the character */
3844                 int size = 1;
3845                 int c = *pos;
3846                 /* Is this a trigraph? */
3847                 if (file->trigraphs &&
3848                         (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3849                 {
3850                         switch(pos[2]) {
3851                         case '=': c = '#'; break;
3852                         case '/': c = '\\'; break;
3853                         case '\'': c = '^'; break;
3854                         case '(': c = '['; break;
3855                         case ')': c = ']'; break;
3856                         case '!': c = '!'; break;
3857                         case '<': c = '{'; break;
3858                         case '>': c = '}'; break;
3859                         case '-': c = '~'; break;
3860                         }
3861                         if (c != '?') {
3862                                 size = 3;
3863                         }
3864                 }
3865                 /* Is this an escaped newline? */
3866                 if (file->join_lines &&
3867                         (c == '\\') && (pos + size < end) && ((pos[1] == '\n') || ((pos[1] == '\r') && (pos[2] == '\n'))))
3868                 {
3869                         int cr_offset = ((pos[1] == '\r') && (pos[2] == '\n'))?1:0;
3870                         /* At the start of a line just eat it */
3871                         if (pos == file->pos) {
3872                                 file->line++;
3873                                 file->report_line++;
3874                                 file->line_start = pos + size + 1 + cr_offset;
3875                         }
3876                         pos += size + 1 + cr_offset;
3877                 }
3878                 /* Do I need to ga any farther? */
3879                 else if (index == 0) {
3880                         break;
3881                 }
3882                 /* Process a normal character */
3883                 else {
3884                         pos += size;
3885                         index -= 1;
3886                 }
3887         }
3888         return pos;
3889 }
3890
3891 static int get_char(struct file_state *file, const char *pos)
3892 {
3893         const char *end = file->buf + file->size;
3894         int c;
3895         c = -1;
3896         pos = next_char(file, pos, 0);
3897         if (pos < end) {
3898                 /* Lookup the character */
3899                 c = *pos;
3900                 /* If it is a trigraph get the trigraph value */
3901                 if (file->trigraphs &&
3902                         (c == '?') && ((end - pos) >= 3) && (pos[1] == '?'))
3903                 {
3904                         switch(pos[2]) {
3905                         case '=': c = '#'; break;
3906                         case '/': c = '\\'; break;
3907                         case '\'': c = '^'; break;
3908                         case '(': c = '['; break;
3909                         case ')': c = ']'; break;
3910                         case '!': c = '!'; break;
3911                         case '<': c = '{'; break;
3912                         case '>': c = '}'; break;
3913                         case '-': c = '~'; break;
3914                         }
3915                 }
3916         }
3917         return c;
3918 }
3919
3920 static void eat_chars(struct file_state *file, const char *targ)
3921 {
3922         const char *pos = file->pos;
3923         while(pos < targ) {
3924                 /* Do we have a newline? */
3925                 if (pos[0] == '\n') {
3926                         file->line++;
3927                         file->report_line++;
3928                         file->line_start = pos + 1;
3929                 }
3930                 pos++;
3931         }
3932         file->pos = pos;
3933 }
3934
3935
3936 static size_t char_strlen(struct file_state *file, const char *src, const char *end)
3937 {
3938         size_t len;
3939         len = 0;
3940         while(src < end) {
3941                 src = next_char(file, src, 1);
3942                 len++;
3943         }
3944         return len;
3945 }
3946
3947 static void char_strcpy(char *dest,
3948         struct file_state *file, const char *src, const char *end)
3949 {
3950         while(src < end) {
3951                 int c;
3952                 c = get_char(file, src);
3953                 src = next_char(file, src, 1);
3954                 *dest++ = c;
3955         }
3956 }
3957
3958 static char *char_strdup(struct file_state *file,
3959         const char *start, const char *end, const char *id)
3960 {
3961         char *str;
3962         size_t str_len;
3963         str_len = char_strlen(file, start, end);
3964         str = xcmalloc(str_len + 1, id);
3965         char_strcpy(str, file, start, end);
3966         str[str_len] = '\0';
3967         return str;
3968 }
3969
3970 static const char *after_digits(struct file_state *file, const char *ptr)
3971 {
3972         while(digitp(get_char(file, ptr))) {
3973                 ptr = next_char(file, ptr, 1);
3974         }
3975         return ptr;
3976 }
3977
3978 static const char *after_octdigits(struct file_state *file, const char *ptr)
3979 {
3980         while(octdigitp(get_char(file, ptr))) {
3981                 ptr = next_char(file, ptr, 1);
3982         }
3983         return ptr;
3984 }
3985
3986 static const char *after_hexdigits(struct file_state *file, const char *ptr)
3987 {
3988         while(hexdigitp(get_char(file, ptr))) {
3989                 ptr = next_char(file, ptr, 1);
3990         }
3991         return ptr;
3992 }
3993
3994 static const char *after_alnums(struct file_state *file, const char *ptr)
3995 {
3996         int c;
3997         c = get_char(file, ptr);
3998         while(letterp(c) || digitp(c)) {
3999                 ptr = next_char(file, ptr, 1);
4000                 c = get_char(file, ptr);
4001         }
4002         return ptr;
4003 }
4004
4005 static void save_string(struct file_state *file,
4006         struct token *tk, const char *start, const char *end, const char *id)
4007 {
4008         char *str;
4009
4010         /* Create a private copy of the string */
4011         str = char_strdup(file, start, end, id);
4012
4013         /* Store the copy in the token */
4014         tk->val.str = str;
4015         tk->str_len = strlen(str);
4016 }
4017
4018 static void raw_next_token(struct compile_state *state,
4019         struct file_state *file, struct token *tk)
4020 {
4021         const char *token;
4022         int c, c1, c2, c3;
4023         const char *tokp;
4024         int eat;
4025         int tok;
4026
4027         tk->str_len = 0;
4028         tk->ident = 0;
4029         token = tokp = next_char(file, file->pos, 0);
4030         tok = TOK_UNKNOWN;
4031         c  = get_char(file, tokp);
4032         tokp = next_char(file, tokp, 1);
4033         eat = 0;
4034         c1 = get_char(file, tokp);
4035         c2 = get_char(file, next_char(file, tokp, 1));
4036         c3 = get_char(file, next_char(file, tokp, 2));
4037
4038         /* The end of the file */
4039         if (c == -1) {
4040                 tok = TOK_EOF;
4041         }
4042         /* Whitespace */
4043         else if (spacep(c)) {
4044                 tok = TOK_SPACE;
4045                 while (spacep(get_char(file, tokp))) {
4046                         tokp = next_char(file, tokp, 1);
4047                 }
4048         }
4049         /* EOL Comments */
4050         else if ((c == '/') && (c1 == '/')) {
4051                 tok = TOK_SPACE;
4052                 tokp = next_char(file, tokp, 1);
4053                 while((c = get_char(file, tokp)) != -1) {
4054                         /* Advance to the next character only after we verify
4055                          * the current character is not a newline.
4056                          * EOL is special to the preprocessor so we don't
4057                          * want to loose any.
4058                          */
4059                         if (c == '\n') {
4060                                 break;
4061                         }
4062                         tokp = next_char(file, tokp, 1);
4063                 }
4064         }
4065         /* Comments */
4066         else if ((c == '/') && (c1 == '*')) {
4067                 tokp = next_char(file, tokp, 2);
4068                 c = c2;
4069                 while((c1 = get_char(file, tokp)) != -1) {
4070                         tokp = next_char(file, tokp, 1);
4071                         if ((c == '*') && (c1 == '/')) {
4072                                 tok = TOK_SPACE;
4073                                 break;
4074                         }
4075                         c = c1;
4076                 }
4077                 if (tok == TOK_UNKNOWN) {
4078                         error(state, 0, "unterminated comment");
4079                 }
4080         }
4081         /* string constants */
4082         else if ((c == '"') || ((c == 'L') && (c1 == '"'))) {
4083                 int multiline;
4084
4085                 multiline = 0;
4086                 if (c == 'L') {
4087                         tokp = next_char(file, tokp, 1);
4088                 }
4089                 while((c = get_char(file, tokp)) != -1) {
4090                         tokp = next_char(file, tokp, 1);
4091                         if (c == '\n') {
4092                                 multiline = 1;
4093                         }
4094                         else if (c == '\\') {
4095                                 tokp = next_char(file, tokp, 1);
4096                         }
4097                         else if (c == '"') {
4098                                 tok = TOK_LIT_STRING;
4099                                 break;
4100                         }
4101                 }
4102                 if (tok == TOK_UNKNOWN) {
4103                         error(state, 0, "unterminated string constant");
4104                 }
4105                 if (multiline) {
4106                         warning(state, 0, "multiline string constant");
4107                 }
4108
4109                 /* Save the string value */
4110                 save_string(file, tk, token, tokp, "literal string");
4111         }
4112         /* character constants */
4113         else if ((c == '\'') || ((c == 'L') && (c1 == '\''))) {
4114                 int multiline;
4115
4116                 multiline = 0;
4117                 if (c == 'L') {
4118                         tokp = next_char(file, tokp, 1);
4119                 }
4120                 while((c = get_char(file, tokp)) != -1) {
4121                         tokp = next_char(file, tokp, 1);
4122                         if (c == '\n') {
4123                                 multiline = 1;
4124                         }
4125                         else if (c == '\\') {
4126                                 tokp = next_char(file, tokp, 1);
4127                         }
4128                         else if (c == '\'') {
4129                                 tok = TOK_LIT_CHAR;
4130                                 break;
4131                         }
4132                 }
4133                 if (tok == TOK_UNKNOWN) {
4134                         error(state, 0, "unterminated character constant");
4135                 }
4136                 if (multiline) {
4137                         warning(state, 0, "multiline character constant");
4138                 }
4139
4140                 /* Save the character value */
4141                 save_string(file, tk, token, tokp, "literal character");
4142         }
4143         /* integer and floating constants
4144          * Integer Constants
4145          * {digits}
4146          * 0[Xx]{hexdigits}
4147          * 0{octdigit}+
4148          *
4149          * Floating constants
4150          * {digits}.{digits}[Ee][+-]?{digits}
4151          * {digits}.{digits}
4152          * {digits}[Ee][+-]?{digits}
4153          * .{digits}[Ee][+-]?{digits}
4154          * .{digits}
4155          */
4156         else if (digitp(c) || ((c == '.') && (digitp(c1)))) {
4157                 const char *next;
4158                 int is_float;
4159                 int cn;
4160                 is_float = 0;
4161                 if (c != '.') {
4162                         next = after_digits(file, tokp);
4163                 }
4164                 else {
4165                         next = token;
4166                 }
4167                 cn = get_char(file, next);
4168                 if (cn == '.') {
4169                         next = next_char(file, next, 1);
4170                         next = after_digits(file, next);
4171                         is_float = 1;
4172                 }
4173                 cn = get_char(file, next);
4174                 if ((cn == 'e') || (cn == 'E')) {
4175                         const char *new;
4176                         next = next_char(file, next, 1);
4177                         cn = get_char(file, next);
4178                         if ((cn == '+') || (cn == '-')) {
4179                                 next = next_char(file, next, 1);
4180                         }
4181                         new = after_digits(file, next);
4182                         is_float |= (new != next);
4183                         next = new;
4184                 }
4185                 if (is_float) {
4186                         tok = TOK_LIT_FLOAT;
4187                         cn = get_char(file, next);
4188                         if ((cn  == 'f') || (cn == 'F') || (cn == 'l') || (cn == 'L')) {
4189                                 next = next_char(file, next, 1);
4190                         }
4191                 }
4192                 if (!is_float && digitp(c)) {
4193                         tok = TOK_LIT_INT;
4194                         if ((c == '0') && ((c1 == 'x') || (c1 == 'X'))) {
4195                                 next = next_char(file, tokp, 1);
4196                                 next = after_hexdigits(file, next);
4197                         }
4198                         else if (c == '0') {
4199                                 next = after_octdigits(file, tokp);
4200                         }
4201                         else {
4202                                 next = after_digits(file, tokp);
4203                         }
4204                         /* crazy integer suffixes */
4205                         cn = get_char(file, next);
4206                         if ((cn == 'u') || (cn == 'U')) {
4207                                 next = next_char(file, next, 1);
4208                                 cn = get_char(file, next);
4209                                 if ((cn == 'l') || (cn == 'L')) {
4210                                         next = next_char(file, next, 1);
4211                                         cn = get_char(file, next);
4212                                 }
4213                                 if ((cn == 'l') || (cn == 'L')) {
4214                                         next = next_char(file, next, 1);
4215                                 }
4216                         }
4217                         else if ((cn == 'l') || (cn == 'L')) {
4218                                 next = next_char(file, next, 1);
4219                                 cn = get_char(file, next);
4220                                 if ((cn == 'l') || (cn == 'L')) {
4221                                         next = next_char(file, next, 1);
4222                                         cn = get_char(file, next);
4223                                 }
4224                                 if ((cn == 'u') || (cn == 'U')) {
4225                                         next = next_char(file, next, 1);
4226                                 }
4227                         }
4228                 }
4229                 tokp = next;
4230
4231                 /* Save the integer/floating point value */
4232                 save_string(file, tk, token, tokp, "literal number");
4233         }
4234         /* identifiers */
4235         else if (letterp(c)) {
4236                 tok = TOK_IDENT;
4237
4238                 /* Find and save the identifier string */
4239                 tokp = after_alnums(file, tokp);
4240                 save_string(file, tk, token, tokp, "identifier");
4241
4242                 /* Look up to see which identifier it is */
4243                 tk->ident = lookup(state, tk->val.str, tk->str_len);
4244
4245                 /* Free the identifier string */
4246                 tk->str_len = 0;
4247                 xfree(tk->val.str);
4248
4249                 /* See if this identifier can be macro expanded */
4250                 tk->val.notmacro = 0;
4251                 c = get_char(file, tokp);
4252                 if (c == '$') {
4253                         tokp = next_char(file, tokp, 1);
4254                         tk->val.notmacro = 1;
4255                 }
4256         }
4257         /* C99 alternate macro characters */
4258         else if ((c == '%') && (c1 == ':') && (c2 == '%') && (c3 == ':')) {
4259                 eat += 3;
4260                 tok = TOK_CONCATENATE;
4261         }
4262         else if ((c == '.') && (c1 == '.') && (c2 == '.')) { eat += 2; tok = TOK_DOTS; }
4263         else if ((c == '<') && (c1 == '<') && (c2 == '=')) { eat += 2; tok = TOK_SLEQ; }
4264         else if ((c == '>') && (c1 == '>') && (c2 == '=')) { eat += 2; tok = TOK_SREQ; }
4265         else if ((c == '*') && (c1 == '=')) { eat += 1; tok = TOK_TIMESEQ; }
4266         else if ((c == '/') && (c1 == '=')) { eat += 1; tok = TOK_DIVEQ; }
4267         else if ((c == '%') && (c1 == '=')) { eat += 1; tok = TOK_MODEQ; }
4268         else if ((c == '+') && (c1 == '=')) { eat += 1; tok = TOK_PLUSEQ; }
4269         else if ((c == '-') && (c1 == '=')) { eat += 1; tok = TOK_MINUSEQ; }
4270         else if ((c == '&') && (c1 == '=')) { eat += 1; tok = TOK_ANDEQ; }
4271         else if ((c == '^') && (c1 == '=')) { eat += 1; tok = TOK_XOREQ; }
4272         else if ((c == '|') && (c1 == '=')) { eat += 1; tok = TOK_OREQ; }
4273         else if ((c == '=') && (c1 == '=')) { eat += 1; tok = TOK_EQEQ; }
4274         else if ((c == '!') && (c1 == '=')) { eat += 1; tok = TOK_NOTEQ; }
4275         else if ((c == '|') && (c1 == '|')) { eat += 1; tok = TOK_LOGOR; }
4276         else if ((c == '&') && (c1 == '&')) { eat += 1; tok = TOK_LOGAND; }
4277         else if ((c == '<') && (c1 == '=')) { eat += 1; tok = TOK_LESSEQ; }
4278         else if ((c == '>') && (c1 == '=')) { eat += 1; tok = TOK_MOREEQ; }
4279         else if ((c == '<') && (c1 == '<')) { eat += 1; tok = TOK_SL; }
4280         else if ((c == '>') && (c1 == '>')) { eat += 1; tok = TOK_SR; }
4281         else if ((c == '+') && (c1 == '+')) { eat += 1; tok = TOK_PLUSPLUS; }
4282         else if ((c == '-') && (c1 == '-')) { eat += 1; tok = TOK_MINUSMINUS; }
4283         else if ((c == '-') && (c1 == '>')) { eat += 1; tok = TOK_ARROW; }
4284         else if ((c == '<') && (c1 == ':')) { eat += 1; tok = TOK_LBRACKET; }
4285         else if ((c == ':') && (c1 == '>')) { eat += 1; tok = TOK_RBRACKET; }
4286         else if ((c == '<') && (c1 == '%')) { eat += 1; tok = TOK_LBRACE; }
4287         else if ((c == '%') && (c1 == '>')) { eat += 1; tok = TOK_RBRACE; }
4288         else if ((c == '%') && (c1 == ':')) { eat += 1; tok = TOK_MACRO; }
4289         else if ((c == '#') && (c1 == '#')) { eat += 1; tok = TOK_CONCATENATE; }
4290         else if (c == ';') { tok = TOK_SEMI; }
4291         else if (c == '{') { tok = TOK_LBRACE; }
4292         else if (c == '}') { tok = TOK_RBRACE; }
4293         else if (c == ',') { tok = TOK_COMMA; }
4294         else if (c == '=') { tok = TOK_EQ; }
4295         else if (c == ':') { tok = TOK_COLON; }
4296         else if (c == '[') { tok = TOK_LBRACKET; }
4297         else if (c == ']') { tok = TOK_RBRACKET; }
4298         else if (c == '(') { tok = TOK_LPAREN; }
4299         else if (c == ')') { tok = TOK_RPAREN; }
4300         else if (c == '*') { tok = TOK_STAR; }
4301         else if (c == '>') { tok = TOK_MORE; }
4302         else if (c == '<') { tok = TOK_LESS; }
4303         else if (c == '?') { tok = TOK_QUEST; }
4304         else if (c == '|') { tok = TOK_OR; }
4305         else if (c == '&') { tok = TOK_AND; }
4306         else if (c == '^') { tok = TOK_XOR; }
4307         else if (c == '+') { tok = TOK_PLUS; }
4308         else if (c == '-') { tok = TOK_MINUS; }
4309         else if (c == '/') { tok = TOK_DIV; }
4310         else if (c == '%') { tok = TOK_MOD; }
4311         else if (c == '!') { tok = TOK_BANG; }
4312         else if (c == '.') { tok = TOK_DOT; }
4313         else if (c == '~') { tok = TOK_TILDE; }
4314         else if (c == '#') { tok = TOK_MACRO; }
4315         else if (c == '\n') { tok = TOK_EOL; }
4316
4317         tokp = next_char(file, tokp, eat);
4318         eat_chars(file, tokp);
4319         tk->tok = tok;
4320         tk->pos = token;
4321 }
4322
4323 static void check_tok(struct compile_state *state, struct token *tk, int tok)
4324 {
4325         if (tk->tok != tok) {
4326                 const char *name1, *name2;
4327                 name1 = tokens[tk->tok];
4328                 name2 = "";
4329                 if ((tk->tok == TOK_IDENT) || (tk->tok == TOK_MIDENT)) {
4330                         name2 = tk->ident->name;
4331                 }
4332                 error(state, 0, "\tfound %s %s expected %s",
4333                         name1, name2, tokens[tok]);
4334         }
4335 }
4336
4337 struct macro_arg_value {
4338         struct hash_entry *ident;
4339         char *value;
4340         size_t len;
4341 };
4342 static struct macro_arg_value *read_macro_args(
4343         struct compile_state *state, struct macro *macro,
4344         struct file_state *file, struct token *tk)
4345 {
4346         struct macro_arg_value *argv;
4347         struct macro_arg *arg;
4348         int paren_depth;
4349         int i;
4350
4351         if (macro->argc == 0) {
4352                 do {
4353                         raw_next_token(state, file, tk);
4354                 } while(tk->tok == TOK_SPACE);
4355                 return NULL;
4356         }
4357         argv = xcmalloc(sizeof(*argv) * macro->argc, "macro args");
4358         for(i = 0, arg = macro->args; arg; arg = arg->next, i++) {
4359                 argv[i].value = 0;
4360                 argv[i].len   = 0;
4361                 argv[i].ident = arg->ident;
4362         }
4363         paren_depth = 0;
4364         i = 0;
4365
4366         for(;;) {
4367                 const char *start;
4368                 size_t len;
4369                 start = file->pos;
4370                 raw_next_token(state, file, tk);
4371
4372                 if (!paren_depth && (tk->tok == TOK_COMMA) &&
4373                         (argv[i].ident != state->i___VA_ARGS__))
4374                 {
4375                         i++;
4376                         if (i >= macro->argc) {
4377                                 error(state, 0, "too many args to %s\n",
4378                                         macro->ident->name);
4379                         }
4380                         continue;
4381                 }
4382
4383                 if (tk->tok == TOK_LPAREN) {
4384                         paren_depth++;
4385                 }
4386
4387                 if (tk->tok == TOK_RPAREN) {
4388                         if (paren_depth == 0) {
4389                                 break;
4390                         }
4391                         paren_depth--;
4392                 }
4393                 if (tk->tok == TOK_EOF) {
4394                         error(state, 0, "End of file encountered while parsing macro arguments");
4395                 }
4396
4397                 len = char_strlen(file, start, file->pos);
4398                 argv[i].value = xrealloc(
4399                         argv[i].value, argv[i].len + len, "macro args");
4400                 char_strcpy((char *)argv[i].value + argv[i].len, file, start, file->pos);
4401                 argv[i].len += len;
4402         }
4403         if (i != macro->argc -1) {
4404                 error(state, 0, "missing %s arg %d\n",
4405                         macro->ident->name, i +2);
4406         }
4407         return argv;
4408 }
4409
4410
4411 static void free_macro_args(struct macro *macro, struct macro_arg_value *argv)
4412 {
4413         int i;
4414         for(i = 0; i < macro->argc; i++) {
4415                 xfree(argv[i].value);
4416         }
4417         xfree(argv);
4418 }
4419
4420 struct macro_buf {
4421         char *str;
4422         size_t len, pos;
4423 };
4424
4425 static void grow_macro_buf(struct compile_state *state,
4426         const char *id, struct macro_buf *buf,
4427         size_t grow)
4428 {
4429         if ((buf->pos + grow) >= buf->len) {
4430                 buf->str = xrealloc(buf->str, buf->len + grow, id);
4431                 buf->len += grow;
4432         }
4433 }
4434
4435 static void append_macro_text(struct compile_state *state,
4436         const char *id, struct macro_buf *buf,
4437         const char *fstart, size_t flen)
4438 {
4439         grow_macro_buf(state, id, buf, flen);
4440         memcpy(buf->str + buf->pos, fstart, flen);
4441 #if 0
4442         fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4443                 buf->pos, buf->pos, buf->str,
4444                 flen, flen, buf->str + buf->pos);
4445 #endif
4446         buf->pos += flen;
4447 }
4448
4449
4450 static void append_macro_chars(struct compile_state *state,
4451         const char *id, struct macro_buf *buf,
4452         struct file_state *file, const char *start, const char *end)
4453 {
4454         size_t flen;
4455         flen = char_strlen(file, start, end);
4456         grow_macro_buf(state, id, buf, flen);
4457         char_strcpy(buf->str + buf->pos, file, start, end);
4458 #if 0
4459         fprintf(state->errout, "append: `%*.*s' `%*.*s'\n",
4460                 buf->pos, buf->pos, buf->str,
4461                 flen, flen, buf->str + buf->pos);
4462 #endif
4463         buf->pos += flen;
4464 }
4465
4466 static int compile_macro(struct compile_state *state,
4467         struct file_state **filep, struct token *tk);
4468
4469 static void macro_expand_args(struct compile_state *state,
4470         struct macro *macro, struct macro_arg_value *argv, struct token *tk)
4471 {
4472         int i;
4473
4474         for(i = 0; i < macro->argc; i++) {
4475                 struct file_state fmacro, *file;
4476                 struct macro_buf buf;
4477
4478                 fmacro.prev        = 0;
4479                 fmacro.basename    = argv[i].ident->name;
4480                 fmacro.dirname     = "";
4481                 fmacro.buf         = (char *)argv[i].value;
4482                 fmacro.size        = argv[i].len;
4483                 fmacro.pos         = fmacro.buf;
4484                 fmacro.line        = 1;
4485                 fmacro.line_start  = fmacro.buf;
4486                 fmacro.report_line = 1;
4487                 fmacro.report_name = fmacro.basename;
4488                 fmacro.report_dir  = fmacro.dirname;
4489                 fmacro.macro       = 1;
4490                 fmacro.trigraphs   = 0;
4491                 fmacro.join_lines  = 0;
4492
4493                 buf.len = argv[i].len;
4494                 buf.str = xmalloc(buf.len, argv[i].ident->name);
4495                 buf.pos = 0;
4496
4497                 file = &fmacro;
4498                 for(;;) {
4499                         raw_next_token(state, file, tk);
4500
4501                         /* If we have recursed into another macro body
4502                          * get out of it.
4503                          */
4504                         if (tk->tok == TOK_EOF) {
4505                                 struct file_state *old;
4506                                 old = file;
4507                                 file = file->prev;
4508                                 if (!file) {
4509                                         break;
4510                                 }
4511                                 /* old->basename is used keep it */
4512                                 xfree(old->dirname);
4513                                 xfree(old->buf);
4514                                 xfree(old);
4515                                 continue;
4516                         }
4517                         else if (tk->ident && tk->ident->sym_define) {
4518                                 if (compile_macro(state, &file, tk)) {
4519                                         continue;
4520                                 }
4521                         }
4522
4523                         append_macro_chars(state, macro->ident->name, &buf,
4524                                 file, tk->pos, file->pos);
4525                 }
4526
4527                 xfree(argv[i].value);
4528                 argv[i].value = buf.str;
4529                 argv[i].len   = buf.pos;
4530         }
4531         return;
4532 }
4533
4534 static void expand_macro(struct compile_state *state,
4535         struct macro *macro, struct macro_buf *buf,
4536         struct macro_arg_value *argv, struct token *tk)
4537 {
4538         struct file_state fmacro;
4539         const char space[] = " ";
4540         const char *fstart;
4541         size_t flen;
4542         int i, j;
4543
4544         /* Place the macro body in a dummy file */
4545         fmacro.prev        = 0;
4546         fmacro.basename    = macro->ident->name;
4547         fmacro.dirname     = "";
4548         fmacro.buf         = macro->buf;
4549         fmacro.size        = macro->buf_len;
4550         fmacro.pos         = fmacro.buf;
4551         fmacro.line        = 1;
4552         fmacro.line_start  = fmacro.buf;
4553         fmacro.report_line = 1;
4554         fmacro.report_name = fmacro.basename;
4555         fmacro.report_dir  = fmacro.dirname;
4556         fmacro.macro       = 1;
4557         fmacro.trigraphs   = 0;
4558         fmacro.join_lines  = 0;
4559
4560         /* Allocate a buffer to hold the macro expansion */
4561         buf->len = macro->buf_len + 3;
4562         buf->str = xmalloc(buf->len, macro->ident->name);
4563         buf->pos = 0;
4564
4565         fstart = fmacro.pos;
4566         raw_next_token(state, &fmacro, tk);
4567         while(tk->tok != TOK_EOF) {
4568                 flen = fmacro.pos - fstart;
4569                 switch(tk->tok) {
4570                 case TOK_IDENT:
4571                         for(i = 0; i < macro->argc; i++) {
4572                                 if (argv[i].ident == tk->ident) {
4573                                         break;
4574                                 }
4575                         }
4576                         if (i >= macro->argc) {
4577                                 break;
4578                         }
4579                         /* Substitute macro parameter */
4580                         fstart = argv[i].value;
4581                         flen   = argv[i].len;
4582                         break;
4583                 case TOK_MACRO:
4584                         if (macro->argc < 0) {
4585                                 break;
4586                         }
4587                         do {
4588                                 raw_next_token(state, &fmacro, tk);
4589                         } while(tk->tok == TOK_SPACE);
4590                         check_tok(state, tk, TOK_IDENT);
4591                         for(i = 0; i < macro->argc; i++) {
4592                                 if (argv[i].ident == tk->ident) {
4593                                         break;
4594                                 }
4595                         }
4596                         if (i >= macro->argc) {
4597                                 error(state, 0, "parameter `%s' not found",
4598                                         tk->ident->name);
4599                         }
4600                         /* Stringize token */
4601                         append_macro_text(state, macro->ident->name, buf, "\"", 1);
4602                         for(j = 0; j < argv[i].len; j++) {
4603                                 char *str = argv[i].value + j;
4604                                 size_t len = 1;
4605                                 if (*str == '\\') {
4606                                         str = "\\";
4607                                         len = 2;
4608                                 }
4609                                 else if (*str == '"') {
4610                                         str = "\\\"";
4611                                         len = 2;
4612                                 }
4613                                 append_macro_text(state, macro->ident->name, buf, str, len);
4614                         }
4615                         append_macro_text(state, macro->ident->name, buf, "\"", 1);
4616                         fstart = 0;
4617                         flen   = 0;
4618                         break;
4619                 case TOK_CONCATENATE:
4620                         /* Concatenate tokens */
4621                         /* Delete the previous whitespace token */
4622                         if (buf->str[buf->pos - 1] == ' ') {
4623                                 buf->pos -= 1;
4624                         }
4625                         /* Skip the next sequence of whitspace tokens */
4626                         do {
4627                                 fstart = fmacro.pos;
4628                                 raw_next_token(state, &fmacro, tk);
4629                         } while(tk->tok == TOK_SPACE);
4630                         /* Restart at the top of the loop.
4631                          * I need to process the non white space token.
4632                          */
4633                         continue;
4634                         break;
4635                 case TOK_SPACE:
4636                         /* Collapse multiple spaces into one */
4637                         if (buf->str[buf->pos - 1] != ' ') {
4638                                 fstart = space;
4639                                 flen   = 1;
4640                         } else {
4641                                 fstart = 0;
4642                                 flen   = 0;
4643                         }
4644                         break;
4645                 default:
4646                         break;
4647                 }
4648
4649                 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4650
4651                 fstart = fmacro.pos;
4652                 raw_next_token(state, &fmacro, tk);
4653         }
4654 }
4655
4656 static void tag_macro_name(struct compile_state *state,
4657         struct macro *macro, struct macro_buf *buf,
4658         struct token *tk)
4659 {
4660         /* Guard all instances of the macro name in the replacement
4661          * text from further macro expansion.
4662          */
4663         struct file_state fmacro;
4664         const char *fstart;
4665         size_t flen;
4666
4667         /* Put the old macro expansion buffer in a file */
4668         fmacro.prev        = 0;
4669         fmacro.basename    = macro->ident->name;
4670         fmacro.dirname     = "";
4671         fmacro.buf         = buf->str;
4672         fmacro.size        = buf->pos;
4673         fmacro.pos         = fmacro.buf;
4674         fmacro.line        = 1;
4675         fmacro.line_start  = fmacro.buf;
4676         fmacro.report_line = 1;
4677         fmacro.report_name = fmacro.basename;
4678         fmacro.report_dir  = fmacro.dirname;
4679         fmacro.macro       = 1;
4680         fmacro.trigraphs   = 0;
4681         fmacro.join_lines  = 0;
4682
4683         /* Allocate a new macro expansion buffer */
4684         buf->len = macro->buf_len + 3;
4685         buf->str = xmalloc(buf->len, macro->ident->name);
4686         buf->pos = 0;
4687
4688         fstart = fmacro.pos;
4689         raw_next_token(state, &fmacro, tk);
4690         while(tk->tok != TOK_EOF) {
4691                 flen = fmacro.pos - fstart;
4692                 if ((tk->tok == TOK_IDENT) &&
4693                         (tk->ident == macro->ident) &&
4694                         (tk->val.notmacro == 0))
4695                 {
4696                         append_macro_text(state, macro->ident->name, buf, fstart, flen);
4697                         fstart = "$";
4698                         flen   = 1;
4699                 }
4700
4701                 append_macro_text(state, macro->ident->name, buf, fstart, flen);
4702
4703                 fstart = fmacro.pos;
4704                 raw_next_token(state, &fmacro, tk);
4705         }
4706         xfree(fmacro.buf);
4707 }
4708
4709 static int compile_macro(struct compile_state *state,
4710         struct file_state **filep, struct token *tk)
4711 {
4712         struct file_state *file;
4713         struct hash_entry *ident;
4714         struct macro *macro;
4715         struct macro_arg_value *argv;
4716         struct macro_buf buf;
4717
4718 #if 0
4719         fprintf(state->errout, "macro: %s\n", tk->ident->name);
4720 #endif
4721         ident = tk->ident;
4722         macro = ident->sym_define;
4723
4724         /* If this token comes from a macro expansion ignore it */
4725         if (tk->val.notmacro) {
4726                 return 0;
4727         }
4728         /* If I am a function like macro and the identifier is not followed
4729          * by a left parenthesis, do nothing.
4730          */
4731         if ((macro->argc >= 0) && (get_char(*filep, (*filep)->pos) != '(')) {
4732                 return 0;
4733         }
4734
4735         /* Read in the macro arguments */
4736         argv = 0;
4737         if (macro->argc >= 0) {
4738                 raw_next_token(state, *filep, tk);
4739                 check_tok(state, tk, TOK_LPAREN);
4740
4741                 argv = read_macro_args(state, macro, *filep, tk);
4742
4743                 check_tok(state, tk, TOK_RPAREN);
4744         }
4745         /* Macro expand the macro arguments */
4746         macro_expand_args(state, macro, argv, tk);
4747
4748         buf.str = 0;
4749         buf.len = 0;
4750         buf.pos = 0;
4751         if (ident == state->i___FILE__) {
4752                 buf.len = strlen(state->file->basename) + 1 + 2 + 3;
4753                 buf.str = xmalloc(buf.len, ident->name);
4754                 sprintf(buf.str, "\"%s\"", state->file->basename);
4755                 buf.pos = strlen(buf.str);
4756         }
4757         else if (ident == state->i___LINE__) {
4758                 buf.len = 30;
4759                 buf.str = xmalloc(buf.len, ident->name);
4760                 sprintf(buf.str, "%d", state->file->line);
4761                 buf.pos = strlen(buf.str);
4762         }
4763         else {
4764                 expand_macro(state, macro, &buf, argv, tk);
4765         }
4766         /* Tag the macro name with a $ so it will no longer
4767          * be regonized as a canidate for macro expansion.
4768          */
4769         tag_macro_name(state, macro, &buf, tk);
4770
4771 #if 0
4772         fprintf(state->errout, "%s: %d -> `%*.*s'\n",
4773                 ident->name, buf.pos, buf.pos, (int)(buf.pos), buf.str);
4774 #endif
4775
4776         free_macro_args(macro, argv);
4777
4778         file = xmalloc(sizeof(*file), "file_state");
4779         file->prev        = *filep;
4780         file->basename    = xstrdup(ident->name);
4781         file->dirname     = xstrdup("");
4782         file->buf         = buf.str;
4783         file->size        = buf.pos;
4784         file->pos         = file->buf;
4785         file->line        = 1;
4786         file->line_start  = file->pos;
4787         file->report_line = 1;
4788         file->report_name = file->basename;
4789         file->report_dir  = file->dirname;
4790         file->macro       = 1;
4791         file->trigraphs   = 0;
4792         file->join_lines  = 0;
4793         *filep = file;
4794         return 1;
4795 }
4796
4797 static void eat_tokens(struct compile_state *state, int targ_tok)
4798 {
4799         if (state->eat_depth > 0) {
4800                 internal_error(state, 0, "Already eating...");
4801         }
4802         state->eat_depth = state->if_depth;
4803         state->eat_targ = targ_tok;
4804 }
4805 static int if_eat(struct compile_state *state)
4806 {
4807         return state->eat_depth > 0;
4808 }
4809 static int if_value(struct compile_state *state)
4810 {
4811         int index, offset;
4812         index = state->if_depth / CHAR_BIT;
4813         offset = state->if_depth % CHAR_BIT;
4814         return !!(state->if_bytes[index] & (1 << (offset)));
4815 }
4816 static void set_if_value(struct compile_state *state, int value)
4817 {
4818         int index, offset;
4819         index = state->if_depth / CHAR_BIT;
4820         offset = state->if_depth % CHAR_BIT;
4821
4822         state->if_bytes[index] &= ~(1 << offset);
4823         if (value) {
4824                 state->if_bytes[index] |= (1 << offset);
4825         }
4826 }
4827 static void in_if(struct compile_state *state, const char *name)
4828 {
4829         if (state->if_depth <= 0) {
4830                 error(state, 0, "%s without #if", name);
4831         }
4832 }
4833 static void enter_if(struct compile_state *state)
4834 {
4835         state->if_depth += 1;
4836         if (state->if_depth > MAX_PP_IF_DEPTH) {
4837                 error(state, 0, "#if depth too great");
4838         }
4839 }
4840 static void reenter_if(struct compile_state *state, const char *name)
4841 {
4842         in_if(state, name);
4843         if ((state->eat_depth == state->if_depth) &&
4844                 (state->eat_targ == TOK_MELSE)) {
4845                 state->eat_depth = 0;
4846                 state->eat_targ = 0;
4847         }
4848 }
4849 static void enter_else(struct compile_state *state, const char *name)
4850 {
4851         in_if(state, name);
4852         if ((state->eat_depth == state->if_depth) &&
4853                 (state->eat_targ == TOK_MELSE)) {
4854                 state->eat_depth = 0;
4855                 state->eat_targ = 0;
4856         }
4857 }
4858 static void exit_if(struct compile_state *state, const char *name)
4859 {
4860         in_if(state, name);
4861         if (state->eat_depth == state->if_depth) {
4862                 state->eat_depth = 0;
4863                 state->eat_targ = 0;
4864         }
4865         state->if_depth -= 1;
4866 }
4867
4868 static void raw_token(struct compile_state *state, struct token *tk)
4869 {
4870         struct file_state *file;
4871         int rescan;
4872
4873         file = state->file;
4874         raw_next_token(state, file, tk);
4875         do {
4876                 rescan = 0;
4877                 file = state->file;
4878                 /* Exit out of an include directive or macro call */
4879                 if ((tk->tok == TOK_EOF) &&
4880                         (file != state->macro_file) && file->prev)
4881                 {
4882                         state->file = file->prev;
4883                         /* file->basename is used keep it */
4884                         xfree(file->dirname);
4885                         xfree(file->buf);
4886                         xfree(file);
4887                         file = 0;
4888                         raw_next_token(state, state->file, tk);
4889                         rescan = 1;
4890                 }
4891         } while(rescan);
4892 }
4893
4894 static void pp_token(struct compile_state *state, struct token *tk)
4895 {
4896         int rescan;
4897
4898         raw_token(state, tk);
4899         do {
4900                 rescan = 0;
4901                 if (tk->tok == TOK_SPACE) {
4902                         raw_token(state, tk);
4903                         rescan = 1;
4904                 }
4905                 else if (tk->tok == TOK_IDENT) {
4906                         if (state->token_base == 0) {
4907                                 ident_to_keyword(state, tk);
4908                         } else {
4909                                 ident_to_macro(state, tk);
4910                         }
4911                 }
4912         } while(rescan);
4913 }
4914
4915 static void preprocess(struct compile_state *state, struct token *tk);
4916
4917 static void token(struct compile_state *state, struct token *tk)
4918 {
4919         int rescan;
4920         pp_token(state, tk);
4921         do {
4922                 rescan = 0;
4923                 /* Process a macro directive */
4924                 if (tk->tok == TOK_MACRO) {
4925                         /* Only match preprocessor directives at the start of a line */
4926                         const char *ptr;
4927                         ptr = state->file->line_start;
4928                         while((ptr < tk->pos)
4929                                 && spacep(get_char(state->file, ptr)))
4930                         {
4931                                 ptr = next_char(state->file, ptr, 1);
4932                         }
4933                         if (ptr == tk->pos) {
4934                                 preprocess(state, tk);
4935                                 rescan = 1;
4936                         }
4937                 }
4938                 /* Expand a macro call */
4939                 else if (tk->ident && tk->ident->sym_define) {
4940                         rescan = compile_macro(state, &state->file, tk);
4941                         if (rescan) {
4942                                 pp_token(state, tk);
4943                         }
4944                 }
4945                 /* Eat tokens disabled by the preprocessor
4946                  * (Unless we are parsing a preprocessor directive
4947                  */
4948                 else if (if_eat(state) && (state->token_base == 0)) {
4949                         pp_token(state, tk);
4950                         rescan = 1;
4951                 }
4952                 /* Make certain EOL only shows up in preprocessor directives */
4953                 else if ((tk->tok == TOK_EOL) && (state->token_base == 0)) {
4954                         pp_token(state, tk);
4955                         rescan = 1;
4956                 }
4957                 /* Error on unknown tokens */
4958                 else if (tk->tok == TOK_UNKNOWN) {
4959                         error(state, 0, "unknown token");
4960                 }
4961         } while(rescan);
4962 }
4963
4964
4965 static inline struct token *get_token(struct compile_state *state, int offset)
4966 {
4967         int index;
4968         index = state->token_base + offset;
4969         if (index >= sizeof(state->token)/sizeof(state->token[0])) {
4970                 internal_error(state, 0, "token array to small");
4971         }
4972         return &state->token[index];
4973 }
4974
4975 static struct token *do_eat_token(struct compile_state *state, int tok)
4976 {
4977         struct token *tk;
4978         int i;
4979         check_tok(state, get_token(state, 1), tok);
4980
4981         /* Free the old token value */
4982         tk = get_token(state, 0);
4983         if (tk->str_len) {
4984                 memset((void *)tk->val.str, -1, tk->str_len);
4985                 xfree(tk->val.str);
4986         }
4987         /* Overwrite the old token with newer tokens */
4988         for(i = state->token_base; i < sizeof(state->token)/sizeof(state->token[0]) - 1; i++) {
4989                 state->token[i] = state->token[i + 1];
4990         }
4991         /* Clear the last token */
4992         memset(&state->token[i], 0, sizeof(state->token[i]));
4993         state->token[i].tok = -1;
4994
4995         /* Return the token */
4996         return tk;
4997 }
4998
4999 static int raw_peek(struct compile_state *state)
5000 {
5001         struct token *tk1;
5002         tk1 = get_token(state, 1);
5003         if (tk1->tok == -1) {
5004                 raw_token(state, tk1);
5005         }
5006         return tk1->tok;
5007 }
5008
5009 static struct token *raw_eat(struct compile_state *state, int tok)
5010 {
5011         raw_peek(state);
5012         return do_eat_token(state, tok);
5013 }
5014
5015 static int pp_peek(struct compile_state *state)
5016 {
5017         struct token *tk1;
5018         tk1 = get_token(state, 1);
5019         if (tk1->tok == -1) {
5020                 pp_token(state, tk1);
5021         }
5022         return tk1->tok;
5023 }
5024
5025 static struct token *pp_eat(struct compile_state *state, int tok)
5026 {
5027         pp_peek(state);
5028         return do_eat_token(state, tok);
5029 }
5030
5031 static int peek(struct compile_state *state)
5032 {
5033         struct token *tk1;
5034         tk1 = get_token(state, 1);
5035         if (tk1->tok == -1) {
5036                 token(state, tk1);
5037         }
5038         return tk1->tok;
5039 }
5040
5041 static int peek2(struct compile_state *state)
5042 {
5043         struct token *tk1, *tk2;
5044         tk1 = get_token(state, 1);
5045         tk2 = get_token(state, 2);
5046         if (tk1->tok == -1) {
5047                 token(state, tk1);
5048         }
5049         if (tk2->tok == -1) {
5050                 token(state, tk2);
5051         }
5052         return tk2->tok;
5053 }
5054
5055 static struct token *eat(struct compile_state *state, int tok)
5056 {
5057         peek(state);
5058         return do_eat_token(state, tok);
5059 }
5060
5061 static void compile_file(struct compile_state *state, const char *filename, int local)
5062 {
5063         char cwd[MAX_CWD_SIZE];
5064         const char *subdir, *base;
5065         int subdir_len;
5066         struct file_state *file;
5067         char *basename;
5068         file = xmalloc(sizeof(*file), "file_state");
5069
5070         base = strrchr(filename, '/');
5071         subdir = filename;
5072         if (base != 0) {
5073                 subdir_len = base - filename;
5074                 base++;
5075         }
5076         else {
5077                 base = filename;
5078                 subdir_len = 0;
5079         }
5080         basename = xmalloc(strlen(base) +1, "basename");
5081         strcpy(basename, base);
5082         file->basename = basename;
5083
5084         if (getcwd(cwd, sizeof(cwd)) == 0) {
5085                 die("cwd buffer to small");
5086         }
5087         if ((subdir[0] == '/') || ((subdir[1] == ':') && ((subdir[2] == '/') || (subdir[2] == '\\')))) {
5088                 file->dirname = xmalloc(subdir_len + 1, "dirname");
5089                 memcpy(file->dirname, subdir, subdir_len);
5090                 file->dirname[subdir_len] = '\0';
5091         }
5092         else {
5093                 const char *dir;
5094                 int dirlen;
5095                 const char **path;
5096                 /* Find the appropriate directory... */
5097                 dir = 0;
5098                 if (!state->file && exists(cwd, filename)) {
5099                         dir = cwd;
5100                 }
5101                 if (local && state->file && exists(state->file->dirname, filename)) {
5102                         dir = state->file->dirname;
5103                 }
5104                 for(path = state->compiler->include_paths; !dir && *path; path++) {
5105                         if (exists(*path, filename)) {
5106                                 dir = *path;
5107                         }
5108                 }
5109                 if (!dir) {
5110                         error(state, 0, "Cannot open `%s'\n", filename);
5111                 }
5112                 dirlen = strlen(dir);
5113                 file->dirname = xmalloc(dirlen + 1 + subdir_len + 1, "dirname");
5114                 memcpy(file->dirname, dir, dirlen);
5115                 file->dirname[dirlen] = '/';
5116                 memcpy(file->dirname + dirlen + 1, subdir, subdir_len);
5117                 file->dirname[dirlen + 1 + subdir_len] = '\0';
5118         }
5119         file->buf = slurp_file(file->dirname, file->basename, &file->size);
5120
5121         file->pos = file->buf;
5122         file->line_start = file->pos;
5123         file->line = 1;
5124
5125         file->report_line = 1;
5126         file->report_name = file->basename;
5127         file->report_dir  = file->dirname;
5128         file->macro       = 0;
5129         file->trigraphs   = (state->compiler->flags & COMPILER_TRIGRAPHS)? 1: 0;
5130         file->join_lines  = 1;
5131
5132         file->prev = state->file;
5133         state->file = file;
5134 }
5135
5136 static struct triple *constant_expr(struct compile_state *state);
5137 static void integral(struct compile_state *state, struct triple *def);
5138
5139 static int mcexpr(struct compile_state *state)
5140 {
5141         struct triple *cvalue;
5142         cvalue = constant_expr(state);
5143         integral(state, cvalue);
5144         if (cvalue->op != OP_INTCONST) {
5145                 error(state, 0, "integer constant expected");
5146         }
5147         return cvalue->u.cval != 0;
5148 }
5149
5150 static void preprocess(struct compile_state *state, struct token *current_token)
5151 {
5152         /* Doing much more with the preprocessor would require
5153          * a parser and a major restructuring.
5154          * Postpone that for later.
5155          */
5156         int old_token_base;
5157         int tok;
5158
5159         state->macro_file = state->file;
5160
5161         old_token_base = state->token_base;
5162         state->token_base = current_token - state->token;
5163
5164         tok = pp_peek(state);
5165         switch(tok) {
5166         case TOK_LIT_INT:
5167         {
5168                 struct token *tk;
5169                 int override_line;
5170                 tk = pp_eat(state, TOK_LIT_INT);
5171                 override_line = strtoul(tk->val.str, 0, 10);
5172                 /* I have a preprocessor  line marker parse it */
5173                 if (pp_peek(state) == TOK_LIT_STRING) {
5174                         const char *token, *base;
5175                         char *name, *dir;
5176                         int name_len, dir_len;
5177                         tk = pp_eat(state, TOK_LIT_STRING);
5178                         name = xmalloc(tk->str_len, "report_name");
5179                         token = tk->val.str + 1;
5180                         base = strrchr(token, '/');
5181                         name_len = tk->str_len -2;
5182                         if (base != 0) {
5183                                 dir_len = base - token;
5184                                 base++;
5185                                 name_len -= base - token;
5186                         } else {
5187                                 dir_len = 0;
5188                                 base = token;
5189                         }
5190                         memcpy(name, base, name_len);
5191                         name[name_len] = '\0';
5192                         dir = xmalloc(dir_len + 1, "report_dir");
5193                         memcpy(dir, token, dir_len);
5194                         dir[dir_len] = '\0';
5195                         state->file->report_line = override_line - 1;
5196                         state->file->report_name = name;
5197                         state->file->report_dir = dir;
5198                         state->file->macro      = 0;
5199                 }
5200                 break;
5201         }
5202         case TOK_MLINE:
5203         {
5204                 struct token *tk;
5205                 pp_eat(state, TOK_MLINE);
5206                 tk = eat(state, TOK_LIT_INT);
5207                 state->file->report_line = strtoul(tk->val.str, 0, 10) -1;
5208                 if (pp_peek(state) == TOK_LIT_STRING) {
5209                         const char *token, *base;
5210                         char *name, *dir;
5211                         int name_len, dir_len;
5212                         tk = pp_eat(state, TOK_LIT_STRING);
5213                         name = xmalloc(tk->str_len, "report_name");
5214                         token = tk->val.str + 1;
5215                         base = strrchr(token, '/');
5216                         name_len = tk->str_len - 2;
5217                         if (base != 0) {
5218                                 dir_len = base - token;
5219                                 base++;
5220                                 name_len -= base - token;
5221                         } else {
5222                                 dir_len = 0;
5223                                 base = token;
5224                         }
5225                         memcpy(name, base, name_len);
5226                         name[name_len] = '\0';
5227                         dir = xmalloc(dir_len + 1, "report_dir");
5228                         memcpy(dir, token, dir_len);
5229                         dir[dir_len] = '\0';
5230                         state->file->report_name = name;
5231                         state->file->report_dir = dir;
5232                         state->file->macro      = 0;
5233                 }
5234                 break;
5235         }
5236         case TOK_MUNDEF:
5237         {
5238                 struct hash_entry *ident;
5239                 pp_eat(state, TOK_MUNDEF);
5240                 if (if_eat(state))  /* quit early when #if'd out */
5241                         break;
5242
5243                 ident = pp_eat(state, TOK_MIDENT)->ident;
5244
5245                 undef_macro(state, ident);
5246                 break;
5247         }
5248         case TOK_MPRAGMA:
5249                 pp_eat(state, TOK_MPRAGMA);
5250                 if (if_eat(state))  /* quit early when #if'd out */
5251                         break;
5252                 warning(state, 0, "Ignoring pragma");
5253                 break;
5254         case TOK_MELIF:
5255                 pp_eat(state, TOK_MELIF);
5256                 reenter_if(state, "#elif");
5257                 if (if_eat(state))   /* quit early when #if'd out */
5258                         break;
5259                 /* If the #if was taken the #elif just disables the following code */
5260                 if (if_value(state)) {
5261                         eat_tokens(state, TOK_MENDIF);
5262                 }
5263                 /* If the previous #if was not taken see if the #elif enables the
5264                  * trailing code.
5265                  */
5266                 else {
5267                         set_if_value(state, mcexpr(state));
5268                         if (!if_value(state)) {
5269                                 eat_tokens(state, TOK_MELSE);
5270                         }
5271                 }
5272                 break;
5273         case TOK_MIF:
5274                 pp_eat(state, TOK_MIF);
5275                 enter_if(state);
5276                 if (if_eat(state))  /* quit early when #if'd out */
5277                         break;
5278                 set_if_value(state, mcexpr(state));
5279                 if (!if_value(state)) {
5280                         eat_tokens(state, TOK_MELSE);
5281                 }
5282                 break;
5283         case TOK_MIFNDEF:
5284         {
5285                 struct hash_entry *ident;
5286
5287                 pp_eat(state, TOK_MIFNDEF);
5288                 enter_if(state);
5289                 if (if_eat(state))  /* quit early when #if'd out */
5290                         break;
5291                 ident = pp_eat(state, TOK_MIDENT)->ident;
5292                 set_if_value(state, ident->sym_define == 0);
5293                 if (!if_value(state)) {
5294                         eat_tokens(state, TOK_MELSE);
5295                 }
5296                 break;
5297         }
5298         case TOK_MIFDEF:
5299         {
5300                 struct hash_entry *ident;
5301                 pp_eat(state, TOK_MIFDEF);
5302                 enter_if(state);
5303                 if (if_eat(state))  /* quit early when #if'd out */
5304                         break;
5305                 ident = pp_eat(state, TOK_MIDENT)->ident;
5306                 set_if_value(state, ident->sym_define != 0);
5307                 if (!if_value(state)) {
5308                         eat_tokens(state, TOK_MELSE);
5309                 }
5310                 break;
5311         }
5312         case TOK_MELSE:
5313                 pp_eat(state, TOK_MELSE);
5314                 enter_else(state, "#else");
5315                 if (!if_eat(state) && if_value(state)) {
5316                         eat_tokens(state, TOK_MENDIF);
5317                 }
5318                 break;
5319         case TOK_MENDIF:
5320                 pp_eat(state, TOK_MENDIF);
5321                 exit_if(state, "#endif");
5322                 break;
5323         case TOK_MDEFINE:
5324         {
5325                 struct hash_entry *ident;
5326                 struct macro_arg *args, **larg;
5327                 const char *mstart, *mend;
5328                 int argc;
5329
5330                 pp_eat(state, TOK_MDEFINE);
5331                 if (if_eat(state))  /* quit early when #if'd out */
5332                         break;
5333                 ident = pp_eat(state, TOK_MIDENT)->ident;
5334                 argc = -1;
5335                 args = 0;
5336                 larg = &args;
5337
5338                 /* Parse macro parameters */
5339                 if (raw_peek(state) == TOK_LPAREN) {
5340                         raw_eat(state, TOK_LPAREN);
5341                         argc += 1;
5342
5343                         for(;;) {
5344                                 struct macro_arg *narg, *arg;
5345                                 struct hash_entry *aident;
5346                                 int tok;
5347
5348                                 tok = pp_peek(state);
5349                                 if (!args && (tok == TOK_RPAREN)) {
5350                                         break;
5351                                 }
5352                                 else if (tok == TOK_DOTS) {
5353                                         pp_eat(state, TOK_DOTS);
5354                                         aident = state->i___VA_ARGS__;
5355                                 }
5356                                 else {
5357                                         aident = pp_eat(state, TOK_MIDENT)->ident;
5358                                 }
5359
5360                                 narg = xcmalloc(sizeof(*arg), "macro arg");
5361                                 narg->ident = aident;
5362
5363                                 /* Verify I don't have a duplicate identifier */
5364                                 for(arg = args; arg; arg = arg->next) {
5365                                         if (arg->ident == narg->ident) {
5366                                                 error(state, 0, "Duplicate macro arg `%s'",
5367                                                         narg->ident->name);
5368                                         }
5369                                 }
5370                                 /* Add the new argument to the end of the list */
5371                                 *larg = narg;
5372                                 larg = &narg->next;
5373                                 argc += 1;
5374
5375                                 if ((aident == state->i___VA_ARGS__) ||
5376                                         (pp_peek(state) != TOK_COMMA)) {
5377                                         break;
5378                                 }
5379                                 pp_eat(state, TOK_COMMA);
5380                         }
5381                         pp_eat(state, TOK_RPAREN);
5382                 }
5383                 /* Remove leading whitespace */
5384                 while(raw_peek(state) == TOK_SPACE) {
5385                         raw_eat(state, TOK_SPACE);
5386                 }
5387
5388                 /* Remember the start of the macro body */
5389                 tok = raw_peek(state);
5390                 mend = mstart = get_token(state, 1)->pos;
5391
5392                 /* Find the end of the macro */
5393                 for(tok = raw_peek(state); tok != TOK_EOL; tok = raw_peek(state)) {
5394                         raw_eat(state, tok);
5395                         /* Remember the end of the last non space token */
5396                         raw_peek(state);
5397                         if (tok != TOK_SPACE) {
5398                                 mend = get_token(state, 1)->pos;
5399                         }
5400                 }
5401
5402                 /* Now that I have found the body defined the token */
5403                 do_define_macro(state, ident,
5404                         char_strdup(state->file, mstart, mend, "macro buf"),
5405                         argc, args);
5406                 break;
5407         }
5408         case TOK_MERROR:
5409         {
5410                 const char *start, *end;
5411                 int len;
5412
5413                 pp_eat(state, TOK_MERROR);
5414                 /* Find the start of the line */
5415                 raw_peek(state);
5416                 start = get_token(state, 1)->pos;
5417
5418                 /* Find the end of the line */
5419                 while((tok = raw_peek(state)) != TOK_EOL) {
5420                         raw_eat(state, tok);
5421                 }
5422                 end = get_token(state, 1)->pos;
5423                 len = end - start;
5424                 if (!if_eat(state)) {
5425                         error(state, 0, "%*.*s", len, len, start);
5426                 }
5427                 break;
5428         }
5429         case TOK_MWARNING:
5430         {
5431                 const char *start, *end;
5432                 int len;
5433
5434                 pp_eat(state, TOK_MWARNING);
5435
5436                 /* Find the start of the line */
5437                 raw_peek(state);
5438                 start = get_token(state, 1)->pos;
5439
5440                 /* Find the end of the line */
5441                 while((tok = raw_peek(state)) != TOK_EOL) {
5442                         raw_eat(state, tok);
5443                 }
5444                 end = get_token(state, 1)->pos;
5445                 len = end - start;
5446                 if (!if_eat(state)) {
5447                         warning(state, 0, "%*.*s", len, len, start);
5448                 }
5449                 break;
5450         }
5451         case TOK_MINCLUDE:
5452         {
5453                 char *name;
5454                 int local;
5455                 local = 0;
5456                 name = 0;
5457
5458                 pp_eat(state, TOK_MINCLUDE);
5459                 if (if_eat(state)) {
5460                         /* Find the end of the line */
5461                         while((tok = raw_peek(state)) != TOK_EOL) {
5462                                 raw_eat(state, tok);
5463                         }
5464                         break;
5465                 }
5466                 tok = peek(state);
5467                 if (tok == TOK_LIT_STRING) {
5468                         struct token *tk;
5469                         const char *token;
5470                         int name_len;
5471                         tk = eat(state, TOK_LIT_STRING);
5472                         name = xmalloc(tk->str_len, "include");
5473                         token = tk->val.str +1;
5474                         name_len = tk->str_len -2;
5475                         if (*token == '"') {
5476                                 token++;
5477                                 name_len--;
5478                         }
5479                         memcpy(name, token, name_len);
5480                         name[name_len] = '\0';
5481                         local = 1;
5482                 }
5483                 else if (tok == TOK_LESS) {
5484                         struct macro_buf buf;
5485                         eat(state, TOK_LESS);
5486
5487                         buf.len = 40;
5488                         buf.str = xmalloc(buf.len, "include");
5489                         buf.pos = 0;
5490
5491                         tok = peek(state);
5492                         while((tok != TOK_MORE) &&
5493                                 (tok != TOK_EOL) && (tok != TOK_EOF))
5494                         {
5495                                 struct token *tk;
5496                                 tk = eat(state, tok);
5497                                 append_macro_chars(state, "include", &buf,
5498                                         state->file, tk->pos, state->file->pos);
5499                                 tok = peek(state);
5500                         }
5501                         append_macro_text(state, "include", &buf, "\0", 1);
5502                         if (peek(state) != TOK_MORE) {
5503                                 error(state, 0, "Unterminated include directive");
5504                         }
5505                         eat(state, TOK_MORE);
5506                         local = 0;
5507                         name = buf.str;
5508                 }
5509                 else {
5510                         error(state, 0, "Invalid include directive");
5511                 }
5512                 /* Error if there are any tokens after the include */
5513                 if (pp_peek(state) != TOK_EOL) {
5514                         error(state, 0, "garbage after include directive");
5515                 }
5516                 if (!if_eat(state)) {
5517                         compile_file(state, name, local);
5518                 }
5519                 xfree(name);
5520                 break;
5521         }
5522         case TOK_EOL:
5523                 /* Ignore # without a follwing ident */
5524                 break;
5525         default:
5526         {
5527                 const char *name1, *name2;
5528                 name1 = tokens[tok];
5529                 name2 = "";
5530                 if (tok == TOK_MIDENT) {
5531                         name2 = get_token(state, 1)->ident->name;
5532                 }
5533                 error(state, 0, "Invalid preprocessor directive: %s %s",
5534                         name1, name2);
5535                 break;
5536         }
5537         }
5538         /* Consume the rest of the macro line */
5539         do {
5540                 tok = pp_peek(state);
5541                 pp_eat(state, tok);
5542         } while((tok != TOK_EOF) && (tok != TOK_EOL));
5543         state->token_base = old_token_base;
5544         state->macro_file = NULL;
5545         return;
5546 }
5547
5548 /* Type helper functions */
5549
5550 static struct type *new_type(
5551         unsigned int type, struct type *left, struct type *right)
5552 {
5553         struct type *result;
5554         result = xmalloc(sizeof(*result), "type");
5555         result->type = type;
5556         result->left = left;
5557         result->right = right;
5558         result->field_ident = 0;
5559         result->type_ident = 0;
5560         result->elements = 0;
5561         return result;
5562 }
5563
5564 static struct type *clone_type(unsigned int specifiers, struct type *old)
5565 {
5566         struct type *result;
5567         result = xmalloc(sizeof(*result), "type");
5568         memcpy(result, old, sizeof(*result));
5569         result->type &= TYPE_MASK;
5570         result->type |= specifiers;
5571         return result;
5572 }
5573
5574 static struct type *dup_type(struct compile_state *state, struct type *orig)
5575 {
5576         struct type *new;
5577         new = xcmalloc(sizeof(*new), "type");
5578         new->type = orig->type;
5579         new->field_ident = orig->field_ident;
5580         new->type_ident  = orig->type_ident;
5581         new->elements    = orig->elements;
5582         if (orig->left) {
5583                 new->left = dup_type(state, orig->left);
5584         }
5585         if (orig->right) {
5586                 new->right = dup_type(state, orig->right);
5587         }
5588         return new;
5589 }
5590
5591
5592 static struct type *invalid_type(struct compile_state *state, struct type *type)
5593 {
5594         struct type *invalid, *member;
5595         invalid = 0;
5596         if (!type) {
5597                 internal_error(state, 0, "type missing?");
5598         }
5599         switch(type->type & TYPE_MASK) {
5600         case TYPE_VOID:
5601         case TYPE_CHAR:         case TYPE_UCHAR:
5602         case TYPE_SHORT:        case TYPE_USHORT:
5603         case TYPE_INT:          case TYPE_UINT:
5604         case TYPE_LONG:         case TYPE_ULONG:
5605         case TYPE_LLONG:        case TYPE_ULLONG:
5606         case TYPE_POINTER:
5607         case TYPE_ENUM:
5608                 break;
5609         case TYPE_BITFIELD:
5610                 invalid = invalid_type(state, type->left);
5611                 break;
5612         case TYPE_ARRAY:
5613                 invalid = invalid_type(state, type->left);
5614                 break;
5615         case TYPE_STRUCT:
5616         case TYPE_TUPLE:
5617                 member = type->left;
5618                 while(member && (invalid == 0) &&
5619                         ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
5620                         invalid = invalid_type(state, member->left);
5621                         member = member->right;
5622                 }
5623                 if (!invalid) {
5624                         invalid = invalid_type(state, member);
5625                 }
5626                 break;
5627         case TYPE_UNION:
5628         case TYPE_JOIN:
5629                 member = type->left;
5630                 while(member && (invalid == 0) &&
5631                         ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
5632                         invalid = invalid_type(state, member->left);
5633                         member = member->right;
5634                 }
5635                 if (!invalid) {
5636                         invalid = invalid_type(state, member);
5637                 }
5638                 break;
5639         default:
5640                 invalid = type;
5641                 break;
5642         }
5643         return invalid;
5644
5645 }
5646
5647 #define MASK_UCHAR(X)    ((X) & ((ulong_t)0xff))
5648 #define MASK_USHORT(X)   ((X) & (((ulong_t)1 << (SIZEOF_SHORT)) - 1))
5649 static inline ulong_t mask_uint(ulong_t x)
5650 {
5651         if (SIZEOF_INT < SIZEOF_LONG) {
5652                 ulong_t mask = (1ULL << ((ulong_t)(SIZEOF_INT))) -1;
5653                 x &= mask;
5654         }
5655         return x;
5656 }
5657 #define MASK_UINT(X)      (mask_uint(X))
5658 #define MASK_ULONG(X)    (X)
5659
5660 static struct type void_type    = { .type  = TYPE_VOID };
5661 static struct type char_type    = { .type  = TYPE_CHAR };
5662 static struct type uchar_type   = { .type  = TYPE_UCHAR };
5663 #if DEBUG_ROMCC_WARNING
5664 static struct type short_type   = { .type  = TYPE_SHORT };
5665 #endif
5666 static struct type ushort_type  = { .type  = TYPE_USHORT };
5667 static struct type int_type     = { .type  = TYPE_INT };
5668 static struct type uint_type    = { .type  = TYPE_UINT };
5669 static struct type long_type    = { .type  = TYPE_LONG };
5670 static struct type ulong_type   = { .type  = TYPE_ULONG };
5671 static struct type unknown_type = { .type  = TYPE_UNKNOWN };
5672
5673 static struct type void_ptr_type  = {
5674         .type = TYPE_POINTER,
5675         .left = &void_type,
5676 };
5677
5678 #if DEBUG_ROMCC_WARNING
5679 static struct type void_func_type = {
5680         .type  = TYPE_FUNCTION,
5681         .left  = &void_type,
5682         .right = &void_type,
5683 };
5684 #endif
5685
5686 static size_t bits_to_bytes(size_t size)
5687 {
5688         return (size + SIZEOF_CHAR - 1)/SIZEOF_CHAR;
5689 }
5690
5691 static struct triple *variable(struct compile_state *state, struct type *type)
5692 {
5693         struct triple *result;
5694         if ((type->type & STOR_MASK) != STOR_PERM) {
5695                 result = triple(state, OP_ADECL, type, 0, 0);
5696                 generate_lhs_pieces(state, result);
5697         }
5698         else {
5699                 result = triple(state, OP_SDECL, type, 0, 0);
5700         }
5701         return result;
5702 }
5703
5704 static void stor_of(FILE *fp, struct type *type)
5705 {
5706         switch(type->type & STOR_MASK) {
5707         case STOR_AUTO:
5708                 fprintf(fp, "auto ");
5709                 break;
5710         case STOR_STATIC:
5711                 fprintf(fp, "static ");
5712                 break;
5713         case STOR_LOCAL:
5714                 fprintf(fp, "local ");
5715                 break;
5716         case STOR_EXTERN:
5717                 fprintf(fp, "extern ");
5718                 break;
5719         case STOR_REGISTER:
5720                 fprintf(fp, "register ");
5721                 break;
5722         case STOR_TYPEDEF:
5723                 fprintf(fp, "typedef ");
5724                 break;
5725         case STOR_INLINE | STOR_LOCAL:
5726                 fprintf(fp, "inline ");
5727                 break;
5728         case STOR_INLINE | STOR_STATIC:
5729                 fprintf(fp, "static inline");
5730                 break;
5731         case STOR_INLINE | STOR_EXTERN:
5732                 fprintf(fp, "extern inline");
5733                 break;
5734         default:
5735                 fprintf(fp, "stor:%x", type->type & STOR_MASK);
5736                 break;
5737         }
5738 }
5739 static void qual_of(FILE *fp, struct type *type)
5740 {
5741         if (type->type & QUAL_CONST) {
5742                 fprintf(fp, " const");
5743         }
5744         if (type->type & QUAL_VOLATILE) {
5745                 fprintf(fp, " volatile");
5746         }
5747         if (type->type & QUAL_RESTRICT) {
5748                 fprintf(fp, " restrict");
5749         }
5750 }
5751
5752 static void name_of(FILE *fp, struct type *type)
5753 {
5754         unsigned int base_type;
5755         base_type = type->type & TYPE_MASK;
5756         if ((base_type != TYPE_PRODUCT) && (base_type != TYPE_OVERLAP)) {
5757                 stor_of(fp, type);
5758         }
5759         switch(base_type) {
5760         case TYPE_VOID:
5761                 fprintf(fp, "void");
5762                 qual_of(fp, type);
5763                 break;
5764         case TYPE_CHAR:
5765                 fprintf(fp, "signed char");
5766                 qual_of(fp, type);
5767                 break;
5768         case TYPE_UCHAR:
5769                 fprintf(fp, "unsigned char");
5770                 qual_of(fp, type);
5771                 break;
5772         case TYPE_SHORT:
5773                 fprintf(fp, "signed short");
5774                 qual_of(fp, type);
5775                 break;
5776         case TYPE_USHORT:
5777                 fprintf(fp, "unsigned short");
5778                 qual_of(fp, type);
5779                 break;
5780         case TYPE_INT:
5781                 fprintf(fp, "signed int");
5782                 qual_of(fp, type);
5783                 break;
5784         case TYPE_UINT:
5785                 fprintf(fp, "unsigned int");
5786                 qual_of(fp, type);
5787                 break;
5788         case TYPE_LONG:
5789                 fprintf(fp, "signed long");
5790                 qual_of(fp, type);
5791                 break;
5792         case TYPE_ULONG:
5793                 fprintf(fp, "unsigned long");
5794                 qual_of(fp, type);
5795                 break;
5796         case TYPE_POINTER:
5797                 name_of(fp, type->left);
5798                 fprintf(fp, " * ");
5799                 qual_of(fp, type);
5800                 break;
5801         case TYPE_PRODUCT:
5802                 name_of(fp, type->left);
5803                 fprintf(fp, ", ");
5804                 name_of(fp, type->right);
5805                 break;
5806         case TYPE_OVERLAP:
5807                 name_of(fp, type->left);
5808                 fprintf(fp, ",| ");
5809                 name_of(fp, type->right);
5810                 break;
5811         case TYPE_ENUM:
5812                 fprintf(fp, "enum %s",
5813                         (type->type_ident)? type->type_ident->name : "");
5814                 qual_of(fp, type);
5815                 break;
5816         case TYPE_STRUCT:
5817                 fprintf(fp, "struct %s { ",
5818                         (type->type_ident)? type->type_ident->name : "");
5819                 name_of(fp, type->left);
5820                 fprintf(fp, " } ");
5821                 qual_of(fp, type);
5822                 break;
5823         case TYPE_UNION:
5824                 fprintf(fp, "union %s { ",
5825                         (type->type_ident)? type->type_ident->name : "");
5826                 name_of(fp, type->left);
5827                 fprintf(fp, " } ");
5828                 qual_of(fp, type);
5829                 break;
5830         case TYPE_FUNCTION:
5831                 name_of(fp, type->left);
5832                 fprintf(fp, " (*)(");
5833                 name_of(fp, type->right);
5834                 fprintf(fp, ")");
5835                 break;
5836         case TYPE_ARRAY:
5837                 name_of(fp, type->left);
5838                 fprintf(fp, " [%ld]", (long)(type->elements));
5839                 break;
5840         case TYPE_TUPLE:
5841                 fprintf(fp, "tuple { ");
5842                 name_of(fp, type->left);
5843                 fprintf(fp, " } ");
5844                 qual_of(fp, type);
5845                 break;
5846         case TYPE_JOIN:
5847                 fprintf(fp, "join { ");
5848                 name_of(fp, type->left);
5849                 fprintf(fp, " } ");
5850                 qual_of(fp, type);
5851                 break;
5852         case TYPE_BITFIELD:
5853                 name_of(fp, type->left);
5854                 fprintf(fp, " : %d ", type->elements);
5855                 qual_of(fp, type);
5856                 break;
5857         case TYPE_UNKNOWN:
5858                 fprintf(fp, "unknown_t");
5859                 break;
5860         default:
5861                 fprintf(fp, "????: %x", base_type);
5862                 break;
5863         }
5864         if (type->field_ident && type->field_ident->name) {
5865                 fprintf(fp, " .%s", type->field_ident->name);
5866         }
5867 }
5868
5869 static size_t align_of(struct compile_state *state, struct type *type)
5870 {
5871         size_t align;
5872         align = 0;
5873         switch(type->type & TYPE_MASK) {
5874         case TYPE_VOID:
5875                 align = 1;
5876                 break;
5877         case TYPE_BITFIELD:
5878                 align = 1;
5879                 break;
5880         case TYPE_CHAR:
5881         case TYPE_UCHAR:
5882                 align = ALIGNOF_CHAR;
5883                 break;
5884         case TYPE_SHORT:
5885         case TYPE_USHORT:
5886                 align = ALIGNOF_SHORT;
5887                 break;
5888         case TYPE_INT:
5889         case TYPE_UINT:
5890         case TYPE_ENUM:
5891                 align = ALIGNOF_INT;
5892                 break;
5893         case TYPE_LONG:
5894         case TYPE_ULONG:
5895                 align = ALIGNOF_LONG;
5896                 break;
5897         case TYPE_POINTER:
5898                 align = ALIGNOF_POINTER;
5899                 break;
5900         case TYPE_PRODUCT:
5901         case TYPE_OVERLAP:
5902         {
5903                 size_t left_align, right_align;
5904                 left_align  = align_of(state, type->left);
5905                 right_align = align_of(state, type->right);
5906                 align = (left_align >= right_align) ? left_align : right_align;
5907                 break;
5908         }
5909         case TYPE_ARRAY:
5910                 align = align_of(state, type->left);
5911                 break;
5912         case TYPE_STRUCT:
5913         case TYPE_TUPLE:
5914         case TYPE_UNION:
5915         case TYPE_JOIN:
5916                 align = align_of(state, type->left);
5917                 break;
5918         default:
5919                 error(state, 0, "alignof not yet defined for type\n");
5920                 break;
5921         }
5922         return align;
5923 }
5924
5925 static size_t reg_align_of(struct compile_state *state, struct type *type)
5926 {
5927         size_t align;
5928         align = 0;
5929         switch(type->type & TYPE_MASK) {
5930         case TYPE_VOID:
5931                 align = 1;
5932                 break;
5933         case TYPE_BITFIELD:
5934                 align = 1;
5935                 break;
5936         case TYPE_CHAR:
5937         case TYPE_UCHAR:
5938                 align = REG_ALIGNOF_CHAR;
5939                 break;
5940         case TYPE_SHORT:
5941         case TYPE_USHORT:
5942                 align = REG_ALIGNOF_SHORT;
5943                 break;
5944         case TYPE_INT:
5945         case TYPE_UINT:
5946         case TYPE_ENUM:
5947                 align = REG_ALIGNOF_INT;
5948                 break;
5949         case TYPE_LONG:
5950         case TYPE_ULONG:
5951                 align = REG_ALIGNOF_LONG;
5952                 break;
5953         case TYPE_POINTER:
5954                 align = REG_ALIGNOF_POINTER;
5955                 break;
5956         case TYPE_PRODUCT:
5957         case TYPE_OVERLAP:
5958         {
5959                 size_t left_align, right_align;
5960                 left_align  = reg_align_of(state, type->left);
5961                 right_align = reg_align_of(state, type->right);
5962                 align = (left_align >= right_align) ? left_align : right_align;
5963                 break;
5964         }
5965         case TYPE_ARRAY:
5966                 align = reg_align_of(state, type->left);
5967                 break;
5968         case TYPE_STRUCT:
5969         case TYPE_UNION:
5970         case TYPE_TUPLE:
5971         case TYPE_JOIN:
5972                 align = reg_align_of(state, type->left);
5973                 break;
5974         default:
5975                 error(state, 0, "alignof not yet defined for type\n");
5976                 break;
5977         }
5978         return align;
5979 }
5980
5981 static size_t align_of_in_bytes(struct compile_state *state, struct type *type)
5982 {
5983         return bits_to_bytes(align_of(state, type));
5984 }
5985 static size_t size_of(struct compile_state *state, struct type *type);
5986 static size_t reg_size_of(struct compile_state *state, struct type *type);
5987
5988 static size_t needed_padding(struct compile_state *state,
5989         struct type *type, size_t offset)
5990 {
5991         size_t padding, align;
5992         align = align_of(state, type);
5993         /* Align to the next machine word if the bitfield does completely
5994          * fit into the current word.
5995          */
5996         if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
5997                 size_t size;
5998                 size = size_of(state, type);
5999                 if ((offset + type->elements)/size != offset/size) {
6000                         align = size;
6001                 }
6002         }
6003         padding = 0;
6004         if (offset % align) {
6005                 padding = align - (offset % align);
6006         }
6007         return padding;
6008 }
6009
6010 static size_t reg_needed_padding(struct compile_state *state,
6011         struct type *type, size_t offset)
6012 {
6013         size_t padding, align;
6014         align = reg_align_of(state, type);
6015         /* Align to the next register word if the bitfield does completely
6016          * fit into the current register.
6017          */
6018         if (((type->type & TYPE_MASK) == TYPE_BITFIELD) &&
6019                 (((offset + type->elements)/REG_SIZEOF_REG) != (offset/REG_SIZEOF_REG)))
6020         {
6021                 align = REG_SIZEOF_REG;
6022         }
6023         padding = 0;
6024         if (offset % align) {
6025                 padding = align - (offset % align);
6026         }
6027         return padding;
6028 }
6029
6030 static size_t size_of(struct compile_state *state, struct type *type)
6031 {
6032         size_t size;
6033         size = 0;
6034         switch(type->type & TYPE_MASK) {
6035         case TYPE_VOID:
6036                 size = 0;
6037                 break;
6038         case TYPE_BITFIELD:
6039                 size = type->elements;
6040                 break;
6041         case TYPE_CHAR:
6042         case TYPE_UCHAR:
6043                 size = SIZEOF_CHAR;
6044                 break;
6045         case TYPE_SHORT:
6046         case TYPE_USHORT:
6047                 size = SIZEOF_SHORT;
6048                 break;
6049         case TYPE_INT:
6050         case TYPE_UINT:
6051         case TYPE_ENUM:
6052                 size = SIZEOF_INT;
6053                 break;
6054         case TYPE_LONG:
6055         case TYPE_ULONG:
6056                 size = SIZEOF_LONG;
6057                 break;
6058         case TYPE_POINTER:
6059                 size = SIZEOF_POINTER;
6060                 break;
6061         case TYPE_PRODUCT:
6062         {
6063                 size_t pad;
6064                 size = 0;
6065                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6066                         pad = needed_padding(state, type->left, size);
6067                         size = size + pad + size_of(state, type->left);
6068                         type = type->right;
6069                 }
6070                 pad = needed_padding(state, type, size);
6071                 size = size + pad + size_of(state, type);
6072                 break;
6073         }
6074         case TYPE_OVERLAP:
6075         {
6076                 size_t size_left, size_right;
6077                 size_left = size_of(state, type->left);
6078                 size_right = size_of(state, type->right);
6079                 size = (size_left >= size_right)? size_left : size_right;
6080                 break;
6081         }
6082         case TYPE_ARRAY:
6083                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6084                         internal_error(state, 0, "Invalid array type");
6085                 } else {
6086                         size = size_of(state, type->left) * type->elements;
6087                 }
6088                 break;
6089         case TYPE_STRUCT:
6090         case TYPE_TUPLE:
6091         {
6092                 size_t pad;
6093                 size = size_of(state, type->left);
6094                 /* Pad structures so their size is a multiples of their alignment */
6095                 pad = needed_padding(state, type, size);
6096                 size = size + pad;
6097                 break;
6098         }
6099         case TYPE_UNION:
6100         case TYPE_JOIN:
6101         {
6102                 size_t pad;
6103                 size = size_of(state, type->left);
6104                 /* Pad unions so their size is a multiple of their alignment */
6105                 pad = needed_padding(state, type, size);
6106                 size = size + pad;
6107                 break;
6108         }
6109         default:
6110                 internal_error(state, 0, "sizeof not yet defined for type");
6111                 break;
6112         }
6113         return size;
6114 }
6115
6116 static size_t reg_size_of(struct compile_state *state, struct type *type)
6117 {
6118         size_t size;
6119         size = 0;
6120         switch(type->type & TYPE_MASK) {
6121         case TYPE_VOID:
6122                 size = 0;
6123                 break;
6124         case TYPE_BITFIELD:
6125                 size = type->elements;
6126                 break;
6127         case TYPE_CHAR:
6128         case TYPE_UCHAR:
6129                 size = REG_SIZEOF_CHAR;
6130                 break;
6131         case TYPE_SHORT:
6132         case TYPE_USHORT:
6133                 size = REG_SIZEOF_SHORT;
6134                 break;
6135         case TYPE_INT:
6136         case TYPE_UINT:
6137         case TYPE_ENUM:
6138                 size = REG_SIZEOF_INT;
6139                 break;
6140         case TYPE_LONG:
6141         case TYPE_ULONG:
6142                 size = REG_SIZEOF_LONG;
6143                 break;
6144         case TYPE_POINTER:
6145                 size = REG_SIZEOF_POINTER;
6146                 break;
6147         case TYPE_PRODUCT:
6148         {
6149                 size_t pad;
6150                 size = 0;
6151                 while((type->type & TYPE_MASK) == TYPE_PRODUCT) {
6152                         pad = reg_needed_padding(state, type->left, size);
6153                         size = size + pad + reg_size_of(state, type->left);
6154                         type = type->right;
6155                 }
6156                 pad = reg_needed_padding(state, type, size);
6157                 size = size + pad + reg_size_of(state, type);
6158                 break;
6159         }
6160         case TYPE_OVERLAP:
6161         {
6162                 size_t size_left, size_right;
6163                 size_left  = reg_size_of(state, type->left);
6164                 size_right = reg_size_of(state, type->right);
6165                 size = (size_left >= size_right)? size_left : size_right;
6166                 break;
6167         }
6168         case TYPE_ARRAY:
6169                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6170                         internal_error(state, 0, "Invalid array type");
6171                 } else {
6172                         size = reg_size_of(state, type->left) * type->elements;
6173                 }
6174                 break;
6175         case TYPE_STRUCT:
6176         case TYPE_TUPLE:
6177         {
6178                 size_t pad;
6179                 size = reg_size_of(state, type->left);
6180                 /* Pad structures so their size is a multiples of their alignment */
6181                 pad = reg_needed_padding(state, type, size);
6182                 size = size + pad;
6183                 break;
6184         }
6185         case TYPE_UNION:
6186         case TYPE_JOIN:
6187         {
6188                 size_t pad;
6189                 size = reg_size_of(state, type->left);
6190                 /* Pad unions so their size is a multiple of their alignment */
6191                 pad = reg_needed_padding(state, type, size);
6192                 size = size + pad;
6193                 break;
6194         }
6195         default:
6196                 internal_error(state, 0, "sizeof not yet defined for type");
6197                 break;
6198         }
6199         return size;
6200 }
6201
6202 static size_t registers_of(struct compile_state *state, struct type *type)
6203 {
6204         size_t registers;
6205         registers = reg_size_of(state, type);
6206         registers += REG_SIZEOF_REG - 1;
6207         registers /= REG_SIZEOF_REG;
6208         return registers;
6209 }
6210
6211 static size_t size_of_in_bytes(struct compile_state *state, struct type *type)
6212 {
6213         return bits_to_bytes(size_of(state, type));
6214 }
6215
6216 static size_t field_offset(struct compile_state *state,
6217         struct type *type, struct hash_entry *field)
6218 {
6219         struct type *member;
6220         size_t size;
6221
6222         size = 0;
6223         member = 0;
6224         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6225                 member = type->left;
6226                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6227                         size += needed_padding(state, member->left, size);
6228                         if (member->left->field_ident == field) {
6229                                 member = member->left;
6230                                 break;
6231                         }
6232                         size += size_of(state, member->left);
6233                         member = member->right;
6234                 }
6235                 size += needed_padding(state, member, size);
6236         }
6237         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6238                 member = type->left;
6239                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6240                         if (member->left->field_ident == field) {
6241                                 member = member->left;
6242                                 break;
6243                         }
6244                         member = member->right;
6245                 }
6246         }
6247         else {
6248                 internal_error(state, 0, "field_offset only works on structures and unions");
6249         }
6250
6251         if (!member || (member->field_ident != field)) {
6252                 error(state, 0, "member %s not present", field->name);
6253         }
6254         return size;
6255 }
6256
6257 static size_t field_reg_offset(struct compile_state *state,
6258         struct type *type, struct hash_entry *field)
6259 {
6260         struct type *member;
6261         size_t size;
6262
6263         size = 0;
6264         member = 0;
6265         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6266                 member = type->left;
6267                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6268                         size += reg_needed_padding(state, member->left, size);
6269                         if (member->left->field_ident == field) {
6270                                 member = member->left;
6271                                 break;
6272                         }
6273                         size += reg_size_of(state, member->left);
6274                         member = member->right;
6275                 }
6276         }
6277         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6278                 member = type->left;
6279                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6280                         if (member->left->field_ident == field) {
6281                                 member = member->left;
6282                                 break;
6283                         }
6284                         member = member->right;
6285                 }
6286         }
6287         else {
6288                 internal_error(state, 0, "field_reg_offset only works on structures and unions");
6289         }
6290
6291         size += reg_needed_padding(state, member, size);
6292         if (!member || (member->field_ident != field)) {
6293                 error(state, 0, "member %s not present", field->name);
6294         }
6295         return size;
6296 }
6297
6298 static struct type *field_type(struct compile_state *state,
6299         struct type *type, struct hash_entry *field)
6300 {
6301         struct type *member;
6302
6303         member = 0;
6304         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
6305                 member = type->left;
6306                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6307                         if (member->left->field_ident == field) {
6308                                 member = member->left;
6309                                 break;
6310                         }
6311                         member = member->right;
6312                 }
6313         }
6314         else if ((type->type & TYPE_MASK) == TYPE_UNION) {
6315                 member = type->left;
6316                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6317                         if (member->left->field_ident == field) {
6318                                 member = member->left;
6319                                 break;
6320                         }
6321                         member = member->right;
6322                 }
6323         }
6324         else {
6325                 internal_error(state, 0, "field_type only works on structures and unions");
6326         }
6327
6328         if (!member || (member->field_ident != field)) {
6329                 error(state, 0, "member %s not present", field->name);
6330         }
6331         return member;
6332 }
6333
6334 static size_t index_offset(struct compile_state *state,
6335         struct type *type, ulong_t index)
6336 {
6337         struct type *member;
6338         size_t size;
6339         size = 0;
6340         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6341                 size = size_of(state, type->left) * index;
6342         }
6343         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6344                 ulong_t i;
6345                 member = type->left;
6346                 i = 0;
6347                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6348                         size += needed_padding(state, member->left, size);
6349                         if (i == index) {
6350                                 member = member->left;
6351                                 break;
6352                         }
6353                         size += size_of(state, member->left);
6354                         i++;
6355                         member = member->right;
6356                 }
6357                 size += needed_padding(state, member, size);
6358                 if (i != index) {
6359                         internal_error(state, 0, "Missing member index: %u", index);
6360                 }
6361         }
6362         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6363                 ulong_t i;
6364                 size = 0;
6365                 member = type->left;
6366                 i = 0;
6367                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6368                         if (i == index) {
6369                                 member = member->left;
6370                                 break;
6371                         }
6372                         i++;
6373                         member = member->right;
6374                 }
6375                 if (i != index) {
6376                         internal_error(state, 0, "Missing member index: %u", index);
6377                 }
6378         }
6379         else {
6380                 internal_error(state, 0,
6381                         "request for index %u in something not an array, tuple or join",
6382                         index);
6383         }
6384         return size;
6385 }
6386
6387 static size_t index_reg_offset(struct compile_state *state,
6388         struct type *type, ulong_t index)
6389 {
6390         struct type *member;
6391         size_t size;
6392         size = 0;
6393         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6394                 size = reg_size_of(state, type->left) * index;
6395         }
6396         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6397                 ulong_t i;
6398                 member = type->left;
6399                 i = 0;
6400                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6401                         size += reg_needed_padding(state, member->left, size);
6402                         if (i == index) {
6403                                 member = member->left;
6404                                 break;
6405                         }
6406                         size += reg_size_of(state, member->left);
6407                         i++;
6408                         member = member->right;
6409                 }
6410                 size += reg_needed_padding(state, member, size);
6411                 if (i != index) {
6412                         internal_error(state, 0, "Missing member index: %u", index);
6413                 }
6414
6415         }
6416         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6417                 ulong_t i;
6418                 size = 0;
6419                 member = type->left;
6420                 i = 0;
6421                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6422                         if (i == index) {
6423                                 member = member->left;
6424                                 break;
6425                         }
6426                         i++;
6427                         member = member->right;
6428                 }
6429                 if (i != index) {
6430                         internal_error(state, 0, "Missing member index: %u", index);
6431                 }
6432         }
6433         else {
6434                 internal_error(state, 0,
6435                         "request for index %u in something not an array, tuple or join",
6436                         index);
6437         }
6438         return size;
6439 }
6440
6441 static struct type *index_type(struct compile_state *state,
6442         struct type *type, ulong_t index)
6443 {
6444         struct type *member;
6445         if (index >= type->elements) {
6446                 internal_error(state, 0, "Invalid element %u requested", index);
6447         }
6448         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6449                 member = type->left;
6450         }
6451         else if ((type->type & TYPE_MASK) == TYPE_TUPLE) {
6452                 ulong_t i;
6453                 member = type->left;
6454                 i = 0;
6455                 while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6456                         if (i == index) {
6457                                 member = member->left;
6458                                 break;
6459                         }
6460                         i++;
6461                         member = member->right;
6462                 }
6463                 if (i != index) {
6464                         internal_error(state, 0, "Missing member index: %u", index);
6465                 }
6466         }
6467         else if ((type->type & TYPE_MASK) == TYPE_JOIN) {
6468                 ulong_t i;
6469                 member = type->left;
6470                 i = 0;
6471                 while(member && ((member->type & TYPE_MASK) == TYPE_OVERLAP)) {
6472                         if (i == index) {
6473                                 member = member->left;
6474                                 break;
6475                         }
6476                         i++;
6477                         member = member->right;
6478                 }
6479                 if (i != index) {
6480                         internal_error(state, 0, "Missing member index: %u", index);
6481                 }
6482         }
6483         else {
6484                 member = 0;
6485                 internal_error(state, 0,
6486                         "request for index %u in something not an array, tuple or join",
6487                         index);
6488         }
6489         return member;
6490 }
6491
6492 static struct type *unpack_type(struct compile_state *state, struct type *type)
6493 {
6494         /* If I have a single register compound type not a bit-field
6495          * find the real type.
6496          */
6497         struct type *start_type;
6498         size_t size;
6499         /* Get out early if I need multiple registers for this type */
6500         size = reg_size_of(state, type);
6501         if (size > REG_SIZEOF_REG) {
6502                 return type;
6503         }
6504         /* Get out early if I don't need any registers for this type */
6505         if (size == 0) {
6506                 return &void_type;
6507         }
6508         /* Loop until I have no more layers I can remove */
6509         do {
6510                 start_type = type;
6511                 switch(type->type & TYPE_MASK) {
6512                 case TYPE_ARRAY:
6513                         /* If I have a single element the unpacked type
6514                          * is that element.
6515                          */
6516                         if (type->elements == 1) {
6517                                 type = type->left;
6518                         }
6519                         break;
6520                 case TYPE_STRUCT:
6521                 case TYPE_TUPLE:
6522                         /* If I have a single element the unpacked type
6523                          * is that element.
6524                          */
6525                         if (type->elements == 1) {
6526                                 type = type->left;
6527                         }
6528                         /* If I have multiple elements the unpacked
6529                          * type is the non-void element.
6530                          */
6531                         else {
6532                                 struct type *next, *member;
6533                                 struct type *sub_type;
6534                                 sub_type = 0;
6535                                 next = type->left;
6536                                 while(next) {
6537                                         member = next;
6538                                         next = 0;
6539                                         if ((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6540                                                 next = member->right;
6541                                                 member = member->left;
6542                                         }
6543                                         if (reg_size_of(state, member) > 0) {
6544                                                 if (sub_type) {
6545                                                         internal_error(state, 0, "true compound type in a register");
6546                                                 }
6547                                                 sub_type = member;
6548                                         }
6549                                 }
6550                                 if (sub_type) {
6551                                         type = sub_type;
6552                                 }
6553                         }
6554                         break;
6555
6556                 case TYPE_UNION:
6557                 case TYPE_JOIN:
6558                         /* If I have a single element the unpacked type
6559                          * is that element.
6560                          */
6561                         if (type->elements == 1) {
6562                                 type = type->left;
6563                         }
6564                         /* I can't in general unpack union types */
6565                         break;
6566                 default:
6567                         /* If I'm not a compound type I can't unpack it */
6568                         break;
6569                 }
6570         } while(start_type != type);
6571         switch(type->type & TYPE_MASK) {
6572         case TYPE_STRUCT:
6573         case TYPE_ARRAY:
6574         case TYPE_TUPLE:
6575                 internal_error(state, 0, "irredicible type?");
6576                 break;
6577         }
6578         return type;
6579 }
6580
6581 static int equiv_types(struct type *left, struct type *right);
6582 static int is_compound_type(struct type *type);
6583
6584 static struct type *reg_type(
6585         struct compile_state *state, struct type *type, int reg_offset)
6586 {
6587         struct type *member;
6588         size_t size;
6589 #if 1
6590         struct type *invalid;
6591         invalid = invalid_type(state, type);
6592         if (invalid) {
6593                 fprintf(state->errout, "type: ");
6594                 name_of(state->errout, type);
6595                 fprintf(state->errout, "\n");
6596                 fprintf(state->errout, "invalid: ");
6597                 name_of(state->errout, invalid);
6598                 fprintf(state->errout, "\n");
6599                 internal_error(state, 0, "bad input type?");
6600         }
6601 #endif
6602
6603         size = reg_size_of(state, type);
6604         if (reg_offset > size) {
6605                 member = 0;
6606                 fprintf(state->errout, "type: ");
6607                 name_of(state->errout, type);
6608                 fprintf(state->errout, "\n");
6609                 internal_error(state, 0, "offset outside of type");
6610         }
6611         else {
6612                 switch(type->type & TYPE_MASK) {
6613                         /* Don't do anything with the basic types */
6614                 case TYPE_VOID:
6615                 case TYPE_CHAR:         case TYPE_UCHAR:
6616                 case TYPE_SHORT:        case TYPE_USHORT:
6617                 case TYPE_INT:          case TYPE_UINT:
6618                 case TYPE_LONG:         case TYPE_ULONG:
6619                 case TYPE_LLONG:        case TYPE_ULLONG:
6620                 case TYPE_FLOAT:        case TYPE_DOUBLE:
6621                 case TYPE_LDOUBLE:
6622                 case TYPE_POINTER:
6623                 case TYPE_ENUM:
6624                 case TYPE_BITFIELD:
6625                         member = type;
6626                         break;
6627                 case TYPE_ARRAY:
6628                         member = type->left;
6629                         size = reg_size_of(state, member);
6630                         if (size > REG_SIZEOF_REG) {
6631                                 member = reg_type(state, member, reg_offset % size);
6632                         }
6633                         break;
6634                 case TYPE_STRUCT:
6635                 case TYPE_TUPLE:
6636                 {
6637                         size_t offset;
6638                         offset = 0;
6639                         member = type->left;
6640                         while(member && ((member->type & TYPE_MASK) == TYPE_PRODUCT)) {
6641                                 size = reg_size_of(state, member->left);
6642                                 offset += reg_needed_padding(state, member->left, offset);
6643                                 if ((offset + size) > reg_offset) {
6644                                         member = member->left;
6645                                         break;
6646                                 }
6647                                 offset += size;
6648                                 member = member->right;
6649                         }
6650                         offset += reg_needed_padding(state, member, offset);
6651                         member = reg_type(state, member, reg_offset - offset);
6652                         break;
6653                 }
6654                 case TYPE_UNION:
6655                 case TYPE_JOIN:
6656                 {
6657                         struct type *join, **jnext, *mnext;
6658                         join = new_type(TYPE_JOIN, 0, 0);
6659                         jnext = &join->left;
6660                         mnext = type->left;
6661                         while(mnext) {
6662                                 size_t size;
6663                                 member = mnext;
6664                                 mnext = 0;
6665                                 if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
6666                                         mnext = member->right;
6667                                         member = member->left;
6668                                 }
6669                                 size = reg_size_of(state, member);
6670                                 if (size > reg_offset) {
6671                                         struct type *part, *hunt;
6672                                         part = reg_type(state, member, reg_offset);
6673                                         /* See if this type is already in the union */
6674                                         hunt = join->left;
6675                                         while(hunt) {
6676                                                 struct type *test = hunt;
6677                                                 hunt = 0;
6678                                                 if ((test->type & TYPE_MASK) == TYPE_OVERLAP) {
6679                                                         hunt = test->right;
6680                                                         test = test->left;
6681                                                 }
6682                                                 if (equiv_types(part, test)) {
6683                                                         goto next;
6684                                                 }
6685                                         }
6686                                         /* Nope add it */
6687                                         if (!*jnext) {
6688                                                 *jnext = part;
6689                                         } else {
6690                                                 *jnext = new_type(TYPE_OVERLAP, *jnext, part);
6691                                                 jnext = &(*jnext)->right;
6692                                         }
6693                                         join->elements++;
6694                                 }
6695                         next:
6696                                 ;
6697                         }
6698                         if (join->elements == 0) {
6699                                 internal_error(state, 0, "No elements?");
6700                         }
6701                         member = join;
6702                         break;
6703                 }
6704                 default:
6705                         member = 0;
6706                         fprintf(state->errout, "type: ");
6707                         name_of(state->errout, type);
6708                         fprintf(state->errout, "\n");
6709                         internal_error(state, 0, "reg_type not yet defined for type");
6710
6711                 }
6712         }
6713         /* If I have a single register compound type not a bit-field
6714          * find the real type.
6715          */
6716         member = unpack_type(state, member);
6717                 ;
6718         size  = reg_size_of(state, member);
6719         if (size > REG_SIZEOF_REG) {
6720                 internal_error(state, 0, "Cannot find type of single register");
6721         }
6722 #if 1
6723         invalid = invalid_type(state, member);
6724         if (invalid) {
6725                 fprintf(state->errout, "type: ");
6726                 name_of(state->errout, member);
6727                 fprintf(state->errout, "\n");
6728                 fprintf(state->errout, "invalid: ");
6729                 name_of(state->errout, invalid);
6730                 fprintf(state->errout, "\n");
6731                 internal_error(state, 0, "returning bad type?");
6732         }
6733 #endif
6734         return member;
6735 }
6736
6737 static struct type *next_field(struct compile_state *state,
6738         struct type *type, struct type *prev_member)
6739 {
6740         struct type *member;
6741         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6742                 internal_error(state, 0, "next_field only works on structures");
6743         }
6744         member = type->left;
6745         while((member->type & TYPE_MASK) == TYPE_PRODUCT) {
6746                 if (!prev_member) {
6747                         member = member->left;
6748                         break;
6749                 }
6750                 if (member->left == prev_member) {
6751                         prev_member = 0;
6752                 }
6753                 member = member->right;
6754         }
6755         if (member == prev_member) {
6756                 prev_member = 0;
6757         }
6758         if (prev_member) {
6759                 internal_error(state, 0, "prev_member %s not present",
6760                         prev_member->field_ident->name);
6761         }
6762         return member;
6763 }
6764
6765 typedef void (*walk_type_fields_cb_t)(struct compile_state *state, struct type *type,
6766         size_t ret_offset, size_t mem_offset, void *arg);
6767
6768 static void walk_type_fields(struct compile_state *state,
6769         struct type *type, size_t reg_offset, size_t mem_offset,
6770         walk_type_fields_cb_t cb, void *arg);
6771
6772 static void walk_struct_fields(struct compile_state *state,
6773         struct type *type, size_t reg_offset, size_t mem_offset,
6774         walk_type_fields_cb_t cb, void *arg)
6775 {
6776         struct type *tptr;
6777         ulong_t i;
6778         if ((type->type & TYPE_MASK) != TYPE_STRUCT) {
6779                 internal_error(state, 0, "walk_struct_fields only works on structures");
6780         }
6781         tptr = type->left;
6782         for(i = 0; i < type->elements; i++) {
6783                 struct type *mtype;
6784                 mtype = tptr;
6785                 if ((mtype->type & TYPE_MASK) == TYPE_PRODUCT) {
6786                         mtype = mtype->left;
6787                 }
6788                 walk_type_fields(state, mtype,
6789                         reg_offset +
6790                         field_reg_offset(state, type, mtype->field_ident),
6791                         mem_offset +
6792                         field_offset(state, type, mtype->field_ident),
6793                         cb, arg);
6794                 tptr = tptr->right;
6795         }
6796
6797 }
6798
6799 static void walk_type_fields(struct compile_state *state,
6800         struct type *type, size_t reg_offset, size_t mem_offset,
6801         walk_type_fields_cb_t cb, void *arg)
6802 {
6803         switch(type->type & TYPE_MASK) {
6804         case TYPE_STRUCT:
6805                 walk_struct_fields(state, type, reg_offset, mem_offset, cb, arg);
6806                 break;
6807         case TYPE_CHAR:
6808         case TYPE_UCHAR:
6809         case TYPE_SHORT:
6810         case TYPE_USHORT:
6811         case TYPE_INT:
6812         case TYPE_UINT:
6813         case TYPE_LONG:
6814         case TYPE_ULONG:
6815                 cb(state, type, reg_offset, mem_offset, arg);
6816                 break;
6817         case TYPE_VOID:
6818                 break;
6819         default:
6820                 internal_error(state, 0, "walk_type_fields not yet implemented for type");
6821         }
6822 }
6823
6824 static void arrays_complete(struct compile_state *state, struct type *type)
6825 {
6826         if ((type->type & TYPE_MASK) == TYPE_ARRAY) {
6827                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
6828                         error(state, 0, "array size not specified");
6829                 }
6830                 arrays_complete(state, type->left);
6831         }
6832 }
6833
6834 static unsigned int get_basic_type(struct type *type)
6835 {
6836         unsigned int basic;
6837         basic = type->type & TYPE_MASK;
6838         /* Convert enums to ints */
6839         if (basic == TYPE_ENUM) {
6840                 basic = TYPE_INT;
6841         }
6842         /* Convert bitfields to standard types */
6843         else if (basic == TYPE_BITFIELD) {
6844                 if (type->elements <= SIZEOF_CHAR) {
6845                         basic = TYPE_CHAR;
6846                 }
6847                 else if (type->elements <= SIZEOF_SHORT) {
6848                         basic = TYPE_SHORT;
6849                 }
6850                 else if (type->elements <= SIZEOF_INT) {
6851                         basic = TYPE_INT;
6852                 }
6853                 else if (type->elements <= SIZEOF_LONG) {
6854                         basic = TYPE_LONG;
6855                 }
6856                 if (!TYPE_SIGNED(type->left->type)) {
6857                         basic += 1;
6858                 }
6859         }
6860         return basic;
6861 }
6862
6863 static unsigned int do_integral_promotion(unsigned int type)
6864 {
6865         if (TYPE_INTEGER(type) && (TYPE_RANK(type) < TYPE_RANK(TYPE_INT))) {
6866                 type = TYPE_INT;
6867         }
6868         return type;
6869 }
6870
6871 static unsigned int do_arithmetic_conversion(
6872         unsigned int left, unsigned int right)
6873 {
6874         if ((left == TYPE_LDOUBLE) || (right == TYPE_LDOUBLE)) {
6875                 return TYPE_LDOUBLE;
6876         }
6877         else if ((left == TYPE_DOUBLE) || (right == TYPE_DOUBLE)) {
6878                 return TYPE_DOUBLE;
6879         }
6880         else if ((left == TYPE_FLOAT) || (right == TYPE_FLOAT)) {
6881                 return TYPE_FLOAT;
6882         }
6883         left = do_integral_promotion(left);
6884         right = do_integral_promotion(right);
6885         /* If both operands have the same size done */
6886         if (left == right) {
6887                 return left;
6888         }
6889         /* If both operands have the same signedness pick the larger */
6890         else if (!!TYPE_UNSIGNED(left) == !!TYPE_UNSIGNED(right)) {
6891                 return (TYPE_RANK(left) >= TYPE_RANK(right)) ? left : right;
6892         }
6893         /* If the signed type can hold everything use it */
6894         else if (TYPE_SIGNED(left) && (TYPE_RANK(left) > TYPE_RANK(right))) {
6895                 return left;
6896         }
6897         else if (TYPE_SIGNED(right) && (TYPE_RANK(right) > TYPE_RANK(left))) {
6898                 return right;
6899         }
6900         /* Convert to the unsigned type with the same rank as the signed type */
6901         else if (TYPE_SIGNED(left)) {
6902                 return TYPE_MKUNSIGNED(left);
6903         }
6904         else {
6905                 return TYPE_MKUNSIGNED(right);
6906         }
6907 }
6908
6909 /* see if two types are the same except for qualifiers */
6910 static int equiv_types(struct type *left, struct type *right)
6911 {
6912         unsigned int type;
6913         /* Error if the basic types do not match */
6914         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6915                 return 0;
6916         }
6917         type = left->type & TYPE_MASK;
6918         /* If the basic types match and it is a void type we are done */
6919         if (type == TYPE_VOID) {
6920                 return 1;
6921         }
6922         /* For bitfields we need to compare the sizes */
6923         else if (type == TYPE_BITFIELD) {
6924                 return (left->elements == right->elements) &&
6925                         (TYPE_SIGNED(left->left->type) == TYPE_SIGNED(right->left->type));
6926         }
6927         /* if the basic types match and it is an arithmetic type we are done */
6928         else if (TYPE_ARITHMETIC(type)) {
6929                 return 1;
6930         }
6931         /* If it is a pointer type recurse and keep testing */
6932         else if (type == TYPE_POINTER) {
6933                 return equiv_types(left->left, right->left);
6934         }
6935         else if (type == TYPE_ARRAY) {
6936                 return (left->elements == right->elements) &&
6937                         equiv_types(left->left, right->left);
6938         }
6939         /* test for struct equality */
6940         else if (type == TYPE_STRUCT) {
6941                 return left->type_ident == right->type_ident;
6942         }
6943         /* test for union equality */
6944         else if (type == TYPE_UNION) {
6945                 return left->type_ident == right->type_ident;
6946         }
6947         /* Test for equivalent functions */
6948         else if (type == TYPE_FUNCTION) {
6949                 return equiv_types(left->left, right->left) &&
6950                         equiv_types(left->right, right->right);
6951         }
6952         /* We only see TYPE_PRODUCT as part of function equivalence matching */
6953         /* We also see TYPE_PRODUCT as part of of tuple equivalence matchin */
6954         else if (type == TYPE_PRODUCT) {
6955                 return equiv_types(left->left, right->left) &&
6956                         equiv_types(left->right, right->right);
6957         }
6958         /* We should see TYPE_OVERLAP when comparing joins */
6959         else if (type == TYPE_OVERLAP) {
6960                 return equiv_types(left->left, right->left) &&
6961                         equiv_types(left->right, right->right);
6962         }
6963         /* Test for equivalence of tuples */
6964         else if (type == TYPE_TUPLE) {
6965                 return (left->elements == right->elements) &&
6966                         equiv_types(left->left, right->left);
6967         }
6968         /* Test for equivalence of joins */
6969         else if (type == TYPE_JOIN) {
6970                 return (left->elements == right->elements) &&
6971                         equiv_types(left->left, right->left);
6972         }
6973         else {
6974                 return 0;
6975         }
6976 }
6977
6978 static int equiv_ptrs(struct type *left, struct type *right)
6979 {
6980         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
6981                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
6982                 return 0;
6983         }
6984         return equiv_types(left->left, right->left);
6985 }
6986
6987 static struct type *compatible_types(struct type *left, struct type *right)
6988 {
6989         struct type *result;
6990         unsigned int type, qual_type;
6991         /* Error if the basic types do not match */
6992         if ((left->type & TYPE_MASK) != (right->type & TYPE_MASK)) {
6993                 return 0;
6994         }
6995         type = left->type & TYPE_MASK;
6996         qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
6997         result = 0;
6998         /* if the basic types match and it is an arithmetic type we are done */
6999         if (TYPE_ARITHMETIC(type)) {
7000                 result = new_type(qual_type, 0, 0);
7001         }
7002         /* If it is a pointer type recurse and keep testing */
7003         else if (type == TYPE_POINTER) {
7004                 result = compatible_types(left->left, right->left);
7005                 if (result) {
7006                         result = new_type(qual_type, result, 0);
7007                 }
7008         }
7009         /* test for struct equality */
7010         else if (type == TYPE_STRUCT) {
7011                 if (left->type_ident == right->type_ident) {
7012                         result = left;
7013                 }
7014         }
7015         /* test for union equality */
7016         else if (type == TYPE_UNION) {
7017                 if (left->type_ident == right->type_ident) {
7018                         result = left;
7019                 }
7020         }
7021         /* Test for equivalent functions */
7022         else if (type == TYPE_FUNCTION) {
7023                 struct type *lf, *rf;
7024                 lf = compatible_types(left->left, right->left);
7025                 rf = compatible_types(left->right, right->right);
7026                 if (lf && rf) {
7027                         result = new_type(qual_type, lf, rf);
7028                 }
7029         }
7030         /* We only see TYPE_PRODUCT as part of function equivalence matching */
7031         else if (type == TYPE_PRODUCT) {
7032                 struct type *lf, *rf;
7033                 lf = compatible_types(left->left, right->left);
7034                 rf = compatible_types(left->right, right->right);
7035                 if (lf && rf) {
7036                         result = new_type(qual_type, lf, rf);
7037                 }
7038         }
7039         else {
7040                 /* Nothing else is compatible */
7041         }
7042         return result;
7043 }
7044
7045 /* See if left is a equivalent to right or right is a union member of left */
7046 static int is_subset_type(struct type *left, struct type *right)
7047 {
7048         if (equiv_types(left, right)) {
7049                 return 1;
7050         }
7051         if ((left->type & TYPE_MASK) == TYPE_JOIN) {
7052                 struct type *member, *mnext;
7053                 mnext = left->left;
7054                 while(mnext) {
7055                         member = mnext;
7056                         mnext = 0;
7057                         if ((member->type & TYPE_MASK) == TYPE_OVERLAP) {
7058                                 mnext = member->right;
7059                                 member = member->left;
7060                         }
7061                         if (is_subset_type( member, right)) {
7062                                 return 1;
7063                         }
7064                 }
7065         }
7066         return 0;
7067 }
7068
7069 static struct type *compatible_ptrs(struct type *left, struct type *right)
7070 {
7071         struct type *result;
7072         if (((left->type & TYPE_MASK) != TYPE_POINTER) ||
7073                 ((right->type & TYPE_MASK) != TYPE_POINTER)) {
7074                 return 0;
7075         }
7076         result = compatible_types(left->left, right->left);
7077         if (result) {
7078                 unsigned int qual_type;
7079                 qual_type = (left->type & ~STOR_MASK) | (right->type & ~STOR_MASK);
7080                 result = new_type(qual_type, result, 0);
7081         }
7082         return result;
7083
7084 }
7085 static struct triple *integral_promotion(
7086         struct compile_state *state, struct triple *def)
7087 {
7088         struct type *type;
7089         type = def->type;
7090         /* As all operations are carried out in registers
7091          * the values are converted on load I just convert
7092          * logical type of the operand.
7093          */
7094         if (TYPE_INTEGER(type->type)) {
7095                 unsigned int int_type;
7096                 int_type = type->type & ~TYPE_MASK;
7097                 int_type |= do_integral_promotion(get_basic_type(type));
7098                 if (int_type != type->type) {
7099                         if (def->op != OP_LOAD) {
7100                                 def->type = new_type(int_type, 0, 0);
7101                         }
7102                         else {
7103                                 def = triple(state, OP_CONVERT,
7104                                         new_type(int_type, 0, 0), def, 0);
7105                         }
7106                 }
7107         }
7108         return def;
7109 }
7110
7111
7112 static void arithmetic(struct compile_state *state, struct triple *def)
7113 {
7114         if (!TYPE_ARITHMETIC(def->type->type)) {
7115                 error(state, 0, "arithmetic type expexted");
7116         }
7117 }
7118
7119 static void ptr_arithmetic(struct compile_state *state, struct triple *def)
7120 {
7121         if (!TYPE_PTR(def->type->type) && !TYPE_ARITHMETIC(def->type->type)) {
7122                 error(state, def, "pointer or arithmetic type expected");
7123         }
7124 }
7125
7126 static int is_integral(struct triple *ins)
7127 {
7128         return TYPE_INTEGER(ins->type->type);
7129 }
7130
7131 static void integral(struct compile_state *state, struct triple *def)
7132 {
7133         if (!is_integral(def)) {
7134                 error(state, 0, "integral type expected");
7135         }
7136 }
7137
7138
7139 static void bool(struct compile_state *state, struct triple *def)
7140 {
7141         if (!TYPE_ARITHMETIC(def->type->type) &&
7142                 ((def->type->type & TYPE_MASK) != TYPE_POINTER)) {
7143                 error(state, 0, "arithmetic or pointer type expected");
7144         }
7145 }
7146
7147 static int is_signed(struct type *type)
7148 {
7149         if ((type->type & TYPE_MASK) == TYPE_BITFIELD) {
7150                 type = type->left;
7151         }
7152         return !!TYPE_SIGNED(type->type);
7153 }
7154 static int is_compound_type(struct type *type)
7155 {
7156         int is_compound;
7157         switch((type->type & TYPE_MASK)) {
7158         case TYPE_ARRAY:
7159         case TYPE_STRUCT:
7160         case TYPE_TUPLE:
7161         case TYPE_UNION:
7162         case TYPE_JOIN:
7163                 is_compound = 1;
7164                 break;
7165         default:
7166                 is_compound = 0;
7167                 break;
7168         }
7169         return is_compound;
7170 }
7171
7172 /* Is this value located in a register otherwise it must be in memory */
7173 static int is_in_reg(struct compile_state *state, struct triple *def)
7174 {
7175         int in_reg;
7176         if (def->op == OP_ADECL) {
7177                 in_reg = 1;
7178         }
7179         else if ((def->op == OP_SDECL) || (def->op == OP_DEREF)) {
7180                 in_reg = 0;
7181         }
7182         else if (triple_is_part(state, def)) {
7183                 in_reg = is_in_reg(state, MISC(def, 0));
7184         }
7185         else {
7186                 internal_error(state, def, "unknown expr storage location");
7187                 in_reg = -1;
7188         }
7189         return in_reg;
7190 }
7191
7192 /* Is this an auto or static variable location? Something that can
7193  * be assigned to.  Otherwise it must must be a pure value, a temporary.
7194  */
7195 static int is_lvalue(struct compile_state *state, struct triple *def)
7196 {
7197         int ret;
7198         ret = 0;
7199         if (!def) {
7200                 return 0;
7201         }
7202         if ((def->op == OP_ADECL) ||
7203                 (def->op == OP_SDECL) ||
7204                 (def->op == OP_DEREF) ||
7205                 (def->op == OP_BLOBCONST) ||
7206                 (def->op == OP_LIST)) {
7207                 ret = 1;
7208         }
7209         else if (triple_is_part(state, def)) {
7210                 ret = is_lvalue(state, MISC(def, 0));
7211         }
7212         return ret;
7213 }
7214
7215 static void clvalue(struct compile_state *state, struct triple *def)
7216 {
7217         if (!def) {
7218                 internal_error(state, def, "nothing where lvalue expected?");
7219         }
7220         if (!is_lvalue(state, def)) {
7221                 error(state, def, "lvalue expected");
7222         }
7223 }
7224 static void lvalue(struct compile_state *state, struct triple *def)
7225 {
7226         clvalue(state, def);
7227         if (def->type->type & QUAL_CONST) {
7228                 error(state, def, "modifable lvalue expected");
7229         }
7230 }
7231
7232 static int is_pointer(struct triple *def)
7233 {
7234         return (def->type->type & TYPE_MASK) == TYPE_POINTER;
7235 }
7236
7237 static void pointer(struct compile_state *state, struct triple *def)
7238 {
7239         if (!is_pointer(def)) {
7240                 error(state, def, "pointer expected");
7241         }
7242 }
7243
7244 static struct triple *int_const(
7245         struct compile_state *state, struct type *type, ulong_t value)
7246 {
7247         struct triple *result;
7248         switch(type->type & TYPE_MASK) {
7249         case TYPE_CHAR:
7250         case TYPE_INT:   case TYPE_UINT:
7251         case TYPE_LONG:  case TYPE_ULONG:
7252                 break;
7253         default:
7254                 internal_error(state, 0, "constant for unknown type");
7255         }
7256         result = triple(state, OP_INTCONST, type, 0, 0);
7257         result->u.cval = value;
7258         return result;
7259 }
7260
7261
7262 static struct triple *read_expr(struct compile_state *state, struct triple *def);
7263
7264 static struct triple *do_mk_addr_expr(struct compile_state *state,
7265         struct triple *expr, struct type *type, ulong_t offset)
7266 {
7267         struct triple *result;
7268         struct type *ptr_type;
7269         clvalue(state, expr);
7270
7271         ptr_type = new_type(TYPE_POINTER | (type->type & QUAL_MASK), type, 0);
7272
7273
7274         result = 0;
7275         if (expr->op == OP_ADECL) {
7276                 error(state, expr, "address of auto variables not supported");
7277         }
7278         else if (expr->op == OP_SDECL) {
7279                 result = triple(state, OP_ADDRCONST, ptr_type, 0, 0);
7280                 MISC(result, 0) = expr;
7281                 result->u.cval = offset;
7282         }
7283         else if (expr->op == OP_DEREF) {
7284                 result = triple(state, OP_ADD, ptr_type,
7285                         RHS(expr, 0),
7286                         int_const(state, &ulong_type, offset));
7287         }
7288         else if (expr->op == OP_BLOBCONST) {
7289                 FINISHME();
7290                 internal_error(state, expr, "not yet implemented");
7291         }
7292         else if (expr->op == OP_LIST) {
7293                 error(state, 0, "Function addresses not supported");
7294         }
7295         else if (triple_is_part(state, expr)) {
7296                 struct triple *part;
7297                 part = expr;
7298                 expr = MISC(expr, 0);
7299                 if (part->op == OP_DOT) {
7300                         offset += bits_to_bytes(
7301                                 field_offset(state, expr->type, part->u.field));
7302                 }
7303                 else if (part->op == OP_INDEX) {
7304                         offset += bits_to_bytes(
7305                                 index_offset(state, expr->type, part->u.cval));
7306                 }
7307                 else {
7308                         internal_error(state, part, "unhandled part type");
7309                 }
7310                 result = do_mk_addr_expr(state, expr, type, offset);
7311         }
7312         if (!result) {
7313                 internal_error(state, expr, "cannot take address of expression");
7314         }
7315         return result;
7316 }
7317
7318 static struct triple *mk_addr_expr(
7319         struct compile_state *state, struct triple *expr, ulong_t offset)
7320 {
7321         return do_mk_addr_expr(state, expr, expr->type, offset);
7322 }
7323
7324 static struct triple *mk_deref_expr(
7325         struct compile_state *state, struct triple *expr)
7326 {
7327         struct type *base_type;
7328         pointer(state, expr);
7329         base_type = expr->type->left;
7330         return triple(state, OP_DEREF, base_type, expr, 0);
7331 }
7332
7333 /* lvalue conversions always apply except when certain operators
7334  * are applied.  So I apply apply it when I know no more
7335  * operators will be applied.
7336  */
7337 static struct triple *lvalue_conversion(struct compile_state *state, struct triple *def)
7338 {
7339         /* Tranform an array to a pointer to the first element */
7340         if ((def->type->type & TYPE_MASK) == TYPE_ARRAY) {
7341                 struct type *type;
7342                 type = new_type(
7343                         TYPE_POINTER | (def->type->type & QUAL_MASK),
7344                         def->type->left, 0);
7345                 if ((def->op == OP_SDECL) || IS_CONST_OP(def->op)) {
7346                         struct triple *addrconst;
7347                         if ((def->op != OP_SDECL) && (def->op != OP_BLOBCONST)) {
7348                                 internal_error(state, def, "bad array constant");
7349                         }
7350                         addrconst = triple(state, OP_ADDRCONST, type, 0, 0);
7351                         MISC(addrconst, 0) = def;
7352                         def = addrconst;
7353                 }
7354                 else {
7355                         def = triple(state, OP_CONVERT, type, def, 0);
7356                 }
7357         }
7358         /* Transform a function to a pointer to it */
7359         else if ((def->type->type & TYPE_MASK) == TYPE_FUNCTION) {
7360                 def = mk_addr_expr(state, def, 0);
7361         }
7362         return def;
7363 }
7364
7365 static struct triple *deref_field(
7366         struct compile_state *state, struct triple *expr, struct hash_entry *field)
7367 {
7368         struct triple *result;
7369         struct type *type, *member;
7370         ulong_t offset;
7371         if (!field) {
7372                 internal_error(state, 0, "No field passed to deref_field");
7373         }
7374         result = 0;
7375         type = expr->type;
7376         if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
7377                 ((type->type & TYPE_MASK) != TYPE_UNION)) {
7378                 error(state, 0, "request for member %s in something not a struct or union",
7379                         field->name);
7380         }
7381         member = field_type(state, type, field);
7382         if ((type->type & STOR_MASK) == STOR_PERM) {
7383                 /* Do the pointer arithmetic to get a deref the field */
7384                 offset = bits_to_bytes(field_offset(state, type, field));
7385                 result = do_mk_addr_expr(state, expr, member, offset);
7386                 result = mk_deref_expr(state, result);
7387         }
7388         else {
7389                 /* Find the variable for the field I want. */
7390                 result = triple(state, OP_DOT, member, expr, 0);
7391                 result->u.field = field;
7392         }
7393         return result;
7394 }
7395
7396 static struct triple *deref_index(
7397         struct compile_state *state, struct triple *expr, size_t index)
7398 {
7399         struct triple *result;
7400         struct type *type, *member;
7401         ulong_t offset;
7402
7403         result = 0;
7404         type = expr->type;
7405         member = index_type(state, type, index);
7406
7407         if ((type->type & STOR_MASK) == STOR_PERM) {
7408                 offset = bits_to_bytes(index_offset(state, type, index));
7409                 result = do_mk_addr_expr(state, expr, member, offset);
7410                 result = mk_deref_expr(state, result);
7411         }
7412         else {
7413                 result = triple(state, OP_INDEX, member, expr, 0);
7414                 result->u.cval = index;
7415         }
7416         return result;
7417 }
7418
7419 static struct triple *read_expr(struct compile_state *state, struct triple *def)
7420 {
7421         int op;
7422         if  (!def) {
7423                 return 0;
7424         }
7425 #if DEBUG_ROMCC_WARNINGS
7426 #warning "CHECK_ME is this the only place I need to do lvalue conversions?"
7427 #endif
7428         /* Transform lvalues into something we can read */
7429         def = lvalue_conversion(state, def);
7430         if (!is_lvalue(state, def)) {
7431                 return def;
7432         }
7433         if (is_in_reg(state, def)) {
7434                 op = OP_READ;
7435         } else {
7436                 if (def->op == OP_SDECL) {
7437                         def = mk_addr_expr(state, def, 0);
7438                         def = mk_deref_expr(state, def);
7439                 }
7440                 op = OP_LOAD;
7441         }
7442         def = triple(state, op, def->type, def, 0);
7443         if (def->type->type & QUAL_VOLATILE) {
7444                 def->id |= TRIPLE_FLAG_VOLATILE;
7445         }
7446         return def;
7447 }
7448
7449 int is_write_compatible(struct compile_state *state,
7450         struct type *dest, struct type *rval)
7451 {
7452         int compatible = 0;
7453         /* Both operands have arithmetic type */
7454         if (TYPE_ARITHMETIC(dest->type) && TYPE_ARITHMETIC(rval->type)) {
7455                 compatible = 1;
7456         }
7457         /* One operand is a pointer and the other is a pointer to void */
7458         else if (((dest->type & TYPE_MASK) == TYPE_POINTER) &&
7459                 ((rval->type & TYPE_MASK) == TYPE_POINTER) &&
7460                 (((dest->left->type & TYPE_MASK) == TYPE_VOID) ||
7461                         ((rval->left->type & TYPE_MASK) == TYPE_VOID))) {
7462                 compatible = 1;
7463         }
7464         /* If both types are the same without qualifiers we are good */
7465         else if (equiv_ptrs(dest, rval)) {
7466                 compatible = 1;
7467         }
7468         /* test for struct/union equality  */
7469         else if (equiv_types(dest, rval)) {
7470                 compatible = 1;
7471         }
7472         return compatible;
7473 }
7474
7475 static void write_compatible(struct compile_state *state,
7476         struct type *dest, struct type *rval)
7477 {
7478         if (!is_write_compatible(state, dest, rval)) {
7479                 FILE *fp = state->errout;
7480                 fprintf(fp, "dest: ");
7481                 name_of(fp, dest);
7482                 fprintf(fp,"\nrval: ");
7483                 name_of(fp, rval);
7484                 fprintf(fp, "\n");
7485                 error(state, 0, "Incompatible types in assignment");
7486         }
7487 }
7488
7489 static int is_init_compatible(struct compile_state *state,
7490         struct type *dest, struct type *rval)
7491 {
7492         int compatible = 0;
7493         if (is_write_compatible(state, dest, rval)) {
7494                 compatible = 1;
7495         }
7496         else if (equiv_types(dest, rval)) {
7497                 compatible = 1;
7498         }
7499         return compatible;
7500 }
7501
7502 static struct triple *write_expr(
7503         struct compile_state *state, struct triple *dest, struct triple *rval)
7504 {
7505         struct triple *def;
7506
7507         def = 0;
7508         if (!rval) {
7509                 internal_error(state, 0, "missing rval");
7510         }
7511
7512         if (rval->op == OP_LIST) {
7513                 internal_error(state, 0, "expression of type OP_LIST?");
7514         }
7515         if (!is_lvalue(state, dest)) {
7516                 internal_error(state, 0, "writing to a non lvalue?");
7517         }
7518         if (dest->type->type & QUAL_CONST) {
7519                 internal_error(state, 0, "modifable lvalue expexted");
7520         }
7521
7522         write_compatible(state, dest->type, rval->type);
7523         if (!equiv_types(dest->type, rval->type)) {
7524                 rval = triple(state, OP_CONVERT, dest->type, rval, 0);
7525         }
7526
7527         /* Now figure out which assignment operator to use */
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         first = state->first;
9164         ins = first;
9165
9166         /* Pass one expand compound values into pseudo registers.
9167          */
9168         next = first;
9169         do {
9170                 ins = next;
9171                 next = ins->next;
9172                 switch(ins->op) {
9173                 case OP_UNKNOWNVAL:
9174                         next = decompose_unknownval(state, ins);
9175                         break;
9176
9177                 case OP_READ:
9178                         next = decompose_read(state, ins);
9179                         break;
9180
9181                 case OP_WRITE:
9182                         next = decompose_write(state, ins);
9183                         break;
9184
9185
9186                 /* Be very careful with the load/store logic. These
9187                  * operations must convert from the in register layout
9188                  * to the in memory layout, which is nontrivial.
9189                  */
9190                 case OP_LOAD:
9191                         next = decompose_load(state, ins);
9192                         break;
9193                 case OP_STORE:
9194                         next = decompose_store(state, ins);
9195                         break;
9196
9197                 case OP_DOT:
9198                         next = decompose_dot(state, ins);
9199                         break;
9200                 case OP_INDEX:
9201                         next = decompose_index(state, ins);
9202                         break;
9203
9204                 }
9205 #if DEBUG_DECOMPOSE_HIRES
9206                 fprintf(fp, "decompose next: %p \n", next);
9207                 fflush(fp);
9208                 fprintf(fp, "next->op: %d %s\n",
9209                         next->op, tops(next->op));
9210                 /* High resolution debugging mode */
9211                 print_triples(state);
9212 #endif
9213         } while (next != first);
9214
9215         /* Pass two remove the tuples.
9216          */
9217         ins = first;
9218         do {
9219                 next = ins->next;
9220                 if (ins->op == OP_TUPLE) {
9221                         if (ins->use) {
9222                                 internal_error(state, ins, "tuple used");
9223                         }
9224                         else {
9225                                 release_triple(state, ins);
9226                         }
9227                 }
9228                 ins = next;
9229         } while(ins != first);
9230         ins = first;
9231         do {
9232                 next = ins->next;
9233                 if (ins->op == OP_BITREF) {
9234                         if (ins->use) {
9235                                 internal_error(state, ins, "bitref used");
9236                         }
9237                         else {
9238                                 release_triple(state, ins);
9239                         }
9240                 }
9241                 ins = next;
9242         } while(ins != first);
9243
9244         /* Pass three verify the state and set ->id to 0.
9245          */
9246         next = first;
9247         do {
9248                 ins = next;
9249                 next = ins->next;
9250                 ins->id &= ~TRIPLE_FLAG_FLATTENED;
9251                 if (triple_stores_block(state, ins)) {
9252                         ins->u.block = 0;
9253                 }
9254                 if (triple_is_def(state, ins)) {
9255                         if (reg_size_of(state, ins->type) > REG_SIZEOF_REG) {
9256                                 internal_error(state, ins, "multi register value remains?");
9257                         }
9258                 }
9259                 if (ins->op == OP_DOT) {
9260                         internal_error(state, ins, "OP_DOT remains?");
9261                 }
9262                 if (ins->op == OP_INDEX) {
9263                         internal_error(state, ins, "OP_INDEX remains?");
9264                 }
9265                 if (ins->op == OP_BITREF) {
9266                         internal_error(state, ins, "OP_BITREF remains?");
9267                 }
9268                 if (ins->op == OP_TUPLE) {
9269                         internal_error(state, ins, "OP_TUPLE remains?");
9270                 }
9271         } while(next != first);
9272 }
9273
9274 /* For those operations that cannot be simplified */
9275 static void simplify_noop(struct compile_state *state, struct triple *ins)
9276 {
9277         return;
9278 }
9279
9280 static void simplify_smul(struct compile_state *state, struct triple *ins)
9281 {
9282         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9283                 struct triple *tmp;
9284                 tmp = RHS(ins, 0);
9285                 RHS(ins, 0) = RHS(ins, 1);
9286                 RHS(ins, 1) = tmp;
9287         }
9288         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9289                 long_t left, right;
9290                 left  = read_sconst(state, ins, RHS(ins, 0));
9291                 right = read_sconst(state, ins, RHS(ins, 1));
9292                 mkconst(state, ins, left * right);
9293         }
9294         else if (is_zero(RHS(ins, 1))) {
9295                 mkconst(state, ins, 0);
9296         }
9297         else if (is_one(RHS(ins, 1))) {
9298                 mkcopy(state, ins, RHS(ins, 0));
9299         }
9300         else if (is_pow2(RHS(ins, 1))) {
9301                 struct triple *val;
9302                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9303                 ins->op = OP_SL;
9304                 insert_triple(state, state->global_pool, val);
9305                 unuse_triple(RHS(ins, 1), ins);
9306                 use_triple(val, ins);
9307                 RHS(ins, 1) = val;
9308         }
9309 }
9310
9311 static void simplify_umul(struct compile_state *state, struct triple *ins)
9312 {
9313         if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9314                 struct triple *tmp;
9315                 tmp = RHS(ins, 0);
9316                 RHS(ins, 0) = RHS(ins, 1);
9317                 RHS(ins, 1) = tmp;
9318         }
9319         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9320                 ulong_t left, right;
9321                 left  = read_const(state, ins, RHS(ins, 0));
9322                 right = read_const(state, ins, RHS(ins, 1));
9323                 mkconst(state, ins, left * right);
9324         }
9325         else if (is_zero(RHS(ins, 1))) {
9326                 mkconst(state, ins, 0);
9327         }
9328         else if (is_one(RHS(ins, 1))) {
9329                 mkcopy(state, ins, RHS(ins, 0));
9330         }
9331         else if (is_pow2(RHS(ins, 1))) {
9332                 struct triple *val;
9333                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9334                 ins->op = OP_SL;
9335                 insert_triple(state, state->global_pool, val);
9336                 unuse_triple(RHS(ins, 1), ins);
9337                 use_triple(val, ins);
9338                 RHS(ins, 1) = val;
9339         }
9340 }
9341
9342 static void simplify_sdiv(struct compile_state *state, struct triple *ins)
9343 {
9344         if (is_const(RHS(ins, 0)) && is_const(RHS(ins, 1))) {
9345                 long_t left, right;
9346                 left  = read_sconst(state, ins, RHS(ins, 0));
9347                 right = read_sconst(state, ins, RHS(ins, 1));
9348                 mkconst(state, ins, left / right);
9349         }
9350         else if (is_zero(RHS(ins, 0))) {
9351                 mkconst(state, ins, 0);
9352         }
9353         else if (is_zero(RHS(ins, 1))) {
9354                 error(state, ins, "division by zero");
9355         }
9356         else if (is_one(RHS(ins, 1))) {
9357                 mkcopy(state, ins, RHS(ins, 0));
9358         }
9359         else if (is_pow2(RHS(ins, 1))) {
9360                 struct triple *val;
9361                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9362                 ins->op = OP_SSR;
9363                 insert_triple(state, state->global_pool, val);
9364                 unuse_triple(RHS(ins, 1), ins);
9365                 use_triple(val, ins);
9366                 RHS(ins, 1) = val;
9367         }
9368 }
9369
9370 static void simplify_udiv(struct compile_state *state, struct triple *ins)
9371 {
9372         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9373                 ulong_t left, right;
9374                 left  = read_const(state, ins, RHS(ins, 0));
9375                 right = read_const(state, ins, RHS(ins, 1));
9376                 mkconst(state, ins, left / right);
9377         }
9378         else if (is_zero(RHS(ins, 0))) {
9379                 mkconst(state, ins, 0);
9380         }
9381         else if (is_zero(RHS(ins, 1))) {
9382                 error(state, ins, "division by zero");
9383         }
9384         else if (is_one(RHS(ins, 1))) {
9385                 mkcopy(state, ins, RHS(ins, 0));
9386         }
9387         else if (is_pow2(RHS(ins, 1))) {
9388                 struct triple *val;
9389                 val = int_const(state, ins->type, tlog2(RHS(ins, 1)));
9390                 ins->op = OP_USR;
9391                 insert_triple(state, state->global_pool, val);
9392                 unuse_triple(RHS(ins, 1), ins);
9393                 use_triple(val, ins);
9394                 RHS(ins, 1) = val;
9395         }
9396 }
9397
9398 static void simplify_smod(struct compile_state *state, struct triple *ins)
9399 {
9400         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9401                 long_t left, right;
9402                 left  = read_const(state, ins, RHS(ins, 0));
9403                 right = read_const(state, ins, RHS(ins, 1));
9404                 mkconst(state, ins, left % right);
9405         }
9406         else if (is_zero(RHS(ins, 0))) {
9407                 mkconst(state, ins, 0);
9408         }
9409         else if (is_zero(RHS(ins, 1))) {
9410                 error(state, ins, "division by zero");
9411         }
9412         else if (is_one(RHS(ins, 1))) {
9413                 mkconst(state, ins, 0);
9414         }
9415         else if (is_pow2(RHS(ins, 1))) {
9416                 struct triple *val;
9417                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9418                 ins->op = OP_AND;
9419                 insert_triple(state, state->global_pool, val);
9420                 unuse_triple(RHS(ins, 1), ins);
9421                 use_triple(val, ins);
9422                 RHS(ins, 1) = val;
9423         }
9424 }
9425
9426 static void simplify_umod(struct compile_state *state, struct triple *ins)
9427 {
9428         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9429                 ulong_t left, right;
9430                 left  = read_const(state, ins, RHS(ins, 0));
9431                 right = read_const(state, ins, RHS(ins, 1));
9432                 mkconst(state, ins, left % right);
9433         }
9434         else if (is_zero(RHS(ins, 0))) {
9435                 mkconst(state, ins, 0);
9436         }
9437         else if (is_zero(RHS(ins, 1))) {
9438                 error(state, ins, "division by zero");
9439         }
9440         else if (is_one(RHS(ins, 1))) {
9441                 mkconst(state, ins, 0);
9442         }
9443         else if (is_pow2(RHS(ins, 1))) {
9444                 struct triple *val;
9445                 val = int_const(state, ins->type, RHS(ins, 1)->u.cval - 1);
9446                 ins->op = OP_AND;
9447                 insert_triple(state, state->global_pool, val);
9448                 unuse_triple(RHS(ins, 1), ins);
9449                 use_triple(val, ins);
9450                 RHS(ins, 1) = val;
9451         }
9452 }
9453
9454 static void simplify_add(struct compile_state *state, struct triple *ins)
9455 {
9456         /* start with the pointer on the left */
9457         if (is_pointer(RHS(ins, 1))) {
9458                 struct triple *tmp;
9459                 tmp = RHS(ins, 0);
9460                 RHS(ins, 0) = RHS(ins, 1);
9461                 RHS(ins, 1) = tmp;
9462         }
9463         if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9464                 if (RHS(ins, 0)->op == OP_INTCONST) {
9465                         ulong_t left, right;
9466                         left  = read_const(state, ins, RHS(ins, 0));
9467                         right = read_const(state, ins, RHS(ins, 1));
9468                         mkconst(state, ins, left + right);
9469                 }
9470                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9471                         struct triple *sdecl;
9472                         ulong_t left, right;
9473                         sdecl = MISC(RHS(ins, 0), 0);
9474                         left  = RHS(ins, 0)->u.cval;
9475                         right = RHS(ins, 1)->u.cval;
9476                         mkaddr_const(state, ins, sdecl, left + right);
9477                 }
9478                 else {
9479                         internal_warning(state, ins, "Optimize me!");
9480                 }
9481         }
9482         else if (is_const(RHS(ins, 0)) && !is_const(RHS(ins, 1))) {
9483                 struct triple *tmp;
9484                 tmp = RHS(ins, 1);
9485                 RHS(ins, 1) = RHS(ins, 0);
9486                 RHS(ins, 0) = tmp;
9487         }
9488 }
9489
9490 static void simplify_sub(struct compile_state *state, struct triple *ins)
9491 {
9492         if (is_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9493                 if (RHS(ins, 0)->op == OP_INTCONST) {
9494                         ulong_t left, right;
9495                         left  = read_const(state, ins, RHS(ins, 0));
9496                         right = read_const(state, ins, RHS(ins, 1));
9497                         mkconst(state, ins, left - right);
9498                 }
9499                 else if (RHS(ins, 0)->op == OP_ADDRCONST) {
9500                         struct triple *sdecl;
9501                         ulong_t left, right;
9502                         sdecl = MISC(RHS(ins, 0), 0);
9503                         left  = RHS(ins, 0)->u.cval;
9504                         right = RHS(ins, 1)->u.cval;
9505                         mkaddr_const(state, ins, sdecl, left - right);
9506                 }
9507                 else {
9508                         internal_warning(state, ins, "Optimize me!");
9509                 }
9510         }
9511 }
9512
9513 static void simplify_sl(struct compile_state *state, struct triple *ins)
9514 {
9515         if (is_simple_const(RHS(ins, 1))) {
9516                 ulong_t right;
9517                 right = read_const(state, ins, RHS(ins, 1));
9518                 if (right >= (size_of(state, ins->type))) {
9519                         warning(state, ins, "left shift count >= width of type");
9520                 }
9521         }
9522         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9523                 ulong_t left, right;
9524                 left  = read_const(state, ins, RHS(ins, 0));
9525                 right = read_const(state, ins, RHS(ins, 1));
9526                 mkconst(state, ins,  left << right);
9527         }
9528 }
9529
9530 static void simplify_usr(struct compile_state *state, struct triple *ins)
9531 {
9532         if (is_simple_const(RHS(ins, 1))) {
9533                 ulong_t right;
9534                 right = read_const(state, ins, RHS(ins, 1));
9535                 if (right >= (size_of(state, ins->type))) {
9536                         warning(state, ins, "right shift count >= width of type");
9537                 }
9538         }
9539         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9540                 ulong_t left, right;
9541                 left  = read_const(state, ins, RHS(ins, 0));
9542                 right = read_const(state, ins, RHS(ins, 1));
9543                 mkconst(state, ins, left >> right);
9544         }
9545 }
9546
9547 static void simplify_ssr(struct compile_state *state, struct triple *ins)
9548 {
9549         if (is_simple_const(RHS(ins, 1))) {
9550                 ulong_t right;
9551                 right = read_const(state, ins, RHS(ins, 1));
9552                 if (right >= (size_of(state, ins->type))) {
9553                         warning(state, ins, "right shift count >= width of type");
9554                 }
9555         }
9556         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9557                 long_t left, right;
9558                 left  = read_sconst(state, ins, RHS(ins, 0));
9559                 right = read_sconst(state, ins, RHS(ins, 1));
9560                 mkconst(state, ins, left >> right);
9561         }
9562 }
9563
9564 static void simplify_and(struct compile_state *state, struct triple *ins)
9565 {
9566         struct triple *left, *right;
9567         left = RHS(ins, 0);
9568         right = RHS(ins, 1);
9569
9570         if (is_simple_const(left) && is_simple_const(right)) {
9571                 ulong_t lval, rval;
9572                 lval = read_const(state, ins, left);
9573                 rval = read_const(state, ins, right);
9574                 mkconst(state, ins, lval & rval);
9575         }
9576         else if (is_zero(right) || is_zero(left)) {
9577                 mkconst(state, ins, 0);
9578         }
9579 }
9580
9581 static void simplify_or(struct compile_state *state, struct triple *ins)
9582 {
9583         struct triple *left, *right;
9584         left = RHS(ins, 0);
9585         right = RHS(ins, 1);
9586
9587         if (is_simple_const(left) && is_simple_const(right)) {
9588                 ulong_t lval, rval;
9589                 lval = read_const(state, ins, left);
9590                 rval = read_const(state, ins, right);
9591                 mkconst(state, ins, lval | rval);
9592         }
9593 #if 0 /* I need to handle type mismatches here... */
9594         else if (is_zero(right)) {
9595                 mkcopy(state, ins, left);
9596         }
9597         else if (is_zero(left)) {
9598                 mkcopy(state, ins, right);
9599         }
9600 #endif
9601 }
9602
9603 static void simplify_xor(struct compile_state *state, struct triple *ins)
9604 {
9605         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9606                 ulong_t left, right;
9607                 left  = read_const(state, ins, RHS(ins, 0));
9608                 right = read_const(state, ins, RHS(ins, 1));
9609                 mkconst(state, ins, left ^ right);
9610         }
9611 }
9612
9613 static void simplify_pos(struct compile_state *state, struct triple *ins)
9614 {
9615         if (is_const(RHS(ins, 0))) {
9616                 mkconst(state, ins, RHS(ins, 0)->u.cval);
9617         }
9618         else {
9619                 mkcopy(state, ins, RHS(ins, 0));
9620         }
9621 }
9622
9623 static void simplify_neg(struct compile_state *state, struct triple *ins)
9624 {
9625         if (is_simple_const(RHS(ins, 0))) {
9626                 ulong_t left;
9627                 left = read_const(state, ins, RHS(ins, 0));
9628                 mkconst(state, ins, -left);
9629         }
9630         else if (RHS(ins, 0)->op == OP_NEG) {
9631                 mkcopy(state, ins, RHS(RHS(ins, 0), 0));
9632         }
9633 }
9634
9635 static void simplify_invert(struct compile_state *state, struct triple *ins)
9636 {
9637         if (is_simple_const(RHS(ins, 0))) {
9638                 ulong_t left;
9639                 left = read_const(state, ins, RHS(ins, 0));
9640                 mkconst(state, ins, ~left);
9641         }
9642 }
9643
9644 static void simplify_eq(struct compile_state *state, struct triple *ins)
9645 {
9646         struct triple *left, *right;
9647         left = RHS(ins, 0);
9648         right = RHS(ins, 1);
9649
9650         if (is_const(left) && is_const(right)) {
9651                 int val;
9652                 val = const_eq(state, ins, left, right);
9653                 if (val >= 0) {
9654                         mkconst(state, ins, val == 1);
9655                 }
9656         }
9657         else if (left == right) {
9658                 mkconst(state, ins, 1);
9659         }
9660 }
9661
9662 static void simplify_noteq(struct compile_state *state, struct triple *ins)
9663 {
9664         struct triple *left, *right;
9665         left = RHS(ins, 0);
9666         right = RHS(ins, 1);
9667
9668         if (is_const(left) && is_const(right)) {
9669                 int val;
9670                 val = const_eq(state, ins, left, right);
9671                 if (val >= 0) {
9672                         mkconst(state, ins, val != 1);
9673                 }
9674         }
9675         if (left == right) {
9676                 mkconst(state, ins, 0);
9677         }
9678 }
9679
9680 static void simplify_sless(struct compile_state *state, struct triple *ins)
9681 {
9682         struct triple *left, *right;
9683         left = RHS(ins, 0);
9684         right = RHS(ins, 1);
9685
9686         if (is_const(left) && is_const(right)) {
9687                 int val;
9688                 val = const_scmp(state, ins, left, right);
9689                 if ((val >= -1) && (val <= 1)) {
9690                         mkconst(state, ins, val < 0);
9691                 }
9692         }
9693         else if (left == right) {
9694                 mkconst(state, ins, 0);
9695         }
9696 }
9697
9698 static void simplify_uless(struct compile_state *state, struct triple *ins)
9699 {
9700         struct triple *left, *right;
9701         left = RHS(ins, 0);
9702         right = RHS(ins, 1);
9703
9704         if (is_const(left) && is_const(right)) {
9705                 int val;
9706                 val = const_ucmp(state, ins, left, right);
9707                 if ((val >= -1) && (val <= 1)) {
9708                         mkconst(state, ins, val < 0);
9709                 }
9710         }
9711         else if (is_zero(right)) {
9712                 mkconst(state, ins, 0);
9713         }
9714         else if (left == right) {
9715                 mkconst(state, ins, 0);
9716         }
9717 }
9718
9719 static void simplify_smore(struct compile_state *state, struct triple *ins)
9720 {
9721         struct triple *left, *right;
9722         left = RHS(ins, 0);
9723         right = RHS(ins, 1);
9724
9725         if (is_const(left) && is_const(right)) {
9726                 int val;
9727                 val = const_scmp(state, ins, left, right);
9728                 if ((val >= -1) && (val <= 1)) {
9729                         mkconst(state, ins, val > 0);
9730                 }
9731         }
9732         else if (left == right) {
9733                 mkconst(state, ins, 0);
9734         }
9735 }
9736
9737 static void simplify_umore(struct compile_state *state, struct triple *ins)
9738 {
9739         struct triple *left, *right;
9740         left = RHS(ins, 0);
9741         right = RHS(ins, 1);
9742
9743         if (is_const(left) && is_const(right)) {
9744                 int val;
9745                 val = const_ucmp(state, ins, left, right);
9746                 if ((val >= -1) && (val <= 1)) {
9747                         mkconst(state, ins, val > 0);
9748                 }
9749         }
9750         else if (is_zero(left)) {
9751                 mkconst(state, ins, 0);
9752         }
9753         else if (left == right) {
9754                 mkconst(state, ins, 0);
9755         }
9756 }
9757
9758
9759 static void simplify_slesseq(struct compile_state *state, struct triple *ins)
9760 {
9761         struct triple *left, *right;
9762         left = RHS(ins, 0);
9763         right = RHS(ins, 1);
9764
9765         if (is_const(left) && is_const(right)) {
9766                 int val;
9767                 val = const_scmp(state, ins, left, right);
9768                 if ((val >= -1) && (val <= 1)) {
9769                         mkconst(state, ins, val <= 0);
9770                 }
9771         }
9772         else if (left == right) {
9773                 mkconst(state, ins, 1);
9774         }
9775 }
9776
9777 static void simplify_ulesseq(struct compile_state *state, struct triple *ins)
9778 {
9779         struct triple *left, *right;
9780         left = RHS(ins, 0);
9781         right = RHS(ins, 1);
9782
9783         if (is_const(left) && is_const(right)) {
9784                 int val;
9785                 val = const_ucmp(state, ins, left, right);
9786                 if ((val >= -1) && (val <= 1)) {
9787                         mkconst(state, ins, val <= 0);
9788                 }
9789         }
9790         else if (is_zero(left)) {
9791                 mkconst(state, ins, 1);
9792         }
9793         else if (left == right) {
9794                 mkconst(state, ins, 1);
9795         }
9796 }
9797
9798 static void simplify_smoreeq(struct compile_state *state, struct triple *ins)
9799 {
9800         struct triple *left, *right;
9801         left = RHS(ins, 0);
9802         right = RHS(ins, 1);
9803
9804         if (is_const(left) && is_const(right)) {
9805                 int val;
9806                 val = const_scmp(state, ins, left, right);
9807                 if ((val >= -1) && (val <= 1)) {
9808                         mkconst(state, ins, val >= 0);
9809                 }
9810         }
9811         else if (left == right) {
9812                 mkconst(state, ins, 1);
9813         }
9814 }
9815
9816 static void simplify_umoreeq(struct compile_state *state, struct triple *ins)
9817 {
9818         struct triple *left, *right;
9819         left = RHS(ins, 0);
9820         right = RHS(ins, 1);
9821
9822         if (is_const(left) && is_const(right)) {
9823                 int val;
9824                 val = const_ucmp(state, ins, left, right);
9825                 if ((val >= -1) && (val <= 1)) {
9826                         mkconst(state, ins, val >= 0);
9827                 }
9828         }
9829         else if (is_zero(right)) {
9830                 mkconst(state, ins, 1);
9831         }
9832         else if (left == right) {
9833                 mkconst(state, ins, 1);
9834         }
9835 }
9836
9837 static void simplify_lfalse(struct compile_state *state, struct triple *ins)
9838 {
9839         struct triple *rhs;
9840         rhs = RHS(ins, 0);
9841
9842         if (is_const(rhs)) {
9843                 mkconst(state, ins, !const_ltrue(state, ins, rhs));
9844         }
9845         /* Otherwise if I am the only user... */
9846         else if ((rhs->use) &&
9847                 (rhs->use->member == ins) && (rhs->use->next == 0)) {
9848                 int need_copy = 1;
9849                 /* Invert a boolean operation */
9850                 switch(rhs->op) {
9851                 case OP_LTRUE:   rhs->op = OP_LFALSE;  break;
9852                 case OP_LFALSE:  rhs->op = OP_LTRUE;   break;
9853                 case OP_EQ:      rhs->op = OP_NOTEQ;   break;
9854                 case OP_NOTEQ:   rhs->op = OP_EQ;      break;
9855                 case OP_SLESS:   rhs->op = OP_SMOREEQ; break;
9856                 case OP_ULESS:   rhs->op = OP_UMOREEQ; break;
9857                 case OP_SMORE:   rhs->op = OP_SLESSEQ; break;
9858                 case OP_UMORE:   rhs->op = OP_ULESSEQ; break;
9859                 case OP_SLESSEQ: rhs->op = OP_SMORE;   break;
9860                 case OP_ULESSEQ: rhs->op = OP_UMORE;   break;
9861                 case OP_SMOREEQ: rhs->op = OP_SLESS;   break;
9862                 case OP_UMOREEQ: rhs->op = OP_ULESS;   break;
9863                 default:
9864                         need_copy = 0;
9865                         break;
9866                 }
9867                 if (need_copy) {
9868                         mkcopy(state, ins, rhs);
9869                 }
9870         }
9871 }
9872
9873 static void simplify_ltrue (struct compile_state *state, struct triple *ins)
9874 {
9875         struct triple *rhs;
9876         rhs = RHS(ins, 0);
9877
9878         if (is_const(rhs)) {
9879                 mkconst(state, ins, const_ltrue(state, ins, rhs));
9880         }
9881         else switch(rhs->op) {
9882         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
9883         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
9884         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
9885                 mkcopy(state, ins, rhs);
9886         }
9887
9888 }
9889
9890 static void simplify_load(struct compile_state *state, struct triple *ins)
9891 {
9892         struct triple *addr, *sdecl, *blob;
9893
9894         /* If I am doing a load with a constant pointer from a constant
9895          * table get the value.
9896          */
9897         addr = RHS(ins, 0);
9898         if ((addr->op == OP_ADDRCONST) && (sdecl = MISC(addr, 0)) &&
9899                 (sdecl->op == OP_SDECL) && (blob = MISC(sdecl, 0)) &&
9900                 (blob->op == OP_BLOBCONST)) {
9901                 unsigned char buffer[SIZEOF_WORD];
9902                 size_t reg_size, mem_size;
9903                 const char *src, *end;
9904                 ulong_t val;
9905                 reg_size = reg_size_of(state, ins->type);
9906                 if (reg_size > REG_SIZEOF_REG) {
9907                         internal_error(state, ins, "load size greater than register");
9908                 }
9909                 mem_size = size_of(state, ins->type);
9910                 end = blob->u.blob;
9911                 end += bits_to_bytes(size_of(state, sdecl->type));
9912                 src = blob->u.blob;
9913                 src += addr->u.cval;
9914
9915                 if (src > end) {
9916                         error(state, ins, "Load address out of bounds");
9917                 }
9918
9919                 memset(buffer, 0, sizeof(buffer));
9920                 memcpy(buffer, src, bits_to_bytes(mem_size));
9921
9922                 switch(mem_size) {
9923                 case SIZEOF_I8:  val = *((uint8_t *) buffer); break;
9924                 case SIZEOF_I16: val = *((uint16_t *)buffer); break;
9925                 case SIZEOF_I32: val = *((uint32_t *)buffer); break;
9926                 case SIZEOF_I64: val = *((uint64_t *)buffer); break;
9927                 default:
9928                         internal_error(state, ins, "mem_size: %d not handled",
9929                                 mem_size);
9930                         val = 0;
9931                         break;
9932                 }
9933                 mkconst(state, ins, val);
9934         }
9935 }
9936
9937 static void simplify_uextract(struct compile_state *state, struct triple *ins)
9938 {
9939         if (is_simple_const(RHS(ins, 0))) {
9940                 ulong_t val;
9941                 ulong_t mask;
9942                 val = read_const(state, ins, RHS(ins, 0));
9943                 mask = 1;
9944                 mask <<= ins->u.bitfield.size;
9945                 mask -= 1;
9946                 val >>= ins->u.bitfield.offset;
9947                 val &= mask;
9948                 mkconst(state, ins, val);
9949         }
9950 }
9951
9952 static void simplify_sextract(struct compile_state *state, struct triple *ins)
9953 {
9954         if (is_simple_const(RHS(ins, 0))) {
9955                 ulong_t val;
9956                 ulong_t mask;
9957                 long_t sval;
9958                 val = read_const(state, ins, RHS(ins, 0));
9959                 mask = 1;
9960                 mask <<= ins->u.bitfield.size;
9961                 mask -= 1;
9962                 val >>= ins->u.bitfield.offset;
9963                 val &= mask;
9964                 val <<= (SIZEOF_LONG - ins->u.bitfield.size);
9965                 sval = val;
9966                 sval >>= (SIZEOF_LONG - ins->u.bitfield.size);
9967                 mkconst(state, ins, sval);
9968         }
9969 }
9970
9971 static void simplify_deposit(struct compile_state *state, struct triple *ins)
9972 {
9973         if (is_simple_const(RHS(ins, 0)) && is_simple_const(RHS(ins, 1))) {
9974                 ulong_t targ, val;
9975                 ulong_t mask;
9976                 targ = read_const(state, ins, RHS(ins, 0));
9977                 val  = read_const(state, ins, RHS(ins, 1));
9978                 mask = 1;
9979                 mask <<= ins->u.bitfield.size;
9980                 mask -= 1;
9981                 mask <<= ins->u.bitfield.offset;
9982                 targ &= ~mask;
9983                 val <<= ins->u.bitfield.offset;
9984                 val &= mask;
9985                 targ |= val;
9986                 mkconst(state, ins, targ);
9987         }
9988 }
9989
9990 static void simplify_copy(struct compile_state *state, struct triple *ins)
9991 {
9992         struct triple *right;
9993         right = RHS(ins, 0);
9994         if (is_subset_type(ins->type, right->type)) {
9995                 ins->type = right->type;
9996         }
9997         if (equiv_types(ins->type, right->type)) {
9998                 ins->op = OP_COPY;/* I don't need to convert if the types match */
9999         } else {
10000                 if (ins->op == OP_COPY) {
10001                         internal_error(state, ins, "type mismatch on copy");
10002                 }
10003         }
10004         if (is_const(right) && (right->op == OP_ADDRCONST) && is_pointer(ins)) {
10005                 struct triple *sdecl;
10006                 ulong_t offset;
10007                 sdecl  = MISC(right, 0);
10008                 offset = right->u.cval;
10009                 mkaddr_const(state, ins, sdecl, offset);
10010         }
10011         else if (is_const(right) && is_write_compatible(state, ins->type, right->type)) {
10012                 switch(right->op) {
10013                 case OP_INTCONST:
10014                 {
10015                         ulong_t left;
10016                         left = read_const(state, ins, right);
10017                         /* Ensure I have not overflowed the destination. */
10018                         if (size_of(state, right->type) > size_of(state, ins->type)) {
10019                                 ulong_t mask;
10020                                 mask = 1;
10021                                 mask <<= size_of(state, ins->type);
10022                                 mask -= 1;
10023                                 left &= mask;
10024                         }
10025                         /* Ensure I am properly sign extended */
10026                         if (size_of(state, right->type) < size_of(state, ins->type) &&
10027                                 is_signed(right->type)) {
10028                                 long_t val;
10029                                 int shift;
10030                                 shift = SIZEOF_LONG - size_of(state, right->type);
10031                                 val = left;
10032                                 val <<= shift;
10033                                 val >>= shift;
10034                                 left = val;
10035                         }
10036                         mkconst(state, ins, left);
10037                         break;
10038                 }
10039                 default:
10040                         internal_error(state, ins, "uknown constant");
10041                         break;
10042                 }
10043         }
10044 }
10045
10046 static int phi_present(struct block *block)
10047 {
10048         struct triple *ptr;
10049         if (!block) {
10050                 return 0;
10051         }
10052         ptr = block->first;
10053         do {
10054                 if (ptr->op == OP_PHI) {
10055                         return 1;
10056                 }
10057                 ptr = ptr->next;
10058         } while(ptr != block->last);
10059         return 0;
10060 }
10061
10062 static int phi_dependency(struct block *block)
10063 {
10064         /* A block has a phi dependency if a phi function
10065          * depends on that block to exist, and makes a block
10066          * that is otherwise useless unsafe to remove.
10067          */
10068         if (block) {
10069                 struct block_set *edge;
10070                 for(edge = block->edges; edge; edge = edge->next) {
10071                         if (phi_present(edge->member)) {
10072                                 return 1;
10073                         }
10074                 }
10075         }
10076         return 0;
10077 }
10078
10079 static struct triple *branch_target(struct compile_state *state, struct triple *ins)
10080 {
10081         struct triple *targ;
10082         targ = TARG(ins, 0);
10083         /* During scc_transform temporary triples are allocated that
10084          * loop back onto themselves. If I see one don't advance the
10085          * target.
10086          */
10087         while(triple_is_structural(state, targ) &&
10088                 (targ->next != targ) && (targ->next != state->first)) {
10089                 targ = targ->next;
10090         }
10091         return targ;
10092 }
10093
10094
10095 static void simplify_branch(struct compile_state *state, struct triple *ins)
10096 {
10097         int simplified, loops;
10098         if ((ins->op != OP_BRANCH) && (ins->op != OP_CBRANCH)) {
10099                 internal_error(state, ins, "not branch");
10100         }
10101         if (ins->use != 0) {
10102                 internal_error(state, ins, "branch use");
10103         }
10104         /* The challenge here with simplify branch is that I need to
10105          * make modifications to the control flow graph as well
10106          * as to the branch instruction itself.  That is handled
10107          * by rebuilding the basic blocks after simplify all is called.
10108          */
10109
10110         /* If we have a branch to an unconditional branch update
10111          * our target.  But watch out for dependencies from phi
10112          * functions.
10113          * Also only do this a limited number of times so
10114          * we don't get into an infinite loop.
10115          */
10116         loops = 0;
10117         do {
10118                 struct triple *targ;
10119                 simplified = 0;
10120                 targ = branch_target(state, ins);
10121                 if ((targ != ins) && (targ->op == OP_BRANCH) &&
10122                         !phi_dependency(targ->u.block))
10123                 {
10124                         unuse_triple(TARG(ins, 0), ins);
10125                         TARG(ins, 0) = TARG(targ, 0);
10126                         use_triple(TARG(ins, 0), ins);
10127                         simplified = 1;
10128                 }
10129         } while(simplified && (++loops < 20));
10130
10131         /* If we have a conditional branch with a constant condition
10132          * make it an unconditional branch.
10133          */
10134         if ((ins->op == OP_CBRANCH) && is_simple_const(RHS(ins, 0))) {
10135                 struct triple *targ;
10136                 ulong_t value;
10137                 value = read_const(state, ins, RHS(ins, 0));
10138                 unuse_triple(RHS(ins, 0), ins);
10139                 targ = TARG(ins, 0);
10140                 ins->rhs  = 0;
10141                 ins->targ = 1;
10142                 ins->op = OP_BRANCH;
10143                 if (value) {
10144                         unuse_triple(ins->next, ins);
10145                         TARG(ins, 0) = targ;
10146                 }
10147                 else {
10148                         unuse_triple(targ, ins);
10149                         TARG(ins, 0) = ins->next;
10150                 }
10151         }
10152
10153         /* If we have a branch to the next instruction,
10154          * make it a noop.
10155          */
10156         if (TARG(ins, 0) == ins->next) {
10157                 unuse_triple(TARG(ins, 0), ins);
10158                 if (ins->op == OP_CBRANCH) {
10159                         unuse_triple(RHS(ins, 0), ins);
10160                         unuse_triple(ins->next, ins);
10161                 }
10162                 ins->lhs = 0;
10163                 ins->rhs = 0;
10164                 ins->misc = 0;
10165                 ins->targ = 0;
10166                 ins->op = OP_NOOP;
10167                 if (ins->use) {
10168                         internal_error(state, ins, "noop use != 0");
10169                 }
10170         }
10171 }
10172
10173 static void simplify_label(struct compile_state *state, struct triple *ins)
10174 {
10175         /* Ignore volatile labels */
10176         if (!triple_is_pure(state, ins, ins->id)) {
10177                 return;
10178         }
10179         if (ins->use == 0) {
10180                 ins->op = OP_NOOP;
10181         }
10182         else if (ins->prev->op == OP_LABEL) {
10183                 /* In general it is not safe to merge one label that
10184                  * imediately follows another.  The problem is that the empty
10185                  * looking block may have phi functions that depend on it.
10186                  */
10187                 if (!phi_dependency(ins->prev->u.block)) {
10188                         struct triple_set *user, *next;
10189                         ins->op = OP_NOOP;
10190                         for(user = ins->use; user; user = next) {
10191                                 struct triple *use, **expr;
10192                                 next = user->next;
10193                                 use = user->member;
10194                                 expr = triple_targ(state, use, 0);
10195                                 for(;expr; expr = triple_targ(state, use, expr)) {
10196                                         if (*expr == ins) {
10197                                                 *expr = ins->prev;
10198                                                 unuse_triple(ins, use);
10199                                                 use_triple(ins->prev, use);
10200                                         }
10201
10202                                 }
10203                         }
10204                         if (ins->use) {
10205                                 internal_error(state, ins, "noop use != 0");
10206                         }
10207                 }
10208         }
10209 }
10210
10211 static void simplify_phi(struct compile_state *state, struct triple *ins)
10212 {
10213         struct triple **slot;
10214         struct triple *value;
10215         int zrhs, i;
10216         ulong_t cvalue;
10217         slot = &RHS(ins, 0);
10218         zrhs = ins->rhs;
10219         if (zrhs == 0) {
10220                 return;
10221         }
10222         /* See if all of the rhs members of a phi have the same value */
10223         if (slot[0] && is_simple_const(slot[0])) {
10224                 cvalue = read_const(state, ins, slot[0]);
10225                 for(i = 1; i < zrhs; i++) {
10226                         if (    !slot[i] ||
10227                                 !is_simple_const(slot[i]) ||
10228                                 !equiv_types(slot[0]->type, slot[i]->type) ||
10229                                 (cvalue != read_const(state, ins, slot[i]))) {
10230                                 break;
10231                         }
10232                 }
10233                 if (i == zrhs) {
10234                         mkconst(state, ins, cvalue);
10235                         return;
10236                 }
10237         }
10238
10239         /* See if all of rhs members of a phi are the same */
10240         value = slot[0];
10241         for(i = 1; i < zrhs; i++) {
10242                 if (slot[i] != value) {
10243                         break;
10244                 }
10245         }
10246         if (i == zrhs) {
10247                 /* If the phi has a single value just copy it */
10248                 if (!is_subset_type(ins->type, value->type)) {
10249                         internal_error(state, ins, "bad input type to phi");
10250                 }
10251                 /* Make the types match */
10252                 if (!equiv_types(ins->type, value->type)) {
10253                         ins->type = value->type;
10254                 }
10255                 /* Now make the actual copy */
10256                 mkcopy(state, ins, value);
10257                 return;
10258         }
10259 }
10260
10261
10262 static void simplify_bsf(struct compile_state *state, struct triple *ins)
10263 {
10264         if (is_simple_const(RHS(ins, 0))) {
10265                 ulong_t left;
10266                 left = read_const(state, ins, RHS(ins, 0));
10267                 mkconst(state, ins, bsf(left));
10268         }
10269 }
10270
10271 static void simplify_bsr(struct compile_state *state, struct triple *ins)
10272 {
10273         if (is_simple_const(RHS(ins, 0))) {
10274                 ulong_t left;
10275                 left = read_const(state, ins, RHS(ins, 0));
10276                 mkconst(state, ins, bsr(left));
10277         }
10278 }
10279
10280
10281 typedef void (*simplify_t)(struct compile_state *state, struct triple *ins);
10282 static const struct simplify_table {
10283         simplify_t func;
10284         unsigned long flag;
10285 } table_simplify[] = {
10286 #define simplify_sdivt    simplify_noop
10287 #define simplify_udivt    simplify_noop
10288 #define simplify_piece    simplify_noop
10289
10290 [OP_SDIVT      ] = { simplify_sdivt,    COMPILER_SIMPLIFY_ARITH },
10291 [OP_UDIVT      ] = { simplify_udivt,    COMPILER_SIMPLIFY_ARITH },
10292 [OP_SMUL       ] = { simplify_smul,     COMPILER_SIMPLIFY_ARITH },
10293 [OP_UMUL       ] = { simplify_umul,     COMPILER_SIMPLIFY_ARITH },
10294 [OP_SDIV       ] = { simplify_sdiv,     COMPILER_SIMPLIFY_ARITH },
10295 [OP_UDIV       ] = { simplify_udiv,     COMPILER_SIMPLIFY_ARITH },
10296 [OP_SMOD       ] = { simplify_smod,     COMPILER_SIMPLIFY_ARITH },
10297 [OP_UMOD       ] = { simplify_umod,     COMPILER_SIMPLIFY_ARITH },
10298 [OP_ADD        ] = { simplify_add,      COMPILER_SIMPLIFY_ARITH },
10299 [OP_SUB        ] = { simplify_sub,      COMPILER_SIMPLIFY_ARITH },
10300 [OP_SL         ] = { simplify_sl,       COMPILER_SIMPLIFY_SHIFT },
10301 [OP_USR        ] = { simplify_usr,      COMPILER_SIMPLIFY_SHIFT },
10302 [OP_SSR        ] = { simplify_ssr,      COMPILER_SIMPLIFY_SHIFT },
10303 [OP_AND        ] = { simplify_and,      COMPILER_SIMPLIFY_BITWISE },
10304 [OP_XOR        ] = { simplify_xor,      COMPILER_SIMPLIFY_BITWISE },
10305 [OP_OR         ] = { simplify_or,       COMPILER_SIMPLIFY_BITWISE },
10306 [OP_POS        ] = { simplify_pos,      COMPILER_SIMPLIFY_ARITH },
10307 [OP_NEG        ] = { simplify_neg,      COMPILER_SIMPLIFY_ARITH },
10308 [OP_INVERT     ] = { simplify_invert,   COMPILER_SIMPLIFY_BITWISE },
10309
10310 [OP_EQ         ] = { simplify_eq,       COMPILER_SIMPLIFY_LOGICAL },
10311 [OP_NOTEQ      ] = { simplify_noteq,    COMPILER_SIMPLIFY_LOGICAL },
10312 [OP_SLESS      ] = { simplify_sless,    COMPILER_SIMPLIFY_LOGICAL },
10313 [OP_ULESS      ] = { simplify_uless,    COMPILER_SIMPLIFY_LOGICAL },
10314 [OP_SMORE      ] = { simplify_smore,    COMPILER_SIMPLIFY_LOGICAL },
10315 [OP_UMORE      ] = { simplify_umore,    COMPILER_SIMPLIFY_LOGICAL },
10316 [OP_SLESSEQ    ] = { simplify_slesseq,  COMPILER_SIMPLIFY_LOGICAL },
10317 [OP_ULESSEQ    ] = { simplify_ulesseq,  COMPILER_SIMPLIFY_LOGICAL },
10318 [OP_SMOREEQ    ] = { simplify_smoreeq,  COMPILER_SIMPLIFY_LOGICAL },
10319 [OP_UMOREEQ    ] = { simplify_umoreeq,  COMPILER_SIMPLIFY_LOGICAL },
10320 [OP_LFALSE     ] = { simplify_lfalse,   COMPILER_SIMPLIFY_LOGICAL },
10321 [OP_LTRUE      ] = { simplify_ltrue,    COMPILER_SIMPLIFY_LOGICAL },
10322
10323 [OP_LOAD       ] = { simplify_load,     COMPILER_SIMPLIFY_OP },
10324 [OP_STORE      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10325
10326 [OP_UEXTRACT   ] = { simplify_uextract, COMPILER_SIMPLIFY_BITFIELD },
10327 [OP_SEXTRACT   ] = { simplify_sextract, COMPILER_SIMPLIFY_BITFIELD },
10328 [OP_DEPOSIT    ] = { simplify_deposit,  COMPILER_SIMPLIFY_BITFIELD },
10329
10330 [OP_NOOP       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10331
10332 [OP_INTCONST   ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10333 [OP_BLOBCONST  ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10334 [OP_ADDRCONST  ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10335 [OP_UNKNOWNVAL ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10336
10337 [OP_WRITE      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10338 [OP_READ       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10339 [OP_COPY       ] = { simplify_copy,     COMPILER_SIMPLIFY_COPY },
10340 [OP_CONVERT    ] = { simplify_copy,     COMPILER_SIMPLIFY_COPY },
10341 [OP_PIECE      ] = { simplify_piece,    COMPILER_SIMPLIFY_OP },
10342 [OP_ASM        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10343
10344 [OP_DOT        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10345 [OP_INDEX      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10346
10347 [OP_LIST       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10348 [OP_BRANCH     ] = { simplify_branch,   COMPILER_SIMPLIFY_BRANCH },
10349 [OP_CBRANCH    ] = { simplify_branch,   COMPILER_SIMPLIFY_BRANCH },
10350 [OP_CALL       ] = { simplify_noop,     COMPILER_SIMPLIFY_BRANCH },
10351 [OP_RET        ] = { simplify_noop,     COMPILER_SIMPLIFY_BRANCH },
10352 [OP_LABEL      ] = { simplify_label,    COMPILER_SIMPLIFY_LABEL },
10353 [OP_ADECL      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10354 [OP_SDECL      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10355 [OP_PHI        ] = { simplify_phi,      COMPILER_SIMPLIFY_PHI },
10356
10357 [OP_INB        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10358 [OP_INW        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10359 [OP_INL        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10360 [OP_OUTB       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10361 [OP_OUTW       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10362 [OP_OUTL       ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10363 [OP_BSF        ] = { simplify_bsf,      COMPILER_SIMPLIFY_OP },
10364 [OP_BSR        ] = { simplify_bsr,      COMPILER_SIMPLIFY_OP },
10365 [OP_RDMSR      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10366 [OP_WRMSR      ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10367 [OP_HLT        ] = { simplify_noop,     COMPILER_SIMPLIFY_OP },
10368 };
10369
10370 static inline void debug_simplify(struct compile_state *state,
10371         simplify_t do_simplify, struct triple *ins)
10372 {
10373 #if DEBUG_SIMPLIFY_HIRES
10374                 if (state->functions_joined && (do_simplify != simplify_noop)) {
10375                         /* High resolution debugging mode */
10376                         fprintf(state->dbgout, "simplifing: ");
10377                         display_triple(state->dbgout, ins);
10378                 }
10379 #endif
10380                 do_simplify(state, ins);
10381 #if DEBUG_SIMPLIFY_HIRES
10382                 if (state->functions_joined && (do_simplify != simplify_noop)) {
10383                         /* High resolution debugging mode */
10384                         fprintf(state->dbgout, "simplified: ");
10385                         display_triple(state->dbgout, ins);
10386                 }
10387 #endif
10388 }
10389 static void simplify(struct compile_state *state, struct triple *ins)
10390 {
10391         int op;
10392         simplify_t do_simplify;
10393         if (ins == &unknown_triple) {
10394                 internal_error(state, ins, "simplifying the unknown triple?");
10395         }
10396         do {
10397                 op = ins->op;
10398                 do_simplify = 0;
10399                 if ((op < 0) || (op > sizeof(table_simplify)/sizeof(table_simplify[0]))) {
10400                         do_simplify = 0;
10401                 }
10402                 else {
10403                         do_simplify = table_simplify[op].func;
10404                 }
10405                 if (do_simplify &&
10406                         !(state->compiler->flags & table_simplify[op].flag)) {
10407                         do_simplify = simplify_noop;
10408                 }
10409                 if (do_simplify && (ins->id & TRIPLE_FLAG_VOLATILE)) {
10410                         do_simplify = simplify_noop;
10411                 }
10412
10413                 if (!do_simplify) {
10414                         internal_error(state, ins, "cannot simplify op: %d %s",
10415                                 op, tops(op));
10416                         return;
10417                 }
10418                 debug_simplify(state, do_simplify, ins);
10419         } while(ins->op != op);
10420 }
10421
10422 static void rebuild_ssa_form(struct compile_state *state);
10423
10424 static void simplify_all(struct compile_state *state)
10425 {
10426         struct triple *ins, *first;
10427         if (!(state->compiler->flags & COMPILER_SIMPLIFY)) {
10428                 return;
10429         }
10430         first = state->first;
10431         ins = first->prev;
10432         do {
10433                 simplify(state, ins);
10434                 ins = ins->prev;
10435         } while(ins != first->prev);
10436         ins = first;
10437         do {
10438                 simplify(state, ins);
10439                 ins = ins->next;
10440         }while(ins != first);
10441         rebuild_ssa_form(state);
10442
10443         print_blocks(state, __func__, state->dbgout);
10444 }
10445
10446 /*
10447  * Builtins....
10448  * ============================
10449  */
10450
10451 static void register_builtin_function(struct compile_state *state,
10452         const char *name, int op, struct type *rtype, ...)
10453 {
10454         struct type *ftype, *atype, *ctype, *crtype, *param, **next;
10455         struct triple *def, *result, *work, *first, *retvar, *ret;
10456         struct hash_entry *ident;
10457         struct file_state file;
10458         int parameters;
10459         int name_len;
10460         va_list args;
10461         int i;
10462
10463         /* Dummy file state to get debug handling right */
10464         memset(&file, 0, sizeof(file));
10465         file.basename = "<built-in>";
10466         file.line = 1;
10467         file.report_line = 1;
10468         file.report_name = file.basename;
10469         file.prev = state->file;
10470         state->file = &file;
10471         state->function = name;
10472
10473         /* Find the Parameter count */
10474         valid_op(state, op);
10475         parameters = table_ops[op].rhs;
10476         if (parameters < 0 ) {
10477                 internal_error(state, 0, "Invalid builtin parameter count");
10478         }
10479
10480         /* Find the function type */
10481         ftype = new_type(TYPE_FUNCTION | STOR_INLINE | STOR_STATIC, rtype, 0);
10482         ftype->elements = parameters;
10483         next = &ftype->right;
10484         va_start(args, rtype);
10485         for(i = 0; i < parameters; i++) {
10486                 atype = va_arg(args, struct type *);
10487                 if (!*next) {
10488                         *next = atype;
10489                 } else {
10490                         *next = new_type(TYPE_PRODUCT, *next, atype);
10491                         next = &((*next)->right);
10492                 }
10493         }
10494         if (!*next) {
10495                 *next = &void_type;
10496         }
10497         va_end(args);
10498
10499         /* Get the initial closure type */
10500         ctype = new_type(TYPE_JOIN, &void_type, 0);
10501         ctype->elements = 1;
10502
10503         /* Get the return type */
10504         crtype = new_type(TYPE_TUPLE, new_type(TYPE_PRODUCT, ctype, rtype), 0);
10505         crtype->elements = 2;
10506
10507         /* Generate the needed triples */
10508         def = triple(state, OP_LIST, ftype, 0, 0);
10509         first = label(state);
10510         RHS(def, 0) = first;
10511         result = flatten(state, first, variable(state, crtype));
10512         retvar = flatten(state, first, variable(state, &void_ptr_type));
10513         ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
10514
10515         /* Now string them together */
10516         param = ftype->right;
10517         for(i = 0; i < parameters; i++) {
10518                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10519                         atype = param->left;
10520                 } else {
10521                         atype = param;
10522                 }
10523                 flatten(state, first, variable(state, atype));
10524                 param = param->right;
10525         }
10526         work = new_triple(state, op, rtype, -1, parameters);
10527         generate_lhs_pieces(state, work);
10528         for(i = 0; i < parameters; i++) {
10529                 RHS(work, i) = read_expr(state, farg(state, def, i));
10530         }
10531         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
10532                 work = write_expr(state, deref_index(state, result, 1), work);
10533         }
10534         work = flatten(state, first, work);
10535         flatten(state, first, label(state));
10536         ret  = flatten(state, first, ret);
10537         name_len = strlen(name);
10538         ident = lookup(state, name, name_len);
10539         ftype->type_ident = ident;
10540         symbol(state, ident, &ident->sym_ident, def, ftype);
10541
10542         state->file = file.prev;
10543         state->function = 0;
10544         state->main_function = 0;
10545
10546         if (!state->functions) {
10547                 state->functions = def;
10548         } else {
10549                 insert_triple(state, state->functions, def);
10550         }
10551         if (state->compiler->debug & DEBUG_INLINE) {
10552                 FILE *fp = state->dbgout;
10553                 fprintf(fp, "\n");
10554                 loc(fp, state, 0);
10555                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
10556                 display_func(state, fp, def);
10557                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
10558         }
10559 }
10560
10561 static struct type *partial_struct(struct compile_state *state,
10562         const char *field_name, struct type *type, struct type *rest)
10563 {
10564         struct hash_entry *field_ident;
10565         struct type *result;
10566         int field_name_len;
10567
10568         field_name_len = strlen(field_name);
10569         field_ident = lookup(state, field_name, field_name_len);
10570
10571         result = clone_type(0, type);
10572         result->field_ident = field_ident;
10573
10574         if (rest) {
10575                 result = new_type(TYPE_PRODUCT, result, rest);
10576         }
10577         return result;
10578 }
10579
10580 static struct type *register_builtin_type(struct compile_state *state,
10581         const char *name, struct type *type)
10582 {
10583         struct hash_entry *ident;
10584         int name_len;
10585
10586         name_len = strlen(name);
10587         ident = lookup(state, name, name_len);
10588
10589         if ((type->type & TYPE_MASK) == TYPE_PRODUCT) {
10590                 ulong_t elements = 0;
10591                 struct type *field;
10592                 type = new_type(TYPE_STRUCT, type, 0);
10593                 field = type->left;
10594                 while((field->type & TYPE_MASK) == TYPE_PRODUCT) {
10595                         elements++;
10596                         field = field->right;
10597                 }
10598                 elements++;
10599                 symbol(state, ident, &ident->sym_tag, 0, type);
10600                 type->type_ident = ident;
10601                 type->elements = elements;
10602         }
10603         symbol(state, ident, &ident->sym_ident, 0, type);
10604         ident->tok = TOK_TYPE_NAME;
10605         return type;
10606 }
10607
10608
10609 static void register_builtins(struct compile_state *state)
10610 {
10611         struct type *div_type, *ldiv_type;
10612         struct type *udiv_type, *uldiv_type;
10613         struct type *msr_type;
10614
10615         div_type = register_builtin_type(state, "__builtin_div_t",
10616                 partial_struct(state, "quot", &int_type,
10617                 partial_struct(state, "rem",  &int_type, 0)));
10618         ldiv_type = register_builtin_type(state, "__builtin_ldiv_t",
10619                 partial_struct(state, "quot", &long_type,
10620                 partial_struct(state, "rem",  &long_type, 0)));
10621         udiv_type = register_builtin_type(state, "__builtin_udiv_t",
10622                 partial_struct(state, "quot", &uint_type,
10623                 partial_struct(state, "rem",  &uint_type, 0)));
10624         uldiv_type = register_builtin_type(state, "__builtin_uldiv_t",
10625                 partial_struct(state, "quot", &ulong_type,
10626                 partial_struct(state, "rem",  &ulong_type, 0)));
10627
10628         register_builtin_function(state, "__builtin_div",   OP_SDIVT, div_type,
10629                 &int_type, &int_type);
10630         register_builtin_function(state, "__builtin_ldiv",  OP_SDIVT, ldiv_type,
10631                 &long_type, &long_type);
10632         register_builtin_function(state, "__builtin_udiv",  OP_UDIVT, udiv_type,
10633                 &uint_type, &uint_type);
10634         register_builtin_function(state, "__builtin_uldiv", OP_UDIVT, uldiv_type,
10635                 &ulong_type, &ulong_type);
10636
10637         register_builtin_function(state, "__builtin_inb", OP_INB, &uchar_type,
10638                 &ushort_type);
10639         register_builtin_function(state, "__builtin_inw", OP_INW, &ushort_type,
10640                 &ushort_type);
10641         register_builtin_function(state, "__builtin_inl", OP_INL, &uint_type,
10642                 &ushort_type);
10643
10644         register_builtin_function(state, "__builtin_outb", OP_OUTB, &void_type,
10645                 &uchar_type, &ushort_type);
10646         register_builtin_function(state, "__builtin_outw", OP_OUTW, &void_type,
10647                 &ushort_type, &ushort_type);
10648         register_builtin_function(state, "__builtin_outl", OP_OUTL, &void_type,
10649                 &uint_type, &ushort_type);
10650
10651         register_builtin_function(state, "__builtin_bsf", OP_BSF, &int_type,
10652                 &int_type);
10653         register_builtin_function(state, "__builtin_bsr", OP_BSR, &int_type,
10654                 &int_type);
10655
10656         msr_type = register_builtin_type(state, "__builtin_msr_t",
10657                 partial_struct(state, "lo", &ulong_type,
10658                 partial_struct(state, "hi", &ulong_type, 0)));
10659
10660         register_builtin_function(state, "__builtin_rdmsr", OP_RDMSR, msr_type,
10661                 &ulong_type);
10662         register_builtin_function(state, "__builtin_wrmsr", OP_WRMSR, &void_type,
10663                 &ulong_type, &ulong_type, &ulong_type);
10664
10665         register_builtin_function(state, "__builtin_hlt", OP_HLT, &void_type,
10666                 &void_type);
10667 }
10668
10669 static struct type *declarator(
10670         struct compile_state *state, struct type *type,
10671         struct hash_entry **ident, int need_ident);
10672 static void decl(struct compile_state *state, struct triple *first);
10673 static struct type *specifier_qualifier_list(struct compile_state *state);
10674 #if DEBUG_ROMCC_WARNING
10675 static int isdecl_specifier(int tok);
10676 #endif
10677 static struct type *decl_specifiers(struct compile_state *state);
10678 static int istype(int tok);
10679 static struct triple *expr(struct compile_state *state);
10680 static struct triple *assignment_expr(struct compile_state *state);
10681 static struct type *type_name(struct compile_state *state);
10682 static void statement(struct compile_state *state, struct triple *first);
10683
10684 static struct triple *call_expr(
10685         struct compile_state *state, struct triple *func)
10686 {
10687         struct triple *def;
10688         struct type *param, *type;
10689         ulong_t pvals, index;
10690
10691         if ((func->type->type & TYPE_MASK) != TYPE_FUNCTION) {
10692                 error(state, 0, "Called object is not a function");
10693         }
10694         if (func->op != OP_LIST) {
10695                 internal_error(state, 0, "improper function");
10696         }
10697         eat(state, TOK_LPAREN);
10698         /* Find the return type without any specifiers */
10699         type = clone_type(0, func->type->left);
10700         /* Count the number of rhs entries for OP_FCALL */
10701         param = func->type->right;
10702         pvals = 0;
10703         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10704                 pvals++;
10705                 param = param->right;
10706         }
10707         if ((param->type & TYPE_MASK) != TYPE_VOID) {
10708                 pvals++;
10709         }
10710         def = new_triple(state, OP_FCALL, type, -1, pvals);
10711         MISC(def, 0) = func;
10712
10713         param = func->type->right;
10714         for(index = 0; index < pvals; index++) {
10715                 struct triple *val;
10716                 struct type *arg_type;
10717                 val = read_expr(state, assignment_expr(state));
10718                 arg_type = param;
10719                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
10720                         arg_type = param->left;
10721                 }
10722                 write_compatible(state, arg_type, val->type);
10723                 RHS(def, index) = val;
10724                 if (index != (pvals - 1)) {
10725                         eat(state, TOK_COMMA);
10726                         param = param->right;
10727                 }
10728         }
10729         eat(state, TOK_RPAREN);
10730         return def;
10731 }
10732
10733
10734 static struct triple *character_constant(struct compile_state *state)
10735 {
10736         struct triple *def;
10737         struct token *tk;
10738         const signed char *str, *end;
10739         int c;
10740         int str_len;
10741         tk = eat(state, TOK_LIT_CHAR);
10742         str = (signed char *)tk->val.str + 1;
10743         str_len = tk->str_len - 2;
10744         if (str_len <= 0) {
10745                 error(state, 0, "empty character constant");
10746         }
10747         end = str + str_len;
10748         c = char_value(state, &str, end);
10749         if (str != end) {
10750                 error(state, 0, "multibyte character constant not supported");
10751         }
10752         def = int_const(state, &char_type, (ulong_t)((long_t)c));
10753         return def;
10754 }
10755
10756 static struct triple *string_constant(struct compile_state *state)
10757 {
10758         struct triple *def;
10759         struct token *tk;
10760         struct type *type;
10761         const signed char *str, *end;
10762         signed char *buf, *ptr;
10763         int str_len;
10764
10765         buf = 0;
10766         type = new_type(TYPE_ARRAY, &char_type, 0);
10767         type->elements = 0;
10768         /* The while loop handles string concatenation */
10769         do {
10770                 tk = eat(state, TOK_LIT_STRING);
10771                 str = (signed char *)tk->val.str + 1;
10772                 str_len = tk->str_len - 2;
10773                 if (str_len < 0) {
10774                         error(state, 0, "negative string constant length");
10775                 }
10776                 /* ignore empty string tokens */
10777                 if ('"' == *str && 0 == str[1])
10778                         continue;
10779                 end = str + str_len;
10780                 ptr = buf;
10781                 buf = xmalloc(type->elements + str_len + 1, "string_constant");
10782                 memcpy(buf, ptr, type->elements);
10783                 ptr = buf + type->elements;
10784                 do {
10785                         *ptr++ = char_value(state, &str, end);
10786                 } while(str < end);
10787                 type->elements = ptr - buf;
10788         } while(peek(state) == TOK_LIT_STRING);
10789         *ptr = '\0';
10790         type->elements += 1;
10791         def = triple(state, OP_BLOBCONST, type, 0, 0);
10792         def->u.blob = buf;
10793
10794         return def;
10795 }
10796
10797
10798 static struct triple *integer_constant(struct compile_state *state)
10799 {
10800         struct triple *def;
10801         unsigned long val;
10802         struct token *tk;
10803         char *end;
10804         int u, l, decimal;
10805         struct type *type;
10806
10807         tk = eat(state, TOK_LIT_INT);
10808         errno = 0;
10809         decimal = (tk->val.str[0] != '0');
10810         val = strtoul(tk->val.str, &end, 0);
10811         if ((val > ULONG_T_MAX) || ((val == ULONG_MAX) && (errno == ERANGE))) {
10812                 error(state, 0, "Integer constant to large");
10813         }
10814         u = l = 0;
10815         if ((*end == 'u') || (*end == 'U')) {
10816                 u = 1;
10817                         end++;
10818         }
10819         if ((*end == 'l') || (*end == 'L')) {
10820                 l = 1;
10821                 end++;
10822         }
10823         if ((*end == 'u') || (*end == 'U')) {
10824                 u = 1;
10825                 end++;
10826         }
10827         if (*end) {
10828                 error(state, 0, "Junk at end of integer constant");
10829         }
10830         if (u && l)  {
10831                 type = &ulong_type;
10832         }
10833         else if (l) {
10834                 type = &long_type;
10835                 if (!decimal && (val > LONG_T_MAX)) {
10836                         type = &ulong_type;
10837                 }
10838         }
10839         else if (u) {
10840                 type = &uint_type;
10841                 if (val > UINT_T_MAX) {
10842                         type = &ulong_type;
10843                 }
10844         }
10845         else {
10846                 type = &int_type;
10847                 if (!decimal && (val > INT_T_MAX) && (val <= UINT_T_MAX)) {
10848                         type = &uint_type;
10849                 }
10850                 else if (!decimal && (val > LONG_T_MAX)) {
10851                         type = &ulong_type;
10852                 }
10853                 else if (val > INT_T_MAX) {
10854                         type = &long_type;
10855                 }
10856         }
10857         def = int_const(state, type, val);
10858         return def;
10859 }
10860
10861 static struct triple *primary_expr(struct compile_state *state)
10862 {
10863         struct triple *def;
10864         int tok;
10865         tok = peek(state);
10866         switch(tok) {
10867         case TOK_IDENT:
10868         {
10869                 struct hash_entry *ident;
10870                 /* Here ident is either:
10871                  * a varable name
10872                  * a function name
10873                  */
10874                 ident = eat(state, TOK_IDENT)->ident;
10875                 if (!ident->sym_ident) {
10876                         error(state, 0, "%s undeclared", ident->name);
10877                 }
10878                 def = ident->sym_ident->def;
10879                 break;
10880         }
10881         case TOK_ENUM_CONST:
10882         {
10883                 struct hash_entry *ident;
10884                 /* Here ident is an enumeration constant */
10885                 ident = eat(state, TOK_ENUM_CONST)->ident;
10886                 if (!ident->sym_ident) {
10887                         error(state, 0, "%s undeclared", ident->name);
10888                 }
10889                 def = ident->sym_ident->def;
10890                 break;
10891         }
10892         case TOK_MIDENT:
10893         {
10894                 struct hash_entry *ident;
10895                 ident = eat(state, TOK_MIDENT)->ident;
10896                 warning(state, 0, "Replacing undefined macro: %s with 0",
10897                         ident->name);
10898                 def = int_const(state, &int_type, 0);
10899                 break;
10900         }
10901         case TOK_LPAREN:
10902                 eat(state, TOK_LPAREN);
10903                 def = expr(state);
10904                 eat(state, TOK_RPAREN);
10905                 break;
10906         case TOK_LIT_INT:
10907                 def = integer_constant(state);
10908                 break;
10909         case TOK_LIT_FLOAT:
10910                 eat(state, TOK_LIT_FLOAT);
10911                 error(state, 0, "Floating point constants not supported");
10912                 def = 0;
10913                 FINISHME();
10914                 break;
10915         case TOK_LIT_CHAR:
10916                 def = character_constant(state);
10917                 break;
10918         case TOK_LIT_STRING:
10919                 def = string_constant(state);
10920                 break;
10921         default:
10922                 def = 0;
10923                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
10924         }
10925         return def;
10926 }
10927
10928 static struct triple *postfix_expr(struct compile_state *state)
10929 {
10930         struct triple *def;
10931         int postfix;
10932         def = primary_expr(state);
10933         do {
10934                 struct triple *left;
10935                 int tok;
10936                 postfix = 1;
10937                 left = def;
10938                 switch((tok = peek(state))) {
10939                 case TOK_LBRACKET:
10940                         eat(state, TOK_LBRACKET);
10941                         def = mk_subscript_expr(state, left, expr(state));
10942                         eat(state, TOK_RBRACKET);
10943                         break;
10944                 case TOK_LPAREN:
10945                         def = call_expr(state, def);
10946                         break;
10947                 case TOK_DOT:
10948                 {
10949                         struct hash_entry *field;
10950                         eat(state, TOK_DOT);
10951                         field = eat(state, TOK_IDENT)->ident;
10952                         def = deref_field(state, def, field);
10953                         break;
10954                 }
10955                 case TOK_ARROW:
10956                 {
10957                         struct hash_entry *field;
10958                         eat(state, TOK_ARROW);
10959                         field = eat(state, TOK_IDENT)->ident;
10960                         def = mk_deref_expr(state, read_expr(state, def));
10961                         def = deref_field(state, def, field);
10962                         break;
10963                 }
10964                 case TOK_PLUSPLUS:
10965                         eat(state, TOK_PLUSPLUS);
10966                         def = mk_post_inc_expr(state, left);
10967                         break;
10968                 case TOK_MINUSMINUS:
10969                         eat(state, TOK_MINUSMINUS);
10970                         def = mk_post_dec_expr(state, left);
10971                         break;
10972                 default:
10973                         postfix = 0;
10974                         break;
10975                 }
10976         } while(postfix);
10977         return def;
10978 }
10979
10980 static struct triple *cast_expr(struct compile_state *state);
10981
10982 static struct triple *unary_expr(struct compile_state *state)
10983 {
10984         struct triple *def, *right;
10985         int tok;
10986         switch((tok = peek(state))) {
10987         case TOK_PLUSPLUS:
10988                 eat(state, TOK_PLUSPLUS);
10989                 def = mk_pre_inc_expr(state, unary_expr(state));
10990                 break;
10991         case TOK_MINUSMINUS:
10992                 eat(state, TOK_MINUSMINUS);
10993                 def = mk_pre_dec_expr(state, unary_expr(state));
10994                 break;
10995         case TOK_AND:
10996                 eat(state, TOK_AND);
10997                 def = mk_addr_expr(state, cast_expr(state), 0);
10998                 break;
10999         case TOK_STAR:
11000                 eat(state, TOK_STAR);
11001                 def = mk_deref_expr(state, read_expr(state, cast_expr(state)));
11002                 break;
11003         case TOK_PLUS:
11004                 eat(state, TOK_PLUS);
11005                 right = read_expr(state, cast_expr(state));
11006                 arithmetic(state, right);
11007                 def = integral_promotion(state, right);
11008                 break;
11009         case TOK_MINUS:
11010                 eat(state, TOK_MINUS);
11011                 right = read_expr(state, cast_expr(state));
11012                 arithmetic(state, right);
11013                 def = integral_promotion(state, right);
11014                 def = triple(state, OP_NEG, def->type, def, 0);
11015                 break;
11016         case TOK_TILDE:
11017                 eat(state, TOK_TILDE);
11018                 right = read_expr(state, cast_expr(state));
11019                 integral(state, right);
11020                 def = integral_promotion(state, right);
11021                 def = triple(state, OP_INVERT, def->type, def, 0);
11022                 break;
11023         case TOK_BANG:
11024                 eat(state, TOK_BANG);
11025                 right = read_expr(state, cast_expr(state));
11026                 bool(state, right);
11027                 def = lfalse_expr(state, right);
11028                 break;
11029         case TOK_SIZEOF:
11030         {
11031                 struct type *type;
11032                 int tok1, tok2;
11033                 eat(state, TOK_SIZEOF);
11034                 tok1 = peek(state);
11035                 tok2 = peek2(state);
11036                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11037                         eat(state, TOK_LPAREN);
11038                         type = type_name(state);
11039                         eat(state, TOK_RPAREN);
11040                 }
11041                 else {
11042                         struct triple *expr;
11043                         expr = unary_expr(state);
11044                         type = expr->type;
11045                         release_expr(state, expr);
11046                 }
11047                 def = int_const(state, &ulong_type, size_of_in_bytes(state, type));
11048                 break;
11049         }
11050         case TOK_ALIGNOF:
11051         {
11052                 struct type *type;
11053                 int tok1, tok2;
11054                 eat(state, TOK_ALIGNOF);
11055                 tok1 = peek(state);
11056                 tok2 = peek2(state);
11057                 if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11058                         eat(state, TOK_LPAREN);
11059                         type = type_name(state);
11060                         eat(state, TOK_RPAREN);
11061                 }
11062                 else {
11063                         struct triple *expr;
11064                         expr = unary_expr(state);
11065                         type = expr->type;
11066                         release_expr(state, expr);
11067                 }
11068                 def = int_const(state, &ulong_type, align_of_in_bytes(state, type));
11069                 break;
11070         }
11071         case TOK_MDEFINED:
11072         {
11073                 /* We only come here if we are called from the preprocessor */
11074                 struct hash_entry *ident;
11075                 int parens;
11076                 eat(state, TOK_MDEFINED);
11077                 parens = 0;
11078                 if (pp_peek(state) == TOK_LPAREN) {
11079                         pp_eat(state, TOK_LPAREN);
11080                         parens = 1;
11081                 }
11082                 ident = pp_eat(state, TOK_MIDENT)->ident;
11083                 if (parens) {
11084                         eat(state, TOK_RPAREN);
11085                 }
11086                 def = int_const(state, &int_type, ident->sym_define != 0);
11087                 break;
11088         }
11089         default:
11090                 def = postfix_expr(state);
11091                 break;
11092         }
11093         return def;
11094 }
11095
11096 static struct triple *cast_expr(struct compile_state *state)
11097 {
11098         struct triple *def;
11099         int tok1, tok2;
11100         tok1 = peek(state);
11101         tok2 = peek2(state);
11102         if ((tok1 == TOK_LPAREN) && istype(tok2)) {
11103                 struct type *type;
11104                 eat(state, TOK_LPAREN);
11105                 type = type_name(state);
11106                 eat(state, TOK_RPAREN);
11107                 def = mk_cast_expr(state, type, cast_expr(state));
11108         }
11109         else {
11110                 def = unary_expr(state);
11111         }
11112         return def;
11113 }
11114
11115 static struct triple *mult_expr(struct compile_state *state)
11116 {
11117         struct triple *def;
11118         int done;
11119         def = cast_expr(state);
11120         do {
11121                 struct triple *left, *right;
11122                 struct type *result_type;
11123                 int tok, op, sign;
11124                 done = 0;
11125                 tok = peek(state);
11126                 switch(tok) {
11127                 case TOK_STAR:
11128                 case TOK_DIV:
11129                 case TOK_MOD:
11130                         left = read_expr(state, def);
11131                         arithmetic(state, left);
11132
11133                         eat(state, tok);
11134
11135                         right = read_expr(state, cast_expr(state));
11136                         arithmetic(state, right);
11137
11138                         result_type = arithmetic_result(state, left, right);
11139                         sign = is_signed(result_type);
11140                         op = -1;
11141                         switch(tok) {
11142                         case TOK_STAR: op = sign? OP_SMUL : OP_UMUL; break;
11143                         case TOK_DIV:  op = sign? OP_SDIV : OP_UDIV; break;
11144                         case TOK_MOD:  op = sign? OP_SMOD : OP_UMOD; break;
11145                         }
11146                         def = triple(state, op, result_type, left, right);
11147                         break;
11148                 default:
11149                         done = 1;
11150                         break;
11151                 }
11152         } while(!done);
11153         return def;
11154 }
11155
11156 static struct triple *add_expr(struct compile_state *state)
11157 {
11158         struct triple *def;
11159         int done;
11160         def = mult_expr(state);
11161         do {
11162                 done = 0;
11163                 switch( peek(state)) {
11164                 case TOK_PLUS:
11165                         eat(state, TOK_PLUS);
11166                         def = mk_add_expr(state, def, mult_expr(state));
11167                         break;
11168                 case TOK_MINUS:
11169                         eat(state, TOK_MINUS);
11170                         def = mk_sub_expr(state, def, mult_expr(state));
11171                         break;
11172                 default:
11173                         done = 1;
11174                         break;
11175                 }
11176         } while(!done);
11177         return def;
11178 }
11179
11180 static struct triple *shift_expr(struct compile_state *state)
11181 {
11182         struct triple *def;
11183         int done;
11184         def = add_expr(state);
11185         do {
11186                 struct triple *left, *right;
11187                 int tok, op;
11188                 done = 0;
11189                 switch((tok = peek(state))) {
11190                 case TOK_SL:
11191                 case TOK_SR:
11192                         left = read_expr(state, def);
11193                         integral(state, left);
11194                         left = integral_promotion(state, left);
11195
11196                         eat(state, tok);
11197
11198                         right = read_expr(state, add_expr(state));
11199                         integral(state, right);
11200                         right = integral_promotion(state, right);
11201
11202                         op = (tok == TOK_SL)? OP_SL :
11203                                 is_signed(left->type)? OP_SSR: OP_USR;
11204
11205                         def = triple(state, op, left->type, left, right);
11206                         break;
11207                 default:
11208                         done = 1;
11209                         break;
11210                 }
11211         } while(!done);
11212         return def;
11213 }
11214
11215 static struct triple *relational_expr(struct compile_state *state)
11216 {
11217 #if DEBUG_ROMCC_WARNINGS
11218 #warning "Extend relational exprs to work on more than arithmetic types"
11219 #endif
11220         struct triple *def;
11221         int done;
11222         def = shift_expr(state);
11223         do {
11224                 struct triple *left, *right;
11225                 struct type *arg_type;
11226                 int tok, op, sign;
11227                 done = 0;
11228                 switch((tok = peek(state))) {
11229                 case TOK_LESS:
11230                 case TOK_MORE:
11231                 case TOK_LESSEQ:
11232                 case TOK_MOREEQ:
11233                         left = read_expr(state, def);
11234                         arithmetic(state, left);
11235
11236                         eat(state, tok);
11237
11238                         right = read_expr(state, shift_expr(state));
11239                         arithmetic(state, right);
11240
11241                         arg_type = arithmetic_result(state, left, right);
11242                         sign = is_signed(arg_type);
11243                         op = -1;
11244                         switch(tok) {
11245                         case TOK_LESS:   op = sign? OP_SLESS : OP_ULESS; break;
11246                         case TOK_MORE:   op = sign? OP_SMORE : OP_UMORE; break;
11247                         case TOK_LESSEQ: op = sign? OP_SLESSEQ : OP_ULESSEQ; break;
11248                         case TOK_MOREEQ: op = sign? OP_SMOREEQ : OP_UMOREEQ; break;
11249                         }
11250                         def = triple(state, op, &int_type, left, right);
11251                         break;
11252                 default:
11253                         done = 1;
11254                         break;
11255                 }
11256         } while(!done);
11257         return def;
11258 }
11259
11260 static struct triple *equality_expr(struct compile_state *state)
11261 {
11262 #if DEBUG_ROMCC_WARNINGS
11263 #warning "Extend equality exprs to work on more than arithmetic types"
11264 #endif
11265         struct triple *def;
11266         int done;
11267         def = relational_expr(state);
11268         do {
11269                 struct triple *left, *right;
11270                 int tok, op;
11271                 done = 0;
11272                 switch((tok = peek(state))) {
11273                 case TOK_EQEQ:
11274                 case TOK_NOTEQ:
11275                         left = read_expr(state, def);
11276                         arithmetic(state, left);
11277                         eat(state, tok);
11278                         right = read_expr(state, relational_expr(state));
11279                         arithmetic(state, right);
11280                         op = (tok == TOK_EQEQ) ? OP_EQ: OP_NOTEQ;
11281                         def = triple(state, op, &int_type, left, right);
11282                         break;
11283                 default:
11284                         done = 1;
11285                         break;
11286                 }
11287         } while(!done);
11288         return def;
11289 }
11290
11291 static struct triple *and_expr(struct compile_state *state)
11292 {
11293         struct triple *def;
11294         def = equality_expr(state);
11295         while(peek(state) == TOK_AND) {
11296                 struct triple *left, *right;
11297                 struct type *result_type;
11298                 left = read_expr(state, def);
11299                 integral(state, left);
11300                 eat(state, TOK_AND);
11301                 right = read_expr(state, equality_expr(state));
11302                 integral(state, right);
11303                 result_type = arithmetic_result(state, left, right);
11304                 def = triple(state, OP_AND, result_type, left, right);
11305         }
11306         return def;
11307 }
11308
11309 static struct triple *xor_expr(struct compile_state *state)
11310 {
11311         struct triple *def;
11312         def = and_expr(state);
11313         while(peek(state) == TOK_XOR) {
11314                 struct triple *left, *right;
11315                 struct type *result_type;
11316                 left = read_expr(state, def);
11317                 integral(state, left);
11318                 eat(state, TOK_XOR);
11319                 right = read_expr(state, and_expr(state));
11320                 integral(state, right);
11321                 result_type = arithmetic_result(state, left, right);
11322                 def = triple(state, OP_XOR, result_type, left, right);
11323         }
11324         return def;
11325 }
11326
11327 static struct triple *or_expr(struct compile_state *state)
11328 {
11329         struct triple *def;
11330         def = xor_expr(state);
11331         while(peek(state) == TOK_OR) {
11332                 struct triple *left, *right;
11333                 struct type *result_type;
11334                 left = read_expr(state, def);
11335                 integral(state, left);
11336                 eat(state, TOK_OR);
11337                 right = read_expr(state, xor_expr(state));
11338                 integral(state, right);
11339                 result_type = arithmetic_result(state, left, right);
11340                 def = triple(state, OP_OR, result_type, left, right);
11341         }
11342         return def;
11343 }
11344
11345 static struct triple *land_expr(struct compile_state *state)
11346 {
11347         struct triple *def;
11348         def = or_expr(state);
11349         while(peek(state) == TOK_LOGAND) {
11350                 struct triple *left, *right;
11351                 left = read_expr(state, def);
11352                 bool(state, left);
11353                 eat(state, TOK_LOGAND);
11354                 right = read_expr(state, or_expr(state));
11355                 bool(state, right);
11356
11357                 def = mkland_expr(state,
11358                         ltrue_expr(state, left),
11359                         ltrue_expr(state, right));
11360         }
11361         return def;
11362 }
11363
11364 static struct triple *lor_expr(struct compile_state *state)
11365 {
11366         struct triple *def;
11367         def = land_expr(state);
11368         while(peek(state) == TOK_LOGOR) {
11369                 struct triple *left, *right;
11370                 left = read_expr(state, def);
11371                 bool(state, left);
11372                 eat(state, TOK_LOGOR);
11373                 right = read_expr(state, land_expr(state));
11374                 bool(state, right);
11375
11376                 def = mklor_expr(state,
11377                         ltrue_expr(state, left),
11378                         ltrue_expr(state, right));
11379         }
11380         return def;
11381 }
11382
11383 static struct triple *conditional_expr(struct compile_state *state)
11384 {
11385         struct triple *def;
11386         def = lor_expr(state);
11387         if (peek(state) == TOK_QUEST) {
11388                 struct triple *test, *left, *right;
11389                 bool(state, def);
11390                 test = ltrue_expr(state, read_expr(state, def));
11391                 eat(state, TOK_QUEST);
11392                 left = read_expr(state, expr(state));
11393                 eat(state, TOK_COLON);
11394                 right = read_expr(state, conditional_expr(state));
11395
11396                 def = mkcond_expr(state, test, left, right);
11397         }
11398         return def;
11399 }
11400
11401 struct cv_triple {
11402         struct triple *val;
11403         int id;
11404 };
11405
11406 static void set_cv(struct compile_state *state, struct cv_triple *cv,
11407         struct triple *dest, struct triple *val)
11408 {
11409         if (cv[dest->id].val) {
11410                 free_triple(state, cv[dest->id].val);
11411         }
11412         cv[dest->id].val = val;
11413 }
11414 static struct triple *get_cv(struct compile_state *state, struct cv_triple *cv,
11415         struct triple *src)
11416 {
11417         return cv[src->id].val;
11418 }
11419
11420 static struct triple *eval_const_expr(
11421         struct compile_state *state, struct triple *expr)
11422 {
11423         struct triple *def;
11424         if (is_const(expr)) {
11425                 def = expr;
11426         }
11427         else {
11428                 /* If we don't start out as a constant simplify into one */
11429                 struct triple *head, *ptr;
11430                 struct cv_triple *cv;
11431                 int i, count;
11432                 head = label(state); /* dummy initial triple */
11433                 flatten(state, head, expr);
11434                 count = 1;
11435                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11436                         count++;
11437                 }
11438                 cv = xcmalloc(sizeof(struct cv_triple)*count, "const value vector");
11439                 i = 1;
11440                 for(ptr = head->next; ptr != head; ptr = ptr->next) {
11441                         cv[i].val = 0;
11442                         cv[i].id  = ptr->id;
11443                         ptr->id   = i;
11444                         i++;
11445                 }
11446                 ptr = head->next;
11447                 do {
11448                         valid_ins(state, ptr);
11449                         if ((ptr->op == OP_PHI) || (ptr->op == OP_LIST)) {
11450                                 internal_error(state, ptr,
11451                                         "unexpected %s in constant expression",
11452                                         tops(ptr->op));
11453                         }
11454                         else if (ptr->op == OP_LIST) {
11455                         }
11456                         else if (triple_is_structural(state, ptr)) {
11457                                 ptr = ptr->next;
11458                         }
11459                         else if (triple_is_ubranch(state, ptr)) {
11460                                 ptr = TARG(ptr, 0);
11461                         }
11462                         else if (triple_is_cbranch(state, ptr)) {
11463                                 struct triple *cond_val;
11464                                 cond_val = get_cv(state, cv, RHS(ptr, 0));
11465                                 if (!cond_val || !is_const(cond_val) ||
11466                                         (cond_val->op != OP_INTCONST))
11467                                 {
11468                                         internal_error(state, ptr, "bad branch condition");
11469                                 }
11470                                 if (cond_val->u.cval == 0) {
11471                                         ptr = ptr->next;
11472                                 } else {
11473                                         ptr = TARG(ptr, 0);
11474                                 }
11475                         }
11476                         else if (triple_is_branch(state, ptr)) {
11477                                 error(state, ptr, "bad branch type in constant expression");
11478                         }
11479                         else if (ptr->op == OP_WRITE) {
11480                                 struct triple *val;
11481                                 val = get_cv(state, cv, RHS(ptr, 0));
11482
11483                                 set_cv(state, cv, MISC(ptr, 0),
11484                                         copy_triple(state, val));
11485                                 set_cv(state, cv, ptr,
11486                                         copy_triple(state, val));
11487                                 ptr = ptr->next;
11488                         }
11489                         else if (ptr->op == OP_READ) {
11490                                 set_cv(state, cv, ptr,
11491                                         copy_triple(state,
11492                                                 get_cv(state, cv, RHS(ptr, 0))));
11493                                 ptr = ptr->next;
11494                         }
11495                         else if (triple_is_pure(state, ptr, cv[ptr->id].id)) {
11496                                 struct triple *val, **rhs;
11497                                 val = copy_triple(state, ptr);
11498                                 rhs = triple_rhs(state, val, 0);
11499                                 for(; rhs; rhs = triple_rhs(state, val, rhs)) {
11500                                         if (!*rhs) {
11501                                                 internal_error(state, ptr, "Missing rhs");
11502                                         }
11503                                         *rhs = get_cv(state, cv, *rhs);
11504                                 }
11505                                 simplify(state, val);
11506                                 set_cv(state, cv, ptr, val);
11507                                 ptr = ptr->next;
11508                         }
11509                         else {
11510                                 error(state, ptr, "impure operation in constant expression");
11511                         }
11512
11513                 } while(ptr != head);
11514
11515                 /* Get the result value */
11516                 def = get_cv(state, cv, head->prev);
11517                 cv[head->prev->id].val = 0;
11518
11519                 /* Free the temporary values */
11520                 for(i = 0; i < count; i++) {
11521                         if (cv[i].val) {
11522                                 free_triple(state, cv[i].val);
11523                                 cv[i].val = 0;
11524                         }
11525                 }
11526                 xfree(cv);
11527                 /* Free the intermediate expressions */
11528                 while(head->next != head) {
11529                         release_triple(state, head->next);
11530                 }
11531                 free_triple(state, head);
11532         }
11533         if (!is_const(def)) {
11534                 error(state, expr, "Not a constant expression");
11535         }
11536         return def;
11537 }
11538
11539 static struct triple *constant_expr(struct compile_state *state)
11540 {
11541         return eval_const_expr(state, conditional_expr(state));
11542 }
11543
11544 static struct triple *assignment_expr(struct compile_state *state)
11545 {
11546         struct triple *def, *left, *right;
11547         int tok, op, sign;
11548         /* The C grammer in K&R shows assignment expressions
11549          * only taking unary expressions as input on their
11550          * left hand side.  But specifies the precedence of
11551          * assignemnt as the lowest operator except for comma.
11552          *
11553          * Allowing conditional expressions on the left hand side
11554          * of an assignement results in a grammar that accepts
11555          * a larger set of statements than standard C.   As long
11556          * as the subset of the grammar that is standard C behaves
11557          * correctly this should cause no problems.
11558          *
11559          * For the extra token strings accepted by the grammar
11560          * none of them should produce a valid lvalue, so they
11561          * should not produce functioning programs.
11562          *
11563          * GCC has this bug as well, so surprises should be minimal.
11564          */
11565         def = conditional_expr(state);
11566         left = def;
11567         switch((tok = peek(state))) {
11568         case TOK_EQ:
11569                 lvalue(state, left);
11570                 eat(state, TOK_EQ);
11571                 def = write_expr(state, left,
11572                         read_expr(state, assignment_expr(state)));
11573                 break;
11574         case TOK_TIMESEQ:
11575         case TOK_DIVEQ:
11576         case TOK_MODEQ:
11577                 lvalue(state, left);
11578                 arithmetic(state, left);
11579                 eat(state, tok);
11580                 right = read_expr(state, assignment_expr(state));
11581                 arithmetic(state, right);
11582
11583                 sign = is_signed(left->type);
11584                 op = -1;
11585                 switch(tok) {
11586                 case TOK_TIMESEQ: op = sign? OP_SMUL : OP_UMUL; break;
11587                 case TOK_DIVEQ:   op = sign? OP_SDIV : OP_UDIV; break;
11588                 case TOK_MODEQ:   op = sign? OP_SMOD : OP_UMOD; break;
11589                 }
11590                 def = write_expr(state, left,
11591                         triple(state, op, left->type,
11592                                 read_expr(state, left), right));
11593                 break;
11594         case TOK_PLUSEQ:
11595                 lvalue(state, left);
11596                 eat(state, TOK_PLUSEQ);
11597                 def = write_expr(state, left,
11598                         mk_add_expr(state, left, assignment_expr(state)));
11599                 break;
11600         case TOK_MINUSEQ:
11601                 lvalue(state, left);
11602                 eat(state, TOK_MINUSEQ);
11603                 def = write_expr(state, left,
11604                         mk_sub_expr(state, left, assignment_expr(state)));
11605                 break;
11606         case TOK_SLEQ:
11607         case TOK_SREQ:
11608         case TOK_ANDEQ:
11609         case TOK_XOREQ:
11610         case TOK_OREQ:
11611                 lvalue(state, left);
11612                 integral(state, left);
11613                 eat(state, tok);
11614                 right = read_expr(state, assignment_expr(state));
11615                 integral(state, right);
11616                 right = integral_promotion(state, right);
11617                 sign = is_signed(left->type);
11618                 op = -1;
11619                 switch(tok) {
11620                 case TOK_SLEQ:  op = OP_SL; break;
11621                 case TOK_SREQ:  op = sign? OP_SSR: OP_USR; break;
11622                 case TOK_ANDEQ: op = OP_AND; break;
11623                 case TOK_XOREQ: op = OP_XOR; break;
11624                 case TOK_OREQ:  op = OP_OR; break;
11625                 }
11626                 def = write_expr(state, left,
11627                         triple(state, op, left->type,
11628                                 read_expr(state, left), right));
11629                 break;
11630         }
11631         return def;
11632 }
11633
11634 static struct triple *expr(struct compile_state *state)
11635 {
11636         struct triple *def;
11637         def = assignment_expr(state);
11638         while(peek(state) == TOK_COMMA) {
11639                 eat(state, TOK_COMMA);
11640                 def = mkprog(state, def, assignment_expr(state), 0UL);
11641         }
11642         return def;
11643 }
11644
11645 static void expr_statement(struct compile_state *state, struct triple *first)
11646 {
11647         if (peek(state) != TOK_SEMI) {
11648                 /* lvalue conversions always apply except when certian operators
11649                  * are applied.  I apply the lvalue conversions here
11650                  * as I know no more operators will be applied.
11651                  */
11652                 flatten(state, first, lvalue_conversion(state, expr(state)));
11653         }
11654         eat(state, TOK_SEMI);
11655 }
11656
11657 static void if_statement(struct compile_state *state, struct triple *first)
11658 {
11659         struct triple *test, *jmp1, *jmp2, *middle, *end;
11660
11661         jmp1 = jmp2 = middle = 0;
11662         eat(state, TOK_IF);
11663         eat(state, TOK_LPAREN);
11664         test = expr(state);
11665         bool(state, test);
11666         /* Cleanup and invert the test */
11667         test = lfalse_expr(state, read_expr(state, test));
11668         eat(state, TOK_RPAREN);
11669         /* Generate the needed pieces */
11670         middle = label(state);
11671         jmp1 = branch(state, middle, test);
11672         /* Thread the pieces together */
11673         flatten(state, first, test);
11674         flatten(state, first, jmp1);
11675         flatten(state, first, label(state));
11676         statement(state, first);
11677         if (peek(state) == TOK_ELSE) {
11678                 eat(state, TOK_ELSE);
11679                 /* Generate the rest of the pieces */
11680                 end = label(state);
11681                 jmp2 = branch(state, end, 0);
11682                 /* Thread them together */
11683                 flatten(state, first, jmp2);
11684                 flatten(state, first, middle);
11685                 statement(state, first);
11686                 flatten(state, first, end);
11687         }
11688         else {
11689                 flatten(state, first, middle);
11690         }
11691 }
11692
11693 static void for_statement(struct compile_state *state, struct triple *first)
11694 {
11695         struct triple *head, *test, *tail, *jmp1, *jmp2, *end;
11696         struct triple *label1, *label2, *label3;
11697         struct hash_entry *ident;
11698
11699         eat(state, TOK_FOR);
11700         eat(state, TOK_LPAREN);
11701         head = test = tail = jmp1 = jmp2 = 0;
11702         if (peek(state) != TOK_SEMI) {
11703                 head = expr(state);
11704         }
11705         eat(state, TOK_SEMI);
11706         if (peek(state) != TOK_SEMI) {
11707                 test = expr(state);
11708                 bool(state, test);
11709                 test = ltrue_expr(state, read_expr(state, test));
11710         }
11711         eat(state, TOK_SEMI);
11712         if (peek(state) != TOK_RPAREN) {
11713                 tail = expr(state);
11714         }
11715         eat(state, TOK_RPAREN);
11716         /* Generate the needed pieces */
11717         label1 = label(state);
11718         label2 = label(state);
11719         label3 = label(state);
11720         if (test) {
11721                 jmp1 = branch(state, label3, 0);
11722                 jmp2 = branch(state, label1, test);
11723         }
11724         else {
11725                 jmp2 = branch(state, label1, 0);
11726         }
11727         end = label(state);
11728         /* Remember where break and continue go */
11729         start_scope(state);
11730         ident = state->i_break;
11731         symbol(state, ident, &ident->sym_ident, end, end->type);
11732         ident = state->i_continue;
11733         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11734         /* Now include the body */
11735         flatten(state, first, head);
11736         flatten(state, first, jmp1);
11737         flatten(state, first, label1);
11738         statement(state, first);
11739         flatten(state, first, label2);
11740         flatten(state, first, tail);
11741         flatten(state, first, label3);
11742         flatten(state, first, test);
11743         flatten(state, first, jmp2);
11744         flatten(state, first, end);
11745         /* Cleanup the break/continue scope */
11746         end_scope(state);
11747 }
11748
11749 static void while_statement(struct compile_state *state, struct triple *first)
11750 {
11751         struct triple *label1, *test, *label2, *jmp1, *jmp2, *end;
11752         struct hash_entry *ident;
11753         eat(state, TOK_WHILE);
11754         eat(state, TOK_LPAREN);
11755         test = expr(state);
11756         bool(state, test);
11757         test = ltrue_expr(state, read_expr(state, test));
11758         eat(state, TOK_RPAREN);
11759         /* Generate the needed pieces */
11760         label1 = label(state);
11761         label2 = label(state);
11762         jmp1 = branch(state, label2, 0);
11763         jmp2 = branch(state, label1, test);
11764         end = label(state);
11765         /* Remember where break and continue go */
11766         start_scope(state);
11767         ident = state->i_break;
11768         symbol(state, ident, &ident->sym_ident, end, end->type);
11769         ident = state->i_continue;
11770         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11771         /* Thread them together */
11772         flatten(state, first, jmp1);
11773         flatten(state, first, label1);
11774         statement(state, first);
11775         flatten(state, first, label2);
11776         flatten(state, first, test);
11777         flatten(state, first, jmp2);
11778         flatten(state, first, end);
11779         /* Cleanup the break/continue scope */
11780         end_scope(state);
11781 }
11782
11783 static void do_statement(struct compile_state *state, struct triple *first)
11784 {
11785         struct triple *label1, *label2, *test, *end;
11786         struct hash_entry *ident;
11787         eat(state, TOK_DO);
11788         /* Generate the needed pieces */
11789         label1 = label(state);
11790         label2 = label(state);
11791         end = label(state);
11792         /* Remember where break and continue go */
11793         start_scope(state);
11794         ident = state->i_break;
11795         symbol(state, ident, &ident->sym_ident, end, end->type);
11796         ident = state->i_continue;
11797         symbol(state, ident, &ident->sym_ident, label2, label2->type);
11798         /* Now include the body */
11799         flatten(state, first, label1);
11800         statement(state, first);
11801         /* Cleanup the break/continue scope */
11802         end_scope(state);
11803         /* Eat the rest of the loop */
11804         eat(state, TOK_WHILE);
11805         eat(state, TOK_LPAREN);
11806         test = read_expr(state, expr(state));
11807         bool(state, test);
11808         eat(state, TOK_RPAREN);
11809         eat(state, TOK_SEMI);
11810         /* Thread the pieces together */
11811         test = ltrue_expr(state, test);
11812         flatten(state, first, label2);
11813         flatten(state, first, test);
11814         flatten(state, first, branch(state, label1, test));
11815         flatten(state, first, end);
11816 }
11817
11818
11819 static void return_statement(struct compile_state *state, struct triple *first)
11820 {
11821         struct triple *jmp, *mv, *dest, *var, *val;
11822         int last;
11823         eat(state, TOK_RETURN);
11824
11825 #if DEBUG_ROMCC_WARNINGS
11826 #warning "FIXME implement a more general excess branch elimination"
11827 #endif
11828         val = 0;
11829         /* If we have a return value do some more work */
11830         if (peek(state) != TOK_SEMI) {
11831                 val = read_expr(state, expr(state));
11832         }
11833         eat(state, TOK_SEMI);
11834
11835         /* See if this last statement in a function */
11836         last = ((peek(state) == TOK_RBRACE) &&
11837                 (state->scope_depth == GLOBAL_SCOPE_DEPTH +2));
11838
11839         /* Find the return variable */
11840         var = fresult(state, state->main_function);
11841
11842         /* Find the return destination */
11843         dest = state->i_return->sym_ident->def;
11844         mv = jmp = 0;
11845         /* If needed generate a jump instruction */
11846         if (!last) {
11847                 jmp = branch(state, dest, 0);
11848         }
11849         /* If needed generate an assignment instruction */
11850         if (val) {
11851                 mv = write_expr(state, deref_index(state, var, 1), val);
11852         }
11853         /* Now put the code together */
11854         if (mv) {
11855                 flatten(state, first, mv);
11856                 flatten(state, first, jmp);
11857         }
11858         else if (jmp) {
11859                 flatten(state, first, jmp);
11860         }
11861 }
11862
11863 static void break_statement(struct compile_state *state, struct triple *first)
11864 {
11865         struct triple *dest;
11866         eat(state, TOK_BREAK);
11867         eat(state, TOK_SEMI);
11868         if (!state->i_break->sym_ident) {
11869                 error(state, 0, "break statement not within loop or switch");
11870         }
11871         dest = state->i_break->sym_ident->def;
11872         flatten(state, first, branch(state, dest, 0));
11873 }
11874
11875 static void continue_statement(struct compile_state *state, struct triple *first)
11876 {
11877         struct triple *dest;
11878         eat(state, TOK_CONTINUE);
11879         eat(state, TOK_SEMI);
11880         if (!state->i_continue->sym_ident) {
11881                 error(state, 0, "continue statement outside of a loop");
11882         }
11883         dest = state->i_continue->sym_ident->def;
11884         flatten(state, first, branch(state, dest, 0));
11885 }
11886
11887 static void goto_statement(struct compile_state *state, struct triple *first)
11888 {
11889         struct hash_entry *ident;
11890         eat(state, TOK_GOTO);
11891         ident = eat(state, TOK_IDENT)->ident;
11892         if (!ident->sym_label) {
11893                 /* If this is a forward branch allocate the label now,
11894                  * it will be flattend in the appropriate location later.
11895                  */
11896                 struct triple *ins;
11897                 ins = label(state);
11898                 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11899         }
11900         eat(state, TOK_SEMI);
11901
11902         flatten(state, first, branch(state, ident->sym_label->def, 0));
11903 }
11904
11905 static void labeled_statement(struct compile_state *state, struct triple *first)
11906 {
11907         struct triple *ins;
11908         struct hash_entry *ident;
11909
11910         ident = eat(state, TOK_IDENT)->ident;
11911         if (ident->sym_label && ident->sym_label->def) {
11912                 ins = ident->sym_label->def;
11913                 put_occurance(ins->occurance);
11914                 ins->occurance = new_occurance(state);
11915         }
11916         else {
11917                 ins = label(state);
11918                 label_symbol(state, ident, ins, FUNCTION_SCOPE_DEPTH);
11919         }
11920         if (ins->id & TRIPLE_FLAG_FLATTENED) {
11921                 error(state, 0, "label %s already defined", ident->name);
11922         }
11923         flatten(state, first, ins);
11924
11925         eat(state, TOK_COLON);
11926         statement(state, first);
11927 }
11928
11929 static void switch_statement(struct compile_state *state, struct triple *first)
11930 {
11931         struct triple *value, *top, *end, *dbranch;
11932         struct hash_entry *ident;
11933
11934         /* See if we have a valid switch statement */
11935         eat(state, TOK_SWITCH);
11936         eat(state, TOK_LPAREN);
11937         value = expr(state);
11938         integral(state, value);
11939         value = read_expr(state, value);
11940         eat(state, TOK_RPAREN);
11941         /* Generate the needed pieces */
11942         top = label(state);
11943         end = label(state);
11944         dbranch = branch(state, end, 0);
11945         /* Remember where case branches and break goes */
11946         start_scope(state);
11947         ident = state->i_switch;
11948         symbol(state, ident, &ident->sym_ident, value, value->type);
11949         ident = state->i_case;
11950         symbol(state, ident, &ident->sym_ident, top, top->type);
11951         ident = state->i_break;
11952         symbol(state, ident, &ident->sym_ident, end, end->type);
11953         ident = state->i_default;
11954         symbol(state, ident, &ident->sym_ident, dbranch, dbranch->type);
11955         /* Thread them together */
11956         flatten(state, first, value);
11957         flatten(state, first, top);
11958         flatten(state, first, dbranch);
11959         statement(state, first);
11960         flatten(state, first, end);
11961         /* Cleanup the switch scope */
11962         end_scope(state);
11963 }
11964
11965 static void case_statement(struct compile_state *state, struct triple *first)
11966 {
11967         struct triple *cvalue, *dest, *test, *jmp;
11968         struct triple *ptr, *value, *top, *dbranch;
11969
11970         /* See if w have a valid case statement */
11971         eat(state, TOK_CASE);
11972         cvalue = constant_expr(state);
11973         integral(state, cvalue);
11974         if (cvalue->op != OP_INTCONST) {
11975                 error(state, 0, "integer constant expected");
11976         }
11977         eat(state, TOK_COLON);
11978         if (!state->i_case->sym_ident) {
11979                 error(state, 0, "case statement not within a switch");
11980         }
11981
11982         /* Lookup the interesting pieces */
11983         top = state->i_case->sym_ident->def;
11984         value = state->i_switch->sym_ident->def;
11985         dbranch = state->i_default->sym_ident->def;
11986
11987         /* See if this case label has already been used */
11988         for(ptr = top; ptr != dbranch; ptr = ptr->next) {
11989                 if (ptr->op != OP_EQ) {
11990                         continue;
11991                 }
11992                 if (RHS(ptr, 1)->u.cval == cvalue->u.cval) {
11993                         error(state, 0, "duplicate case %d statement",
11994                                 cvalue->u.cval);
11995                 }
11996         }
11997         /* Generate the needed pieces */
11998         dest = label(state);
11999         test = triple(state, OP_EQ, &int_type, value, cvalue);
12000         jmp = branch(state, dest, test);
12001         /* Thread the pieces together */
12002         flatten(state, dbranch, test);
12003         flatten(state, dbranch, jmp);
12004         flatten(state, dbranch, label(state));
12005         flatten(state, first, dest);
12006         statement(state, first);
12007 }
12008
12009 static void default_statement(struct compile_state *state, struct triple *first)
12010 {
12011         struct triple *dest;
12012         struct triple *dbranch, *end;
12013
12014         /* See if we have a valid default statement */
12015         eat(state, TOK_DEFAULT);
12016         eat(state, TOK_COLON);
12017
12018         if (!state->i_case->sym_ident) {
12019                 error(state, 0, "default statement not within a switch");
12020         }
12021
12022         /* Lookup the interesting pieces */
12023         dbranch = state->i_default->sym_ident->def;
12024         end = state->i_break->sym_ident->def;
12025
12026         /* See if a default statement has already happened */
12027         if (TARG(dbranch, 0) != end) {
12028                 error(state, 0, "duplicate default statement");
12029         }
12030
12031         /* Generate the needed pieces */
12032         dest = label(state);
12033
12034         /* Blame the branch on the default statement */
12035         put_occurance(dbranch->occurance);
12036         dbranch->occurance = new_occurance(state);
12037
12038         /* Thread the pieces together */
12039         TARG(dbranch, 0) = dest;
12040         use_triple(dest, dbranch);
12041         flatten(state, first, dest);
12042         statement(state, first);
12043 }
12044
12045 static void asm_statement(struct compile_state *state, struct triple *first)
12046 {
12047         struct asm_info *info;
12048         struct {
12049                 struct triple *constraint;
12050                 struct triple *expr;
12051         } out_param[MAX_LHS], in_param[MAX_RHS], clob_param[MAX_LHS];
12052         struct triple *def, *asm_str;
12053         int out, in, clobbers, more, colons, i;
12054         int flags;
12055
12056         flags = 0;
12057         eat(state, TOK_ASM);
12058         /* For now ignore the qualifiers */
12059         switch(peek(state)) {
12060         case TOK_CONST:
12061                 eat(state, TOK_CONST);
12062                 break;
12063         case TOK_VOLATILE:
12064                 eat(state, TOK_VOLATILE);
12065                 flags |= TRIPLE_FLAG_VOLATILE;
12066                 break;
12067         }
12068         eat(state, TOK_LPAREN);
12069         asm_str = string_constant(state);
12070
12071         colons = 0;
12072         out = in = clobbers = 0;
12073         /* Outputs */
12074         if ((colons == 0) && (peek(state) == TOK_COLON)) {
12075                 eat(state, TOK_COLON);
12076                 colons++;
12077                 more = (peek(state) == TOK_LIT_STRING);
12078                 while(more) {
12079                         struct triple *var;
12080                         struct triple *constraint;
12081                         char *str;
12082                         more = 0;
12083                         if (out > MAX_LHS) {
12084                                 error(state, 0, "Maximum output count exceeded.");
12085                         }
12086                         constraint = string_constant(state);
12087                         str = constraint->u.blob;
12088                         if (str[0] != '=') {
12089                                 error(state, 0, "Output constraint does not start with =");
12090                         }
12091                         constraint->u.blob = str + 1;
12092                         eat(state, TOK_LPAREN);
12093                         var = conditional_expr(state);
12094                         eat(state, TOK_RPAREN);
12095
12096                         lvalue(state, var);
12097                         out_param[out].constraint = constraint;
12098                         out_param[out].expr       = var;
12099                         if (peek(state) == TOK_COMMA) {
12100                                 eat(state, TOK_COMMA);
12101                                 more = 1;
12102                         }
12103                         out++;
12104                 }
12105         }
12106         /* Inputs */
12107         if ((colons == 1) && (peek(state) == TOK_COLON)) {
12108                 eat(state, TOK_COLON);
12109                 colons++;
12110                 more = (peek(state) == TOK_LIT_STRING);
12111                 while(more) {
12112                         struct triple *val;
12113                         struct triple *constraint;
12114                         char *str;
12115                         more = 0;
12116                         if (in > MAX_RHS) {
12117                                 error(state, 0, "Maximum input count exceeded.");
12118                         }
12119                         constraint = string_constant(state);
12120                         str = constraint->u.blob;
12121                         if (digitp(str[0] && str[1] == '\0')) {
12122                                 int val;
12123                                 val = digval(str[0]);
12124                                 if ((val < 0) || (val >= out)) {
12125                                         error(state, 0, "Invalid input constraint %d", val);
12126                                 }
12127                         }
12128                         eat(state, TOK_LPAREN);
12129                         val = conditional_expr(state);
12130                         eat(state, TOK_RPAREN);
12131
12132                         in_param[in].constraint = constraint;
12133                         in_param[in].expr       = val;
12134                         if (peek(state) == TOK_COMMA) {
12135                                 eat(state, TOK_COMMA);
12136                                 more = 1;
12137                         }
12138                         in++;
12139                 }
12140         }
12141
12142         /* Clobber */
12143         if ((colons == 2) && (peek(state) == TOK_COLON)) {
12144                 eat(state, TOK_COLON);
12145                 colons++;
12146                 more = (peek(state) == TOK_LIT_STRING);
12147                 while(more) {
12148                         struct triple *clobber;
12149                         more = 0;
12150                         if ((clobbers + out) > MAX_LHS) {
12151                                 error(state, 0, "Maximum clobber limit exceeded.");
12152                         }
12153                         clobber = string_constant(state);
12154
12155                         clob_param[clobbers].constraint = clobber;
12156                         if (peek(state) == TOK_COMMA) {
12157                                 eat(state, TOK_COMMA);
12158                                 more = 1;
12159                         }
12160                         clobbers++;
12161                 }
12162         }
12163         eat(state, TOK_RPAREN);
12164         eat(state, TOK_SEMI);
12165
12166
12167         info = xcmalloc(sizeof(*info), "asm_info");
12168         info->str = asm_str->u.blob;
12169         free_triple(state, asm_str);
12170
12171         def = new_triple(state, OP_ASM, &void_type, clobbers + out, in);
12172         def->u.ainfo = info;
12173         def->id |= flags;
12174
12175         /* Find the register constraints */
12176         for(i = 0; i < out; i++) {
12177                 struct triple *constraint;
12178                 constraint = out_param[i].constraint;
12179                 info->tmpl.lhs[i] = arch_reg_constraint(state,
12180                         out_param[i].expr->type, constraint->u.blob);
12181                 free_triple(state, constraint);
12182         }
12183         for(; i - out < clobbers; i++) {
12184                 struct triple *constraint;
12185                 constraint = clob_param[i - out].constraint;
12186                 info->tmpl.lhs[i] = arch_reg_clobber(state, constraint->u.blob);
12187                 free_triple(state, constraint);
12188         }
12189         for(i = 0; i < in; i++) {
12190                 struct triple *constraint;
12191                 const char *str;
12192                 constraint = in_param[i].constraint;
12193                 str = constraint->u.blob;
12194                 if (digitp(str[0]) && str[1] == '\0') {
12195                         struct reg_info cinfo;
12196                         int val;
12197                         val = digval(str[0]);
12198                         cinfo.reg = info->tmpl.lhs[val].reg;
12199                         cinfo.regcm = arch_type_to_regcm(state, in_param[i].expr->type);
12200                         cinfo.regcm &= info->tmpl.lhs[val].regcm;
12201                         if (cinfo.reg == REG_UNSET) {
12202                                 cinfo.reg = REG_VIRT0 + val;
12203                         }
12204                         if (cinfo.regcm == 0) {
12205                                 error(state, 0, "No registers for %d", val);
12206                         }
12207                         info->tmpl.lhs[val] = cinfo;
12208                         info->tmpl.rhs[i]   = cinfo;
12209
12210                 } else {
12211                         info->tmpl.rhs[i] = arch_reg_constraint(state,
12212                                 in_param[i].expr->type, str);
12213                 }
12214                 free_triple(state, constraint);
12215         }
12216
12217         /* Now build the helper expressions */
12218         for(i = 0; i < in; i++) {
12219                 RHS(def, i) = read_expr(state, in_param[i].expr);
12220         }
12221         flatten(state, first, def);
12222         for(i = 0; i < (out + clobbers); i++) {
12223                 struct type *type;
12224                 struct triple *piece;
12225                 if (i < out) {
12226                         type = out_param[i].expr->type;
12227                 } else {
12228                         size_t size = arch_reg_size(info->tmpl.lhs[i].reg);
12229                         if (size >= SIZEOF_LONG) {
12230                                 type = &ulong_type;
12231                         }
12232                         else if (size >= SIZEOF_INT) {
12233                                 type = &uint_type;
12234                         }
12235                         else if (size >= SIZEOF_SHORT) {
12236                                 type = &ushort_type;
12237                         }
12238                         else {
12239                                 type = &uchar_type;
12240                         }
12241                 }
12242                 piece = triple(state, OP_PIECE, type, def, 0);
12243                 piece->u.cval = i;
12244                 LHS(def, i) = piece;
12245                 flatten(state, first, piece);
12246         }
12247         /* And write the helpers to their destinations */
12248         for(i = 0; i < out; i++) {
12249                 struct triple *piece;
12250                 piece = LHS(def, i);
12251                 flatten(state, first,
12252                         write_expr(state, out_param[i].expr, piece));
12253         }
12254 }
12255
12256
12257 static int isdecl(int tok)
12258 {
12259         switch(tok) {
12260         case TOK_AUTO:
12261         case TOK_REGISTER:
12262         case TOK_STATIC:
12263         case TOK_EXTERN:
12264         case TOK_TYPEDEF:
12265         case TOK_CONST:
12266         case TOK_RESTRICT:
12267         case TOK_VOLATILE:
12268         case TOK_VOID:
12269         case TOK_CHAR:
12270         case TOK_SHORT:
12271         case TOK_INT:
12272         case TOK_LONG:
12273         case TOK_FLOAT:
12274         case TOK_DOUBLE:
12275         case TOK_SIGNED:
12276         case TOK_UNSIGNED:
12277         case TOK_STRUCT:
12278         case TOK_UNION:
12279         case TOK_ENUM:
12280         case TOK_TYPE_NAME: /* typedef name */
12281                 return 1;
12282         default:
12283                 return 0;
12284         }
12285 }
12286
12287 static void compound_statement(struct compile_state *state, struct triple *first)
12288 {
12289         eat(state, TOK_LBRACE);
12290         start_scope(state);
12291
12292         /* statement-list opt */
12293         while (peek(state) != TOK_RBRACE) {
12294                 statement(state, first);
12295         }
12296         end_scope(state);
12297         eat(state, TOK_RBRACE);
12298 }
12299
12300 static void statement(struct compile_state *state, struct triple *first)
12301 {
12302         int tok;
12303         tok = peek(state);
12304         if (tok == TOK_LBRACE) {
12305                 compound_statement(state, first);
12306         }
12307         else if (tok == TOK_IF) {
12308                 if_statement(state, first);
12309         }
12310         else if (tok == TOK_FOR) {
12311                 for_statement(state, first);
12312         }
12313         else if (tok == TOK_WHILE) {
12314                 while_statement(state, first);
12315         }
12316         else if (tok == TOK_DO) {
12317                 do_statement(state, first);
12318         }
12319         else if (tok == TOK_RETURN) {
12320                 return_statement(state, first);
12321         }
12322         else if (tok == TOK_BREAK) {
12323                 break_statement(state, first);
12324         }
12325         else if (tok == TOK_CONTINUE) {
12326                 continue_statement(state, first);
12327         }
12328         else if (tok == TOK_GOTO) {
12329                 goto_statement(state, first);
12330         }
12331         else if (tok == TOK_SWITCH) {
12332                 switch_statement(state, first);
12333         }
12334         else if (tok == TOK_ASM) {
12335                 asm_statement(state, first);
12336         }
12337         else if ((tok == TOK_IDENT) && (peek2(state) == TOK_COLON)) {
12338                 labeled_statement(state, first);
12339         }
12340         else if (tok == TOK_CASE) {
12341                 case_statement(state, first);
12342         }
12343         else if (tok == TOK_DEFAULT) {
12344                 default_statement(state, first);
12345         }
12346         else if (isdecl(tok)) {
12347                 /* This handles C99 intermixing of statements and decls */
12348                 decl(state, first);
12349         }
12350         else {
12351                 expr_statement(state, first);
12352         }
12353 }
12354
12355 static struct type *param_decl(struct compile_state *state)
12356 {
12357         struct type *type;
12358         struct hash_entry *ident;
12359         /* Cheat so the declarator will know we are not global */
12360         start_scope(state);
12361         ident = 0;
12362         type = decl_specifiers(state);
12363         type = declarator(state, type, &ident, 0);
12364         type->field_ident = ident;
12365         end_scope(state);
12366         return type;
12367 }
12368
12369 static struct type *param_type_list(struct compile_state *state, struct type *type)
12370 {
12371         struct type *ftype, **next;
12372         ftype = new_type(TYPE_FUNCTION | (type->type & STOR_MASK), type, param_decl(state));
12373         next = &ftype->right;
12374         ftype->elements = 1;
12375         while(peek(state) == TOK_COMMA) {
12376                 eat(state, TOK_COMMA);
12377                 if (peek(state) == TOK_DOTS) {
12378                         eat(state, TOK_DOTS);
12379                         error(state, 0, "variadic functions not supported");
12380                 }
12381                 else {
12382                         *next = new_type(TYPE_PRODUCT, *next, param_decl(state));
12383                         next = &((*next)->right);
12384                         ftype->elements++;
12385                 }
12386         }
12387         return ftype;
12388 }
12389
12390 static struct type *type_name(struct compile_state *state)
12391 {
12392         struct type *type;
12393         type = specifier_qualifier_list(state);
12394         /* abstract-declarator (may consume no tokens) */
12395         type = declarator(state, type, 0, 0);
12396         return type;
12397 }
12398
12399 static struct type *direct_declarator(
12400         struct compile_state *state, struct type *type,
12401         struct hash_entry **pident, int need_ident)
12402 {
12403         struct hash_entry *ident;
12404         struct type *outer;
12405         int op;
12406         outer = 0;
12407         arrays_complete(state, type);
12408         switch(peek(state)) {
12409         case TOK_IDENT:
12410                 ident = eat(state, TOK_IDENT)->ident;
12411                 if (!ident) {
12412                         error(state, 0, "Unexpected identifier found");
12413                 }
12414                 /* The name of what we are declaring */
12415                 *pident = ident;
12416                 break;
12417         case TOK_LPAREN:
12418                 eat(state, TOK_LPAREN);
12419                 outer = declarator(state, type, pident, need_ident);
12420                 eat(state, TOK_RPAREN);
12421                 break;
12422         default:
12423                 if (need_ident) {
12424                         error(state, 0, "Identifier expected");
12425                 }
12426                 break;
12427         }
12428         do {
12429                 op = 1;
12430                 arrays_complete(state, type);
12431                 switch(peek(state)) {
12432                 case TOK_LPAREN:
12433                         eat(state, TOK_LPAREN);
12434                         type = param_type_list(state, type);
12435                         eat(state, TOK_RPAREN);
12436                         break;
12437                 case TOK_LBRACKET:
12438                 {
12439                         unsigned int qualifiers;
12440                         struct triple *value;
12441                         value = 0;
12442                         eat(state, TOK_LBRACKET);
12443                         if (peek(state) != TOK_RBRACKET) {
12444                                 value = constant_expr(state);
12445                                 integral(state, value);
12446                         }
12447                         eat(state, TOK_RBRACKET);
12448
12449                         qualifiers = type->type & (QUAL_MASK | STOR_MASK);
12450                         type = new_type(TYPE_ARRAY | qualifiers, type, 0);
12451                         if (value) {
12452                                 type->elements = value->u.cval;
12453                                 free_triple(state, value);
12454                         } else {
12455                                 type->elements = ELEMENT_COUNT_UNSPECIFIED;
12456                                 op = 0;
12457                         }
12458                 }
12459                         break;
12460                 default:
12461                         op = 0;
12462                         break;
12463                 }
12464         } while(op);
12465         if (outer) {
12466                 struct type *inner;
12467                 arrays_complete(state, type);
12468                 FINISHME();
12469                 for(inner = outer; inner->left; inner = inner->left)
12470                         ;
12471                 inner->left = type;
12472                 type = outer;
12473         }
12474         return type;
12475 }
12476
12477 static struct type *declarator(
12478         struct compile_state *state, struct type *type,
12479         struct hash_entry **pident, int need_ident)
12480 {
12481         while(peek(state) == TOK_STAR) {
12482                 eat(state, TOK_STAR);
12483                 type = new_type(TYPE_POINTER | (type->type & STOR_MASK), type, 0);
12484         }
12485         type = direct_declarator(state, type, pident, need_ident);
12486         return type;
12487 }
12488
12489 static struct type *typedef_name(
12490         struct compile_state *state, unsigned int specifiers)
12491 {
12492         struct hash_entry *ident;
12493         struct type *type;
12494         ident = eat(state, TOK_TYPE_NAME)->ident;
12495         type = ident->sym_ident->type;
12496         specifiers |= type->type & QUAL_MASK;
12497         if ((specifiers & (STOR_MASK | QUAL_MASK)) !=
12498                 (type->type & (STOR_MASK | QUAL_MASK))) {
12499                 type = clone_type(specifiers, type);
12500         }
12501         return type;
12502 }
12503
12504 static struct type *enum_specifier(
12505         struct compile_state *state, unsigned int spec)
12506 {
12507         struct hash_entry *ident;
12508         ulong_t base;
12509         int tok;
12510         struct type *enum_type;
12511         enum_type = 0;
12512         ident = 0;
12513         eat(state, TOK_ENUM);
12514         tok = peek(state);
12515         if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12516                 ident = eat(state, tok)->ident;
12517         }
12518         base = 0;
12519         if (!ident || (peek(state) == TOK_LBRACE)) {
12520                 struct type **next;
12521                 eat(state, TOK_LBRACE);
12522                 enum_type = new_type(TYPE_ENUM | spec, 0, 0);
12523                 enum_type->type_ident = ident;
12524                 next = &enum_type->right;
12525                 do {
12526                         struct hash_entry *eident;
12527                         struct triple *value;
12528                         struct type *entry;
12529                         eident = eat(state, TOK_IDENT)->ident;
12530                         if (eident->sym_ident) {
12531                                 error(state, 0, "%s already declared",
12532                                         eident->name);
12533                         }
12534                         eident->tok = TOK_ENUM_CONST;
12535                         if (peek(state) == TOK_EQ) {
12536                                 struct triple *val;
12537                                 eat(state, TOK_EQ);
12538                                 val = constant_expr(state);
12539                                 integral(state, val);
12540                                 base = val->u.cval;
12541                         }
12542                         value = int_const(state, &int_type, base);
12543                         symbol(state, eident, &eident->sym_ident, value, &int_type);
12544                         entry = new_type(TYPE_LIST, 0, 0);
12545                         entry->field_ident = eident;
12546                         *next = entry;
12547                         next = &entry->right;
12548                         base += 1;
12549                         if (peek(state) == TOK_COMMA) {
12550                                 eat(state, TOK_COMMA);
12551                         }
12552                 } while(peek(state) != TOK_RBRACE);
12553                 eat(state, TOK_RBRACE);
12554                 if (ident) {
12555                         symbol(state, ident, &ident->sym_tag, 0, enum_type);
12556                 }
12557         }
12558         if (ident && ident->sym_tag &&
12559                 ident->sym_tag->type &&
12560                 ((ident->sym_tag->type->type & TYPE_MASK) == TYPE_ENUM)) {
12561                 enum_type = clone_type(spec, ident->sym_tag->type);
12562         }
12563         else if (ident && !enum_type) {
12564                 error(state, 0, "enum %s undeclared", ident->name);
12565         }
12566         return enum_type;
12567 }
12568
12569 static struct type *struct_declarator(
12570         struct compile_state *state, struct type *type, struct hash_entry **ident)
12571 {
12572         if (peek(state) != TOK_COLON) {
12573                 type = declarator(state, type, ident, 1);
12574         }
12575         if (peek(state) == TOK_COLON) {
12576                 struct triple *value;
12577                 eat(state, TOK_COLON);
12578                 value = constant_expr(state);
12579                 if (value->op != OP_INTCONST) {
12580                         error(state, 0, "Invalid constant expression");
12581                 }
12582                 if (value->u.cval > size_of(state, type)) {
12583                         error(state, 0, "bitfield larger than base type");
12584                 }
12585                 if (!TYPE_INTEGER(type->type) || ((type->type & TYPE_MASK) == TYPE_BITFIELD)) {
12586                         error(state, 0, "bitfield base not an integer type");
12587                 }
12588                 type = new_type(TYPE_BITFIELD, type, 0);
12589                 type->elements = value->u.cval;
12590         }
12591         return type;
12592 }
12593
12594 static struct type *struct_or_union_specifier(
12595         struct compile_state *state, unsigned int spec)
12596 {
12597         struct type *struct_type;
12598         struct hash_entry *ident;
12599         unsigned int type_main;
12600         unsigned int type_join;
12601         int tok;
12602         struct_type = 0;
12603         ident = 0;
12604         switch(peek(state)) {
12605         case TOK_STRUCT:
12606                 eat(state, TOK_STRUCT);
12607                 type_main = TYPE_STRUCT;
12608                 type_join = TYPE_PRODUCT;
12609                 break;
12610         case TOK_UNION:
12611                 eat(state, TOK_UNION);
12612                 type_main = TYPE_UNION;
12613                 type_join = TYPE_OVERLAP;
12614                 break;
12615         default:
12616                 eat(state, TOK_STRUCT);
12617                 type_main = TYPE_STRUCT;
12618                 type_join = TYPE_PRODUCT;
12619                 break;
12620         }
12621         tok = peek(state);
12622         if ((tok == TOK_IDENT) || (tok == TOK_ENUM_CONST) || (tok == TOK_TYPE_NAME)) {
12623                 ident = eat(state, tok)->ident;
12624         }
12625         if (!ident || (peek(state) == TOK_LBRACE)) {
12626                 ulong_t elements;
12627                 struct type **next;
12628                 elements = 0;
12629                 eat(state, TOK_LBRACE);
12630                 next = &struct_type;
12631                 do {
12632                         struct type *base_type;
12633                         int done;
12634                         base_type = specifier_qualifier_list(state);
12635                         do {
12636                                 struct type *type;
12637                                 struct hash_entry *fident;
12638                                 done = 1;
12639                                 type = struct_declarator(state, base_type, &fident);
12640                                 elements++;
12641                                 if (peek(state) == TOK_COMMA) {
12642                                         done = 0;
12643                                         eat(state, TOK_COMMA);
12644                                 }
12645                                 type = clone_type(0, type);
12646                                 type->field_ident = fident;
12647                                 if (*next) {
12648                                         *next = new_type(type_join, *next, type);
12649                                         next = &((*next)->right);
12650                                 } else {
12651                                         *next = type;
12652                                 }
12653                         } while(!done);
12654                         eat(state, TOK_SEMI);
12655                 } while(peek(state) != TOK_RBRACE);
12656                 eat(state, TOK_RBRACE);
12657                 struct_type = new_type(type_main | spec, struct_type, 0);
12658                 struct_type->type_ident = ident;
12659                 struct_type->elements = elements;
12660                 if (ident) {
12661                         symbol(state, ident, &ident->sym_tag, 0, struct_type);
12662                 }
12663         }
12664         if (ident && ident->sym_tag &&
12665                 ident->sym_tag->type &&
12666                 ((ident->sym_tag->type->type & TYPE_MASK) == type_main)) {
12667                 struct_type = clone_type(spec, ident->sym_tag->type);
12668         }
12669         else if (ident && !struct_type) {
12670                 error(state, 0, "%s %s undeclared",
12671                         (type_main == TYPE_STRUCT)?"struct" : "union",
12672                         ident->name);
12673         }
12674         return struct_type;
12675 }
12676
12677 static unsigned int storage_class_specifier_opt(struct compile_state *state)
12678 {
12679         unsigned int specifiers;
12680         switch(peek(state)) {
12681         case TOK_AUTO:
12682                 eat(state, TOK_AUTO);
12683                 specifiers = STOR_AUTO;
12684                 break;
12685         case TOK_REGISTER:
12686                 eat(state, TOK_REGISTER);
12687                 specifiers = STOR_REGISTER;
12688                 break;
12689         case TOK_STATIC:
12690                 eat(state, TOK_STATIC);
12691                 specifiers = STOR_STATIC;
12692                 break;
12693         case TOK_EXTERN:
12694                 eat(state, TOK_EXTERN);
12695                 specifiers = STOR_EXTERN;
12696                 break;
12697         case TOK_TYPEDEF:
12698                 eat(state, TOK_TYPEDEF);
12699                 specifiers = STOR_TYPEDEF;
12700                 break;
12701         default:
12702                 if (state->scope_depth <= GLOBAL_SCOPE_DEPTH) {
12703                         specifiers = STOR_LOCAL;
12704                 }
12705                 else {
12706                         specifiers = STOR_AUTO;
12707                 }
12708         }
12709         return specifiers;
12710 }
12711
12712 static unsigned int function_specifier_opt(struct compile_state *state)
12713 {
12714         /* Ignore the inline keyword */
12715         unsigned int specifiers;
12716         specifiers = 0;
12717         switch(peek(state)) {
12718         case TOK_INLINE:
12719                 eat(state, TOK_INLINE);
12720                 specifiers = STOR_INLINE;
12721         }
12722         return specifiers;
12723 }
12724
12725 static unsigned int attrib(struct compile_state *state, unsigned int attributes)
12726 {
12727         int tok = peek(state);
12728         switch(tok) {
12729         case TOK_COMMA:
12730         case TOK_LPAREN:
12731                 /* The empty attribute ignore it */
12732                 break;
12733         case TOK_IDENT:
12734         case TOK_ENUM_CONST:
12735         case TOK_TYPE_NAME:
12736         {
12737                 struct hash_entry *ident;
12738                 ident = eat(state, TOK_IDENT)->ident;
12739
12740                 if (ident == state->i_noinline) {
12741                         if (attributes & ATTRIB_ALWAYS_INLINE) {
12742                                 error(state, 0, "both always_inline and noinline attribtes");
12743                         }
12744                         attributes |= ATTRIB_NOINLINE;
12745                 }
12746                 else if (ident == state->i_always_inline) {
12747                         if (attributes & ATTRIB_NOINLINE) {
12748                                 error(state, 0, "both noinline and always_inline attribtes");
12749                         }
12750                         attributes |= ATTRIB_ALWAYS_INLINE;
12751                 }
12752                 else if (ident == state->i_noreturn) {
12753                         // attribute((noreturn)) does nothing (yet?)
12754                 }
12755                 else {
12756                         error(state, 0, "Unknown attribute:%s", ident->name);
12757                 }
12758                 break;
12759         }
12760         default:
12761                 error(state, 0, "Unexpected token: %s\n", tokens[tok]);
12762                 break;
12763         }
12764         return attributes;
12765 }
12766
12767 static unsigned int attribute_list(struct compile_state *state, unsigned type)
12768 {
12769         type = attrib(state, type);
12770         while(peek(state) == TOK_COMMA) {
12771                 eat(state, TOK_COMMA);
12772                 type = attrib(state, type);
12773         }
12774         return type;
12775 }
12776
12777 static unsigned int attributes_opt(struct compile_state *state, unsigned type)
12778 {
12779         if (peek(state) == TOK_ATTRIBUTE) {
12780                 eat(state, TOK_ATTRIBUTE);
12781                 eat(state, TOK_LPAREN);
12782                 eat(state, TOK_LPAREN);
12783                 type = attribute_list(state, type);
12784                 eat(state, TOK_RPAREN);
12785                 eat(state, TOK_RPAREN);
12786         }
12787         return type;
12788 }
12789
12790 static unsigned int type_qualifiers(struct compile_state *state)
12791 {
12792         unsigned int specifiers;
12793         int done;
12794         done = 0;
12795         specifiers = QUAL_NONE;
12796         do {
12797                 switch(peek(state)) {
12798                 case TOK_CONST:
12799                         eat(state, TOK_CONST);
12800                         specifiers |= QUAL_CONST;
12801                         break;
12802                 case TOK_VOLATILE:
12803                         eat(state, TOK_VOLATILE);
12804                         specifiers |= QUAL_VOLATILE;
12805                         break;
12806                 case TOK_RESTRICT:
12807                         eat(state, TOK_RESTRICT);
12808                         specifiers |= QUAL_RESTRICT;
12809                         break;
12810                 default:
12811                         done = 1;
12812                         break;
12813                 }
12814         } while(!done);
12815         return specifiers;
12816 }
12817
12818 static struct type *type_specifier(
12819         struct compile_state *state, unsigned int spec)
12820 {
12821         struct type *type;
12822         int tok;
12823         type = 0;
12824         switch((tok = peek(state))) {
12825         case TOK_VOID:
12826                 eat(state, TOK_VOID);
12827                 type = new_type(TYPE_VOID | spec, 0, 0);
12828                 break;
12829         case TOK_CHAR:
12830                 eat(state, TOK_CHAR);
12831                 type = new_type(TYPE_CHAR | spec, 0, 0);
12832                 break;
12833         case TOK_SHORT:
12834                 eat(state, TOK_SHORT);
12835                 if (peek(state) == TOK_INT) {
12836                         eat(state, TOK_INT);
12837                 }
12838                 type = new_type(TYPE_SHORT | spec, 0, 0);
12839                 break;
12840         case TOK_INT:
12841                 eat(state, TOK_INT);
12842                 type = new_type(TYPE_INT | spec, 0, 0);
12843                 break;
12844         case TOK_LONG:
12845                 eat(state, TOK_LONG);
12846                 switch(peek(state)) {
12847                 case TOK_LONG:
12848                         eat(state, TOK_LONG);
12849                         error(state, 0, "long long not supported");
12850                         break;
12851                 case TOK_DOUBLE:
12852                         eat(state, TOK_DOUBLE);
12853                         error(state, 0, "long double not supported");
12854                         break;
12855                 case TOK_INT:
12856                         eat(state, TOK_INT);
12857                         type = new_type(TYPE_LONG | spec, 0, 0);
12858                         break;
12859                 default:
12860                         type = new_type(TYPE_LONG | spec, 0, 0);
12861                         break;
12862                 }
12863                 break;
12864         case TOK_FLOAT:
12865                 eat(state, TOK_FLOAT);
12866                 error(state, 0, "type float not supported");
12867                 break;
12868         case TOK_DOUBLE:
12869                 eat(state, TOK_DOUBLE);
12870                 error(state, 0, "type double not supported");
12871                 break;
12872         case TOK_SIGNED:
12873                 eat(state, TOK_SIGNED);
12874                 switch(peek(state)) {
12875                 case TOK_LONG:
12876                         eat(state, TOK_LONG);
12877                         switch(peek(state)) {
12878                         case TOK_LONG:
12879                                 eat(state, TOK_LONG);
12880                                 error(state, 0, "type long long not supported");
12881                                 break;
12882                         case TOK_INT:
12883                                 eat(state, TOK_INT);
12884                                 type = new_type(TYPE_LONG | spec, 0, 0);
12885                                 break;
12886                         default:
12887                                 type = new_type(TYPE_LONG | spec, 0, 0);
12888                                 break;
12889                         }
12890                         break;
12891                 case TOK_INT:
12892                         eat(state, TOK_INT);
12893                         type = new_type(TYPE_INT | spec, 0, 0);
12894                         break;
12895                 case TOK_SHORT:
12896                         eat(state, TOK_SHORT);
12897                         type = new_type(TYPE_SHORT | spec, 0, 0);
12898                         break;
12899                 case TOK_CHAR:
12900                         eat(state, TOK_CHAR);
12901                         type = new_type(TYPE_CHAR | spec, 0, 0);
12902                         break;
12903                 default:
12904                         type = new_type(TYPE_INT | spec, 0, 0);
12905                         break;
12906                 }
12907                 break;
12908         case TOK_UNSIGNED:
12909                 eat(state, TOK_UNSIGNED);
12910                 switch(peek(state)) {
12911                 case TOK_LONG:
12912                         eat(state, TOK_LONG);
12913                         switch(peek(state)) {
12914                         case TOK_LONG:
12915                                 eat(state, TOK_LONG);
12916                                 error(state, 0, "unsigned long long not supported");
12917                                 break;
12918                         case TOK_INT:
12919                                 eat(state, TOK_INT);
12920                                 type = new_type(TYPE_ULONG | spec, 0, 0);
12921                                 break;
12922                         default:
12923                                 type = new_type(TYPE_ULONG | spec, 0, 0);
12924                                 break;
12925                         }
12926                         break;
12927                 case TOK_INT:
12928                         eat(state, TOK_INT);
12929                         type = new_type(TYPE_UINT | spec, 0, 0);
12930                         break;
12931                 case TOK_SHORT:
12932                         eat(state, TOK_SHORT);
12933                         type = new_type(TYPE_USHORT | spec, 0, 0);
12934                         break;
12935                 case TOK_CHAR:
12936                         eat(state, TOK_CHAR);
12937                         type = new_type(TYPE_UCHAR | spec, 0, 0);
12938                         break;
12939                 default:
12940                         type = new_type(TYPE_UINT | spec, 0, 0);
12941                         break;
12942                 }
12943                 break;
12944                 /* struct or union specifier */
12945         case TOK_STRUCT:
12946         case TOK_UNION:
12947                 type = struct_or_union_specifier(state, spec);
12948                 break;
12949                 /* enum-spefifier */
12950         case TOK_ENUM:
12951                 type = enum_specifier(state, spec);
12952                 break;
12953                 /* typedef name */
12954         case TOK_TYPE_NAME:
12955                 type = typedef_name(state, spec);
12956                 break;
12957         default:
12958                 error(state, 0, "bad type specifier %s",
12959                         tokens[tok]);
12960                 break;
12961         }
12962         return type;
12963 }
12964
12965 static int istype(int tok)
12966 {
12967         switch(tok) {
12968         case TOK_CONST:
12969         case TOK_RESTRICT:
12970         case TOK_VOLATILE:
12971         case TOK_VOID:
12972         case TOK_CHAR:
12973         case TOK_SHORT:
12974         case TOK_INT:
12975         case TOK_LONG:
12976         case TOK_FLOAT:
12977         case TOK_DOUBLE:
12978         case TOK_SIGNED:
12979         case TOK_UNSIGNED:
12980         case TOK_STRUCT:
12981         case TOK_UNION:
12982         case TOK_ENUM:
12983         case TOK_TYPE_NAME:
12984                 return 1;
12985         default:
12986                 return 0;
12987         }
12988 }
12989
12990
12991 static struct type *specifier_qualifier_list(struct compile_state *state)
12992 {
12993         struct type *type;
12994         unsigned int specifiers = 0;
12995
12996         /* type qualifiers */
12997         specifiers |= type_qualifiers(state);
12998
12999         /* type specifier */
13000         type = type_specifier(state, specifiers);
13001
13002         return type;
13003 }
13004
13005 #if DEBUG_ROMCC_WARNING
13006 static int isdecl_specifier(int tok)
13007 {
13008         switch(tok) {
13009                 /* storage class specifier */
13010         case TOK_AUTO:
13011         case TOK_REGISTER:
13012         case TOK_STATIC:
13013         case TOK_EXTERN:
13014         case TOK_TYPEDEF:
13015                 /* type qualifier */
13016         case TOK_CONST:
13017         case TOK_RESTRICT:
13018         case TOK_VOLATILE:
13019                 /* type specifiers */
13020         case TOK_VOID:
13021         case TOK_CHAR:
13022         case TOK_SHORT:
13023         case TOK_INT:
13024         case TOK_LONG:
13025         case TOK_FLOAT:
13026         case TOK_DOUBLE:
13027         case TOK_SIGNED:
13028         case TOK_UNSIGNED:
13029                 /* struct or union specifier */
13030         case TOK_STRUCT:
13031         case TOK_UNION:
13032                 /* enum-spefifier */
13033         case TOK_ENUM:
13034                 /* typedef name */
13035         case TOK_TYPE_NAME:
13036                 /* function specifiers */
13037         case TOK_INLINE:
13038                 return 1;
13039         default:
13040                 return 0;
13041         }
13042 }
13043 #endif
13044
13045 static struct type *decl_specifiers(struct compile_state *state)
13046 {
13047         struct type *type;
13048         unsigned int specifiers;
13049         /* I am overly restrictive in the arragement of specifiers supported.
13050          * C is overly flexible in this department it makes interpreting
13051          * the parse tree difficult.
13052          */
13053         specifiers = 0;
13054
13055         /* storage class specifier */
13056         specifiers |= storage_class_specifier_opt(state);
13057
13058         /* function-specifier */
13059         specifiers |= function_specifier_opt(state);
13060
13061         /* attributes */
13062         specifiers |= attributes_opt(state, 0);
13063
13064         /* type qualifier */
13065         specifiers |= type_qualifiers(state);
13066
13067         /* type specifier */
13068         type = type_specifier(state, specifiers);
13069         return type;
13070 }
13071
13072 struct field_info {
13073         struct type *type;
13074         size_t offset;
13075 };
13076
13077 static struct field_info designator(struct compile_state *state, struct type *type)
13078 {
13079         int tok;
13080         struct field_info info;
13081         info.offset = ~0U;
13082         info.type = 0;
13083         do {
13084                 switch(peek(state)) {
13085                 case TOK_LBRACKET:
13086                 {
13087                         struct triple *value;
13088                         if ((type->type & TYPE_MASK) != TYPE_ARRAY) {
13089                                 error(state, 0, "Array designator not in array initializer");
13090                         }
13091                         eat(state, TOK_LBRACKET);
13092                         value = constant_expr(state);
13093                         eat(state, TOK_RBRACKET);
13094
13095                         info.type = type->left;
13096                         info.offset = value->u.cval * size_of(state, info.type);
13097                         break;
13098                 }
13099                 case TOK_DOT:
13100                 {
13101                         struct hash_entry *field;
13102                         if (((type->type & TYPE_MASK) != TYPE_STRUCT) &&
13103                                 ((type->type & TYPE_MASK) != TYPE_UNION))
13104                         {
13105                                 error(state, 0, "Struct designator not in struct initializer");
13106                         }
13107                         eat(state, TOK_DOT);
13108                         field = eat(state, TOK_IDENT)->ident;
13109                         info.offset = field_offset(state, type, field);
13110                         info.type   = field_type(state, type, field);
13111                         break;
13112                 }
13113                 default:
13114                         error(state, 0, "Invalid designator");
13115                 }
13116                 tok = peek(state);
13117         } while((tok == TOK_LBRACKET) || (tok == TOK_DOT));
13118         eat(state, TOK_EQ);
13119         return info;
13120 }
13121
13122 static struct triple *initializer(
13123         struct compile_state *state, struct type *type)
13124 {
13125         struct triple *result;
13126 #if DEBUG_ROMCC_WARNINGS
13127 #warning "FIXME more consistent initializer handling (where should eval_const_expr go?"
13128 #endif
13129         if (peek(state) != TOK_LBRACE) {
13130                 result = assignment_expr(state);
13131                 if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13132                         (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13133                         ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13134                         (result->type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13135                         (equiv_types(type->left, result->type->left))) {
13136                         type->elements = result->type->elements;
13137                 }
13138                 if (is_lvalue(state, result) &&
13139                         ((result->type->type & TYPE_MASK) == TYPE_ARRAY) &&
13140                         (type->type & TYPE_MASK) != TYPE_ARRAY)
13141                 {
13142                         result = lvalue_conversion(state, result);
13143                 }
13144                 if (!is_init_compatible(state, type, result->type)) {
13145                         error(state, 0, "Incompatible types in initializer");
13146                 }
13147                 if (!equiv_types(type, result->type)) {
13148                         result = mk_cast_expr(state, type, result);
13149                 }
13150         }
13151         else {
13152                 int comma;
13153                 size_t max_offset;
13154                 struct field_info info;
13155                 void *buf;
13156                 if (((type->type & TYPE_MASK) != TYPE_ARRAY) &&
13157                         ((type->type & TYPE_MASK) != TYPE_STRUCT)) {
13158                         internal_error(state, 0, "unknown initializer type");
13159                 }
13160                 info.offset = 0;
13161                 info.type = type->left;
13162                 if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13163                         info.type = next_field(state, type, 0);
13164                 }
13165                 if (type->elements == ELEMENT_COUNT_UNSPECIFIED) {
13166                         max_offset = 0;
13167                 } else {
13168                         max_offset = size_of(state, type);
13169                 }
13170                 buf = xcmalloc(bits_to_bytes(max_offset), "initializer");
13171                 eat(state, TOK_LBRACE);
13172                 do {
13173                         struct triple *value;
13174                         struct type *value_type;
13175                         size_t value_size;
13176                         void *dest;
13177                         int tok;
13178                         comma = 0;
13179                         tok = peek(state);
13180                         if ((tok == TOK_LBRACKET) || (tok == TOK_DOT)) {
13181                                 info = designator(state, type);
13182                         }
13183                         if ((type->elements != ELEMENT_COUNT_UNSPECIFIED) &&
13184                                 (info.offset >= max_offset)) {
13185                                 error(state, 0, "element beyond bounds");
13186                         }
13187                         value_type = info.type;
13188                         value = eval_const_expr(state, initializer(state, value_type));
13189                         value_size = size_of(state, value_type);
13190                         if (((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13191                                 (type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13192                                 (max_offset <= info.offset)) {
13193                                 void *old_buf;
13194                                 size_t old_size;
13195                                 old_buf = buf;
13196                                 old_size = max_offset;
13197                                 max_offset = info.offset + value_size;
13198                                 buf = xmalloc(bits_to_bytes(max_offset), "initializer");
13199                                 memcpy(buf, old_buf, bits_to_bytes(old_size));
13200                                 xfree(old_buf);
13201                         }
13202                         dest = ((char *)buf) + bits_to_bytes(info.offset);
13203 #if DEBUG_INITIALIZER
13204                         fprintf(state->errout, "dest = buf + %d max_offset: %d value_size: %d op: %d\n",
13205                                 dest - buf,
13206                                 bits_to_bytes(max_offset),
13207                                 bits_to_bytes(value_size),
13208                                 value->op);
13209 #endif
13210                         if (value->op == OP_BLOBCONST) {
13211                                 memcpy(dest, value->u.blob, bits_to_bytes(value_size));
13212                         }
13213                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I8)) {
13214 #if DEBUG_INITIALIZER
13215                                 fprintf(state->errout, "byte: %02x\n", value->u.cval & 0xff);
13216 #endif
13217                                 *((uint8_t *)dest) = value->u.cval & 0xff;
13218                         }
13219                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I16)) {
13220                                 *((uint16_t *)dest) = value->u.cval & 0xffff;
13221                         }
13222                         else if ((value->op == OP_INTCONST) && (value_size == SIZEOF_I32)) {
13223                                 *((uint32_t *)dest) = value->u.cval & 0xffffffff;
13224                         }
13225                         else {
13226                                 internal_error(state, 0, "unhandled constant initializer");
13227                         }
13228                         free_triple(state, value);
13229                         if (peek(state) == TOK_COMMA) {
13230                                 eat(state, TOK_COMMA);
13231                                 comma = 1;
13232                         }
13233                         info.offset += value_size;
13234                         if ((type->type & TYPE_MASK) == TYPE_STRUCT) {
13235                                 info.type = next_field(state, type, info.type);
13236                                 info.offset = field_offset(state, type,
13237                                         info.type->field_ident);
13238                         }
13239                 } while(comma && (peek(state) != TOK_RBRACE));
13240                 if ((type->elements == ELEMENT_COUNT_UNSPECIFIED) &&
13241                         ((type->type & TYPE_MASK) == TYPE_ARRAY)) {
13242                         type->elements = max_offset / size_of(state, type->left);
13243                 }
13244                 eat(state, TOK_RBRACE);
13245                 result = triple(state, OP_BLOBCONST, type, 0, 0);
13246                 result->u.blob = buf;
13247         }
13248         return result;
13249 }
13250
13251 static void resolve_branches(struct compile_state *state, struct triple *first)
13252 {
13253         /* Make a second pass and finish anything outstanding
13254          * with respect to branches.  The only outstanding item
13255          * is to see if there are goto to labels that have not
13256          * been defined and to error about them.
13257          */
13258         int i;
13259         struct triple *ins;
13260         /* Also error on branches that do not use their targets */
13261         ins = first;
13262         do {
13263                 if (!triple_is_ret(state, ins)) {
13264                         struct triple **expr ;
13265                         struct triple_set *set;
13266                         expr = triple_targ(state, ins, 0);
13267                         for(; expr; expr = triple_targ(state, ins, expr)) {
13268                                 struct triple *targ;
13269                                 targ = *expr;
13270                                 for(set = targ?targ->use:0; set; set = set->next) {
13271                                         if (set->member == ins) {
13272                                                 break;
13273                                         }
13274                                 }
13275                                 if (!set) {
13276                                         internal_error(state, ins, "targ not used");
13277                                 }
13278                         }
13279                 }
13280                 ins = ins->next;
13281         } while(ins != first);
13282         /* See if there are goto to labels that have not been defined */
13283         for(i = 0; i < HASH_TABLE_SIZE; i++) {
13284                 struct hash_entry *entry;
13285                 for(entry = state->hash_table[i]; entry; entry = entry->next) {
13286                         struct triple *ins;
13287                         if (!entry->sym_label) {
13288                                 continue;
13289                         }
13290                         ins = entry->sym_label->def;
13291                         if (!(ins->id & TRIPLE_FLAG_FLATTENED)) {
13292                                 error(state, ins, "label `%s' used but not defined",
13293                                         entry->name);
13294                         }
13295                 }
13296         }
13297 }
13298
13299 static struct triple *function_definition(
13300         struct compile_state *state, struct type *type)
13301 {
13302         struct triple *def, *tmp, *first, *end, *retvar, *ret;
13303         struct triple *fname;
13304         struct type *fname_type;
13305         struct hash_entry *ident;
13306         struct type *param, *crtype, *ctype;
13307         int i;
13308         if ((type->type &TYPE_MASK) != TYPE_FUNCTION) {
13309                 error(state, 0, "Invalid function header");
13310         }
13311
13312         /* Verify the function type */
13313         if (((type->right->type & TYPE_MASK) != TYPE_VOID)  &&
13314                 ((type->right->type & TYPE_MASK) != TYPE_PRODUCT) &&
13315                 (type->right->field_ident == 0)) {
13316                 error(state, 0, "Invalid function parameters");
13317         }
13318         param = type->right;
13319         i = 0;
13320         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13321                 i++;
13322                 if (!param->left->field_ident) {
13323                         error(state, 0, "No identifier for parameter %d\n", i);
13324                 }
13325                 param = param->right;
13326         }
13327         i++;
13328         if (((param->type & TYPE_MASK) != TYPE_VOID) && !param->field_ident) {
13329                 error(state, 0, "No identifier for paramter %d\n", i);
13330         }
13331
13332         /* Get a list of statements for this function. */
13333         def = triple(state, OP_LIST, type, 0, 0);
13334
13335         /* Start a new scope for the passed parameters */
13336         start_scope(state);
13337
13338         /* Put a label at the very start of a function */
13339         first = label(state);
13340         RHS(def, 0) = first;
13341
13342         /* Put a label at the very end of a function */
13343         end = label(state);
13344         flatten(state, first, end);
13345         /* Remember where return goes */
13346         ident = state->i_return;
13347         symbol(state, ident, &ident->sym_ident, end, end->type);
13348
13349         /* Get the initial closure type */
13350         ctype = new_type(TYPE_JOIN, &void_type, 0);
13351         ctype->elements = 1;
13352
13353         /* Add a variable for the return value */
13354         crtype = new_type(TYPE_TUPLE,
13355                 /* Remove all type qualifiers from the return type */
13356                 new_type(TYPE_PRODUCT, ctype, clone_type(0, type->left)), 0);
13357         crtype->elements = 2;
13358         flatten(state, end, variable(state, crtype));
13359
13360         /* Allocate a variable for the return address */
13361         retvar = flatten(state, end, variable(state, &void_ptr_type));
13362
13363         /* Add in the return instruction */
13364         ret = triple(state, OP_RET, &void_type, read_expr(state, retvar), 0);
13365         ret = flatten(state, first, ret);
13366
13367         /* Walk through the parameters and create symbol table entries
13368          * for them.
13369          */
13370         param = type->right;
13371         while((param->type & TYPE_MASK) == TYPE_PRODUCT) {
13372                 ident = param->left->field_ident;
13373                 tmp = variable(state, param->left);
13374                 var_symbol(state, ident, tmp);
13375                 flatten(state, end, tmp);
13376                 param = param->right;
13377         }
13378         if ((param->type & TYPE_MASK) != TYPE_VOID) {
13379                 /* And don't forget the last parameter */
13380                 ident = param->field_ident;
13381                 tmp = variable(state, param);
13382                 symbol(state, ident, &ident->sym_ident, tmp, tmp->type);
13383                 flatten(state, end, tmp);
13384         }
13385
13386         /* Add the declaration static const char __func__ [] = "func-name"  */
13387         fname_type = new_type(TYPE_ARRAY,
13388                 clone_type(QUAL_CONST | STOR_STATIC, &char_type), 0);
13389         fname_type->type |= QUAL_CONST | STOR_STATIC;
13390         fname_type->elements = strlen(state->function) + 1;
13391
13392         fname = triple(state, OP_BLOBCONST, fname_type, 0, 0);
13393         fname->u.blob = (void *)state->function;
13394         fname = flatten(state, end, fname);
13395
13396         ident = state->i___func__;
13397         symbol(state, ident, &ident->sym_ident, fname, fname_type);
13398
13399         /* Remember which function I am compiling.
13400          * Also assume the last defined function is the main function.
13401          */
13402         state->main_function = def;
13403
13404         /* Now get the actual function definition */
13405         compound_statement(state, end);
13406
13407         /* Finish anything unfinished with branches */
13408         resolve_branches(state, first);
13409
13410         /* Remove the parameter scope */
13411         end_scope(state);
13412
13413
13414         /* Remember I have defined a function */
13415         if (!state->functions) {
13416                 state->functions = def;
13417         } else {
13418                 insert_triple(state, state->functions, def);
13419         }
13420         if (state->compiler->debug & DEBUG_INLINE) {
13421                 FILE *fp = state->dbgout;
13422                 fprintf(fp, "\n");
13423                 loc(fp, state, 0);
13424                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13425                 display_func(state, fp, def);
13426                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13427         }
13428
13429         return def;
13430 }
13431
13432 static struct triple *do_decl(struct compile_state *state,
13433         struct type *type, struct hash_entry *ident)
13434 {
13435         struct triple *def;
13436         def = 0;
13437         /* Clean up the storage types used */
13438         switch (type->type & STOR_MASK) {
13439         case STOR_AUTO:
13440         case STOR_STATIC:
13441                 /* These are the good types I am aiming for */
13442                 break;
13443         case STOR_REGISTER:
13444                 type->type &= ~STOR_MASK;
13445                 type->type |= STOR_AUTO;
13446                 break;
13447         case STOR_LOCAL:
13448         case STOR_EXTERN:
13449                 type->type &= ~STOR_MASK;
13450                 type->type |= STOR_STATIC;
13451                 break;
13452         case STOR_TYPEDEF:
13453                 if (!ident) {
13454                         error(state, 0, "typedef without name");
13455                 }
13456                 symbol(state, ident, &ident->sym_ident, 0, type);
13457                 ident->tok = TOK_TYPE_NAME;
13458                 return 0;
13459                 break;
13460         default:
13461                 internal_error(state, 0, "Undefined storage class");
13462         }
13463         if ((type->type & TYPE_MASK) == TYPE_FUNCTION) {
13464                 error(state, 0, "Function prototypes not supported");
13465         }
13466         if (ident &&
13467                 ((type->type & TYPE_MASK) == TYPE_ARRAY) &&
13468                 ((type->type & STOR_MASK) != STOR_STATIC))
13469                 error(state, 0, "non static arrays not supported");
13470         if (ident &&
13471                 ((type->type & STOR_MASK) == STOR_STATIC) &&
13472                 ((type->type & QUAL_CONST) == 0)) {
13473                 error(state, 0, "non const static variables not supported");
13474         }
13475         if (ident) {
13476                 def = variable(state, type);
13477                 var_symbol(state, ident, def);
13478         }
13479         return def;
13480 }
13481
13482 static void decl(struct compile_state *state, struct triple *first)
13483 {
13484         struct type *base_type, *type;
13485         struct hash_entry *ident;
13486         struct triple *def;
13487         int global;
13488         global = (state->scope_depth <= GLOBAL_SCOPE_DEPTH);
13489         base_type = decl_specifiers(state);
13490         ident = 0;
13491         type = declarator(state, base_type, &ident, 0);
13492         type->type = attributes_opt(state, type->type);
13493         if (global && ident && (peek(state) == TOK_LBRACE)) {
13494                 /* function */
13495                 type->type_ident = ident;
13496                 state->function = ident->name;
13497                 def = function_definition(state, type);
13498                 symbol(state, ident, &ident->sym_ident, def, type);
13499                 state->function = 0;
13500         }
13501         else {
13502                 int done;
13503                 flatten(state, first, do_decl(state, type, ident));
13504                 /* type or variable definition */
13505                 do {
13506                         done = 1;
13507                         if (peek(state) == TOK_EQ) {
13508                                 if (!ident) {
13509                                         error(state, 0, "cannot assign to a type");
13510                                 }
13511                                 eat(state, TOK_EQ);
13512                                 flatten(state, first,
13513                                         init_expr(state,
13514                                                 ident->sym_ident->def,
13515                                                 initializer(state, type)));
13516                         }
13517                         arrays_complete(state, type);
13518                         if (peek(state) == TOK_COMMA) {
13519                                 eat(state, TOK_COMMA);
13520                                 ident = 0;
13521                                 type = declarator(state, base_type, &ident, 0);
13522                                 flatten(state, first, do_decl(state, type, ident));
13523                                 done = 0;
13524                         }
13525                 } while(!done);
13526                 eat(state, TOK_SEMI);
13527         }
13528 }
13529
13530 static void decls(struct compile_state *state)
13531 {
13532         struct triple *list;
13533         int tok;
13534         list = label(state);
13535         while(1) {
13536                 tok = peek(state);
13537                 if (tok == TOK_EOF) {
13538                         return;
13539                 }
13540                 if (tok == TOK_SPACE) {
13541                         eat(state, TOK_SPACE);
13542                 }
13543                 decl(state, list);
13544                 if (list->next != list) {
13545                         error(state, 0, "global variables not supported");
13546                 }
13547         }
13548 }
13549
13550 /*
13551  * Function inlining
13552  */
13553 struct triple_reg_set {
13554         struct triple_reg_set *next;
13555         struct triple *member;
13556         struct triple *new;
13557 };
13558 struct reg_block {
13559         struct block *block;
13560         struct triple_reg_set *in;
13561         struct triple_reg_set *out;
13562         int vertex;
13563 };
13564 static void setup_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13565 static void analyze_basic_blocks(struct compile_state *state, struct basic_blocks *bb);
13566 static void free_basic_blocks(struct compile_state *, struct basic_blocks *bb);
13567 static int tdominates(struct compile_state *state, struct triple *dom, struct triple *sub);
13568 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
13569         void (*cb)(struct compile_state *state, struct block *block, void *arg),
13570         void *arg);
13571 static void print_block(
13572         struct compile_state *state, struct block *block, void *arg);
13573 static int do_triple_set(struct triple_reg_set **head,
13574         struct triple *member, struct triple *new_member);
13575 static void do_triple_unset(struct triple_reg_set **head, struct triple *member);
13576 static struct reg_block *compute_variable_lifetimes(
13577         struct compile_state *state, struct basic_blocks *bb);
13578 static void free_variable_lifetimes(struct compile_state *state,
13579         struct basic_blocks *bb, struct reg_block *blocks);
13580 #if DEBUG_EXPLICIT_CLOSURES
13581 static void print_live_variables(struct compile_state *state,
13582         struct basic_blocks *bb, struct reg_block *rb, FILE *fp);
13583 #endif
13584
13585
13586 static struct triple *call(struct compile_state *state,
13587         struct triple *retvar, struct triple *ret_addr,
13588         struct triple *targ, struct triple *ret)
13589 {
13590         struct triple *call;
13591
13592         if (!retvar || !is_lvalue(state, retvar)) {
13593                 internal_error(state, 0, "writing to a non lvalue?");
13594         }
13595         write_compatible(state, retvar->type, &void_ptr_type);
13596
13597         call = new_triple(state, OP_CALL, &void_type, 1, 0);
13598         TARG(call, 0) = targ;
13599         MISC(call, 0) = ret;
13600         if (!targ || (targ->op != OP_LABEL)) {
13601                 internal_error(state, 0, "call not to a label");
13602         }
13603         if (!ret || (ret->op != OP_RET)) {
13604                 internal_error(state, 0, "call not matched with return");
13605         }
13606         return call;
13607 }
13608
13609 static void walk_functions(struct compile_state *state,
13610         void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13611         void *arg)
13612 {
13613         struct triple *func, *first;
13614         func = first = state->functions;
13615         do {
13616                 cb(state, func, arg);
13617                 func = func->next;
13618         } while(func != first);
13619 }
13620
13621 static void reverse_walk_functions(struct compile_state *state,
13622         void (*cb)(struct compile_state *state, struct triple *func, void *arg),
13623         void *arg)
13624 {
13625         struct triple *func, *first;
13626         func = first = state->functions;
13627         do {
13628                 func = func->prev;
13629                 cb(state, func, arg);
13630         } while(func != first);
13631 }
13632
13633
13634 static void mark_live(struct compile_state *state, struct triple *func, void *arg)
13635 {
13636         struct triple *ptr, *first;
13637         if (func->u.cval == 0) {
13638                 return;
13639         }
13640         ptr = first = RHS(func, 0);
13641         do {
13642                 if (ptr->op == OP_FCALL) {
13643                         struct triple *called_func;
13644                         called_func = MISC(ptr, 0);
13645                         /* Mark the called function as used */
13646                         if (!(func->id & TRIPLE_FLAG_FLATTENED)) {
13647                                 called_func->u.cval++;
13648                         }
13649                         /* Remove the called function from the list */
13650                         called_func->prev->next = called_func->next;
13651                         called_func->next->prev = called_func->prev;
13652
13653                         /* Place the called function before me on the list */
13654                         called_func->next       = func;
13655                         called_func->prev       = func->prev;
13656                         called_func->prev->next = called_func;
13657                         called_func->next->prev = called_func;
13658                 }
13659                 ptr = ptr->next;
13660         } while(ptr != first);
13661         func->id |= TRIPLE_FLAG_FLATTENED;
13662 }
13663
13664 static void mark_live_functions(struct compile_state *state)
13665 {
13666         /* Ensure state->main_function is the last function in
13667          * the list of functions.
13668          */
13669         if ((state->main_function->next != state->functions) ||
13670                 (state->functions->prev != state->main_function)) {
13671                 internal_error(state, 0,
13672                         "state->main_function is not at the end of the function list ");
13673         }
13674         state->main_function->u.cval = 1;
13675         reverse_walk_functions(state, mark_live, 0);
13676 }
13677
13678 static int local_triple(struct compile_state *state,
13679         struct triple *func, struct triple *ins)
13680 {
13681         int local = (ins->id & TRIPLE_FLAG_LOCAL);
13682 #if 0
13683         if (!local) {
13684                 FILE *fp = state->errout;
13685                 fprintf(fp, "global: ");
13686                 display_triple(fp, ins);
13687         }
13688 #endif
13689         return local;
13690 }
13691
13692 struct triple *copy_func(struct compile_state *state, struct triple *ofunc,
13693         struct occurance *base_occurance)
13694 {
13695         struct triple *nfunc;
13696         struct triple *nfirst, *ofirst;
13697         struct triple *new, *old;
13698
13699         if (state->compiler->debug & DEBUG_INLINE) {
13700                 FILE *fp = state->dbgout;
13701                 fprintf(fp, "\n");
13702                 loc(fp, state, 0);
13703                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13704                 display_func(state, fp, ofunc);
13705                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13706         }
13707
13708         /* Make a new copy of the old function */
13709         nfunc = triple(state, OP_LIST, ofunc->type, 0, 0);
13710         nfirst = 0;
13711         ofirst = old = RHS(ofunc, 0);
13712         do {
13713                 struct triple *new;
13714                 struct occurance *occurance;
13715                 int old_lhs, old_rhs;
13716                 old_lhs = old->lhs;
13717                 old_rhs = old->rhs;
13718                 occurance = inline_occurance(state, base_occurance, old->occurance);
13719                 if (ofunc->u.cval && (old->op == OP_FCALL)) {
13720                         MISC(old, 0)->u.cval += 1;
13721                 }
13722                 new = alloc_triple(state, old->op, old->type, old_lhs, old_rhs,
13723                         occurance);
13724                 if (!triple_stores_block(state, new)) {
13725                         memcpy(&new->u, &old->u, sizeof(new->u));
13726                 }
13727                 if (!nfirst) {
13728                         RHS(nfunc, 0) = nfirst = new;
13729                 }
13730                 else {
13731                         insert_triple(state, nfirst, new);
13732                 }
13733                 new->id |= TRIPLE_FLAG_FLATTENED;
13734                 new->id |= old->id & TRIPLE_FLAG_COPY;
13735
13736                 /* During the copy remember new as user of old */
13737                 use_triple(old, new);
13738
13739                 /* Remember which instructions are local */
13740                 old->id |= TRIPLE_FLAG_LOCAL;
13741                 old = old->next;
13742         } while(old != ofirst);
13743
13744         /* Make a second pass to fix up any unresolved references */
13745         old = ofirst;
13746         new = nfirst;
13747         do {
13748                 struct triple **oexpr, **nexpr;
13749                 int count, i;
13750                 /* Lookup where the copy is, to join pointers */
13751                 count = TRIPLE_SIZE(old);
13752                 for(i = 0; i < count; i++) {
13753                         oexpr = &old->param[i];
13754                         nexpr = &new->param[i];
13755                         if (*oexpr && !*nexpr) {
13756                                 if (!local_triple(state, ofunc, *oexpr)) {
13757                                         *nexpr = *oexpr;
13758                                 }
13759                                 else if ((*oexpr)->use) {
13760                                         *nexpr = (*oexpr)->use->member;
13761                                 }
13762                                 if (*nexpr == old) {
13763                                         internal_error(state, 0, "new == old?");
13764                                 }
13765                                 use_triple(*nexpr, new);
13766                         }
13767                         if (!*nexpr && *oexpr) {
13768                                 internal_error(state, 0, "Could not copy %d", i);
13769                         }
13770                 }
13771                 old = old->next;
13772                 new = new->next;
13773         } while((old != ofirst) && (new != nfirst));
13774
13775         /* Make a third pass to cleanup the extra useses */
13776         old = ofirst;
13777         new = nfirst;
13778         do {
13779                 unuse_triple(old, new);
13780                 /* Forget which instructions are local */
13781                 old->id &= ~TRIPLE_FLAG_LOCAL;
13782                 old = old->next;
13783                 new = new->next;
13784         } while ((old != ofirst) && (new != nfirst));
13785         return nfunc;
13786 }
13787
13788 static void expand_inline_call(
13789         struct compile_state *state, struct triple *me, struct triple *fcall)
13790 {
13791         /* Inline the function call */
13792         struct type *ptype;
13793         struct triple *ofunc, *nfunc, *nfirst, *result, *retvar, *ins;
13794         struct triple *end, *nend;
13795         int pvals, i;
13796
13797         /* Find the triples */
13798         ofunc = MISC(fcall, 0);
13799         if (ofunc->op != OP_LIST) {
13800                 internal_error(state, 0, "improper function");
13801         }
13802         nfunc = copy_func(state, ofunc, fcall->occurance);
13803         /* Prepend the parameter reading into the new function list */
13804         ptype = nfunc->type->right;
13805         pvals = fcall->rhs;
13806         for(i = 0; i < pvals; i++) {
13807                 struct type *atype;
13808                 struct triple *arg, *param;
13809                 atype = ptype;
13810                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
13811                         atype = ptype->left;
13812                 }
13813                 param = farg(state, nfunc, i);
13814                 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
13815                         internal_error(state, fcall, "param %d type mismatch", i);
13816                 }
13817                 arg = RHS(fcall, i);
13818                 flatten(state, fcall, write_expr(state, param, arg));
13819                 ptype = ptype->right;
13820         }
13821         result = 0;
13822         if ((nfunc->type->left->type & TYPE_MASK) != TYPE_VOID) {
13823                 result = read_expr(state,
13824                         deref_index(state, fresult(state, nfunc), 1));
13825         }
13826         if (state->compiler->debug & DEBUG_INLINE) {
13827                 FILE *fp = state->dbgout;
13828                 fprintf(fp, "\n");
13829                 loc(fp, state, 0);
13830                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
13831                 display_func(state, fp, nfunc);
13832                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
13833         }
13834
13835         /*
13836          * Get rid of the extra triples
13837          */
13838         /* Remove the read of the return address */
13839         ins = RHS(nfunc, 0)->prev->prev;
13840         if ((ins->op != OP_READ) || (RHS(ins, 0) != fretaddr(state, nfunc))) {
13841                 internal_error(state, ins, "Not return addres read?");
13842         }
13843         release_triple(state, ins);
13844         /* Remove the return instruction */
13845         ins = RHS(nfunc, 0)->prev;
13846         if (ins->op != OP_RET) {
13847                 internal_error(state, ins, "Not return?");
13848         }
13849         release_triple(state, ins);
13850         /* Remove the retaddres variable */
13851         retvar = fretaddr(state, nfunc);
13852         if ((retvar->lhs != 1) ||
13853                 (retvar->op != OP_ADECL) ||
13854                 (retvar->next->op != OP_PIECE) ||
13855                 (MISC(retvar->next, 0) != retvar)) {
13856                 internal_error(state, retvar, "Not the return address?");
13857         }
13858         release_triple(state, retvar->next);
13859         release_triple(state, retvar);
13860
13861         /* Remove the label at the start of the function */
13862         ins = RHS(nfunc, 0);
13863         if (ins->op != OP_LABEL) {
13864                 internal_error(state, ins, "Not label?");
13865         }
13866         nfirst = ins->next;
13867         free_triple(state, ins);
13868         /* Release the new function header */
13869         RHS(nfunc, 0) = 0;
13870         free_triple(state, nfunc);
13871
13872         /* Append the new function list onto the return list */
13873         end = fcall->prev;
13874         nend = nfirst->prev;
13875         end->next    = nfirst;
13876         nfirst->prev = end;
13877         nend->next   = fcall;
13878         fcall->prev  = nend;
13879
13880         /* Now the result reading code */
13881         if (result) {
13882                 result = flatten(state, fcall, result);
13883                 propogate_use(state, fcall, result);
13884         }
13885
13886         /* Release the original fcall instruction */
13887         release_triple(state, fcall);
13888
13889         return;
13890 }
13891
13892 /*
13893  *
13894  * Type of the result variable.
13895  *
13896  *                                     result
13897  *                                        |
13898  *                             +----------+------------+
13899  *                             |                       |
13900  *                     union of closures         result_type
13901  *                             |
13902  *          +------------------+---------------+
13903  *          |                                  |
13904  *       closure1                    ...   closuerN
13905  *          |                                  |
13906  *  +----+--+-+--------+-----+       +----+----+---+-----+
13907  *  |    |    |        |     |       |    |        |     |
13908  * var1 var2 var3 ... varN result   var1 var2 ... varN result
13909  *                           |
13910  *                  +--------+---------+
13911  *                  |                  |
13912  *          union of closures     result_type
13913  *                  |
13914  *            +-----+-------------------+
13915  *            |                         |
13916  *         closure1            ...  closureN
13917  *            |                         |
13918  *  +-----+---+----+----+      +----+---+----+-----+
13919  *  |     |        |    |      |    |        |     |
13920  * var1 var2 ... varN result  var1 var2 ... varN result
13921  */
13922
13923 static int add_closure_type(struct compile_state *state,
13924         struct triple *func, struct type *closure_type)
13925 {
13926         struct type *type, *ctype, **next;
13927         struct triple *var, *new_var;
13928         int i;
13929
13930 #if 0
13931         FILE *fp = state->errout;
13932         fprintf(fp, "original_type: ");
13933         name_of(fp, fresult(state, func)->type);
13934         fprintf(fp, "\n");
13935 #endif
13936         /* find the original type */
13937         var = fresult(state, func);
13938         type = var->type;
13939         if (type->elements != 2) {
13940                 internal_error(state, var, "bad return type");
13941         }
13942
13943         /* Find the complete closure type and update it */
13944         ctype = type->left->left;
13945         next = &ctype->left;
13946         while(((*next)->type & TYPE_MASK) == TYPE_OVERLAP) {
13947                 next = &(*next)->right;
13948         }
13949         *next = new_type(TYPE_OVERLAP, *next, dup_type(state, closure_type));
13950         ctype->elements += 1;
13951
13952 #if 0
13953         fprintf(fp, "new_type: ");
13954         name_of(fp, type);
13955         fprintf(fp, "\n");
13956         fprintf(fp, "ctype: %p %d bits: %d ",
13957                 ctype, ctype->elements, reg_size_of(state, ctype));
13958         name_of(fp, ctype);
13959         fprintf(fp, "\n");
13960 #endif
13961
13962         /* Regenerate the variable with the new type definition */
13963         new_var = pre_triple(state, var, OP_ADECL, type, 0, 0);
13964         new_var->id |= TRIPLE_FLAG_FLATTENED;
13965         for(i = 0; i < new_var->lhs; i++) {
13966                 LHS(new_var, i)->id |= TRIPLE_FLAG_FLATTENED;
13967         }
13968
13969         /* Point everyone at the new variable */
13970         propogate_use(state, var, new_var);
13971
13972         /* Release the original variable */
13973         for(i = 0; i < var->lhs; i++) {
13974                 release_triple(state, LHS(var, i));
13975         }
13976         release_triple(state, var);
13977
13978         /* Return the index of the added closure type */
13979         return ctype->elements - 1;
13980 }
13981
13982 static struct triple *closure_expr(struct compile_state *state,
13983         struct triple *func, int closure_idx, int var_idx)
13984 {
13985         return deref_index(state,
13986                 deref_index(state,
13987                         deref_index(state, fresult(state, func), 0),
13988                         closure_idx),
13989                 var_idx);
13990 }
13991
13992
13993 static void insert_triple_set(
13994         struct triple_reg_set **head, struct triple *member)
13995 {
13996         struct triple_reg_set *new;
13997         new = xcmalloc(sizeof(*new), "triple_set");
13998         new->member = member;
13999         new->new    = 0;
14000         new->next   = *head;
14001         *head       = new;
14002 }
14003
14004 static int ordered_triple_set(
14005         struct triple_reg_set **head, struct triple *member)
14006 {
14007         struct triple_reg_set **ptr;
14008         if (!member)
14009                 return 0;
14010         ptr = head;
14011         while(*ptr) {
14012                 if (member == (*ptr)->member) {
14013                         return 0;
14014                 }
14015                 /* keep the list ordered */
14016                 if (member->id < (*ptr)->member->id) {
14017                         break;
14018                 }
14019                 ptr = &(*ptr)->next;
14020         }
14021         insert_triple_set(ptr, member);
14022         return 1;
14023 }
14024
14025
14026 static void free_closure_variables(struct compile_state *state,
14027         struct triple_reg_set **enclose)
14028 {
14029         struct triple_reg_set *entry, *next;
14030         for(entry = *enclose; entry; entry = next) {
14031                 next = entry->next;
14032                 do_triple_unset(enclose, entry->member);
14033         }
14034 }
14035
14036 static int lookup_closure_index(struct compile_state *state,
14037         struct triple *me, struct triple *val)
14038 {
14039         struct triple *first, *ins, *next;
14040         first = RHS(me, 0);
14041         ins = next = first;
14042         do {
14043                 struct triple *result;
14044                 struct triple *index0, *index1, *index2, *read, *write;
14045                 ins = next;
14046                 next = ins->next;
14047                 if (ins->op != OP_CALL) {
14048                         continue;
14049                 }
14050                 /* I am at a previous call point examine it closely */
14051                 if (ins->next->op != OP_LABEL) {
14052                         internal_error(state, ins, "call not followed by label");
14053                 }
14054                 /* Does this call does not enclose any variables? */
14055                 if ((ins->next->next->op != OP_INDEX) ||
14056                         (ins->next->next->u.cval != 0) ||
14057                         (result = MISC(ins->next->next, 0)) ||
14058                         (result->id & TRIPLE_FLAG_LOCAL)) {
14059                         continue;
14060                 }
14061                 index0 = ins->next->next;
14062                 /* The pattern is:
14063                  * 0 index result < 0 >
14064                  * 1 index 0 < ? >
14065                  * 2 index 1 < ? >
14066                  * 3 read  2
14067                  * 4 write 3 var
14068                  */
14069                 for(index0 = ins->next->next;
14070                         (index0->op == OP_INDEX) &&
14071                                 (MISC(index0, 0) == result) &&
14072                                 (index0->u.cval == 0) ;
14073                         index0 = write->next)
14074                 {
14075                         index1 = index0->next;
14076                         index2 = index1->next;
14077                         read   = index2->next;
14078                         write  = read->next;
14079                         if ((index0->op != OP_INDEX) ||
14080                                 (index1->op != OP_INDEX) ||
14081                                 (index2->op != OP_INDEX) ||
14082                                 (read->op != OP_READ) ||
14083                                 (write->op != OP_WRITE) ||
14084                                 (MISC(index1, 0) != index0) ||
14085                                 (MISC(index2, 0) != index1) ||
14086                                 (RHS(read, 0) != index2) ||
14087                                 (RHS(write, 0) != read)) {
14088                                 internal_error(state, index0, "bad var read");
14089                         }
14090                         if (MISC(write, 0) == val) {
14091                                 return index2->u.cval;
14092                         }
14093                 }
14094         } while(next != first);
14095         return -1;
14096 }
14097
14098 static inline int enclose_triple(struct triple *ins)
14099 {
14100         return (ins && ((ins->type->type & TYPE_MASK) != TYPE_VOID));
14101 }
14102
14103 static void compute_closure_variables(struct compile_state *state,
14104         struct triple *me, struct triple *fcall, struct triple_reg_set **enclose)
14105 {
14106         struct triple_reg_set *set, *vars, **last_var;
14107         struct basic_blocks bb;
14108         struct reg_block *rb;
14109         struct block *block;
14110         struct triple *old_result, *first, *ins;
14111         size_t count, idx;
14112         unsigned long used_indicies;
14113         int i, max_index;
14114 #define MAX_INDICIES (sizeof(used_indicies)*CHAR_BIT)
14115 #define ID_BITS(X) ((X) & (TRIPLE_FLAG_LOCAL -1))
14116         struct {
14117                 unsigned id;
14118                 int index;
14119         } *info;
14120
14121
14122         /* Find the basic blocks of this function */
14123         bb.func = me;
14124         bb.first = RHS(me, 0);
14125         old_result = 0;
14126         if (!triple_is_ret(state, bb.first->prev)) {
14127                 bb.func = 0;
14128         } else {
14129                 old_result = fresult(state, me);
14130         }
14131         analyze_basic_blocks(state, &bb);
14132
14133         /* Find which variables are currently alive in a given block */
14134         rb = compute_variable_lifetimes(state, &bb);
14135
14136         /* Find the variables that are currently alive */
14137         block = block_of_triple(state, fcall);
14138         if (!block || (block->vertex <= 0) || (block->vertex > bb.last_vertex)) {
14139                 internal_error(state, fcall, "No reg block? block: %p", block);
14140         }
14141
14142 #if DEBUG_EXPLICIT_CLOSURES
14143         print_live_variables(state, &bb, rb, state->dbgout);
14144         fflush(state->dbgout);
14145 #endif
14146
14147         /* Count the number of triples in the function */
14148         first = RHS(me, 0);
14149         ins = first;
14150         count = 0;
14151         do {
14152                 count++;
14153                 ins = ins->next;
14154         } while(ins != first);
14155
14156         /* Allocate some memory to temorary hold the id info */
14157         info = xcmalloc(sizeof(*info) * (count +1), "info");
14158
14159         /* Mark the local function */
14160         first = RHS(me, 0);
14161         ins = first;
14162         idx = 1;
14163         do {
14164                 info[idx].id = ins->id;
14165                 ins->id = TRIPLE_FLAG_LOCAL | idx;
14166                 idx++;
14167                 ins = ins->next;
14168         } while(ins != first);
14169
14170         /*
14171          * Build the list of variables to enclose.
14172          *
14173          * A target it to put the same variable in the
14174          * same slot for ever call of a given function.
14175          * After coloring this removes all of the variable
14176          * manipulation code.
14177          *
14178          * The list of variables to enclose is built ordered
14179          * program order because except in corner cases this
14180          * gives me the stability of assignment I need.
14181          *
14182          * To gurantee that stability I lookup the variables
14183          * to see where they have been used before and
14184          * I build my final list with the assigned indicies.
14185          */
14186         vars = 0;
14187         if (enclose_triple(old_result)) {
14188                 ordered_triple_set(&vars, old_result);
14189         }
14190         for(set = rb[block->vertex].out; set; set = set->next) {
14191                 if (!enclose_triple(set->member)) {
14192                         continue;
14193                 }
14194                 if ((set->member == fcall) || (set->member == old_result)) {
14195                         continue;
14196                 }
14197                 if (!local_triple(state, me, set->member)) {
14198                         internal_error(state, set->member, "not local?");
14199                 }
14200                 ordered_triple_set(&vars, set->member);
14201         }
14202
14203         /* Lookup the current indicies of the live varialbe */
14204         used_indicies = 0;
14205         max_index = -1;
14206         for(set = vars; set ; set = set->next) {
14207                 struct triple *ins;
14208                 int index;
14209                 ins = set->member;
14210                 index  = lookup_closure_index(state, me, ins);
14211                 info[ID_BITS(ins->id)].index = index;
14212                 if (index < 0) {
14213                         continue;
14214                 }
14215                 if (index >= MAX_INDICIES) {
14216                         internal_error(state, ins, "index unexpectedly large");
14217                 }
14218                 if (used_indicies & (1 << index)) {
14219                         internal_error(state, ins, "index previously used?");
14220                 }
14221                 /* Remember which indicies have been used */
14222                 used_indicies |= (1 << index);
14223                 if (index > max_index) {
14224                         max_index = index;
14225                 }
14226         }
14227
14228         /* Walk through the live variables and make certain
14229          * everything is assigned an index.
14230          */
14231         for(set = vars; set; set = set->next) {
14232                 struct triple *ins;
14233                 int index;
14234                 ins = set->member;
14235                 index = info[ID_BITS(ins->id)].index;
14236                 if (index >= 0) {
14237                         continue;
14238                 }
14239                 /* Find the lowest unused index value */
14240                 for(index = 0; index < MAX_INDICIES; index++) {
14241                         if (!(used_indicies & (1 << index))) {
14242                                 break;
14243                         }
14244                 }
14245                 if (index == MAX_INDICIES) {
14246                         internal_error(state, ins, "no free indicies?");
14247                 }
14248                 info[ID_BITS(ins->id)].index = index;
14249                 /* Remember which indicies have been used */
14250                 used_indicies |= (1 << index);
14251                 if (index > max_index) {
14252                         max_index = index;
14253                 }
14254         }
14255
14256         /* Build the return list of variables with positions matching
14257          * their indicies.
14258          */
14259         *enclose = 0;
14260         last_var = enclose;
14261         for(i = 0; i <= max_index; i++) {
14262                 struct triple *var;
14263                 var = 0;
14264                 if (used_indicies & (1 << i)) {
14265                         for(set = vars; set; set = set->next) {
14266                                 int index;
14267                                 index = info[ID_BITS(set->member->id)].index;
14268                                 if (index == i) {
14269                                         var = set->member;
14270                                         break;
14271                                 }
14272                         }
14273                         if (!var) {
14274                                 internal_error(state, me, "missing variable");
14275                         }
14276                 }
14277                 insert_triple_set(last_var, var);
14278                 last_var = &(*last_var)->next;
14279         }
14280
14281 #if DEBUG_EXPLICIT_CLOSURES
14282         /* Print out the variables to be enclosed */
14283         loc(state->dbgout, state, fcall);
14284         fprintf(state->dbgout, "Alive: \n");
14285         for(set = *enclose; set; set = set->next) {
14286                 display_triple(state->dbgout, set->member);
14287         }
14288         fflush(state->dbgout);
14289 #endif
14290
14291         /* Clear the marks */
14292         ins = first;
14293         do {
14294                 ins->id = info[ID_BITS(ins->id)].id;
14295                 ins = ins->next;
14296         } while(ins != first);
14297
14298         /* Release the ordered list of live variables */
14299         free_closure_variables(state, &vars);
14300
14301         /* Release the storage of the old ids */
14302         xfree(info);
14303
14304         /* Release the variable lifetime information */
14305         free_variable_lifetimes(state, &bb, rb);
14306
14307         /* Release the basic blocks of this function */
14308         free_basic_blocks(state, &bb);
14309 }
14310
14311 static void expand_function_call(
14312         struct compile_state *state, struct triple *me, struct triple *fcall)
14313 {
14314         /* Generate an ordinary function call */
14315         struct type *closure_type, **closure_next;
14316         struct triple *func, *func_first, *func_last, *retvar;
14317         struct triple *first;
14318         struct type *ptype, *rtype;
14319         struct triple *ret_addr, *ret_loc;
14320         struct triple_reg_set *enclose, *set;
14321         int closure_idx, pvals, i;
14322
14323 #if DEBUG_EXPLICIT_CLOSURES
14324         FILE *fp = state->dbgout;
14325         fprintf(fp, "\ndisplay_func(me) ptr: %p\n", fcall);
14326         display_func(state, fp, MISC(fcall, 0));
14327         display_func(state, fp, me);
14328         fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14329 #endif
14330
14331         /* Find the triples */
14332         func = MISC(fcall, 0);
14333         func_first = RHS(func, 0);
14334         retvar = fretaddr(state, func);
14335         func_last  = func_first->prev;
14336         first = fcall->next;
14337
14338         /* Find what I need to enclose */
14339         compute_closure_variables(state, me, fcall, &enclose);
14340
14341         /* Compute the closure type */
14342         closure_type = new_type(TYPE_TUPLE, 0, 0);
14343         closure_type->elements = 0;
14344         closure_next = &closure_type->left;
14345         for(set = enclose; set ; set = set->next) {
14346                 struct type *type;
14347                 type = &void_type;
14348                 if (set->member) {
14349                         type = set->member->type;
14350                 }
14351                 if (!*closure_next) {
14352                         *closure_next = type;
14353                 } else {
14354                         *closure_next = new_type(TYPE_PRODUCT, *closure_next,
14355                                 type);
14356                         closure_next = &(*closure_next)->right;
14357                 }
14358                 closure_type->elements += 1;
14359         }
14360         if (closure_type->elements == 0) {
14361                 closure_type->type = TYPE_VOID;
14362         }
14363
14364
14365 #if DEBUG_EXPLICIT_CLOSURES
14366         fprintf(state->dbgout, "closure type: ");
14367         name_of(state->dbgout, closure_type);
14368         fprintf(state->dbgout, "\n");
14369 #endif
14370
14371         /* Update the called functions closure variable */
14372         closure_idx = add_closure_type(state, func, closure_type);
14373
14374         /* Generate some needed triples */
14375         ret_loc = label(state);
14376         ret_addr = triple(state, OP_ADDRCONST, &void_ptr_type, ret_loc, 0);
14377
14378         /* Pass the parameters to the new function */
14379         ptype = func->type->right;
14380         pvals = fcall->rhs;
14381         for(i = 0; i < pvals; i++) {
14382                 struct type *atype;
14383                 struct triple *arg, *param;
14384                 atype = ptype;
14385                 if ((ptype->type & TYPE_MASK) == TYPE_PRODUCT) {
14386                         atype = ptype->left;
14387                 }
14388                 param = farg(state, func, i);
14389                 if ((param->type->type & TYPE_MASK) != (atype->type & TYPE_MASK)) {
14390                         internal_error(state, fcall, "param type mismatch");
14391                 }
14392                 arg = RHS(fcall, i);
14393                 flatten(state, first, write_expr(state, param, arg));
14394                 ptype = ptype->right;
14395         }
14396         rtype = func->type->left;
14397
14398         /* Thread the triples together */
14399         ret_loc       = flatten(state, first, ret_loc);
14400
14401         /* Save the active variables in the result variable */
14402         for(i = 0, set = enclose; set ; set = set->next, i++) {
14403                 if (!set->member) {
14404                         continue;
14405                 }
14406                 flatten(state, ret_loc,
14407                         write_expr(state,
14408                                 closure_expr(state, func, closure_idx, i),
14409                                 read_expr(state, set->member)));
14410         }
14411
14412         /* Initialize the return value */
14413         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14414                 flatten(state, ret_loc,
14415                         write_expr(state,
14416                                 deref_index(state, fresult(state, func), 1),
14417                                 new_triple(state, OP_UNKNOWNVAL, rtype,  0, 0)));
14418         }
14419
14420         ret_addr      = flatten(state, ret_loc, ret_addr);
14421         flatten(state, ret_loc, write_expr(state, retvar, ret_addr));
14422         flatten(state, ret_loc,
14423                 call(state, retvar, ret_addr, func_first, func_last));
14424
14425         /* Find the result */
14426         if ((rtype->type & TYPE_MASK) != TYPE_VOID) {
14427                 struct triple * result;
14428                 result = flatten(state, first,
14429                         read_expr(state,
14430                                 deref_index(state, fresult(state, func), 1)));
14431
14432                 propogate_use(state, fcall, result);
14433         }
14434
14435         /* Release the original fcall instruction */
14436         release_triple(state, fcall);
14437
14438         /* Restore the active variables from the result variable */
14439         for(i = 0, set = enclose; set ; set = set->next, i++) {
14440                 struct triple_set *use, *next;
14441                 struct triple *new;
14442                 struct basic_blocks bb;
14443                 if (!set->member || (set->member == fcall)) {
14444                         continue;
14445                 }
14446                 /* Generate an expression for the value */
14447                 new = flatten(state, first,
14448                         read_expr(state,
14449                                 closure_expr(state, func, closure_idx, i)));
14450
14451
14452                 /* If the original is an lvalue restore the preserved value */
14453                 if (is_lvalue(state, set->member)) {
14454                         flatten(state, first,
14455                                 write_expr(state, set->member, new));
14456                         continue;
14457                 }
14458                 /*
14459                  * If the original is a value update the dominated uses.
14460                  */
14461
14462                 /* Analyze the basic blocks so I can see who dominates whom */
14463                 bb.func = me;
14464                 bb.first = RHS(me, 0);
14465                 if (!triple_is_ret(state, bb.first->prev)) {
14466                         bb.func = 0;
14467                 }
14468                 analyze_basic_blocks(state, &bb);
14469
14470
14471 #if DEBUG_EXPLICIT_CLOSURES
14472                 fprintf(state->errout, "Updating domindated uses: %p -> %p\n",
14473                         set->member, new);
14474 #endif
14475                 /* If fcall dominates the use update the expression */
14476                 for(use = set->member->use; use; use = next) {
14477                         /* Replace use modifies the use chain and
14478                          * removes use, so I must take a copy of the
14479                          * next entry early.
14480                          */
14481                         next = use->next;
14482                         if (!tdominates(state, fcall, use->member)) {
14483                                 continue;
14484                         }
14485                         replace_use(state, set->member, new, use->member);
14486                 }
14487
14488                 /* Release the basic blocks, the instructions will be
14489                  * different next time, and flatten/insert_triple does
14490                  * not update the block values so I can't cache the analysis.
14491                  */
14492                 free_basic_blocks(state, &bb);
14493         }
14494
14495         /* Release the closure variable list */
14496         free_closure_variables(state, &enclose);
14497
14498         if (state->compiler->debug & DEBUG_INLINE) {
14499                 FILE *fp = state->dbgout;
14500                 fprintf(fp, "\n");
14501                 loc(fp, state, 0);
14502                 fprintf(fp, "\n__________ %s _________\n", __FUNCTION__);
14503                 display_func(state, fp, func);
14504                 display_func(state, fp, me);
14505                 fprintf(fp, "__________ %s _________ done\n\n", __FUNCTION__);
14506         }
14507
14508         return;
14509 }
14510
14511 static int do_inline(struct compile_state *state, struct triple *func)
14512 {
14513         int do_inline;
14514         int policy;
14515
14516         policy = state->compiler->flags & COMPILER_INLINE_MASK;
14517         switch(policy) {
14518         case COMPILER_INLINE_ALWAYS:
14519                 do_inline = 1;
14520                 if (func->type->type & ATTRIB_NOINLINE) {
14521                         error(state, func, "noinline with always_inline compiler option");
14522                 }
14523                 break;
14524         case COMPILER_INLINE_NEVER:
14525                 do_inline = 0;
14526                 if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14527                         error(state, func, "always_inline with noinline compiler option");
14528                 }
14529                 break;
14530         case COMPILER_INLINE_DEFAULTON:
14531                 switch(func->type->type & STOR_MASK) {
14532                 case STOR_STATIC | STOR_INLINE:
14533                 case STOR_LOCAL  | STOR_INLINE:
14534                 case STOR_EXTERN | STOR_INLINE:
14535                         do_inline = 1;
14536                         break;
14537                 default:
14538                         do_inline = 1;
14539                         break;
14540                 }
14541                 break;
14542         case COMPILER_INLINE_DEFAULTOFF:
14543                 switch(func->type->type & STOR_MASK) {
14544                 case STOR_STATIC | STOR_INLINE:
14545                 case STOR_LOCAL  | STOR_INLINE:
14546                 case STOR_EXTERN | STOR_INLINE:
14547                         do_inline = 1;
14548                         break;
14549                 default:
14550                         do_inline = 0;
14551                         break;
14552                 }
14553                 break;
14554         case COMPILER_INLINE_NOPENALTY:
14555                 switch(func->type->type & STOR_MASK) {
14556                 case STOR_STATIC | STOR_INLINE:
14557                 case STOR_LOCAL  | STOR_INLINE:
14558                 case STOR_EXTERN | STOR_INLINE:
14559                         do_inline = 1;
14560                         break;
14561                 default:
14562                         do_inline = (func->u.cval == 1);
14563                         break;
14564                 }
14565                 break;
14566         default:
14567                 do_inline = 0;
14568                 internal_error(state, 0, "Unimplemented inline policy");
14569                 break;
14570         }
14571         /* Force inlining */
14572         if (func->type->type & ATTRIB_NOINLINE) {
14573                 do_inline = 0;
14574         }
14575         if (func->type->type & ATTRIB_ALWAYS_INLINE) {
14576                 do_inline = 1;
14577         }
14578         return do_inline;
14579 }
14580
14581 static void inline_function(struct compile_state *state, struct triple *me, void *arg)
14582 {
14583         struct triple *first, *ptr, *next;
14584         /* If the function is not used don't bother */
14585         if (me->u.cval <= 0) {
14586                 return;
14587         }
14588         if (state->compiler->debug & DEBUG_CALLS2) {
14589                 FILE *fp = state->dbgout;
14590                 fprintf(fp, "in: %s\n",
14591                         me->type->type_ident->name);
14592         }
14593
14594         first = RHS(me, 0);
14595         ptr = next = first;
14596         do {
14597                 struct triple *func, *prev;
14598                 ptr = next;
14599                 prev = ptr->prev;
14600                 next = ptr->next;
14601                 if (ptr->op != OP_FCALL) {
14602                         continue;
14603                 }
14604                 func = MISC(ptr, 0);
14605                 /* See if the function should be inlined */
14606                 if (!do_inline(state, func)) {
14607                         /* Put a label after the fcall */
14608                         post_triple(state, ptr, OP_LABEL, &void_type, 0, 0);
14609                         continue;
14610                 }
14611                 if (state->compiler->debug & DEBUG_CALLS) {
14612                         FILE *fp = state->dbgout;
14613                         if (state->compiler->debug & DEBUG_CALLS2) {
14614                                 loc(fp, state, ptr);
14615                         }
14616                         fprintf(fp, "inlining %s\n",
14617                                 func->type->type_ident->name);
14618                         fflush(fp);
14619                 }
14620
14621                 /* Update the function use counts */
14622                 func->u.cval -= 1;
14623
14624                 /* Replace the fcall with the called function */
14625                 expand_inline_call(state, me, ptr);
14626
14627                 next = prev->next;
14628         } while (next != first);
14629
14630         ptr = next = first;
14631         do {
14632                 struct triple *prev, *func;
14633                 ptr = next;
14634                 prev = ptr->prev;
14635                 next = ptr->next;
14636                 if (ptr->op != OP_FCALL) {
14637                         continue;
14638                 }
14639                 func = MISC(ptr, 0);
14640                 if (state->compiler->debug & DEBUG_CALLS) {
14641                         FILE *fp = state->dbgout;
14642                         if (state->compiler->debug & DEBUG_CALLS2) {
14643                                 loc(fp, state, ptr);
14644                         }
14645                         fprintf(fp, "calling %s\n",
14646                                 func->type->type_ident->name);
14647                         fflush(fp);
14648                 }
14649                 /* Replace the fcall with the instruction sequence
14650                  * needed to make the call.
14651                  */
14652                 expand_function_call(state, me, ptr);
14653                 next = prev->next;
14654         } while(next != first);
14655 }
14656
14657 static void inline_functions(struct compile_state *state, struct triple *func)
14658 {
14659         inline_function(state, func, 0);
14660         reverse_walk_functions(state, inline_function, 0);
14661 }
14662
14663 static void insert_function(struct compile_state *state,
14664         struct triple *func, void *arg)
14665 {
14666         struct triple *first, *end, *ffirst, *fend;
14667
14668         if (state->compiler->debug & DEBUG_INLINE) {
14669                 FILE *fp = state->errout;
14670                 fprintf(fp, "%s func count: %d\n",
14671                         func->type->type_ident->name, func->u.cval);
14672         }
14673         if (func->u.cval == 0) {
14674                 return;
14675         }
14676
14677         /* Find the end points of the lists */
14678         first  = arg;
14679         end    = first->prev;
14680         ffirst = RHS(func, 0);
14681         fend   = ffirst->prev;
14682
14683         /* splice the lists together */
14684         end->next    = ffirst;
14685         ffirst->prev = end;
14686         fend->next   = first;
14687         first->prev  = fend;
14688 }
14689
14690 struct triple *input_asm(struct compile_state *state)
14691 {
14692         struct asm_info *info;
14693         struct triple *def;
14694         int i, out;
14695
14696         info = xcmalloc(sizeof(*info), "asm_info");
14697         info->str = "";
14698
14699         out = sizeof(arch_input_regs)/sizeof(arch_input_regs[0]);
14700         memcpy(&info->tmpl.lhs, arch_input_regs, sizeof(arch_input_regs));
14701
14702         def = new_triple(state, OP_ASM, &void_type, out, 0);
14703         def->u.ainfo = info;
14704         def->id |= TRIPLE_FLAG_VOLATILE;
14705
14706         for(i = 0; i < out; i++) {
14707                 struct triple *piece;
14708                 piece = triple(state, OP_PIECE, &int_type, def, 0);
14709                 piece->u.cval = i;
14710                 LHS(def, i) = piece;
14711         }
14712
14713         return def;
14714 }
14715
14716 struct triple *output_asm(struct compile_state *state)
14717 {
14718         struct asm_info *info;
14719         struct triple *def;
14720         int in;
14721
14722         info = xcmalloc(sizeof(*info), "asm_info");
14723         info->str = "";
14724
14725         in = sizeof(arch_output_regs)/sizeof(arch_output_regs[0]);
14726         memcpy(&info->tmpl.rhs, arch_output_regs, sizeof(arch_output_regs));
14727
14728         def = new_triple(state, OP_ASM, &void_type, 0, in);
14729         def->u.ainfo = info;
14730         def->id |= TRIPLE_FLAG_VOLATILE;
14731
14732         return def;
14733 }
14734
14735 static void join_functions(struct compile_state *state)
14736 {
14737         struct triple *start, *end, *call, *in, *out, *func;
14738         struct file_state file;
14739         struct type *pnext, *param;
14740         struct type *result_type, *args_type;
14741         int idx;
14742
14743         /* Be clear the functions have not been joined yet */
14744         state->functions_joined = 0;
14745
14746         /* Dummy file state to get debug handing right */
14747         memset(&file, 0, sizeof(file));
14748         file.basename = "";
14749         file.line = 0;
14750         file.report_line = 0;
14751         file.report_name = file.basename;
14752         file.prev = state->file;
14753         state->file = &file;
14754         state->function = "";
14755
14756         if (!state->main_function) {
14757                 error(state, 0, "No functions to compile\n");
14758         }
14759
14760         /* The type of arguments */
14761         args_type   = state->main_function->type->right;
14762         /* The return type without any specifiers */
14763         result_type = clone_type(0, state->main_function->type->left);
14764
14765
14766         /* Verify the external arguments */
14767         if (registers_of(state, args_type) > ARCH_INPUT_REGS) {
14768                 error(state, state->main_function,
14769                         "Too many external input arguments");
14770         }
14771         if (registers_of(state, result_type) > ARCH_OUTPUT_REGS) {
14772                 error(state, state->main_function,
14773                         "Too many external output arguments");
14774         }
14775
14776         /* Lay down the basic program structure */
14777         end           = label(state);
14778         start         = label(state);
14779         start         = flatten(state, state->first, start);
14780         end           = flatten(state, state->first, end);
14781         in            = input_asm(state);
14782         out           = output_asm(state);
14783         call          = new_triple(state, OP_FCALL, result_type, -1, registers_of(state, args_type));
14784         MISC(call, 0) = state->main_function;
14785         in            = flatten(state, state->first, in);
14786         call          = flatten(state, state->first, call);
14787         out           = flatten(state, state->first, out);
14788
14789
14790         /* Read the external input arguments */
14791         pnext = args_type;
14792         idx = 0;
14793         while(pnext && ((pnext->type & TYPE_MASK) != TYPE_VOID)) {
14794                 struct triple *expr;
14795                 param = pnext;
14796                 pnext = 0;
14797                 if ((param->type & TYPE_MASK) == TYPE_PRODUCT) {
14798                         pnext = param->right;
14799                         param = param->left;
14800                 }
14801                 if (registers_of(state, param) != 1) {
14802                         error(state, state->main_function,
14803                                 "Arg: %d %s requires multiple registers",
14804                                 idx + 1, param->field_ident->name);
14805                 }
14806                 expr = read_expr(state, LHS(in, idx));
14807                 RHS(call, idx) = expr;
14808                 expr = flatten(state, call, expr);
14809                 use_triple(expr, call);
14810
14811                 idx++;
14812         }
14813
14814
14815         /* Write the external output arguments */
14816         pnext = result_type;
14817         if ((pnext->type & TYPE_MASK) == TYPE_STRUCT) {
14818                 pnext = result_type->left;
14819         }
14820         for(idx = 0; idx < out->rhs; idx++) {
14821                 struct triple *expr;
14822                 param = pnext;
14823                 pnext = 0;
14824                 if (param && ((param->type & TYPE_MASK) == TYPE_PRODUCT)) {
14825                         pnext = param->right;
14826                         param = param->left;
14827                 }
14828                 if (param && ((param->type & TYPE_MASK) == TYPE_VOID)) {
14829                         param = 0;
14830                 }
14831                 if (param) {
14832                         if (registers_of(state, param) != 1) {
14833                                 error(state, state->main_function,
14834                                         "Result: %d %s requires multiple registers",
14835                                         idx, param->field_ident->name);
14836                         }
14837                         expr = read_expr(state, call);
14838                         if ((result_type->type & TYPE_MASK) == TYPE_STRUCT) {
14839                                 expr = deref_field(state, expr, param->field_ident);
14840                         }
14841                 } else {
14842                         expr = triple(state, OP_UNKNOWNVAL, &int_type, 0, 0);
14843                 }
14844                 flatten(state, out, expr);
14845                 RHS(out, idx) = expr;
14846                 use_triple(expr, out);
14847         }
14848
14849         /* Allocate a dummy containing function */
14850         func = triple(state, OP_LIST,
14851                 new_type(TYPE_FUNCTION, &void_type, &void_type), 0, 0);
14852         func->type->type_ident = lookup(state, "", 0);
14853         RHS(func, 0) = state->first;
14854         func->u.cval = 1;
14855
14856         /* See which functions are called, and how often */
14857         mark_live_functions(state);
14858         inline_functions(state, func);
14859         walk_functions(state, insert_function, end);
14860
14861         if (start->next != end) {
14862                 flatten(state, start, branch(state, end, 0));
14863         }
14864
14865         /* OK now the functions have been joined. */
14866         state->functions_joined = 1;
14867
14868         /* Done now cleanup */
14869         state->file = file.prev;
14870         state->function = 0;
14871 }
14872
14873 /*
14874  * Data structurs for optimation.
14875  */
14876
14877
14878 static int do_use_block(
14879         struct block *used, struct block_set **head, struct block *user,
14880         int front)
14881 {
14882         struct block_set **ptr, *new;
14883         if (!used)
14884                 return 0;
14885         if (!user)
14886                 return 0;
14887         ptr = head;
14888         while(*ptr) {
14889                 if ((*ptr)->member == user) {
14890                         return 0;
14891                 }
14892                 ptr = &(*ptr)->next;
14893         }
14894         new = xcmalloc(sizeof(*new), "block_set");
14895         new->member = user;
14896         if (front) {
14897                 new->next = *head;
14898                 *head = new;
14899         }
14900         else {
14901                 new->next = 0;
14902                 *ptr = new;
14903         }
14904         return 1;
14905 }
14906 static int do_unuse_block(
14907         struct block *used, struct block_set **head, struct block *unuser)
14908 {
14909         struct block_set *use, **ptr;
14910         int count;
14911         count = 0;
14912         ptr = head;
14913         while(*ptr) {
14914                 use = *ptr;
14915                 if (use->member == unuser) {
14916                         *ptr = use->next;
14917                         memset(use, -1, sizeof(*use));
14918                         xfree(use);
14919                         count += 1;
14920                 }
14921                 else {
14922                         ptr = &use->next;
14923                 }
14924         }
14925         return count;
14926 }
14927
14928 static void use_block(struct block *used, struct block *user)
14929 {
14930         int count;
14931         /* Append new to the head of the list, print_block
14932          * depends on this.
14933          */
14934         count = do_use_block(used, &used->use, user, 1);
14935         used->users += count;
14936 }
14937 static void unuse_block(struct block *used, struct block *unuser)
14938 {
14939         int count;
14940         count = do_unuse_block(used, &used->use, unuser);
14941         used->users -= count;
14942 }
14943
14944 static void add_block_edge(struct block *block, struct block *edge, int front)
14945 {
14946         int count;
14947         count = do_use_block(block, &block->edges, edge, front);
14948         block->edge_count += count;
14949 }
14950
14951 static void remove_block_edge(struct block *block, struct block *edge)
14952 {
14953         int count;
14954         count = do_unuse_block(block, &block->edges, edge);
14955         block->edge_count -= count;
14956 }
14957
14958 static void idom_block(struct block *idom, struct block *user)
14959 {
14960         do_use_block(idom, &idom->idominates, user, 0);
14961 }
14962
14963 static void unidom_block(struct block *idom, struct block *unuser)
14964 {
14965         do_unuse_block(idom, &idom->idominates, unuser);
14966 }
14967
14968 static void domf_block(struct block *block, struct block *domf)
14969 {
14970         do_use_block(block, &block->domfrontier, domf, 0);
14971 }
14972
14973 static void undomf_block(struct block *block, struct block *undomf)
14974 {
14975         do_unuse_block(block, &block->domfrontier, undomf);
14976 }
14977
14978 static void ipdom_block(struct block *ipdom, struct block *user)
14979 {
14980         do_use_block(ipdom, &ipdom->ipdominates, user, 0);
14981 }
14982
14983 static void unipdom_block(struct block *ipdom, struct block *unuser)
14984 {
14985         do_unuse_block(ipdom, &ipdom->ipdominates, unuser);
14986 }
14987
14988 static void ipdomf_block(struct block *block, struct block *ipdomf)
14989 {
14990         do_use_block(block, &block->ipdomfrontier, ipdomf, 0);
14991 }
14992
14993 static void unipdomf_block(struct block *block, struct block *unipdomf)
14994 {
14995         do_unuse_block(block, &block->ipdomfrontier, unipdomf);
14996 }
14997
14998 static int walk_triples(
14999         struct compile_state *state,
15000         int (*cb)(struct compile_state *state, struct triple *ptr, void *arg),
15001         void *arg)
15002 {
15003         struct triple *ptr;
15004         int result;
15005         ptr = state->first;
15006         do {
15007                 result = cb(state, ptr, arg);
15008                 if (ptr->next->prev != ptr) {
15009                         internal_error(state, ptr->next, "bad prev");
15010                 }
15011                 ptr = ptr->next;
15012         } while((result == 0) && (ptr != state->first));
15013         return result;
15014 }
15015
15016 #define PRINT_LIST 1
15017 static int do_print_triple(struct compile_state *state, struct triple *ins, void *arg)
15018 {
15019         FILE *fp = arg;
15020         int op;
15021         op = ins->op;
15022         if (op == OP_LIST) {
15023 #if !PRINT_LIST
15024                 return 0;
15025 #endif
15026         }
15027         if ((op == OP_LABEL) && (ins->use)) {
15028                 fprintf(fp, "\n%p:\n", ins);
15029         }
15030         display_triple(fp, ins);
15031
15032         if (triple_is_branch(state, ins) && ins->use &&
15033                 (ins->op != OP_RET) && (ins->op != OP_FCALL)) {
15034                 internal_error(state, ins, "branch used?");
15035         }
15036         if (triple_is_branch(state, ins)) {
15037                 fprintf(fp, "\n");
15038         }
15039         return 0;
15040 }
15041
15042 static void print_triples(struct compile_state *state)
15043 {
15044         if (state->compiler->debug & DEBUG_TRIPLES) {
15045                 FILE *fp = state->dbgout;
15046                 fprintf(fp, "--------------- triples ---------------\n");
15047                 walk_triples(state, do_print_triple, fp);
15048                 fprintf(fp, "\n");
15049         }
15050 }
15051
15052 struct cf_block {
15053         struct block *block;
15054 };
15055 static void find_cf_blocks(struct cf_block *cf, struct block *block)
15056 {
15057         struct block_set *edge;
15058         if (!block || (cf[block->vertex].block == block)) {
15059                 return;
15060         }
15061         cf[block->vertex].block = block;
15062         for(edge = block->edges; edge; edge = edge->next) {
15063                 find_cf_blocks(cf, edge->member);
15064         }
15065 }
15066
15067 static void print_control_flow(struct compile_state *state,
15068         FILE *fp, struct basic_blocks *bb)
15069 {
15070         struct cf_block *cf;
15071         int i;
15072         fprintf(fp, "\ncontrol flow\n");
15073         cf = xcmalloc(sizeof(*cf) * (bb->last_vertex + 1), "cf_block");
15074         find_cf_blocks(cf, bb->first_block);
15075
15076         for(i = 1; i <= bb->last_vertex; i++) {
15077                 struct block *block;
15078                 struct block_set *edge;
15079                 block = cf[i].block;
15080                 if (!block)
15081                         continue;
15082                 fprintf(fp, "(%p) %d:", block, block->vertex);
15083                 for(edge = block->edges; edge; edge = edge->next) {
15084                         fprintf(fp, " %d", edge->member->vertex);
15085                 }
15086                 fprintf(fp, "\n");
15087         }
15088
15089         xfree(cf);
15090 }
15091
15092 static void free_basic_block(struct compile_state *state, struct block *block)
15093 {
15094         struct block_set *edge, *entry;
15095         struct block *child;
15096         if (!block) {
15097                 return;
15098         }
15099         if (block->vertex == -1) {
15100                 return;
15101         }
15102         block->vertex = -1;
15103         for(edge = block->edges; edge; edge = edge->next) {
15104                 if (edge->member) {
15105                         unuse_block(edge->member, block);
15106                 }
15107         }
15108         if (block->idom) {
15109                 unidom_block(block->idom, block);
15110         }
15111         block->idom = 0;
15112         if (block->ipdom) {
15113                 unipdom_block(block->ipdom, block);
15114         }
15115         block->ipdom = 0;
15116         while((entry = block->use)) {
15117                 child = entry->member;
15118                 unuse_block(block, child);
15119                 if (child && (child->vertex != -1)) {
15120                         for(edge = child->edges; edge; edge = edge->next) {
15121                                 edge->member = 0;
15122                         }
15123                 }
15124         }
15125         while((entry = block->idominates)) {
15126                 child = entry->member;
15127                 unidom_block(block, child);
15128                 if (child && (child->vertex != -1)) {
15129                         child->idom = 0;
15130                 }
15131         }
15132         while((entry = block->domfrontier)) {
15133                 child = entry->member;
15134                 undomf_block(block, child);
15135         }
15136         while((entry = block->ipdominates)) {
15137                 child = entry->member;
15138                 unipdom_block(block, child);
15139                 if (child && (child->vertex != -1)) {
15140                         child->ipdom = 0;
15141                 }
15142         }
15143         while((entry = block->ipdomfrontier)) {
15144                 child = entry->member;
15145                 unipdomf_block(block, child);
15146         }
15147         if (block->users != 0) {
15148                 internal_error(state, 0, "block still has users");
15149         }
15150         while((edge = block->edges)) {
15151                 child = edge->member;
15152                 remove_block_edge(block, child);
15153
15154                 if (child && (child->vertex != -1)) {
15155                         free_basic_block(state, child);
15156                 }
15157         }
15158         memset(block, -1, sizeof(*block));
15159 #ifndef WIN32
15160         xfree(block);
15161 #endif
15162 }
15163
15164 static void free_basic_blocks(struct compile_state *state,
15165         struct basic_blocks *bb)
15166 {
15167         struct triple *first, *ins;
15168         free_basic_block(state, bb->first_block);
15169         bb->last_vertex = 0;
15170         bb->first_block = bb->last_block = 0;
15171         first = bb->first;
15172         ins = first;
15173         do {
15174                 if (triple_stores_block(state, ins)) {
15175                         ins->u.block = 0;
15176                 }
15177                 ins = ins->next;
15178         } while(ins != first);
15179
15180 }
15181
15182 static struct block *basic_block(struct compile_state *state,
15183         struct basic_blocks *bb, struct triple *first)
15184 {
15185         struct block *block;
15186         struct triple *ptr;
15187         if (!triple_is_label(state, first)) {
15188                 internal_error(state, first, "block does not start with a label");
15189         }
15190         /* See if this basic block has already been setup */
15191         if (first->u.block != 0) {
15192                 return first->u.block;
15193         }
15194         /* Allocate another basic block structure */
15195         bb->last_vertex += 1;
15196         block = xcmalloc(sizeof(*block), "block");
15197         block->first = block->last = first;
15198         block->vertex = bb->last_vertex;
15199         ptr = first;
15200         do {
15201                 if ((ptr != first) && triple_is_label(state, ptr) && (ptr->use)) {
15202                         break;
15203                 }
15204                 block->last = ptr;
15205                 /* If ptr->u is not used remember where the baic block is */
15206                 if (triple_stores_block(state, ptr)) {
15207                         ptr->u.block = block;
15208                 }
15209                 if (triple_is_branch(state, ptr)) {
15210                         break;
15211                 }
15212                 ptr = ptr->next;
15213         } while (ptr != bb->first);
15214         if ((ptr == bb->first) ||
15215                 ((ptr->next == bb->first) && (
15216                         triple_is_end(state, ptr) ||
15217                         triple_is_ret(state, ptr))))
15218         {
15219                 /* The block has no outflowing edges */
15220         }
15221         else if (triple_is_label(state, ptr)) {
15222                 struct block *next;
15223                 next = basic_block(state, bb, ptr);
15224                 add_block_edge(block, next, 0);
15225                 use_block(next, block);
15226         }
15227         else if (triple_is_branch(state, ptr)) {
15228                 struct triple **expr, *first;
15229                 struct block *child;
15230                 /* Find the branch targets.
15231                  * I special case the first branch as that magically
15232                  * avoids some difficult cases for the register allocator.
15233                  */
15234                 expr = triple_edge_targ(state, ptr, 0);
15235                 if (!expr) {
15236                         internal_error(state, ptr, "branch without targets");
15237                 }
15238                 first = *expr;
15239                 expr = triple_edge_targ(state, ptr, expr);
15240                 for(; expr; expr = triple_edge_targ(state, ptr, expr)) {
15241                         if (!*expr) continue;
15242                         child = basic_block(state, bb, *expr);
15243                         use_block(child, block);
15244                         add_block_edge(block, child, 0);
15245                 }
15246                 if (first) {
15247                         child = basic_block(state, bb, first);
15248                         use_block(child, block);
15249                         add_block_edge(block, child, 1);
15250
15251                         /* Be certain the return block of a call is
15252                          * in a basic block.  When it is not find
15253                          * start of the block, insert a label if
15254                          * necessary and build the basic block.
15255                          * Then add a fake edge from the start block
15256                          * to the return block of the function.
15257                          */
15258                         if (state->functions_joined && triple_is_call(state, ptr)
15259                                 && !block_of_triple(state, MISC(ptr, 0))) {
15260                                 struct block *tail;
15261                                 struct triple *start;
15262                                 start = triple_to_block_start(state, MISC(ptr, 0));
15263                                 if (!triple_is_label(state, start)) {
15264                                         start = pre_triple(state,
15265                                                 start, OP_LABEL, &void_type, 0, 0);
15266                                 }
15267                                 tail = basic_block(state, bb, start);
15268                                 add_block_edge(child, tail, 0);
15269                                 use_block(tail, child);
15270                         }
15271                 }
15272         }
15273         else {
15274                 internal_error(state, 0, "Bad basic block split");
15275         }
15276 #if 0
15277 {
15278         struct block_set *edge;
15279         FILE *fp = state->errout;
15280         fprintf(fp, "basic_block: %10p [%2d] ( %10p - %10p )",
15281                 block, block->vertex,
15282                 block->first, block->last);
15283         for(edge = block->edges; edge; edge = edge->next) {
15284                 fprintf(fp, " %10p [%2d]",
15285                         edge->member ? edge->member->first : 0,
15286                         edge->member ? edge->member->vertex : -1);
15287         }
15288         fprintf(fp, "\n");
15289 }
15290 #endif
15291         return block;
15292 }
15293
15294
15295 static void walk_blocks(struct compile_state *state, struct basic_blocks *bb,
15296         void (*cb)(struct compile_state *state, struct block *block, void *arg),
15297         void *arg)
15298 {
15299         struct triple *ptr, *first;
15300         struct block *last_block;
15301         last_block = 0;
15302         first = bb->first;
15303         ptr = first;
15304         do {
15305                 if (triple_stores_block(state, ptr)) {
15306                         struct block *block;
15307                         block = ptr->u.block;
15308                         if (block && (block != last_block)) {
15309                                 cb(state, block, arg);
15310                         }
15311                         last_block = block;
15312                 }
15313                 ptr = ptr->next;
15314         } while(ptr != first);
15315 }
15316
15317 static void print_block(
15318         struct compile_state *state, struct block *block, void *arg)
15319 {
15320         struct block_set *user, *edge;
15321         struct triple *ptr;
15322         FILE *fp = arg;
15323
15324         fprintf(fp, "\nblock: %p (%d) ",
15325                 block,
15326                 block->vertex);
15327
15328         for(edge = block->edges; edge; edge = edge->next) {
15329                 fprintf(fp, " %p<-%p",
15330                         edge->member,
15331                         (edge->member && edge->member->use)?
15332                         edge->member->use->member : 0);
15333         }
15334         fprintf(fp, "\n");
15335         if (block->first->op == OP_LABEL) {
15336                 fprintf(fp, "%p:\n", block->first);
15337         }
15338         for(ptr = block->first; ; ) {
15339                 display_triple(fp, ptr);
15340                 if (ptr == block->last)
15341                         break;
15342                 ptr = ptr->next;
15343                 if (ptr == block->first) {
15344                         internal_error(state, 0, "missing block last?");
15345                 }
15346         }
15347         fprintf(fp, "users %d: ", block->users);
15348         for(user = block->use; user; user = user->next) {
15349                 fprintf(fp, "%p (%d) ",
15350                         user->member,
15351                         user->member->vertex);
15352         }
15353         fprintf(fp,"\n\n");
15354 }
15355
15356
15357 static void romcc_print_blocks(struct compile_state *state, FILE *fp)
15358 {
15359         fprintf(fp, "--------------- blocks ---------------\n");
15360         walk_blocks(state, &state->bb, print_block, fp);
15361 }
15362 static void print_blocks(struct compile_state *state, const char *func, FILE *fp)
15363 {
15364         if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15365                 fprintf(fp, "After %s\n", func);
15366                 romcc_print_blocks(state, fp);
15367                 if (state->compiler->debug & DEBUG_FDOMINATORS) {
15368                         print_dominators(state, fp, &state->bb);
15369                         print_dominance_frontiers(state, fp, &state->bb);
15370                 }
15371                 print_control_flow(state, fp, &state->bb);
15372         }
15373 }
15374
15375 static void prune_nonblock_triples(struct compile_state *state,
15376         struct basic_blocks *bb)
15377 {
15378         struct block *block;
15379         struct triple *first, *ins, *next;
15380         /* Delete the triples not in a basic block */
15381         block = 0;
15382         first = bb->first;
15383         ins = first;
15384         do {
15385                 next = ins->next;
15386                 if (ins->op == OP_LABEL) {
15387                         block = ins->u.block;
15388                 }
15389                 if (!block) {
15390                         struct triple_set *use;
15391                         for(use = ins->use; use; use = use->next) {
15392                                 struct block *block;
15393                                 block = block_of_triple(state, use->member);
15394                                 if (block != 0) {
15395                                         internal_error(state, ins, "pruning used ins?");
15396                                 }
15397                         }
15398                         release_triple(state, ins);
15399                 }
15400                 if (block && block->last == ins) {
15401                         block = 0;
15402                 }
15403                 ins = next;
15404         } while(ins != first);
15405 }
15406
15407 static void setup_basic_blocks(struct compile_state *state,
15408         struct basic_blocks *bb)
15409 {
15410         if (!triple_stores_block(state, bb->first)) {
15411                 internal_error(state, 0, "ins will not store block?");
15412         }
15413         /* Initialize the state */
15414         bb->first_block = bb->last_block = 0;
15415         bb->last_vertex = 0;
15416         free_basic_blocks(state, bb);
15417
15418         /* Find the basic blocks */
15419         bb->first_block = basic_block(state, bb, bb->first);
15420
15421         /* Be certain the last instruction of a function, or the
15422          * entire program is in a basic block.  When it is not find
15423          * the start of the block, insert a label if necessary and build
15424          * basic block.  Then add a fake edge from the start block
15425          * to the final block.
15426          */
15427         if (!block_of_triple(state, bb->first->prev)) {
15428                 struct triple *start;
15429                 struct block *tail;
15430                 start = triple_to_block_start(state, bb->first->prev);
15431                 if (!triple_is_label(state, start)) {
15432                         start = pre_triple(state,
15433                                 start, OP_LABEL, &void_type, 0, 0);
15434                 }
15435                 tail = basic_block(state, bb, start);
15436                 add_block_edge(bb->first_block, tail, 0);
15437                 use_block(tail, bb->first_block);
15438         }
15439
15440         /* Find the last basic block.
15441          */
15442         bb->last_block = block_of_triple(state, bb->first->prev);
15443
15444         /* Delete the triples not in a basic block */
15445         prune_nonblock_triples(state, bb);
15446
15447 #if 0
15448         /* If we are debugging print what I have just done */
15449         if (state->compiler->debug & DEBUG_BASIC_BLOCKS) {
15450                 print_blocks(state, state->dbgout);
15451                 print_control_flow(state, bb);
15452         }
15453 #endif
15454 }
15455
15456
15457 struct sdom_block {
15458         struct block *block;
15459         struct sdom_block *sdominates;
15460         struct sdom_block *sdom_next;
15461         struct sdom_block *sdom;
15462         struct sdom_block *label;
15463         struct sdom_block *parent;
15464         struct sdom_block *ancestor;
15465         int vertex;
15466 };
15467
15468
15469 static void unsdom_block(struct sdom_block *block)
15470 {
15471         struct sdom_block **ptr;
15472         if (!block->sdom_next) {
15473                 return;
15474         }
15475         ptr = &block->sdom->sdominates;
15476         while(*ptr) {
15477                 if ((*ptr) == block) {
15478                         *ptr = block->sdom_next;
15479                         return;
15480                 }
15481                 ptr = &(*ptr)->sdom_next;
15482         }
15483 }
15484
15485 static void sdom_block(struct sdom_block *sdom, struct sdom_block *block)
15486 {
15487         unsdom_block(block);
15488         block->sdom = sdom;
15489         block->sdom_next = sdom->sdominates;
15490         sdom->sdominates = block;
15491 }
15492
15493
15494
15495 static int initialize_sdblock(struct sdom_block *sd,
15496         struct block *parent, struct block *block, int vertex)
15497 {
15498         struct block_set *edge;
15499         if (!block || (sd[block->vertex].block == block)) {
15500                 return vertex;
15501         }
15502         vertex += 1;
15503         /* Renumber the blocks in a convinient fashion */
15504         block->vertex = vertex;
15505         sd[vertex].block    = block;
15506         sd[vertex].sdom     = &sd[vertex];
15507         sd[vertex].label    = &sd[vertex];
15508         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
15509         sd[vertex].ancestor = 0;
15510         sd[vertex].vertex   = vertex;
15511         for(edge = block->edges; edge; edge = edge->next) {
15512                 vertex = initialize_sdblock(sd, block, edge->member, vertex);
15513         }
15514         return vertex;
15515 }
15516
15517 static int initialize_spdblock(
15518         struct compile_state *state, struct sdom_block *sd,
15519         struct block *parent, struct block *block, int vertex)
15520 {
15521         struct block_set *user;
15522         if (!block || (sd[block->vertex].block == block)) {
15523                 return vertex;
15524         }
15525         vertex += 1;
15526         /* Renumber the blocks in a convinient fashion */
15527         block->vertex = vertex;
15528         sd[vertex].block    = block;
15529         sd[vertex].sdom     = &sd[vertex];
15530         sd[vertex].label    = &sd[vertex];
15531         sd[vertex].parent   = parent? &sd[parent->vertex] : 0;
15532         sd[vertex].ancestor = 0;
15533         sd[vertex].vertex   = vertex;
15534         for(user = block->use; user; user = user->next) {
15535                 vertex = initialize_spdblock(state, sd, block, user->member, vertex);
15536         }
15537         return vertex;
15538 }
15539
15540 static int setup_spdblocks(struct compile_state *state,
15541         struct basic_blocks *bb, struct sdom_block *sd)
15542 {
15543         struct block *block;
15544         int vertex;
15545         /* Setup as many sdpblocks as possible without using fake edges */
15546         vertex = initialize_spdblock(state, sd, 0, bb->last_block, 0);
15547
15548         /* Walk through the graph and find unconnected blocks.  Add a
15549          * fake edge from the unconnected blocks to the end of the
15550          * graph.
15551          */
15552         block = bb->first_block->last->next->u.block;
15553         for(; block && block != bb->first_block; block = block->last->next->u.block) {
15554                 if (sd[block->vertex].block == block) {
15555                         continue;
15556                 }
15557 #if DEBUG_SDP_BLOCKS
15558                 {
15559                         FILE *fp = state->errout;
15560                         fprintf(fp, "Adding %d\n", vertex +1);
15561                 }
15562 #endif
15563                 add_block_edge(block, bb->last_block, 0);
15564                 use_block(bb->last_block, block);
15565
15566                 vertex = initialize_spdblock(state, sd, bb->last_block, block, vertex);
15567         }
15568         return vertex;
15569 }
15570
15571 static void compress_ancestors(struct sdom_block *v)
15572 {
15573         /* This procedure assumes ancestor(v) != 0 */
15574         /* if (ancestor(ancestor(v)) != 0) {
15575          *      compress(ancestor(ancestor(v)));
15576          *      if (semi(label(ancestor(v))) < semi(label(v))) {
15577          *              label(v) = label(ancestor(v));
15578          *      }
15579          *      ancestor(v) = ancestor(ancestor(v));
15580          * }
15581          */
15582         if (!v->ancestor) {
15583                 return;
15584         }
15585         if (v->ancestor->ancestor) {
15586                 compress_ancestors(v->ancestor->ancestor);
15587                 if (v->ancestor->label->sdom->vertex < v->label->sdom->vertex) {
15588                         v->label = v->ancestor->label;
15589                 }
15590                 v->ancestor = v->ancestor->ancestor;
15591         }
15592 }
15593
15594 static void compute_sdom(struct compile_state *state,
15595         struct basic_blocks *bb, struct sdom_block *sd)
15596 {
15597         int i;
15598         /* // step 2
15599          *  for each v <= pred(w) {
15600          *      u = EVAL(v);
15601          *      if (semi[u] < semi[w] {
15602          *              semi[w] = semi[u];
15603          *      }
15604          * }
15605          * add w to bucket(vertex(semi[w]));
15606          * LINK(parent(w), w);
15607          *
15608          * // step 3
15609          * for each v <= bucket(parent(w)) {
15610          *      delete v from bucket(parent(w));
15611          *      u = EVAL(v);
15612          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15613          * }
15614          */
15615         for(i = bb->last_vertex; i >= 2; i--) {
15616                 struct sdom_block *v, *parent, *next;
15617                 struct block_set *user;
15618                 struct block *block;
15619                 block = sd[i].block;
15620                 parent = sd[i].parent;
15621                 /* Step 2 */
15622                 for(user = block->use; user; user = user->next) {
15623                         struct sdom_block *v, *u;
15624                         v = &sd[user->member->vertex];
15625                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15626                         if (u->sdom->vertex < sd[i].sdom->vertex) {
15627                                 sd[i].sdom = u->sdom;
15628                         }
15629                 }
15630                 sdom_block(sd[i].sdom, &sd[i]);
15631                 sd[i].ancestor = parent;
15632                 /* Step 3 */
15633                 for(v = parent->sdominates; v; v = next) {
15634                         struct sdom_block *u;
15635                         next = v->sdom_next;
15636                         unsdom_block(v);
15637                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15638                         v->block->idom = (u->sdom->vertex < v->sdom->vertex)?
15639                                 u->block : parent->block;
15640                 }
15641         }
15642 }
15643
15644 static void compute_spdom(struct compile_state *state,
15645         struct basic_blocks *bb, struct sdom_block *sd)
15646 {
15647         int i;
15648         /* // step 2
15649          *  for each v <= pred(w) {
15650          *      u = EVAL(v);
15651          *      if (semi[u] < semi[w] {
15652          *              semi[w] = semi[u];
15653          *      }
15654          * }
15655          * add w to bucket(vertex(semi[w]));
15656          * LINK(parent(w), w);
15657          *
15658          * // step 3
15659          * for each v <= bucket(parent(w)) {
15660          *      delete v from bucket(parent(w));
15661          *      u = EVAL(v);
15662          *      dom(v) = (semi[u] < semi[v]) ? u : parent(w);
15663          * }
15664          */
15665         for(i = bb->last_vertex; i >= 2; i--) {
15666                 struct sdom_block *u, *v, *parent, *next;
15667                 struct block_set *edge;
15668                 struct block *block;
15669                 block = sd[i].block;
15670                 parent = sd[i].parent;
15671                 /* Step 2 */
15672                 for(edge = block->edges; edge; edge = edge->next) {
15673                         v = &sd[edge->member->vertex];
15674                         u = !(v->ancestor)? v : (compress_ancestors(v), v->label);
15675                         if (u->sdom->vertex < sd[i].sdom->vertex) {
15676                                 sd[i].sdom = u->sdom;
15677                         }
15678                 }
15679                 sdom_block(sd[i].sdom, &sd[i]);
15680                 sd[i].ancestor = parent;
15681                 /* Step 3 */
15682                 for(v = parent->sdominates; v; v = next) {
15683                         struct sdom_block *u;
15684                         next = v->sdom_next;
15685                         unsdom_block(v);
15686                         u = (!v->ancestor) ? v : (compress_ancestors(v), v->label);
15687                         v->block->ipdom = (u->sdom->vertex < v->sdom->vertex)?
15688                                 u->block : parent->block;
15689                 }
15690         }
15691 }
15692
15693 static void compute_idom(struct compile_state *state,
15694         struct basic_blocks *bb, struct sdom_block *sd)
15695 {
15696         int i;
15697         for(i = 2; i <= bb->last_vertex; i++) {
15698                 struct block *block;
15699                 block = sd[i].block;
15700                 if (block->idom->vertex != sd[i].sdom->vertex) {
15701                         block->idom = block->idom->idom;
15702                 }
15703                 idom_block(block->idom, block);
15704         }
15705         sd[1].block->idom = 0;
15706 }
15707
15708 static void compute_ipdom(struct compile_state *state,
15709         struct basic_blocks *bb, struct sdom_block *sd)
15710 {
15711         int i;
15712         for(i = 2; i <= bb->last_vertex; i++) {
15713                 struct block *block;
15714                 block = sd[i].block;
15715                 if (block->ipdom->vertex != sd[i].sdom->vertex) {
15716                         block->ipdom = block->ipdom->ipdom;
15717                 }
15718                 ipdom_block(block->ipdom, block);
15719         }
15720         sd[1].block->ipdom = 0;
15721 }
15722
15723         /* Theorem 1:
15724          *   Every vertex of a flowgraph G = (V, E, r) except r has
15725          *   a unique immediate dominator.
15726          *   The edges {(idom(w), w) |w <= V - {r}} form a directed tree
15727          *   rooted at r, called the dominator tree of G, such that
15728          *   v dominates w if and only if v is a proper ancestor of w in
15729          *   the dominator tree.
15730          */
15731         /* Lemma 1:
15732          *   If v and w are vertices of G such that v <= w,
15733          *   than any path from v to w must contain a common ancestor
15734          *   of v and w in T.
15735          */
15736         /* Lemma 2:  For any vertex w != r, idom(w) -> w */
15737         /* Lemma 3:  For any vertex w != r, sdom(w) -> w */
15738         /* Lemma 4:  For any vertex w != r, idom(w) -> sdom(w) */
15739         /* Theorem 2:
15740          *   Let w != r.  Suppose every u for which sdom(w) -> u -> w satisfies
15741          *   sdom(u) >= sdom(w).  Then idom(w) = sdom(w).
15742          */
15743         /* Theorem 3:
15744          *   Let w != r and let u be a vertex for which sdom(u) is
15745          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
15746          *   Then sdom(u) <= sdom(w) and idom(u) = idom(w).
15747          */
15748         /* Lemma 5:  Let vertices v,w satisfy v -> w.
15749          *           Then v -> idom(w) or idom(w) -> idom(v)
15750          */
15751
15752 static void find_immediate_dominators(struct compile_state *state,
15753         struct basic_blocks *bb)
15754 {
15755         struct sdom_block *sd;
15756         /* w->sdom = min{v| there is a path v = v0,v1,...,vk = w such that:
15757          *           vi > w for (1 <= i <= k - 1}
15758          */
15759         /* Theorem 4:
15760          *   For any vertex w != r.
15761          *   sdom(w) = min(
15762          *                 {v|(v,w) <= E  and v < w } U
15763          *                 {sdom(u) | u > w and there is an edge (v, w) such that u -> v})
15764          */
15765         /* Corollary 1:
15766          *   Let w != r and let u be a vertex for which sdom(u) is
15767          *   minimum amoung vertices u satisfying sdom(w) -> u -> w.
15768          *   Then:
15769          *                   { sdom(w) if sdom(w) = sdom(u),
15770          *        idom(w) = {
15771          *                   { idom(u) otherwise
15772          */
15773         /* The algorithm consists of the following 4 steps.
15774          * Step 1.  Carry out a depth-first search of the problem graph.
15775          *    Number the vertices from 1 to N as they are reached during
15776          *    the search.  Initialize the variables used in succeeding steps.
15777          * Step 2.  Compute the semidominators of all vertices by applying
15778          *    theorem 4.   Carry out the computation vertex by vertex in
15779          *    decreasing order by number.
15780          * Step 3.  Implicitly define the immediate dominator of each vertex
15781          *    by applying Corollary 1.
15782          * Step 4.  Explicitly define the immediate dominator of each vertex,
15783          *    carrying out the computation vertex by vertex in increasing order
15784          *    by number.
15785          */
15786         /* Step 1 initialize the basic block information */
15787         sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15788         initialize_sdblock(sd, 0, bb->first_block, 0);
15789 #if 0
15790         sd[1].size  = 0;
15791         sd[1].label = 0;
15792         sd[1].sdom  = 0;
15793 #endif
15794         /* Step 2 compute the semidominators */
15795         /* Step 3 implicitly define the immediate dominator of each vertex */
15796         compute_sdom(state, bb, sd);
15797         /* Step 4 explicitly define the immediate dominator of each vertex */
15798         compute_idom(state, bb, sd);
15799         xfree(sd);
15800 }
15801
15802 static void find_post_dominators(struct compile_state *state,
15803         struct basic_blocks *bb)
15804 {
15805         struct sdom_block *sd;
15806         int vertex;
15807         /* Step 1 initialize the basic block information */
15808         sd = xcmalloc(sizeof(*sd) * (bb->last_vertex + 1), "sdom_state");
15809
15810         vertex = setup_spdblocks(state, bb, sd);
15811         if (vertex != bb->last_vertex) {
15812                 internal_error(state, 0, "missing %d blocks",
15813                         bb->last_vertex - vertex);
15814         }
15815
15816         /* Step 2 compute the semidominators */
15817         /* Step 3 implicitly define the immediate dominator of each vertex */
15818         compute_spdom(state, bb, sd);
15819         /* Step 4 explicitly define the immediate dominator of each vertex */
15820         compute_ipdom(state, bb, sd);
15821         xfree(sd);
15822 }
15823
15824
15825
15826 static void find_block_domf(struct compile_state *state, struct block *block)
15827 {
15828         struct block *child;
15829         struct block_set *user, *edge;
15830         if (block->domfrontier != 0) {
15831                 internal_error(state, block->first, "domfrontier present?");
15832         }
15833         for(user = block->idominates; user; user = user->next) {
15834                 child = user->member;
15835                 if (child->idom != block) {
15836                         internal_error(state, block->first, "bad idom");
15837                 }
15838                 find_block_domf(state, child);
15839         }
15840         for(edge = block->edges; edge; edge = edge->next) {
15841                 if (edge->member->idom != block) {
15842                         domf_block(block, edge->member);
15843                 }
15844         }
15845         for(user = block->idominates; user; user = user->next) {
15846                 struct block_set *frontier;
15847                 child = user->member;
15848                 for(frontier = child->domfrontier; frontier; frontier = frontier->next) {
15849                         if (frontier->member->idom != block) {
15850                                 domf_block(block, frontier->member);
15851                         }
15852                 }
15853         }
15854 }
15855
15856 static void find_block_ipdomf(struct compile_state *state, struct block *block)
15857 {
15858         struct block *child;
15859         struct block_set *user;
15860         if (block->ipdomfrontier != 0) {
15861                 internal_error(state, block->first, "ipdomfrontier present?");
15862         }
15863         for(user = block->ipdominates; user; user = user->next) {
15864                 child = user->member;
15865                 if (child->ipdom != block) {
15866                         internal_error(state, block->first, "bad ipdom");
15867                 }
15868                 find_block_ipdomf(state, child);
15869         }
15870         for(user = block->use; user; user = user->next) {
15871                 if (user->member->ipdom != block) {
15872                         ipdomf_block(block, user->member);
15873                 }
15874         }
15875         for(user = block->ipdominates; user; user = user->next) {
15876                 struct block_set *frontier;
15877                 child = user->member;
15878                 for(frontier = child->ipdomfrontier; frontier; frontier = frontier->next) {
15879                         if (frontier->member->ipdom != block) {
15880                                 ipdomf_block(block, frontier->member);
15881                         }
15882                 }
15883         }
15884 }
15885
15886 static void print_dominated(
15887         struct compile_state *state, struct block *block, void *arg)
15888 {
15889         struct block_set *user;
15890         FILE *fp = arg;
15891
15892         fprintf(fp, "%d:", block->vertex);
15893         for(user = block->idominates; user; user = user->next) {
15894                 fprintf(fp, " %d", user->member->vertex);
15895                 if (user->member->idom != block) {
15896                         internal_error(state, user->member->first, "bad idom");
15897                 }
15898         }
15899         fprintf(fp,"\n");
15900 }
15901
15902 static void print_dominated2(
15903         struct compile_state *state, FILE *fp, int depth, struct block *block)
15904 {
15905         struct block_set *user;
15906         struct triple *ins;
15907         struct occurance *ptr, *ptr2;
15908         const char *filename1, *filename2;
15909         int equal_filenames;
15910         int i;
15911         for(i = 0; i < depth; i++) {
15912                 fprintf(fp, "   ");
15913         }
15914         fprintf(fp, "%3d: %p (%p - %p) @",
15915                 block->vertex, block, block->first, block->last);
15916         ins = block->first;
15917         while(ins != block->last && (ins->occurance->line == 0)) {
15918                 ins = ins->next;
15919         }
15920         ptr = ins->occurance;
15921         ptr2 = block->last->occurance;
15922         filename1 = ptr->filename? ptr->filename : "";
15923         filename2 = ptr2->filename? ptr2->filename : "";
15924         equal_filenames = (strcmp(filename1, filename2) == 0);
15925         if ((ptr == ptr2) || (equal_filenames && ptr->line == ptr2->line)) {
15926                 fprintf(fp, " %s:%d", ptr->filename, ptr->line);
15927         } else if (equal_filenames) {
15928                 fprintf(fp, " %s:(%d - %d)",
15929                         ptr->filename, ptr->line, ptr2->line);
15930         } else {
15931                 fprintf(fp, " (%s:%d - %s:%d)",
15932                         ptr->filename, ptr->line,
15933                         ptr2->filename, ptr2->line);
15934         }
15935         fprintf(fp, "\n");
15936         for(user = block->idominates; user; user = user->next) {
15937                 print_dominated2(state, fp, depth + 1, user->member);
15938         }
15939 }
15940
15941 static void print_dominators(struct compile_state *state, FILE *fp, struct basic_blocks *bb)
15942 {
15943         fprintf(fp, "\ndominates\n");
15944         walk_blocks(state, bb, print_dominated, fp);
15945         fprintf(fp, "dominates\n");
15946         print_dominated2(state, fp, 0, bb->first_block);
15947 }
15948
15949
15950 static int print_frontiers(
15951         struct compile_state *state, FILE *fp, struct block *block, int vertex)
15952 {
15953         struct block_set *user, *edge;
15954
15955         if (!block || (block->vertex != vertex + 1)) {
15956                 return vertex;
15957         }
15958         vertex += 1;
15959
15960         fprintf(fp, "%d:", block->vertex);
15961         for(user = block->domfrontier; user; user = user->next) {
15962                 fprintf(fp, " %d", user->member->vertex);
15963         }
15964         fprintf(fp, "\n");
15965
15966         for(edge = block->edges; edge; edge = edge->next) {
15967                 vertex = print_frontiers(state, fp, edge->member, vertex);
15968         }
15969         return vertex;
15970 }
15971 static void print_dominance_frontiers(struct compile_state *state,
15972         FILE *fp, struct basic_blocks *bb)
15973 {
15974         fprintf(fp, "\ndominance frontiers\n");
15975         print_frontiers(state, fp, bb->first_block, 0);
15976
15977 }
15978
15979 static void analyze_idominators(struct compile_state *state, struct basic_blocks *bb)
15980 {
15981         /* Find the immediate dominators */
15982         find_immediate_dominators(state, bb);
15983         /* Find the dominance frontiers */
15984         find_block_domf(state, bb->first_block);
15985         /* If debuging print the print what I have just found */
15986         if (state->compiler->debug & DEBUG_FDOMINATORS) {
15987                 print_dominators(state, state->dbgout, bb);
15988                 print_dominance_frontiers(state, state->dbgout, bb);
15989                 print_control_flow(state, state->dbgout, bb);
15990         }
15991 }
15992
15993
15994 static void print_ipdominated(
15995         struct compile_state *state, struct block *block, void *arg)
15996 {
15997         struct block_set *user;
15998         FILE *fp = arg;
15999
16000         fprintf(fp, "%d:", block->vertex);
16001         for(user = block->ipdominates; user; user = user->next) {
16002                 fprintf(fp, " %d", user->member->vertex);
16003                 if (user->member->ipdom != block) {
16004                         internal_error(state, user->member->first, "bad ipdom");
16005                 }
16006         }
16007         fprintf(fp, "\n");
16008 }
16009
16010 static void print_ipdominators(struct compile_state *state, FILE *fp,
16011         struct basic_blocks *bb)
16012 {
16013         fprintf(fp, "\nipdominates\n");
16014         walk_blocks(state, bb, print_ipdominated, fp);
16015 }
16016
16017 static int print_pfrontiers(
16018         struct compile_state *state, FILE *fp, struct block *block, int vertex)
16019 {
16020         struct block_set *user;
16021
16022         if (!block || (block->vertex != vertex + 1)) {
16023                 return vertex;
16024         }
16025         vertex += 1;
16026
16027         fprintf(fp, "%d:", block->vertex);
16028         for(user = block->ipdomfrontier; user; user = user->next) {
16029                 fprintf(fp, " %d", user->member->vertex);
16030         }
16031         fprintf(fp, "\n");
16032         for(user = block->use; user; user = user->next) {
16033                 vertex = print_pfrontiers(state, fp, user->member, vertex);
16034         }
16035         return vertex;
16036 }
16037 static void print_ipdominance_frontiers(struct compile_state *state,
16038         FILE *fp, struct basic_blocks *bb)
16039 {
16040         fprintf(fp, "\nipdominance frontiers\n");
16041         print_pfrontiers(state, fp, bb->last_block, 0);
16042
16043 }
16044
16045 static void analyze_ipdominators(struct compile_state *state,
16046         struct basic_blocks *bb)
16047 {
16048         /* Find the post dominators */
16049         find_post_dominators(state, bb);
16050         /* Find the control dependencies (post dominance frontiers) */
16051         find_block_ipdomf(state, bb->last_block);
16052         /* If debuging print the print what I have just found */
16053         if (state->compiler->debug & DEBUG_RDOMINATORS) {
16054                 print_ipdominators(state, state->dbgout, bb);
16055                 print_ipdominance_frontiers(state, state->dbgout, bb);
16056                 print_control_flow(state, state->dbgout, bb);
16057         }
16058 }
16059
16060 static int bdominates(struct compile_state *state,
16061         struct block *dom, struct block *sub)
16062 {
16063         while(sub && (sub != dom)) {
16064                 sub = sub->idom;
16065         }
16066         return sub == dom;
16067 }
16068
16069 static int tdominates(struct compile_state *state,
16070         struct triple *dom, struct triple *sub)
16071 {
16072         struct block *bdom, *bsub;
16073         int result;
16074         bdom = block_of_triple(state, dom);
16075         bsub = block_of_triple(state, sub);
16076         if (bdom != bsub) {
16077                 result = bdominates(state, bdom, bsub);
16078         }
16079         else {
16080                 struct triple *ins;
16081                 if (!bdom || !bsub) {
16082                         internal_error(state, dom, "huh?");
16083                 }
16084                 ins = sub;
16085                 while((ins != bsub->first) && (ins != dom)) {
16086                         ins = ins->prev;
16087                 }
16088                 result = (ins == dom);
16089         }
16090         return result;
16091 }
16092
16093 static void analyze_basic_blocks(
16094         struct compile_state *state, struct basic_blocks *bb)
16095 {
16096         setup_basic_blocks(state, bb);
16097         analyze_idominators(state, bb);
16098         analyze_ipdominators(state, bb);
16099 }
16100
16101 static void insert_phi_operations(struct compile_state *state)
16102 {
16103         size_t size;
16104         struct triple *first;
16105         int *has_already, *work;
16106         struct block *work_list, **work_list_tail;
16107         int iter;
16108         struct triple *var, *vnext;
16109
16110         size = sizeof(int) * (state->bb.last_vertex + 1);
16111         has_already = xcmalloc(size, "has_already");
16112         work =        xcmalloc(size, "work");
16113         iter = 0;
16114
16115         first = state->first;
16116         for(var = first->next; var != first ; var = vnext) {
16117                 struct block *block;
16118                 struct triple_set *user, *unext;
16119                 vnext = var->next;
16120
16121                 if (!triple_is_auto_var(state, var) || !var->use) {
16122                         continue;
16123                 }
16124
16125                 iter += 1;
16126                 work_list = 0;
16127                 work_list_tail = &work_list;
16128                 for(user = var->use; user; user = unext) {
16129                         unext = user->next;
16130                         if (MISC(var, 0) == user->member) {
16131                                 continue;
16132                         }
16133                         if (user->member->op == OP_READ) {
16134                                 continue;
16135                         }
16136                         if (user->member->op != OP_WRITE) {
16137                                 internal_error(state, user->member,
16138                                         "bad variable access");
16139                         }
16140                         block = user->member->u.block;
16141                         if (!block) {
16142                                 warning(state, user->member, "dead code");
16143                                 release_triple(state, user->member);
16144                                 continue;
16145                         }
16146                         if (work[block->vertex] >= iter) {
16147                                 continue;
16148                         }
16149                         work[block->vertex] = iter;
16150                         *work_list_tail = block;
16151                         block->work_next = 0;
16152                         work_list_tail = &block->work_next;
16153                 }
16154                 for(block = work_list; block; block = block->work_next) {
16155                         struct block_set *df;
16156                         for(df = block->domfrontier; df; df = df->next) {
16157                                 struct triple *phi;
16158                                 struct block *front;
16159                                 int in_edges;
16160                                 front = df->member;
16161
16162                                 if (has_already[front->vertex] >= iter) {
16163                                         continue;
16164                                 }
16165                                 /* Count how many edges flow into this block */
16166                                 in_edges = front->users;
16167                                 /* Insert a phi function for this variable */
16168                                 get_occurance(var->occurance);
16169                                 phi = alloc_triple(
16170                                         state, OP_PHI, var->type, -1, in_edges,
16171                                         var->occurance);
16172                                 phi->u.block = front;
16173                                 MISC(phi, 0) = var;
16174                                 use_triple(var, phi);
16175 #if 1
16176                                 if (phi->rhs != in_edges) {
16177                                         internal_error(state, phi, "phi->rhs: %d != in_edges: %d",
16178                                                 phi->rhs, in_edges);
16179                                 }
16180 #endif
16181                                 /* Insert the phi functions immediately after the label */
16182                                 insert_triple(state, front->first->next, phi);
16183                                 if (front->first == front->last) {
16184                                         front->last = front->first->next;
16185                                 }
16186                                 has_already[front->vertex] = iter;
16187                                 transform_to_arch_instruction(state, phi);
16188
16189                                 /* If necessary plan to visit the basic block */
16190                                 if (work[front->vertex] >= iter) {
16191                                         continue;
16192                                 }
16193                                 work[front->vertex] = iter;
16194                                 *work_list_tail = front;
16195                                 front->work_next = 0;
16196                                 work_list_tail = &front->work_next;
16197                         }
16198                 }
16199         }
16200         xfree(has_already);
16201         xfree(work);
16202 }
16203
16204
16205 struct stack {
16206         struct triple_set *top;
16207         unsigned orig_id;
16208 };
16209
16210 static int count_auto_vars(struct compile_state *state)
16211 {
16212         struct triple *first, *ins;
16213         int auto_vars = 0;
16214         first = state->first;
16215         ins = first;
16216         do {
16217                 if (triple_is_auto_var(state, ins)) {
16218                         auto_vars += 1;
16219                 }
16220                 ins = ins->next;
16221         } while(ins != first);
16222         return auto_vars;
16223 }
16224
16225 static void number_auto_vars(struct compile_state *state, struct stack *stacks)
16226 {
16227         struct triple *first, *ins;
16228         int auto_vars = 0;
16229         first = state->first;
16230         ins = first;
16231         do {
16232                 if (triple_is_auto_var(state, ins)) {
16233                         auto_vars += 1;
16234                         stacks[auto_vars].orig_id = ins->id;
16235                         ins->id = auto_vars;
16236                 }
16237                 ins = ins->next;
16238         } while(ins != first);
16239 }
16240
16241 static void restore_auto_vars(struct compile_state *state, struct stack *stacks)
16242 {
16243         struct triple *first, *ins;
16244         first = state->first;
16245         ins = first;
16246         do {
16247                 if (triple_is_auto_var(state, ins)) {
16248                         ins->id = stacks[ins->id].orig_id;
16249                 }
16250                 ins = ins->next;
16251         } while(ins != first);
16252 }
16253
16254 static struct triple *peek_triple(struct stack *stacks, struct triple *var)
16255 {
16256         struct triple_set *head;
16257         struct triple *top_val;
16258         top_val = 0;
16259         head = stacks[var->id].top;
16260         if (head) {
16261                 top_val = head->member;
16262         }
16263         return top_val;
16264 }
16265
16266 static void push_triple(struct stack *stacks, struct triple *var, struct triple *val)
16267 {
16268         struct triple_set *new;
16269         /* Append new to the head of the list,
16270          * it's the only sensible behavoir for a stack.
16271          */
16272         new = xcmalloc(sizeof(*new), "triple_set");
16273         new->member = val;
16274         new->next   = stacks[var->id].top;
16275         stacks[var->id].top = new;
16276 }
16277
16278 static void pop_triple(struct stack *stacks, struct triple *var, struct triple *oldval)
16279 {
16280         struct triple_set *set, **ptr;
16281         ptr = &stacks[var->id].top;
16282         while(*ptr) {
16283                 set = *ptr;
16284                 if (set->member == oldval) {
16285                         *ptr = set->next;
16286                         xfree(set);
16287                         /* Only free one occurance from the stack */
16288                         return;
16289                 }
16290                 else {
16291                         ptr = &set->next;
16292                 }
16293         }
16294 }
16295
16296 /*
16297  * C(V)
16298  * S(V)
16299  */
16300 static void fixup_block_phi_variables(
16301         struct compile_state *state, struct stack *stacks, struct block *parent, struct block *block)
16302 {
16303         struct block_set *set;
16304         struct triple *ptr;
16305         int edge;
16306         if (!parent || !block)
16307                 return;
16308         /* Find the edge I am coming in on */
16309         edge = 0;
16310         for(set = block->use; set; set = set->next, edge++) {
16311                 if (set->member == parent) {
16312                         break;
16313                 }
16314         }
16315         if (!set) {
16316                 internal_error(state, 0, "phi input is not on a control predecessor");
16317         }
16318         for(ptr = block->first; ; ptr = ptr->next) {
16319                 if (ptr->op == OP_PHI) {
16320                         struct triple *var, *val, **slot;
16321                         var = MISC(ptr, 0);
16322                         if (!var) {
16323                                 internal_error(state, ptr, "no var???");
16324                         }
16325                         /* Find the current value of the variable */
16326                         val = peek_triple(stacks, var);
16327                         if (val && ((val->op == OP_WRITE) || (val->op == OP_READ))) {
16328                                 internal_error(state, val, "bad value in phi");
16329                         }
16330                         if (edge >= ptr->rhs) {
16331                                 internal_error(state, ptr, "edges > phi rhs");
16332                         }
16333                         slot = &RHS(ptr, edge);
16334                         if ((*slot != 0) && (*slot != val)) {
16335                                 internal_error(state, ptr, "phi already bound on this edge");
16336                         }
16337                         *slot = val;
16338                         use_triple(val, ptr);
16339                 }
16340                 if (ptr == block->last) {
16341                         break;
16342                 }
16343         }
16344 }
16345
16346
16347 static void rename_block_variables(
16348         struct compile_state *state, struct stack *stacks, struct block *block)
16349 {
16350         struct block_set *user, *edge;
16351         struct triple *ptr, *next, *last;
16352         int done;
16353         if (!block)
16354                 return;
16355         last = block->first;
16356         done = 0;
16357         for(ptr = block->first; !done; ptr = next) {
16358                 next = ptr->next;
16359                 if (ptr == block->last) {
16360                         done = 1;
16361                 }
16362                 /* RHS(A) */
16363                 if (ptr->op == OP_READ) {
16364                         struct triple *var, *val;
16365                         var = RHS(ptr, 0);
16366                         if (!triple_is_auto_var(state, var)) {
16367                                 internal_error(state, ptr, "read of non auto var!");
16368                         }
16369                         unuse_triple(var, ptr);
16370                         /* Find the current value of the variable */
16371                         val = peek_triple(stacks, var);
16372                         if (!val) {
16373                                 /* Let the optimizer at variables that are not initially
16374                                  * set.  But give it a bogus value so things seem to
16375                                  * work by accident.  This is useful for bitfields because
16376                                  * setting them always involves a read-modify-write.
16377                                  */
16378                                 if (TYPE_ARITHMETIC(ptr->type->type)) {
16379                                         val = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16380                                         val->u.cval = 0xdeadbeaf;
16381                                 } else {
16382                                         val = pre_triple(state, ptr, OP_UNKNOWNVAL, ptr->type, 0, 0);
16383                                 }
16384                         }
16385                         if (!val) {
16386                                 error(state, ptr, "variable used without being set");
16387                         }
16388                         if ((val->op == OP_WRITE) || (val->op == OP_READ)) {
16389                                 internal_error(state, val, "bad value in read");
16390                         }
16391                         propogate_use(state, ptr, val);
16392                         release_triple(state, ptr);
16393                         continue;
16394                 }
16395                 /* LHS(A) */
16396                 if (ptr->op == OP_WRITE) {
16397                         struct triple *var, *val, *tval;
16398                         var = MISC(ptr, 0);
16399                         if (!triple_is_auto_var(state, var)) {
16400                                 internal_error(state, ptr, "write to non auto var!");
16401                         }
16402                         tval = val = RHS(ptr, 0);
16403                         if ((val->op == OP_WRITE) || (val->op == OP_READ) ||
16404                                 triple_is_auto_var(state, val)) {
16405                                 internal_error(state, ptr, "bad value in write");
16406                         }
16407                         /* Insert a cast if the types differ */
16408                         if (!is_subset_type(ptr->type, val->type)) {
16409                                 if (val->op == OP_INTCONST) {
16410                                         tval = pre_triple(state, ptr, OP_INTCONST, ptr->type, 0, 0);
16411                                         tval->u.cval = val->u.cval;
16412                                 }
16413                                 else {
16414                                         tval = pre_triple(state, ptr, OP_CONVERT, ptr->type, val, 0);
16415                                         use_triple(val, tval);
16416                                 }
16417                                 transform_to_arch_instruction(state, tval);
16418                                 unuse_triple(val, ptr);
16419                                 RHS(ptr, 0) = tval;
16420                                 use_triple(tval, ptr);
16421                         }
16422                         propogate_use(state, ptr, tval);
16423                         unuse_triple(var, ptr);
16424                         /* Push OP_WRITE ptr->right onto a stack of variable uses */
16425                         push_triple(stacks, var, tval);
16426                 }
16427                 if (ptr->op == OP_PHI) {
16428                         struct triple *var;
16429                         var = MISC(ptr, 0);
16430                         if (!triple_is_auto_var(state, var)) {
16431                                 internal_error(state, ptr, "phi references non auto var!");
16432                         }
16433                         /* Push OP_PHI onto a stack of variable uses */
16434                         push_triple(stacks, var, ptr);
16435                 }
16436                 last = ptr;
16437         }
16438         block->last = last;
16439
16440         /* Fixup PHI functions in the cf successors */
16441         for(edge = block->edges; edge; edge = edge->next) {
16442                 fixup_block_phi_variables(state, stacks, block, edge->member);
16443         }
16444         /* rename variables in the dominated nodes */
16445         for(user = block->idominates; user; user = user->next) {
16446                 rename_block_variables(state, stacks, user->member);
16447         }
16448         /* pop the renamed variable stack */
16449         last = block->first;
16450         done = 0;
16451         for(ptr = block->first; !done ; ptr = next) {
16452                 next = ptr->next;
16453                 if (ptr == block->last) {
16454                         done = 1;
16455                 }
16456                 if (ptr->op == OP_WRITE) {
16457                         struct triple *var;
16458                         var = MISC(ptr, 0);
16459                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
16460                         pop_triple(stacks, var, RHS(ptr, 0));
16461                         release_triple(state, ptr);
16462                         continue;
16463                 }
16464                 if (ptr->op == OP_PHI) {
16465                         struct triple *var;
16466                         var = MISC(ptr, 0);
16467                         /* Pop OP_WRITE ptr->right from the stack of variable uses */
16468                         pop_triple(stacks, var, ptr);
16469                 }
16470                 last = ptr;
16471         }
16472         block->last = last;
16473 }
16474
16475 static void rename_variables(struct compile_state *state)
16476 {
16477         struct stack *stacks;
16478         int auto_vars;
16479
16480         /* Allocate stacks for the Variables */
16481         auto_vars = count_auto_vars(state);
16482         stacks = xcmalloc(sizeof(stacks[0])*(auto_vars + 1), "auto var stacks");
16483
16484         /* Give each auto_var a stack */
16485         number_auto_vars(state, stacks);
16486
16487         /* Rename the variables */
16488         rename_block_variables(state, stacks, state->bb.first_block);
16489
16490         /* Remove the stacks from the auto_vars */
16491         restore_auto_vars(state, stacks);
16492         xfree(stacks);
16493 }
16494
16495 static void prune_block_variables(struct compile_state *state,
16496         struct block *block)
16497 {
16498         struct block_set *user;
16499         struct triple *next, *ptr;
16500         int done;
16501
16502         done = 0;
16503         for(ptr = block->first; !done; ptr = next) {
16504                 /* Be extremely careful I am deleting the list
16505                  * as I walk trhough it.
16506                  */
16507                 next = ptr->next;
16508                 if (ptr == block->last) {
16509                         done = 1;
16510                 }
16511                 if (triple_is_auto_var(state, ptr)) {
16512                         struct triple_set *user, *next;
16513                         for(user = ptr->use; user; user = next) {
16514                                 struct triple *use;
16515                                 next = user->next;
16516                                 use = user->member;
16517                                 if (MISC(ptr, 0) == user->member) {
16518                                         continue;
16519                                 }
16520                                 if (use->op != OP_PHI) {
16521                                         internal_error(state, use, "decl still used");
16522                                 }
16523                                 if (MISC(use, 0) != ptr) {
16524                                         internal_error(state, use, "bad phi use of decl");
16525                                 }
16526                                 unuse_triple(ptr, use);
16527                                 MISC(use, 0) = 0;
16528                         }
16529                         if ((ptr->u.cval == 0) && (MISC(ptr, 0)->lhs == 1)) {
16530                                 /* Delete the adecl */
16531                                 release_triple(state, MISC(ptr, 0));
16532                                 /* And the piece */
16533                                 release_triple(state, ptr);
16534                         }
16535                         continue;
16536                 }
16537         }
16538         for(user = block->idominates; user; user = user->next) {
16539                 prune_block_variables(state, user->member);
16540         }
16541 }
16542
16543 struct phi_triple {
16544         struct triple *phi;
16545         unsigned orig_id;
16546         int alive;
16547 };
16548
16549 static void keep_phi(struct compile_state *state, struct phi_triple *live, struct triple *phi)
16550 {
16551         struct triple **slot;
16552         int zrhs, i;
16553         if (live[phi->id].alive) {
16554                 return;
16555         }
16556         live[phi->id].alive = 1;
16557         zrhs = phi->rhs;
16558         slot = &RHS(phi, 0);
16559         for(i = 0; i < zrhs; i++) {
16560                 struct triple *used;
16561                 used = slot[i];
16562                 if (used && (used->op == OP_PHI)) {
16563                         keep_phi(state, live, used);
16564                 }
16565         }
16566 }
16567
16568 static void prune_unused_phis(struct compile_state *state)
16569 {
16570         struct triple *first, *phi;
16571         struct phi_triple *live;
16572         int phis, i;
16573
16574         /* Find the first instruction */
16575         first = state->first;
16576
16577         /* Count how many phi functions I need to process */
16578         phis = 0;
16579         for(phi = first->next; phi != first; phi = phi->next) {
16580                 if (phi->op == OP_PHI) {
16581                         phis += 1;
16582                 }
16583         }
16584
16585         /* Mark them all dead */
16586         live = xcmalloc(sizeof(*live) * (phis + 1), "phi_triple");
16587         phis = 0;
16588         for(phi = first->next; phi != first; phi = phi->next) {
16589                 if (phi->op != OP_PHI) {
16590                         continue;
16591                 }
16592                 live[phis].alive   = 0;
16593                 live[phis].orig_id = phi->id;
16594                 live[phis].phi     = phi;
16595                 phi->id = phis;
16596                 phis += 1;
16597         }
16598
16599         /* Mark phis alive that are used by non phis */
16600         for(i = 0; i < phis; i++) {
16601                 struct triple_set *set;
16602                 for(set = live[i].phi->use; !live[i].alive && set; set = set->next) {
16603                         if (set->member->op != OP_PHI) {
16604                                 keep_phi(state, live, live[i].phi);
16605                                 break;
16606                         }
16607                 }
16608         }
16609
16610         /* Delete the extraneous phis */
16611         for(i = 0; i < phis; i++) {
16612                 struct triple **slot;
16613                 int zrhs, j;
16614                 if (!live[i].alive) {
16615                         release_triple(state, live[i].phi);
16616                         continue;
16617                 }
16618                 phi = live[i].phi;
16619                 slot = &RHS(phi, 0);
16620                 zrhs = phi->rhs;
16621                 for(j = 0; j < zrhs; j++) {
16622                         if(!slot[j]) {
16623                                 struct triple *unknown;
16624                                 get_occurance(phi->occurance);
16625                                 unknown = flatten(state, state->global_pool,
16626                                         alloc_triple(state, OP_UNKNOWNVAL,
16627                                                 phi->type, 0, 0, phi->occurance));
16628                                 slot[j] = unknown;
16629                                 use_triple(unknown, phi);
16630                                 transform_to_arch_instruction(state, unknown);
16631 #if 0
16632                                 warning(state, phi, "variable not set at index %d on all paths to use", j);
16633 #endif
16634                         }
16635                 }
16636         }
16637         xfree(live);
16638 }
16639
16640 static void transform_to_ssa_form(struct compile_state *state)
16641 {
16642         insert_phi_operations(state);
16643         rename_variables(state);
16644
16645         prune_block_variables(state, state->bb.first_block);
16646         prune_unused_phis(state);
16647
16648         print_blocks(state, __func__, state->dbgout);
16649 }
16650
16651
16652 static void clear_vertex(
16653         struct compile_state *state, struct block *block, void *arg)
16654 {
16655         /* Clear the current blocks vertex and the vertex of all
16656          * of the current blocks neighbors in case there are malformed
16657          * blocks with now instructions at this point.
16658          */
16659         struct block_set *user, *edge;
16660         block->vertex = 0;
16661         for(edge = block->edges; edge; edge = edge->next) {
16662                 edge->member->vertex = 0;
16663         }
16664         for(user = block->use; user; user = user->next) {
16665                 user->member->vertex = 0;
16666         }
16667 }
16668
16669 static void mark_live_block(
16670         struct compile_state *state, struct block *block, int *next_vertex)
16671 {
16672         /* See if this is a block that has not been marked */
16673         if (block->vertex != 0) {
16674                 return;
16675         }
16676         block->vertex = *next_vertex;
16677         *next_vertex += 1;
16678         if (triple_is_branch(state, block->last)) {
16679                 struct triple **targ;
16680                 targ = triple_edge_targ(state, block->last, 0);
16681                 for(; targ; targ = triple_edge_targ(state, block->last, targ)) {
16682                         if (!*targ) {
16683                                 continue;
16684                         }
16685                         if (!triple_stores_block(state, *targ)) {
16686                                 internal_error(state, 0, "bad targ");
16687                         }
16688                         mark_live_block(state, (*targ)->u.block, next_vertex);
16689                 }
16690                 /* Ensure the last block of a function remains alive */
16691                 if (triple_is_call(state, block->last)) {
16692                         mark_live_block(state, MISC(block->last, 0)->u.block, next_vertex);
16693                 }
16694         }
16695         else if (block->last->next != state->first) {
16696                 struct triple *ins;
16697                 ins = block->last->next;
16698                 if (!triple_stores_block(state, ins)) {
16699                         internal_error(state, 0, "bad block start");
16700                 }
16701                 mark_live_block(state, ins->u.block, next_vertex);
16702         }
16703 }
16704
16705 static void transform_from_ssa_form(struct compile_state *state)
16706 {
16707         /* To get out of ssa form we insert moves on the incoming
16708          * edges to blocks containting phi functions.
16709          */
16710         struct triple *first;
16711         struct triple *phi, *var, *next;
16712         int next_vertex;
16713
16714         /* Walk the control flow to see which blocks remain alive */
16715         walk_blocks(state, &state->bb, clear_vertex, 0);
16716         next_vertex = 1;
16717         mark_live_block(state, state->bb.first_block, &next_vertex);
16718
16719         /* Walk all of the operations to find the phi functions */
16720         first = state->first;
16721         for(phi = first->next; phi != first ; phi = next) {
16722                 struct block_set *set;
16723                 struct block *block;
16724                 struct triple **slot;
16725                 struct triple *var;
16726                 struct triple_set *use, *use_next;
16727                 int edge, writers, readers;
16728                 next = phi->next;
16729                 if (phi->op != OP_PHI) {
16730                         continue;
16731                 }
16732
16733                 block = phi->u.block;
16734                 slot  = &RHS(phi, 0);
16735
16736                 /* If this phi is in a dead block just forget it */
16737                 if (block->vertex == 0) {
16738                         release_triple(state, phi);
16739                         continue;
16740                 }
16741
16742                 /* Forget uses from code in dead blocks */
16743                 for(use = phi->use; use; use = use_next) {
16744                         struct block *ublock;
16745                         struct triple **expr;
16746                         use_next = use->next;
16747                         ublock = block_of_triple(state, use->member);
16748                         if ((use->member == phi) || (ublock->vertex != 0)) {
16749                                 continue;
16750                         }
16751                         expr = triple_rhs(state, use->member, 0);
16752                         for(; expr; expr = triple_rhs(state, use->member, expr)) {
16753                                 if (*expr == phi) {
16754                                         *expr = 0;
16755                                 }
16756                         }
16757                         unuse_triple(phi, use->member);
16758                 }
16759                 /* A variable to replace the phi function */
16760                 if (registers_of(state, phi->type) != 1) {
16761                         internal_error(state, phi, "phi->type does not fit in a single register!");
16762                 }
16763                 var = post_triple(state, phi, OP_ADECL, phi->type, 0, 0);
16764                 var = var->next; /* point at the var */
16765
16766                 /* Replaces use of phi with var */
16767                 propogate_use(state, phi, var);
16768
16769                 /* Count the readers */
16770                 readers = 0;
16771                 for(use = var->use; use; use = use->next) {
16772                         if (use->member != MISC(var, 0)) {
16773                                 readers++;
16774                         }
16775                 }
16776
16777                 /* Walk all of the incoming edges/blocks and insert moves.
16778                  */
16779                 writers = 0;
16780                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
16781                         struct block *eblock, *vblock;
16782                         struct triple *move;
16783                         struct triple *val, *base;
16784                         eblock = set->member;
16785                         val = slot[edge];
16786                         slot[edge] = 0;
16787                         unuse_triple(val, phi);
16788                         vblock = block_of_triple(state, val);
16789
16790                         /* If we don't have a value that belongs in an OP_WRITE
16791                          * continue on.
16792                          */
16793                         if (!val || (val == &unknown_triple) || (val == phi)
16794                                 || (vblock && (vblock->vertex == 0))) {
16795                                 continue;
16796                         }
16797                         /* If the value should never occur error */
16798                         if (!vblock) {
16799                                 internal_error(state, val, "no vblock?");
16800                                 continue;
16801                         }
16802
16803                         /* If the value occurs in a dead block see if a replacement
16804                          * block can be found.
16805                          */
16806                         while(eblock && (eblock->vertex == 0)) {
16807                                 eblock = eblock->idom;
16808                         }
16809                         /* If not continue on with the next value. */
16810                         if (!eblock || (eblock->vertex == 0)) {
16811                                 continue;
16812                         }
16813
16814                         /* If we have an empty incoming block ignore it. */
16815                         if (!eblock->first) {
16816                                 internal_error(state, 0, "empty block?");
16817                         }
16818
16819                         /* Make certain the write is placed in the edge block... */
16820                         /* Walk through the edge block backwards to find an
16821                          * appropriate location for the OP_WRITE.
16822                          */
16823                         for(base = eblock->last; base != eblock->first; base = base->prev) {
16824                                 struct triple **expr;
16825                                 if (base->op == OP_PIECE) {
16826                                         base = MISC(base, 0);
16827                                 }
16828                                 if ((base == var) || (base == val)) {
16829                                         goto out;
16830                                 }
16831                                 expr = triple_lhs(state, base, 0);
16832                                 for(; expr; expr = triple_lhs(state, base, expr)) {
16833                                         if ((*expr) == val) {
16834                                                 goto out;
16835                                         }
16836                                 }
16837                                 expr = triple_rhs(state, base, 0);
16838                                 for(; expr; expr = triple_rhs(state, base, expr)) {
16839                                         if ((*expr) == var) {
16840                                                 goto out;
16841                                         }
16842                                 }
16843                         }
16844                 out:
16845                         if (triple_is_branch(state, base)) {
16846                                 internal_error(state, base,
16847                                         "Could not insert write to phi");
16848                         }
16849                         move = post_triple(state, base, OP_WRITE, var->type, val, var);
16850                         use_triple(val, move);
16851                         use_triple(var, move);
16852                         writers++;
16853                 }
16854                 if (!writers && readers) {
16855                         internal_error(state, var, "no value written to in use phi?");
16856                 }
16857                 /* If var is not used free it */
16858                 if (!writers) {
16859                         release_triple(state, MISC(var, 0));
16860                         release_triple(state, var);
16861                 }
16862                 /* Release the phi function */
16863                 release_triple(state, phi);
16864         }
16865
16866         /* Walk all of the operations to find the adecls */
16867         for(var = first->next; var != first ; var = var->next) {
16868                 struct triple_set *use, *use_next;
16869                 if (!triple_is_auto_var(state, var)) {
16870                         continue;
16871                 }
16872
16873                 /* Walk through all of the rhs uses of var and
16874                  * replace them with read of var.
16875                  */
16876                 for(use = var->use; use; use = use_next) {
16877                         struct triple *read, *user;
16878                         struct triple **slot;
16879                         int zrhs, i, used;
16880                         use_next = use->next;
16881                         user = use->member;
16882
16883                         /* Generate a read of var */
16884                         read = pre_triple(state, user, OP_READ, var->type, var, 0);
16885                         use_triple(var, read);
16886
16887                         /* Find the rhs uses and see if they need to be replaced */
16888                         used = 0;
16889                         zrhs = user->rhs;
16890                         slot = &RHS(user, 0);
16891                         for(i = 0; i < zrhs; i++) {
16892                                 if (slot[i] == var) {
16893                                         slot[i] = read;
16894                                         used = 1;
16895                                 }
16896                         }
16897                         /* If we did use it cleanup the uses */
16898                         if (used) {
16899                                 unuse_triple(var, user);
16900                                 use_triple(read, user);
16901                         }
16902                         /* If we didn't use it release the extra triple */
16903                         else {
16904                                 release_triple(state, read);
16905                         }
16906                 }
16907         }
16908 }
16909
16910 #define HI() if (state->compiler->debug & DEBUG_REBUILD_SSA_FORM) { \
16911         FILE *fp = state->dbgout; \
16912         fprintf(fp, "@ %s:%d\n", __FILE__, __LINE__); romcc_print_blocks(state, fp); \
16913         }
16914
16915 static void rebuild_ssa_form(struct compile_state *state)
16916 {
16917 HI();
16918         transform_from_ssa_form(state);
16919 HI();
16920         state->bb.first = state->first;
16921         free_basic_blocks(state, &state->bb);
16922         analyze_basic_blocks(state, &state->bb);
16923 HI();
16924         insert_phi_operations(state);
16925 HI();
16926         rename_variables(state);
16927 HI();
16928
16929         prune_block_variables(state, state->bb.first_block);
16930 HI();
16931         prune_unused_phis(state);
16932 HI();
16933 }
16934 #undef HI
16935
16936 /*
16937  * Register conflict resolution
16938  * =========================================================
16939  */
16940
16941 static struct reg_info find_def_color(
16942         struct compile_state *state, struct triple *def)
16943 {
16944         struct triple_set *set;
16945         struct reg_info info;
16946         info.reg = REG_UNSET;
16947         info.regcm = 0;
16948         if (!triple_is_def(state, def)) {
16949                 return info;
16950         }
16951         info = arch_reg_lhs(state, def, 0);
16952         if (info.reg >= MAX_REGISTERS) {
16953                 info.reg = REG_UNSET;
16954         }
16955         for(set = def->use; set; set = set->next) {
16956                 struct reg_info tinfo;
16957                 int i;
16958                 i = find_rhs_use(state, set->member, def);
16959                 if (i < 0) {
16960                         continue;
16961                 }
16962                 tinfo = arch_reg_rhs(state, set->member, i);
16963                 if (tinfo.reg >= MAX_REGISTERS) {
16964                         tinfo.reg = REG_UNSET;
16965                 }
16966                 if ((tinfo.reg != REG_UNSET) &&
16967                         (info.reg != REG_UNSET) &&
16968                         (tinfo.reg != info.reg)) {
16969                         internal_error(state, def, "register conflict");
16970                 }
16971                 if ((info.regcm & tinfo.regcm) == 0) {
16972                         internal_error(state, def, "regcm conflict %x & %x == 0",
16973                                 info.regcm, tinfo.regcm);
16974                 }
16975                 if (info.reg == REG_UNSET) {
16976                         info.reg = tinfo.reg;
16977                 }
16978                 info.regcm &= tinfo.regcm;
16979         }
16980         if (info.reg >= MAX_REGISTERS) {
16981                 internal_error(state, def, "register out of range");
16982         }
16983         return info;
16984 }
16985
16986 static struct reg_info find_lhs_pre_color(
16987         struct compile_state *state, struct triple *ins, int index)
16988 {
16989         struct reg_info info;
16990         int zlhs, zrhs, i;
16991         zrhs = ins->rhs;
16992         zlhs = ins->lhs;
16993         if (!zlhs && triple_is_def(state, ins)) {
16994                 zlhs = 1;
16995         }
16996         if (index >= zlhs) {
16997                 internal_error(state, ins, "Bad lhs %d", index);
16998         }
16999         info = arch_reg_lhs(state, ins, index);
17000         for(i = 0; i < zrhs; i++) {
17001                 struct reg_info rinfo;
17002                 rinfo = arch_reg_rhs(state, ins, i);
17003                 if ((info.reg == rinfo.reg) &&
17004                         (rinfo.reg >= MAX_REGISTERS)) {
17005                         struct reg_info tinfo;
17006                         tinfo = find_lhs_pre_color(state, RHS(ins, index), 0);
17007                         info.reg = tinfo.reg;
17008                         info.regcm &= tinfo.regcm;
17009                         break;
17010                 }
17011         }
17012         if (info.reg >= MAX_REGISTERS) {
17013                 info.reg = REG_UNSET;
17014         }
17015         return info;
17016 }
17017
17018 static struct reg_info find_rhs_post_color(
17019         struct compile_state *state, struct triple *ins, int index);
17020
17021 static struct reg_info find_lhs_post_color(
17022         struct compile_state *state, struct triple *ins, int index)
17023 {
17024         struct triple_set *set;
17025         struct reg_info info;
17026         struct triple *lhs;
17027 #if DEBUG_TRIPLE_COLOR
17028         fprintf(state->errout, "find_lhs_post_color(%p, %d)\n",
17029                 ins, index);
17030 #endif
17031         if ((index == 0) && triple_is_def(state, ins)) {
17032                 lhs = ins;
17033         }
17034         else if (index < ins->lhs) {
17035                 lhs = LHS(ins, index);
17036         }
17037         else {
17038                 internal_error(state, ins, "Bad lhs %d", index);
17039                 lhs = 0;
17040         }
17041         info = arch_reg_lhs(state, ins, index);
17042         if (info.reg >= MAX_REGISTERS) {
17043                 info.reg = REG_UNSET;
17044         }
17045         for(set = lhs->use; set; set = set->next) {
17046                 struct reg_info rinfo;
17047                 struct triple *user;
17048                 int zrhs, i;
17049                 user = set->member;
17050                 zrhs = user->rhs;
17051                 for(i = 0; i < zrhs; i++) {
17052                         if (RHS(user, i) != lhs) {
17053                                 continue;
17054                         }
17055                         rinfo = find_rhs_post_color(state, user, i);
17056                         if ((info.reg != REG_UNSET) &&
17057                                 (rinfo.reg != REG_UNSET) &&
17058                                 (info.reg != rinfo.reg)) {
17059                                 internal_error(state, ins, "register conflict");
17060                         }
17061                         if ((info.regcm & rinfo.regcm) == 0) {
17062                                 internal_error(state, ins, "regcm conflict %x & %x == 0",
17063                                         info.regcm, rinfo.regcm);
17064                         }
17065                         if (info.reg == REG_UNSET) {
17066                                 info.reg = rinfo.reg;
17067                         }
17068                         info.regcm &= rinfo.regcm;
17069                 }
17070         }
17071 #if DEBUG_TRIPLE_COLOR
17072         fprintf(state->errout, "find_lhs_post_color(%p, %d) -> ( %d, %x)\n",
17073                 ins, index, info.reg, info.regcm);
17074 #endif
17075         return info;
17076 }
17077
17078 static struct reg_info find_rhs_post_color(
17079         struct compile_state *state, struct triple *ins, int index)
17080 {
17081         struct reg_info info, rinfo;
17082         int zlhs, i;
17083 #if DEBUG_TRIPLE_COLOR
17084         fprintf(state->errout, "find_rhs_post_color(%p, %d)\n",
17085                 ins, index);
17086 #endif
17087         rinfo = arch_reg_rhs(state, ins, index);
17088         zlhs = ins->lhs;
17089         if (!zlhs && triple_is_def(state, ins)) {
17090                 zlhs = 1;
17091         }
17092         info = rinfo;
17093         if (info.reg >= MAX_REGISTERS) {
17094                 info.reg = REG_UNSET;
17095         }
17096         for(i = 0; i < zlhs; i++) {
17097                 struct reg_info linfo;
17098                 linfo = arch_reg_lhs(state, ins, i);
17099                 if ((linfo.reg == rinfo.reg) &&
17100                         (linfo.reg >= MAX_REGISTERS)) {
17101                         struct reg_info tinfo;
17102                         tinfo = find_lhs_post_color(state, ins, i);
17103                         if (tinfo.reg >= MAX_REGISTERS) {
17104                                 tinfo.reg = REG_UNSET;
17105                         }
17106                         info.regcm &= linfo.regcm;
17107                         info.regcm &= tinfo.regcm;
17108                         if (info.reg != REG_UNSET) {
17109                                 internal_error(state, ins, "register conflict");
17110                         }
17111                         if (info.regcm == 0) {
17112                                 internal_error(state, ins, "regcm conflict");
17113                         }
17114                         info.reg = tinfo.reg;
17115                 }
17116         }
17117 #if DEBUG_TRIPLE_COLOR
17118         fprintf(state->errout, "find_rhs_post_color(%p, %d) -> ( %d, %x)\n",
17119                 ins, index, info.reg, info.regcm);
17120 #endif
17121         return info;
17122 }
17123
17124 static struct reg_info find_lhs_color(
17125         struct compile_state *state, struct triple *ins, int index)
17126 {
17127         struct reg_info pre, post, info;
17128 #if DEBUG_TRIPLE_COLOR
17129         fprintf(state->errout, "find_lhs_color(%p, %d)\n",
17130                 ins, index);
17131 #endif
17132         pre = find_lhs_pre_color(state, ins, index);
17133         post = find_lhs_post_color(state, ins, index);
17134         if ((pre.reg != post.reg) &&
17135                 (pre.reg != REG_UNSET) &&
17136                 (post.reg != REG_UNSET)) {
17137                 internal_error(state, ins, "register conflict");
17138         }
17139         info.regcm = pre.regcm & post.regcm;
17140         info.reg = pre.reg;
17141         if (info.reg == REG_UNSET) {
17142                 info.reg = post.reg;
17143         }
17144 #if DEBUG_TRIPLE_COLOR
17145         fprintf(state->errout, "find_lhs_color(%p, %d) -> ( %d, %x) ... (%d, %x) (%d, %x)\n",
17146                 ins, index, info.reg, info.regcm,
17147                 pre.reg, pre.regcm, post.reg, post.regcm);
17148 #endif
17149         return info;
17150 }
17151
17152 static struct triple *post_copy(struct compile_state *state, struct triple *ins)
17153 {
17154         struct triple_set *entry, *next;
17155         struct triple *out;
17156         struct reg_info info, rinfo;
17157
17158         info = arch_reg_lhs(state, ins, 0);
17159         out = post_triple(state, ins, OP_COPY, ins->type, ins, 0);
17160         use_triple(RHS(out, 0), out);
17161         /* Get the users of ins to use out instead */
17162         for(entry = ins->use; entry; entry = next) {
17163                 int i;
17164                 next = entry->next;
17165                 if (entry->member == out) {
17166                         continue;
17167                 }
17168                 i = find_rhs_use(state, entry->member, ins);
17169                 if (i < 0) {
17170                         continue;
17171                 }
17172                 rinfo = arch_reg_rhs(state, entry->member, i);
17173                 if ((info.reg == REG_UNNEEDED) && (rinfo.reg == REG_UNNEEDED)) {
17174                         continue;
17175                 }
17176                 replace_rhs_use(state, ins, out, entry->member);
17177         }
17178         transform_to_arch_instruction(state, out);
17179         return out;
17180 }
17181
17182 static struct triple *typed_pre_copy(
17183         struct compile_state *state, struct type *type, struct triple *ins, int index)
17184 {
17185         /* Carefully insert enough operations so that I can
17186          * enter any operation with a GPR32.
17187          */
17188         struct triple *in;
17189         struct triple **expr;
17190         unsigned classes;
17191         struct reg_info info;
17192         int op;
17193         if (ins->op == OP_PHI) {
17194                 internal_error(state, ins, "pre_copy on a phi?");
17195         }
17196         classes = arch_type_to_regcm(state, type);
17197         info = arch_reg_rhs(state, ins, index);
17198         expr = &RHS(ins, index);
17199         if ((info.regcm & classes) == 0) {
17200                 FILE *fp = state->errout;
17201                 fprintf(fp, "src_type: ");
17202                 name_of(fp, ins->type);
17203                 fprintf(fp, "\ndst_type: ");
17204                 name_of(fp, type);
17205                 fprintf(fp, "\n");
17206                 internal_error(state, ins, "pre_copy with no register classes");
17207         }
17208         op = OP_COPY;
17209         if (!equiv_types(type, (*expr)->type)) {
17210                 op = OP_CONVERT;
17211         }
17212         in = pre_triple(state, ins, op, type, *expr, 0);
17213         unuse_triple(*expr, ins);
17214         *expr = in;
17215         use_triple(RHS(in, 0), in);
17216         use_triple(in, ins);
17217         transform_to_arch_instruction(state, in);
17218         return in;
17219
17220 }
17221 static struct triple *pre_copy(
17222         struct compile_state *state, struct triple *ins, int index)
17223 {
17224         return typed_pre_copy(state, RHS(ins, index)->type, ins, index);
17225 }
17226
17227
17228 static void insert_copies_to_phi(struct compile_state *state)
17229 {
17230         /* To get out of ssa form we insert moves on the incoming
17231          * edges to blocks containting phi functions.
17232          */
17233         struct triple *first;
17234         struct triple *phi;
17235
17236         /* Walk all of the operations to find the phi functions */
17237         first = state->first;
17238         for(phi = first->next; phi != first ; phi = phi->next) {
17239                 struct block_set *set;
17240                 struct block *block;
17241                 struct triple **slot, *copy;
17242                 int edge;
17243                 if (phi->op != OP_PHI) {
17244                         continue;
17245                 }
17246                 phi->id |= TRIPLE_FLAG_POST_SPLIT;
17247                 block = phi->u.block;
17248                 slot  = &RHS(phi, 0);
17249                 /* Phi's that feed into mandatory live range joins
17250                  * cause nasty complications.  Insert a copy of
17251                  * the phi value so I never have to deal with
17252                  * that in the rest of the code.
17253                  */
17254                 copy = post_copy(state, phi);
17255                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
17256                 /* Walk all of the incoming edges/blocks and insert moves.
17257                  */
17258                 for(edge = 0, set = block->use; set; set = set->next, edge++) {
17259                         struct block *eblock;
17260                         struct triple *move;
17261                         struct triple *val;
17262                         struct triple *ptr;
17263                         eblock = set->member;
17264                         val = slot[edge];
17265
17266                         if (val == phi) {
17267                                 continue;
17268                         }
17269
17270                         get_occurance(val->occurance);
17271                         move = build_triple(state, OP_COPY, val->type, val, 0,
17272                                 val->occurance);
17273                         move->u.block = eblock;
17274                         move->id |= TRIPLE_FLAG_PRE_SPLIT;
17275                         use_triple(val, move);
17276
17277                         slot[edge] = move;
17278                         unuse_triple(val, phi);
17279                         use_triple(move, phi);
17280
17281                         /* Walk up the dominator tree until I have found the appropriate block */
17282                         while(eblock && !tdominates(state, val, eblock->last)) {
17283                                 eblock = eblock->idom;
17284                         }
17285                         if (!eblock) {
17286                                 internal_error(state, phi, "Cannot find block dominated by %p",
17287                                         val);
17288                         }
17289
17290                         /* Walk through the block backwards to find
17291                          * an appropriate location for the OP_COPY.
17292                          */
17293                         for(ptr = eblock->last; ptr != eblock->first; ptr = ptr->prev) {
17294                                 struct triple **expr;
17295                                 if (ptr->op == OP_PIECE) {
17296                                         ptr = MISC(ptr, 0);
17297                                 }
17298                                 if ((ptr == phi) || (ptr == val)) {
17299                                         goto out;
17300                                 }
17301                                 expr = triple_lhs(state, ptr, 0);
17302                                 for(;expr; expr = triple_lhs(state, ptr, expr)) {
17303                                         if ((*expr) == val) {
17304                                                 goto out;
17305                                         }
17306                                 }
17307                                 expr = triple_rhs(state, ptr, 0);
17308                                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17309                                         if ((*expr) == phi) {
17310                                                 goto out;
17311                                         }
17312                                 }
17313                         }
17314                 out:
17315                         if (triple_is_branch(state, ptr)) {
17316                                 internal_error(state, ptr,
17317                                         "Could not insert write to phi");
17318                         }
17319                         insert_triple(state, after_lhs(state, ptr), move);
17320                         if (eblock->last == after_lhs(state, ptr)->prev) {
17321                                 eblock->last = move;
17322                         }
17323                         transform_to_arch_instruction(state, move);
17324                 }
17325         }
17326         print_blocks(state, __func__, state->dbgout);
17327 }
17328
17329 struct triple_reg_set;
17330 struct reg_block;
17331
17332
17333 static int do_triple_set(struct triple_reg_set **head,
17334         struct triple *member, struct triple *new_member)
17335 {
17336         struct triple_reg_set **ptr, *new;
17337         if (!member)
17338                 return 0;
17339         ptr = head;
17340         while(*ptr) {
17341                 if ((*ptr)->member == member) {
17342                         return 0;
17343                 }
17344                 ptr = &(*ptr)->next;
17345         }
17346         new = xcmalloc(sizeof(*new), "triple_set");
17347         new->member = member;
17348         new->new    = new_member;
17349         new->next   = *head;
17350         *head       = new;
17351         return 1;
17352 }
17353
17354 static void do_triple_unset(struct triple_reg_set **head, struct triple *member)
17355 {
17356         struct triple_reg_set *entry, **ptr;
17357         ptr = head;
17358         while(*ptr) {
17359                 entry = *ptr;
17360                 if (entry->member == member) {
17361                         *ptr = entry->next;
17362                         xfree(entry);
17363                         return;
17364                 }
17365                 else {
17366                         ptr = &entry->next;
17367                 }
17368         }
17369 }
17370
17371 static int in_triple(struct reg_block *rb, struct triple *in)
17372 {
17373         return do_triple_set(&rb->in, in, 0);
17374 }
17375
17376 #if DEBUG_ROMCC_WARNING
17377 static void unin_triple(struct reg_block *rb, struct triple *unin)
17378 {
17379         do_triple_unset(&rb->in, unin);
17380 }
17381 #endif
17382
17383 static int out_triple(struct reg_block *rb, struct triple *out)
17384 {
17385         return do_triple_set(&rb->out, out, 0);
17386 }
17387 #if DEBUG_ROMCC_WARNING
17388 static void unout_triple(struct reg_block *rb, struct triple *unout)
17389 {
17390         do_triple_unset(&rb->out, unout);
17391 }
17392 #endif
17393
17394 static int initialize_regblock(struct reg_block *blocks,
17395         struct block *block, int vertex)
17396 {
17397         struct block_set *user;
17398         if (!block || (blocks[block->vertex].block == block)) {
17399                 return vertex;
17400         }
17401         vertex += 1;
17402         /* Renumber the blocks in a convinient fashion */
17403         block->vertex = vertex;
17404         blocks[vertex].block    = block;
17405         blocks[vertex].vertex   = vertex;
17406         for(user = block->use; user; user = user->next) {
17407                 vertex = initialize_regblock(blocks, user->member, vertex);
17408         }
17409         return vertex;
17410 }
17411
17412 static struct triple *part_to_piece(struct compile_state *state, struct triple *ins)
17413 {
17414 /* Part to piece is a best attempt and it cannot be correct all by
17415  * itself.  If various values are read as different sizes in different
17416  * parts of the code this function cannot work.  Or rather it cannot
17417  * work in conjunction with compute_variable_liftimes.  As the
17418  * analysis will get confused.
17419  */
17420         struct triple *base;
17421         unsigned reg;
17422         if (!is_lvalue(state, ins)) {
17423                 return ins;
17424         }
17425         base = 0;
17426         reg = 0;
17427         while(ins && triple_is_part(state, ins) && (ins->op != OP_PIECE)) {
17428                 base = MISC(ins, 0);
17429                 switch(ins->op) {
17430                 case OP_INDEX:
17431                         reg += index_reg_offset(state, base->type, ins->u.cval)/REG_SIZEOF_REG;
17432                         break;
17433                 case OP_DOT:
17434                         reg += field_reg_offset(state, base->type, ins->u.field)/REG_SIZEOF_REG;
17435                         break;
17436                 default:
17437                         internal_error(state, ins, "unhandled part");
17438                         break;
17439                 }
17440                 ins = base;
17441         }
17442         if (base) {
17443                 if (reg > base->lhs) {
17444                         internal_error(state, base, "part out of range?");
17445                 }
17446                 ins = LHS(base, reg);
17447         }
17448         return ins;
17449 }
17450
17451 static int this_def(struct compile_state *state,
17452         struct triple *ins, struct triple *other)
17453 {
17454         if (ins == other) {
17455                 return 1;
17456         }
17457         if (ins->op == OP_WRITE) {
17458                 ins = part_to_piece(state, MISC(ins, 0));
17459         }
17460         return ins == other;
17461 }
17462
17463 static int phi_in(struct compile_state *state, struct reg_block *blocks,
17464         struct reg_block *rb, struct block *suc)
17465 {
17466         /* Read the conditional input set of a successor block
17467          * (i.e. the input to the phi nodes) and place it in the
17468          * current blocks output set.
17469          */
17470         struct block_set *set;
17471         struct triple *ptr;
17472         int edge;
17473         int done, change;
17474         change = 0;
17475         /* Find the edge I am coming in on */
17476         for(edge = 0, set = suc->use; set; set = set->next, edge++) {
17477                 if (set->member == rb->block) {
17478                         break;
17479                 }
17480         }
17481         if (!set) {
17482                 internal_error(state, 0, "Not coming on a control edge?");
17483         }
17484         for(done = 0, ptr = suc->first; !done; ptr = ptr->next) {
17485                 struct triple **slot, *expr, *ptr2;
17486                 int out_change, done2;
17487                 done = (ptr == suc->last);
17488                 if (ptr->op != OP_PHI) {
17489                         continue;
17490                 }
17491                 slot = &RHS(ptr, 0);
17492                 expr = slot[edge];
17493                 out_change = out_triple(rb, expr);
17494                 if (!out_change) {
17495                         continue;
17496                 }
17497                 /* If we don't define the variable also plast it
17498                  * in the current blocks input set.
17499                  */
17500                 ptr2 = rb->block->first;
17501                 for(done2 = 0; !done2; ptr2 = ptr2->next) {
17502                         if (this_def(state, ptr2, expr)) {
17503                                 break;
17504                         }
17505                         done2 = (ptr2 == rb->block->last);
17506                 }
17507                 if (!done2) {
17508                         continue;
17509                 }
17510                 change |= in_triple(rb, expr);
17511         }
17512         return change;
17513 }
17514
17515 static int reg_in(struct compile_state *state, struct reg_block *blocks,
17516         struct reg_block *rb, struct block *suc)
17517 {
17518         struct triple_reg_set *in_set;
17519         int change;
17520         change = 0;
17521         /* Read the input set of a successor block
17522          * and place it in the current blocks output set.
17523          */
17524         in_set = blocks[suc->vertex].in;
17525         for(; in_set; in_set = in_set->next) {
17526                 int out_change, done;
17527                 struct triple *first, *last, *ptr;
17528                 out_change = out_triple(rb, in_set->member);
17529                 if (!out_change) {
17530                         continue;
17531                 }
17532                 /* If we don't define the variable also place it
17533                  * in the current blocks input set.
17534                  */
17535                 first = rb->block->first;
17536                 last = rb->block->last;
17537                 done = 0;
17538                 for(ptr = first; !done; ptr = ptr->next) {
17539                         if (this_def(state, ptr, in_set->member)) {
17540                                 break;
17541                         }
17542                         done = (ptr == last);
17543                 }
17544                 if (!done) {
17545                         continue;
17546                 }
17547                 change |= in_triple(rb, in_set->member);
17548         }
17549         change |= phi_in(state, blocks, rb, suc);
17550         return change;
17551 }
17552
17553 static int use_in(struct compile_state *state, struct reg_block *rb)
17554 {
17555         /* Find the variables we use but don't define and add
17556          * it to the current blocks input set.
17557          */
17558 #if DEBUG_ROMCC_WARNINGS
17559 #warning "FIXME is this O(N^2) algorithm bad?"
17560 #endif
17561         struct block *block;
17562         struct triple *ptr;
17563         int done;
17564         int change;
17565         block = rb->block;
17566         change = 0;
17567         for(done = 0, ptr = block->last; !done; ptr = ptr->prev) {
17568                 struct triple **expr;
17569                 done = (ptr == block->first);
17570                 /* The variable a phi function uses depends on the
17571                  * control flow, and is handled in phi_in, not
17572                  * here.
17573                  */
17574                 if (ptr->op == OP_PHI) {
17575                         continue;
17576                 }
17577                 expr = triple_rhs(state, ptr, 0);
17578                 for(;expr; expr = triple_rhs(state, ptr, expr)) {
17579                         struct triple *rhs, *test;
17580                         int tdone;
17581                         rhs = part_to_piece(state, *expr);
17582                         if (!rhs) {
17583                                 continue;
17584                         }
17585
17586                         /* See if rhs is defined in this block.
17587                          * A write counts as a definition.
17588                          */
17589                         for(tdone = 0, test = ptr; !tdone; test = test->prev) {
17590                                 tdone = (test == block->first);
17591                                 if (this_def(state, test, rhs)) {
17592                                         rhs = 0;
17593                                         break;
17594                                 }
17595                         }
17596                         /* If I still have a valid rhs add it to in */
17597                         change |= in_triple(rb, rhs);
17598                 }
17599         }
17600         return change;
17601 }
17602
17603 static struct reg_block *compute_variable_lifetimes(
17604         struct compile_state *state, struct basic_blocks *bb)
17605 {
17606         struct reg_block *blocks;
17607         int change;
17608         blocks = xcmalloc(
17609                 sizeof(*blocks)*(bb->last_vertex + 1), "reg_block");
17610         initialize_regblock(blocks, bb->last_block, 0);
17611         do {
17612                 int i;
17613                 change = 0;
17614                 for(i = 1; i <= bb->last_vertex; i++) {
17615                         struct block_set *edge;
17616                         struct reg_block *rb;
17617                         rb = &blocks[i];
17618                         /* Add the all successor's input set to in */
17619                         for(edge = rb->block->edges; edge; edge = edge->next) {
17620                                 change |= reg_in(state, blocks, rb, edge->member);
17621                         }
17622                         /* Add use to in... */
17623                         change |= use_in(state, rb);
17624                 }
17625         } while(change);
17626         return blocks;
17627 }
17628
17629 static void free_variable_lifetimes(struct compile_state *state,
17630         struct basic_blocks *bb, struct reg_block *blocks)
17631 {
17632         int i;
17633         /* free in_set && out_set on each block */
17634         for(i = 1; i <= bb->last_vertex; i++) {
17635                 struct triple_reg_set *entry, *next;
17636                 struct reg_block *rb;
17637                 rb = &blocks[i];
17638                 for(entry = rb->in; entry ; entry = next) {
17639                         next = entry->next;
17640                         do_triple_unset(&rb->in, entry->member);
17641                 }
17642                 for(entry = rb->out; entry; entry = next) {
17643                         next = entry->next;
17644                         do_triple_unset(&rb->out, entry->member);
17645                 }
17646         }
17647         xfree(blocks);
17648
17649 }
17650
17651 typedef void (*wvl_cb_t)(
17652         struct compile_state *state,
17653         struct reg_block *blocks, struct triple_reg_set *live,
17654         struct reg_block *rb, struct triple *ins, void *arg);
17655
17656 static void walk_variable_lifetimes(struct compile_state *state,
17657         struct basic_blocks *bb, struct reg_block *blocks,
17658         wvl_cb_t cb, void *arg)
17659 {
17660         int i;
17661
17662         for(i = 1; i <= state->bb.last_vertex; i++) {
17663                 struct triple_reg_set *live;
17664                 struct triple_reg_set *entry, *next;
17665                 struct triple *ptr, *prev;
17666                 struct reg_block *rb;
17667                 struct block *block;
17668                 int done;
17669
17670                 /* Get the blocks */
17671                 rb = &blocks[i];
17672                 block = rb->block;
17673
17674                 /* Copy out into live */
17675                 live = 0;
17676                 for(entry = rb->out; entry; entry = next) {
17677                         next = entry->next;
17678                         do_triple_set(&live, entry->member, entry->new);
17679                 }
17680                 /* Walk through the basic block calculating live */
17681                 for(done = 0, ptr = block->last; !done; ptr = prev) {
17682                         struct triple **expr;
17683
17684                         prev = ptr->prev;
17685                         done = (ptr == block->first);
17686
17687                         /* Ensure the current definition is in live */
17688                         if (triple_is_def(state, ptr)) {
17689                                 do_triple_set(&live, ptr, 0);
17690                         }
17691
17692                         /* Inform the callback function of what is
17693                          * going on.
17694                          */
17695                          cb(state, blocks, live, rb, ptr, arg);
17696
17697                         /* Remove the current definition from live */
17698                         do_triple_unset(&live, ptr);
17699
17700                         /* Add the current uses to live.
17701                          *
17702                          * It is safe to skip phi functions because they do
17703                          * not have any block local uses, and the block
17704                          * output sets already properly account for what
17705                          * control flow depedent uses phi functions do have.
17706                          */
17707                         if (ptr->op == OP_PHI) {
17708                                 continue;
17709                         }
17710                         expr = triple_rhs(state, ptr, 0);
17711                         for(;expr; expr = triple_rhs(state, ptr, expr)) {
17712                                 /* If the triple is not a definition skip it. */
17713                                 if (!*expr || !triple_is_def(state, *expr)) {
17714                                         continue;
17715                                 }
17716                                 do_triple_set(&live, *expr, 0);
17717                         }
17718                 }
17719                 /* Free live */
17720                 for(entry = live; entry; entry = next) {
17721                         next = entry->next;
17722                         do_triple_unset(&live, entry->member);
17723                 }
17724         }
17725 }
17726
17727 struct print_live_variable_info {
17728         struct reg_block *rb;
17729         FILE *fp;
17730 };
17731 #if DEBUG_EXPLICIT_CLOSURES
17732 static void print_live_variables_block(
17733         struct compile_state *state, struct block *block, void *arg)
17734
17735 {
17736         struct print_live_variable_info *info = arg;
17737         struct block_set *edge;
17738         FILE *fp = info->fp;
17739         struct reg_block *rb;
17740         struct triple *ptr;
17741         int phi_present;
17742         int done;
17743         rb = &info->rb[block->vertex];
17744
17745         fprintf(fp, "\nblock: %p (%d),",
17746                 block,  block->vertex);
17747         for(edge = block->edges; edge; edge = edge->next) {
17748                 fprintf(fp, " %p<-%p",
17749                         edge->member,
17750                         edge->member && edge->member->use?edge->member->use->member : 0);
17751         }
17752         fprintf(fp, "\n");
17753         if (rb->in) {
17754                 struct triple_reg_set *in_set;
17755                 fprintf(fp, "        in:");
17756                 for(in_set = rb->in; in_set; in_set = in_set->next) {
17757                         fprintf(fp, " %-10p", in_set->member);
17758                 }
17759                 fprintf(fp, "\n");
17760         }
17761         phi_present = 0;
17762         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17763                 done = (ptr == block->last);
17764                 if (ptr->op == OP_PHI) {
17765                         phi_present = 1;
17766                         break;
17767                 }
17768         }
17769         if (phi_present) {
17770                 int edge;
17771                 for(edge = 0; edge < block->users; edge++) {
17772                         fprintf(fp, "     in(%d):", edge);
17773                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17774                                 struct triple **slot;
17775                                 done = (ptr == block->last);
17776                                 if (ptr->op != OP_PHI) {
17777                                         continue;
17778                                 }
17779                                 slot = &RHS(ptr, 0);
17780                                 fprintf(fp, " %-10p", slot[edge]);
17781                         }
17782                         fprintf(fp, "\n");
17783                 }
17784         }
17785         if (block->first->op == OP_LABEL) {
17786                 fprintf(fp, "%p:\n", block->first);
17787         }
17788         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
17789                 done = (ptr == block->last);
17790                 display_triple(fp, ptr);
17791         }
17792         if (rb->out) {
17793                 struct triple_reg_set *out_set;
17794                 fprintf(fp, "       out:");
17795                 for(out_set = rb->out; out_set; out_set = out_set->next) {
17796                         fprintf(fp, " %-10p", out_set->member);
17797                 }
17798                 fprintf(fp, "\n");
17799         }
17800         fprintf(fp, "\n");
17801 }
17802
17803 static void print_live_variables(struct compile_state *state,
17804         struct basic_blocks *bb, struct reg_block *rb, FILE *fp)
17805 {
17806         struct print_live_variable_info info;
17807         info.rb = rb;
17808         info.fp = fp;
17809         fprintf(fp, "\nlive variables by block\n");
17810         walk_blocks(state, bb, print_live_variables_block, &info);
17811
17812 }
17813 #endif
17814
17815 static int count_triples(struct compile_state *state)
17816 {
17817         struct triple *first, *ins;
17818         int triples = 0;
17819         first = state->first;
17820         ins = first;
17821         do {
17822                 triples++;
17823                 ins = ins->next;
17824         } while (ins != first);
17825         return triples;
17826 }
17827
17828
17829 struct dead_triple {
17830         struct triple *triple;
17831         struct dead_triple *work_next;
17832         struct block *block;
17833         int old_id;
17834         int flags;
17835 #define TRIPLE_FLAG_ALIVE 1
17836 #define TRIPLE_FLAG_FREE  1
17837 };
17838
17839 static void print_dead_triples(struct compile_state *state,
17840         struct dead_triple *dtriple)
17841 {
17842         struct triple *first, *ins;
17843         struct dead_triple *dt;
17844         FILE *fp;
17845         if (!(state->compiler->debug & DEBUG_TRIPLES)) {
17846                 return;
17847         }
17848         fp = state->dbgout;
17849         fprintf(fp, "--------------- dtriples ---------------\n");
17850         first = state->first;
17851         ins = first;
17852         do {
17853                 dt = &dtriple[ins->id];
17854                 if ((ins->op == OP_LABEL) && (ins->use)) {
17855                         fprintf(fp, "\n%p:\n", ins);
17856                 }
17857                 fprintf(fp, "%c",
17858                         (dt->flags & TRIPLE_FLAG_ALIVE)?' ': '-');
17859                 display_triple(fp, ins);
17860                 if (triple_is_branch(state, ins)) {
17861                         fprintf(fp, "\n");
17862                 }
17863                 ins = ins->next;
17864         } while(ins != first);
17865         fprintf(fp, "\n");
17866 }
17867
17868
17869 static void awaken(
17870         struct compile_state *state,
17871         struct dead_triple *dtriple, struct triple **expr,
17872         struct dead_triple ***work_list_tail)
17873 {
17874         struct triple *triple;
17875         struct dead_triple *dt;
17876         if (!expr) {
17877                 return;
17878         }
17879         triple = *expr;
17880         if (!triple) {
17881                 return;
17882         }
17883         if (triple->id <= 0)  {
17884                 internal_error(state, triple, "bad triple id: %d",
17885                         triple->id);
17886         }
17887         if (triple->op == OP_NOOP) {
17888                 internal_error(state, triple, "awakening noop?");
17889                 return;
17890         }
17891         dt = &dtriple[triple->id];
17892         if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17893                 dt->flags |= TRIPLE_FLAG_ALIVE;
17894                 if (!dt->work_next) {
17895                         **work_list_tail = dt;
17896                         *work_list_tail = &dt->work_next;
17897                 }
17898         }
17899 }
17900
17901 static void eliminate_inefectual_code(struct compile_state *state)
17902 {
17903         struct dead_triple *dtriple, *work_list, **work_list_tail, *dt;
17904         int triples, i;
17905         struct triple *first, *ins;
17906
17907         if (!(state->compiler->flags & COMPILER_ELIMINATE_INEFECTUAL_CODE)) {
17908                 return;
17909         }
17910
17911         /* Setup the work list */
17912         work_list = 0;
17913         work_list_tail = &work_list;
17914
17915         first = state->first;
17916
17917         /* Count how many triples I have */
17918         triples = count_triples(state);
17919
17920         /* Now put then in an array and mark all of the triples dead */
17921         dtriple = xcmalloc(sizeof(*dtriple) * (triples + 1), "dtriples");
17922
17923         ins = first;
17924         i = 1;
17925         do {
17926                 dtriple[i].triple = ins;
17927                 dtriple[i].block  = block_of_triple(state, ins);
17928                 dtriple[i].flags  = 0;
17929                 dtriple[i].old_id = ins->id;
17930                 ins->id = i;
17931                 /* See if it is an operation we always keep */
17932                 if (!triple_is_pure(state, ins, dtriple[i].old_id)) {
17933                         awaken(state, dtriple, &ins, &work_list_tail);
17934                 }
17935                 i++;
17936                 ins = ins->next;
17937         } while(ins != first);
17938         while(work_list) {
17939                 struct block *block;
17940                 struct dead_triple *dt;
17941                 struct block_set *user;
17942                 struct triple **expr;
17943                 dt = work_list;
17944                 work_list = dt->work_next;
17945                 if (!work_list) {
17946                         work_list_tail = &work_list;
17947                 }
17948                 /* Make certain the block the current instruction is in lives */
17949                 block = block_of_triple(state, dt->triple);
17950                 awaken(state, dtriple, &block->first, &work_list_tail);
17951                 if (triple_is_branch(state, block->last)) {
17952                         awaken(state, dtriple, &block->last, &work_list_tail);
17953                 } else {
17954                         awaken(state, dtriple, &block->last->next, &work_list_tail);
17955                 }
17956
17957                 /* Wake up the data depencencies of this triple */
17958                 expr = 0;
17959                 do {
17960                         expr = triple_rhs(state, dt->triple, expr);
17961                         awaken(state, dtriple, expr, &work_list_tail);
17962                 } while(expr);
17963                 do {
17964                         expr = triple_lhs(state, dt->triple, expr);
17965                         awaken(state, dtriple, expr, &work_list_tail);
17966                 } while(expr);
17967                 do {
17968                         expr = triple_misc(state, dt->triple, expr);
17969                         awaken(state, dtriple, expr, &work_list_tail);
17970                 } while(expr);
17971                 /* Wake up the forward control dependencies */
17972                 do {
17973                         expr = triple_targ(state, dt->triple, expr);
17974                         awaken(state, dtriple, expr, &work_list_tail);
17975                 } while(expr);
17976                 /* Wake up the reverse control dependencies of this triple */
17977                 for(user = dt->block->ipdomfrontier; user; user = user->next) {
17978                         struct triple *last;
17979                         last = user->member->last;
17980                         while((last->op == OP_NOOP) && (last != user->member->first)) {
17981 #if DEBUG_ROMCC_WARNINGS
17982 #warning "Should we bring the awakening noops back?"
17983 #endif
17984                                 // internal_warning(state, last, "awakening noop?");
17985                                 last = last->prev;
17986                         }
17987                         awaken(state, dtriple, &last, &work_list_tail);
17988                 }
17989         }
17990         print_dead_triples(state, dtriple);
17991         for(dt = &dtriple[1]; dt <= &dtriple[triples]; dt++) {
17992                 if ((dt->triple->op == OP_NOOP) &&
17993                         (dt->flags & TRIPLE_FLAG_ALIVE)) {
17994                         internal_error(state, dt->triple, "noop effective?");
17995                 }
17996                 dt->triple->id = dt->old_id;    /* Restore the color */
17997                 if (!(dt->flags & TRIPLE_FLAG_ALIVE)) {
17998                         release_triple(state, dt->triple);
17999                 }
18000         }
18001         xfree(dtriple);
18002
18003         rebuild_ssa_form(state);
18004
18005         print_blocks(state, __func__, state->dbgout);
18006 }
18007
18008
18009 static void insert_mandatory_copies(struct compile_state *state)
18010 {
18011         struct triple *ins, *first;
18012
18013         /* The object is with a minimum of inserted copies,
18014          * to resolve in fundamental register conflicts between
18015          * register value producers and consumers.
18016          * Theoretically we may be greater than minimal when we
18017          * are inserting copies before instructions but that
18018          * case should be rare.
18019          */
18020         first = state->first;
18021         ins = first;
18022         do {
18023                 struct triple_set *entry, *next;
18024                 struct triple *tmp;
18025                 struct reg_info info;
18026                 unsigned reg, regcm;
18027                 int do_post_copy, do_pre_copy;
18028                 tmp = 0;
18029                 if (!triple_is_def(state, ins)) {
18030                         goto next;
18031                 }
18032                 /* Find the architecture specific color information */
18033                 info = find_lhs_pre_color(state, ins, 0);
18034                 if (info.reg >= MAX_REGISTERS) {
18035                         info.reg = REG_UNSET;
18036                 }
18037
18038                 reg = REG_UNSET;
18039                 regcm = arch_type_to_regcm(state, ins->type);
18040                 do_post_copy = do_pre_copy = 0;
18041
18042                 /* Walk through the uses of ins and check for conflicts */
18043                 for(entry = ins->use; entry; entry = next) {
18044                         struct reg_info rinfo;
18045                         int i;
18046                         next = entry->next;
18047                         i = find_rhs_use(state, entry->member, ins);
18048                         if (i < 0) {
18049                                 continue;
18050                         }
18051
18052                         /* Find the users color requirements */
18053                         rinfo = arch_reg_rhs(state, entry->member, i);
18054                         if (rinfo.reg >= MAX_REGISTERS) {
18055                                 rinfo.reg = REG_UNSET;
18056                         }
18057
18058                         /* See if I need a pre_copy */
18059                         if (rinfo.reg != REG_UNSET) {
18060                                 if ((reg != REG_UNSET) && (reg != rinfo.reg)) {
18061                                         do_pre_copy = 1;
18062                                 }
18063                                 reg = rinfo.reg;
18064                         }
18065                         regcm &= rinfo.regcm;
18066                         regcm = arch_regcm_normalize(state, regcm);
18067                         if (regcm == 0) {
18068                                 do_pre_copy = 1;
18069                         }
18070                         /* Always use pre_copies for constants.
18071                          * They do not take up any registers until a
18072                          * copy places them in one.
18073                          */
18074                         if ((info.reg == REG_UNNEEDED) &&
18075                                 (rinfo.reg != REG_UNNEEDED)) {
18076                                 do_pre_copy = 1;
18077                         }
18078                 }
18079                 do_post_copy =
18080                         !do_pre_copy &&
18081                         (((info.reg != REG_UNSET) &&
18082                                 (reg != REG_UNSET) &&
18083                                 (info.reg != reg)) ||
18084                         ((info.regcm & regcm) == 0));
18085
18086                 reg = info.reg;
18087                 regcm = info.regcm;
18088                 /* Walk through the uses of ins and do a pre_copy or see if a post_copy is warranted */
18089                 for(entry = ins->use; entry; entry = next) {
18090                         struct reg_info rinfo;
18091                         int i;
18092                         next = entry->next;
18093                         i = find_rhs_use(state, entry->member, ins);
18094                         if (i < 0) {
18095                                 continue;
18096                         }
18097
18098                         /* Find the users color requirements */
18099                         rinfo = arch_reg_rhs(state, entry->member, i);
18100                         if (rinfo.reg >= MAX_REGISTERS) {
18101                                 rinfo.reg = REG_UNSET;
18102                         }
18103
18104                         /* Now see if it is time to do the pre_copy */
18105                         if (rinfo.reg != REG_UNSET) {
18106                                 if (((reg != REG_UNSET) && (reg != rinfo.reg)) ||
18107                                         ((regcm & rinfo.regcm) == 0) ||
18108                                         /* Don't let a mandatory coalesce sneak
18109                                          * into a operation that is marked to prevent
18110                                          * coalescing.
18111                                          */
18112                                         ((reg != REG_UNNEEDED) &&
18113                                         ((ins->id & TRIPLE_FLAG_POST_SPLIT) ||
18114                                         (entry->member->id & TRIPLE_FLAG_PRE_SPLIT)))
18115                                         ) {
18116                                         if (do_pre_copy) {
18117                                                 struct triple *user;
18118                                                 user = entry->member;
18119                                                 if (RHS(user, i) != ins) {
18120                                                         internal_error(state, user, "bad rhs");
18121                                                 }
18122                                                 tmp = pre_copy(state, user, i);
18123                                                 tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18124                                                 continue;
18125                                         } else {
18126                                                 do_post_copy = 1;
18127                                         }
18128                                 }
18129                                 reg = rinfo.reg;
18130                         }
18131                         if ((regcm & rinfo.regcm) == 0) {
18132                                 if (do_pre_copy) {
18133                                         struct triple *user;
18134                                         user = entry->member;
18135                                         if (RHS(user, i) != ins) {
18136                                                 internal_error(state, user, "bad rhs");
18137                                         }
18138                                         tmp = pre_copy(state, user, i);
18139                                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18140                                         continue;
18141                                 } else {
18142                                         do_post_copy = 1;
18143                                 }
18144                         }
18145                         regcm &= rinfo.regcm;
18146
18147                 }
18148                 if (do_post_copy) {
18149                         struct reg_info pre, post;
18150                         tmp = post_copy(state, ins);
18151                         tmp->id |= TRIPLE_FLAG_PRE_SPLIT;
18152                         pre = arch_reg_lhs(state, ins, 0);
18153                         post = arch_reg_lhs(state, tmp, 0);
18154                         if ((pre.reg == post.reg) && (pre.regcm == post.regcm)) {
18155                                 internal_error(state, tmp, "useless copy");
18156                         }
18157                 }
18158         next:
18159                 ins = ins->next;
18160         } while(ins != first);
18161
18162         print_blocks(state, __func__, state->dbgout);
18163 }
18164
18165
18166 struct live_range_edge;
18167 struct live_range_def;
18168 struct live_range {
18169         struct live_range_edge *edges;
18170         struct live_range_def *defs;
18171 /* Note. The list pointed to by defs is kept in order.
18172  * That is baring splits in the flow control
18173  * defs dominates defs->next wich dominates defs->next->next
18174  * etc.
18175  */
18176         unsigned color;
18177         unsigned classes;
18178         unsigned degree;
18179         unsigned length;
18180         struct live_range *group_next, **group_prev;
18181 };
18182
18183 struct live_range_edge {
18184         struct live_range_edge *next;
18185         struct live_range *node;
18186 };
18187
18188 struct live_range_def {
18189         struct live_range_def *next;
18190         struct live_range_def *prev;
18191         struct live_range *lr;
18192         struct triple *def;
18193         unsigned orig_id;
18194 };
18195
18196 #define LRE_HASH_SIZE 2048
18197 struct lre_hash {
18198         struct lre_hash *next;
18199         struct live_range *left;
18200         struct live_range *right;
18201 };
18202
18203
18204 struct reg_state {
18205         struct lre_hash *hash[LRE_HASH_SIZE];
18206         struct reg_block *blocks;
18207         struct live_range_def *lrd;
18208         struct live_range *lr;
18209         struct live_range *low, **low_tail;
18210         struct live_range *high, **high_tail;
18211         unsigned defs;
18212         unsigned ranges;
18213         int passes, max_passes;
18214 };
18215
18216
18217 struct print_interference_block_info {
18218         struct reg_state *rstate;
18219         FILE *fp;
18220         int need_edges;
18221 };
18222 static void print_interference_block(
18223         struct compile_state *state, struct block *block, void *arg)
18224
18225 {
18226         struct print_interference_block_info *info = arg;
18227         struct reg_state *rstate = info->rstate;
18228         struct block_set *edge;
18229         FILE *fp = info->fp;
18230         struct reg_block *rb;
18231         struct triple *ptr;
18232         int phi_present;
18233         int done;
18234         rb = &rstate->blocks[block->vertex];
18235
18236         fprintf(fp, "\nblock: %p (%d),",
18237                 block,  block->vertex);
18238         for(edge = block->edges; edge; edge = edge->next) {
18239                 fprintf(fp, " %p<-%p",
18240                         edge->member,
18241                         edge->member && edge->member->use?edge->member->use->member : 0);
18242         }
18243         fprintf(fp, "\n");
18244         if (rb->in) {
18245                 struct triple_reg_set *in_set;
18246                 fprintf(fp, "        in:");
18247                 for(in_set = rb->in; in_set; in_set = in_set->next) {
18248                         fprintf(fp, " %-10p", in_set->member);
18249                 }
18250                 fprintf(fp, "\n");
18251         }
18252         phi_present = 0;
18253         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18254                 done = (ptr == block->last);
18255                 if (ptr->op == OP_PHI) {
18256                         phi_present = 1;
18257                         break;
18258                 }
18259         }
18260         if (phi_present) {
18261                 int edge;
18262                 for(edge = 0; edge < block->users; edge++) {
18263                         fprintf(fp, "     in(%d):", edge);
18264                         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18265                                 struct triple **slot;
18266                                 done = (ptr == block->last);
18267                                 if (ptr->op != OP_PHI) {
18268                                         continue;
18269                                 }
18270                                 slot = &RHS(ptr, 0);
18271                                 fprintf(fp, " %-10p", slot[edge]);
18272                         }
18273                         fprintf(fp, "\n");
18274                 }
18275         }
18276         if (block->first->op == OP_LABEL) {
18277                 fprintf(fp, "%p:\n", block->first);
18278         }
18279         for(done = 0, ptr = block->first; !done; ptr = ptr->next) {
18280                 struct live_range *lr;
18281                 unsigned id;
18282                 done = (ptr == block->last);
18283                 lr = rstate->lrd[ptr->id].lr;
18284
18285                 id = ptr->id;
18286                 ptr->id = rstate->lrd[id].orig_id;
18287                 SET_REG(ptr->id, lr->color);
18288                 display_triple(fp, ptr);
18289                 ptr->id = id;
18290
18291                 if (triple_is_def(state, ptr) && (lr->defs == 0)) {
18292                         internal_error(state, ptr, "lr has no defs!");
18293                 }
18294                 if (info->need_edges) {
18295                         if (lr->defs) {
18296                                 struct live_range_def *lrd;
18297                                 fprintf(fp, "       range:");
18298                                 lrd = lr->defs;
18299                                 do {
18300                                         fprintf(fp, " %-10p", lrd->def);
18301                                         lrd = lrd->next;
18302                                 } while(lrd != lr->defs);
18303                                 fprintf(fp, "\n");
18304                         }
18305                         if (lr->edges > 0) {
18306                                 struct live_range_edge *edge;
18307                                 fprintf(fp, "       edges:");
18308                                 for(edge = lr->edges; edge; edge = edge->next) {
18309                                         struct live_range_def *lrd;
18310                                         lrd = edge->node->defs;
18311                                         do {
18312                                                 fprintf(fp, " %-10p", lrd->def);
18313                                                 lrd = lrd->next;
18314                                         } while(lrd != edge->node->defs);
18315                                         fprintf(fp, "|");
18316                                 }
18317                                 fprintf(fp, "\n");
18318                         }
18319                 }
18320                 /* Do a bunch of sanity checks */
18321                 valid_ins(state, ptr);
18322                 if ((ptr->id < 0) || (ptr->id > rstate->defs)) {
18323                         internal_error(state, ptr, "Invalid triple id: %d",
18324                                 ptr->id);
18325                 }
18326         }
18327         if (rb->out) {
18328                 struct triple_reg_set *out_set;
18329                 fprintf(fp, "       out:");
18330                 for(out_set = rb->out; out_set; out_set = out_set->next) {
18331                         fprintf(fp, " %-10p", out_set->member);
18332                 }
18333                 fprintf(fp, "\n");
18334         }
18335         fprintf(fp, "\n");
18336 }
18337
18338 static void print_interference_blocks(
18339         struct compile_state *state, struct reg_state *rstate, FILE *fp, int need_edges)
18340 {
18341         struct print_interference_block_info info;
18342         info.rstate = rstate;
18343         info.fp = fp;
18344         info.need_edges = need_edges;
18345         fprintf(fp, "\nlive variables by block\n");
18346         walk_blocks(state, &state->bb, print_interference_block, &info);
18347
18348 }
18349
18350 static unsigned regc_max_size(struct compile_state *state, int classes)
18351 {
18352         unsigned max_size;
18353         int i;
18354         max_size = 0;
18355         for(i = 0; i < MAX_REGC; i++) {
18356                 if (classes & (1 << i)) {
18357                         unsigned size;
18358                         size = arch_regc_size(state, i);
18359                         if (size > max_size) {
18360                                 max_size = size;
18361                         }
18362                 }
18363         }
18364         return max_size;
18365 }
18366
18367 static int reg_is_reg(struct compile_state *state, int reg1, int reg2)
18368 {
18369         unsigned equivs[MAX_REG_EQUIVS];
18370         int i;
18371         if ((reg1 < 0) || (reg1 >= MAX_REGISTERS)) {
18372                 internal_error(state, 0, "invalid register");
18373         }
18374         if ((reg2 < 0) || (reg2 >= MAX_REGISTERS)) {
18375                 internal_error(state, 0, "invalid register");
18376         }
18377         arch_reg_equivs(state, equivs, reg1);
18378         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18379                 if (equivs[i] == reg2) {
18380                         return 1;
18381                 }
18382         }
18383         return 0;
18384 }
18385
18386 static void reg_fill_used(struct compile_state *state, char *used, int reg)
18387 {
18388         unsigned equivs[MAX_REG_EQUIVS];
18389         int i;
18390         if (reg == REG_UNNEEDED) {
18391                 return;
18392         }
18393         arch_reg_equivs(state, equivs, reg);
18394         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18395                 used[equivs[i]] = 1;
18396         }
18397         return;
18398 }
18399
18400 static void reg_inc_used(struct compile_state *state, char *used, int reg)
18401 {
18402         unsigned equivs[MAX_REG_EQUIVS];
18403         int i;
18404         if (reg == REG_UNNEEDED) {
18405                 return;
18406         }
18407         arch_reg_equivs(state, equivs, reg);
18408         for(i = 0; (i < MAX_REG_EQUIVS) && equivs[i] != REG_UNSET; i++) {
18409                 used[equivs[i]] += 1;
18410         }
18411         return;
18412 }
18413
18414 static unsigned int hash_live_edge(
18415         struct live_range *left, struct live_range *right)
18416 {
18417         unsigned int hash, val;
18418         unsigned long lval, rval;
18419         lval = ((unsigned long)left)/sizeof(struct live_range);
18420         rval = ((unsigned long)right)/sizeof(struct live_range);
18421         hash = 0;
18422         while(lval) {
18423                 val = lval & 0xff;
18424                 lval >>= 8;
18425                 hash = (hash *263) + val;
18426         }
18427         while(rval) {
18428                 val = rval & 0xff;
18429                 rval >>= 8;
18430                 hash = (hash *263) + val;
18431         }
18432         hash = hash & (LRE_HASH_SIZE - 1);
18433         return hash;
18434 }
18435
18436 static struct lre_hash **lre_probe(struct reg_state *rstate,
18437         struct live_range *left, struct live_range *right)
18438 {
18439         struct lre_hash **ptr;
18440         unsigned int index;
18441         /* Ensure left <= right */
18442         if (left > right) {
18443                 struct live_range *tmp;
18444                 tmp = left;
18445                 left = right;
18446                 right = tmp;
18447         }
18448         index = hash_live_edge(left, right);
18449
18450         ptr = &rstate->hash[index];
18451         while(*ptr) {
18452                 if (((*ptr)->left == left) && ((*ptr)->right == right)) {
18453                         break;
18454                 }
18455                 ptr = &(*ptr)->next;
18456         }
18457         return ptr;
18458 }
18459
18460 static int interfere(struct reg_state *rstate,
18461         struct live_range *left, struct live_range *right)
18462 {
18463         struct lre_hash **ptr;
18464         ptr = lre_probe(rstate, left, right);
18465         return ptr && *ptr;
18466 }
18467
18468 static void add_live_edge(struct reg_state *rstate,
18469         struct live_range *left, struct live_range *right)
18470 {
18471         /* FIXME the memory allocation overhead is noticeable here... */
18472         struct lre_hash **ptr, *new_hash;
18473         struct live_range_edge *edge;
18474
18475         if (left == right) {
18476                 return;
18477         }
18478         if ((left == &rstate->lr[0]) || (right == &rstate->lr[0])) {
18479                 return;
18480         }
18481         /* Ensure left <= right */
18482         if (left > right) {
18483                 struct live_range *tmp;
18484                 tmp = left;
18485                 left = right;
18486                 right = tmp;
18487         }
18488         ptr = lre_probe(rstate, left, right);
18489         if (*ptr) {
18490                 return;
18491         }
18492 #if 0
18493         fprintf(state->errout, "new_live_edge(%p, %p)\n",
18494                 left, right);
18495 #endif
18496         new_hash = xmalloc(sizeof(*new_hash), "lre_hash");
18497         new_hash->next  = *ptr;
18498         new_hash->left  = left;
18499         new_hash->right = right;
18500         *ptr = new_hash;
18501
18502         edge = xmalloc(sizeof(*edge), "live_range_edge");
18503         edge->next   = left->edges;
18504         edge->node   = right;
18505         left->edges  = edge;
18506         left->degree += 1;
18507
18508         edge = xmalloc(sizeof(*edge), "live_range_edge");
18509         edge->next    = right->edges;
18510         edge->node    = left;
18511         right->edges  = edge;
18512         right->degree += 1;
18513 }
18514
18515 static void remove_live_edge(struct reg_state *rstate,
18516         struct live_range *left, struct live_range *right)
18517 {
18518         struct live_range_edge *edge, **ptr;
18519         struct lre_hash **hptr, *entry;
18520         hptr = lre_probe(rstate, left, right);
18521         if (!hptr || !*hptr) {
18522                 return;
18523         }
18524         entry = *hptr;
18525         *hptr = entry->next;
18526         xfree(entry);
18527
18528         for(ptr = &left->edges; *ptr; ptr = &(*ptr)->next) {
18529                 edge = *ptr;
18530                 if (edge->node == right) {
18531                         *ptr = edge->next;
18532                         memset(edge, 0, sizeof(*edge));
18533                         xfree(edge);
18534                         right->degree--;
18535                         break;
18536                 }
18537         }
18538         for(ptr = &right->edges; *ptr; ptr = &(*ptr)->next) {
18539                 edge = *ptr;
18540                 if (edge->node == left) {
18541                         *ptr = edge->next;
18542                         memset(edge, 0, sizeof(*edge));
18543                         xfree(edge);
18544                         left->degree--;
18545                         break;
18546                 }
18547         }
18548 }
18549
18550 static void remove_live_edges(struct reg_state *rstate, struct live_range *range)
18551 {
18552         struct live_range_edge *edge, *next;
18553         for(edge = range->edges; edge; edge = next) {
18554                 next = edge->next;
18555                 remove_live_edge(rstate, range, edge->node);
18556         }
18557 }
18558
18559 static void transfer_live_edges(struct reg_state *rstate,
18560         struct live_range *dest, struct live_range *src)
18561 {
18562         struct live_range_edge *edge, *next;
18563         for(edge = src->edges; edge; edge = next) {
18564                 struct live_range *other;
18565                 next = edge->next;
18566                 other = edge->node;
18567                 remove_live_edge(rstate, src, other);
18568                 add_live_edge(rstate, dest, other);
18569         }
18570 }
18571
18572
18573 /* Interference graph...
18574  *
18575  * new(n) --- Return a graph with n nodes but no edges.
18576  * add(g,x,y) --- Return a graph including g with an between x and y
18577  * interfere(g, x, y) --- Return true if there exists an edge between the nodes
18578  *                x and y in the graph g
18579  * degree(g, x) --- Return the degree of the node x in the graph g
18580  * neighbors(g, x, f) --- Apply function f to each neighbor of node x in the graph g
18581  *
18582  * Implement with a hash table && a set of adjcency vectors.
18583  * The hash table supports constant time implementations of add and interfere.
18584  * The adjacency vectors support an efficient implementation of neighbors.
18585  */
18586
18587 /*
18588  *     +---------------------------------------------------+
18589  *     |         +--------------+                          |
18590  *     v         v              |                          |
18591  * renumber -> build graph -> colalesce -> spill_costs -> simplify -> select
18592  *
18593  * -- In simplify implment optimistic coloring... (No backtracking)
18594  * -- Implement Rematerialization it is the only form of spilling we can perform
18595  *    Essentially this means dropping a constant from a register because
18596  *    we can regenerate it later.
18597  *
18598  * --- Very conservative colalescing (don't colalesce just mark the opportunities)
18599  *     coalesce at phi points...
18600  * --- Bias coloring if at all possible do the coalesing a compile time.
18601  *
18602  *
18603  */
18604
18605 #if DEBUG_ROMCC_WARNING
18606 static void different_colored(
18607         struct compile_state *state, struct reg_state *rstate,
18608         struct triple *parent, struct triple *ins)
18609 {
18610         struct live_range *lr;
18611         struct triple **expr;
18612         lr = rstate->lrd[ins->id].lr;
18613         expr = triple_rhs(state, ins, 0);
18614         for(;expr; expr = triple_rhs(state, ins, expr)) {
18615                 struct live_range *lr2;
18616                 if (!*expr || (*expr == parent) || (*expr == ins)) {
18617                         continue;
18618                 }
18619                 lr2 = rstate->lrd[(*expr)->id].lr;
18620                 if (lr->color == lr2->color) {
18621                         internal_error(state, ins, "live range too big");
18622                 }
18623         }
18624 }
18625 #endif
18626
18627 static struct live_range *coalesce_ranges(
18628         struct compile_state *state, struct reg_state *rstate,
18629         struct live_range *lr1, struct live_range *lr2)
18630 {
18631         struct live_range_def *head, *mid1, *mid2, *end, *lrd;
18632         unsigned color;
18633         unsigned classes;
18634         if (lr1 == lr2) {
18635                 return lr1;
18636         }
18637         if (!lr1->defs || !lr2->defs) {
18638                 internal_error(state, 0,
18639                         "cannot coalese dead live ranges");
18640         }
18641         if ((lr1->color == REG_UNNEEDED) ||
18642                 (lr2->color == REG_UNNEEDED)) {
18643                 internal_error(state, 0,
18644                         "cannot coalesce live ranges without a possible color");
18645         }
18646         if ((lr1->color != lr2->color) &&
18647                 (lr1->color != REG_UNSET) &&
18648                 (lr2->color != REG_UNSET)) {
18649                 internal_error(state, lr1->defs->def,
18650                         "cannot coalesce live ranges of different colors");
18651         }
18652         color = lr1->color;
18653         if (color == REG_UNSET) {
18654                 color = lr2->color;
18655         }
18656         classes = lr1->classes & lr2->classes;
18657         if (!classes) {
18658                 internal_error(state, lr1->defs->def,
18659                         "cannot coalesce live ranges with dissimilar register classes");
18660         }
18661         if (state->compiler->debug & DEBUG_COALESCING) {
18662                 FILE *fp = state->errout;
18663                 fprintf(fp, "coalescing:");
18664                 lrd = lr1->defs;
18665                 do {
18666                         fprintf(fp, " %p", lrd->def);
18667                         lrd = lrd->next;
18668                 } while(lrd != lr1->defs);
18669                 fprintf(fp, " |");
18670                 lrd = lr2->defs;
18671                 do {
18672                         fprintf(fp, " %p", lrd->def);
18673                         lrd = lrd->next;
18674                 } while(lrd != lr2->defs);
18675                 fprintf(fp, "\n");
18676         }
18677         /* If there is a clear dominate live range put it in lr1,
18678          * For purposes of this test phi functions are
18679          * considered dominated by the definitions that feed into
18680          * them.
18681          */
18682         if ((lr1->defs->prev->def->op == OP_PHI) ||
18683                 ((lr2->defs->prev->def->op != OP_PHI) &&
18684                 tdominates(state, lr2->defs->def, lr1->defs->def))) {
18685                 struct live_range *tmp;
18686                 tmp = lr1;
18687                 lr1 = lr2;
18688                 lr2 = tmp;
18689         }
18690 #if 0
18691         if (lr1->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
18692                 fprintf(state->errout, "lr1 post\n");
18693         }
18694         if (lr1->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18695                 fprintf(state->errout, "lr1 pre\n");
18696         }
18697         if (lr2->defs->orig_id  & TRIPLE_FLAG_POST_SPLIT) {
18698                 fprintf(state->errout, "lr2 post\n");
18699         }
18700         if (lr2->defs->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
18701                 fprintf(state->errout, "lr2 pre\n");
18702         }
18703 #endif
18704 #if 0
18705         fprintf(state->errout, "coalesce color1(%p): %3d color2(%p) %3d\n",
18706                 lr1->defs->def,
18707                 lr1->color,
18708                 lr2->defs->def,
18709                 lr2->color);
18710 #endif
18711
18712         /* Append lr2 onto lr1 */
18713 #if DEBUG_ROMCC_WARNINGS
18714 #warning "FIXME should this be a merge instead of a splice?"
18715 #endif
18716         /* This FIXME item applies to the correctness of live_range_end
18717          * and to the necessity of making multiple passes of coalesce_live_ranges.
18718          * A failure to find some coalesce opportunities in coaleace_live_ranges
18719          * does not impact the correct of the compiler just the efficiency with
18720          * which registers are allocated.
18721          */
18722         head = lr1->defs;
18723         mid1 = lr1->defs->prev;
18724         mid2 = lr2->defs;
18725         end  = lr2->defs->prev;
18726
18727         head->prev = end;
18728         end->next  = head;
18729
18730         mid1->next = mid2;
18731         mid2->prev = mid1;
18732
18733         /* Fixup the live range in the added live range defs */
18734         lrd = head;
18735         do {
18736                 lrd->lr = lr1;
18737                 lrd = lrd->next;
18738         } while(lrd != head);
18739
18740         /* Mark lr2 as free. */
18741         lr2->defs = 0;
18742         lr2->color = REG_UNNEEDED;
18743         lr2->classes = 0;
18744
18745         if (!lr1->defs) {
18746                 internal_error(state, 0, "lr1->defs == 0 ?");
18747         }
18748
18749         lr1->color   = color;
18750         lr1->classes = classes;
18751
18752         /* Keep the graph in sync by transfering the edges from lr2 to lr1 */
18753         transfer_live_edges(rstate, lr1, lr2);
18754
18755         return lr1;
18756 }
18757
18758 static struct live_range_def *live_range_head(
18759         struct compile_state *state, struct live_range *lr,
18760         struct live_range_def *last)
18761 {
18762         struct live_range_def *result;
18763         result = 0;
18764         if (last == 0) {
18765                 result = lr->defs;
18766         }
18767         else if (!tdominates(state, lr->defs->def, last->next->def)) {
18768                 result = last->next;
18769         }
18770         return result;
18771 }
18772
18773 static struct live_range_def *live_range_end(
18774         struct compile_state *state, struct live_range *lr,
18775         struct live_range_def *last)
18776 {
18777         struct live_range_def *result;
18778         result = 0;
18779         if (last == 0) {
18780                 result = lr->defs->prev;
18781         }
18782         else if (!tdominates(state, last->prev->def, lr->defs->prev->def)) {
18783                 result = last->prev;
18784         }
18785         return result;
18786 }
18787
18788
18789 static void initialize_live_ranges(
18790         struct compile_state *state, struct reg_state *rstate)
18791 {
18792         struct triple *ins, *first;
18793         size_t count, size;
18794         int i, j;
18795
18796         first = state->first;
18797         /* First count how many instructions I have.
18798          */
18799         count = count_triples(state);
18800         /* Potentially I need one live range definitions for each
18801          * instruction.
18802          */
18803         rstate->defs = count;
18804         /* Potentially I need one live range for each instruction
18805          * plus an extra for the dummy live range.
18806          */
18807         rstate->ranges = count + 1;
18808         size = sizeof(rstate->lrd[0]) * rstate->defs;
18809         rstate->lrd = xcmalloc(size, "live_range_def");
18810         size = sizeof(rstate->lr[0]) * rstate->ranges;
18811         rstate->lr  = xcmalloc(size, "live_range");
18812
18813         /* Setup the dummy live range */
18814         rstate->lr[0].classes = 0;
18815         rstate->lr[0].color = REG_UNSET;
18816         rstate->lr[0].defs = 0;
18817         i = j = 0;
18818         ins = first;
18819         do {
18820                 /* If the triple is a variable give it a live range */
18821                 if (triple_is_def(state, ins)) {
18822                         struct reg_info info;
18823                         /* Find the architecture specific color information */
18824                         info = find_def_color(state, ins);
18825                         i++;
18826                         rstate->lr[i].defs    = &rstate->lrd[j];
18827                         rstate->lr[i].color   = info.reg;
18828                         rstate->lr[i].classes = info.regcm;
18829                         rstate->lr[i].degree  = 0;
18830                         rstate->lrd[j].lr = &rstate->lr[i];
18831                 }
18832                 /* Otherwise give the triple the dummy live range. */
18833                 else {
18834                         rstate->lrd[j].lr = &rstate->lr[0];
18835                 }
18836
18837                 /* Initalize the live_range_def */
18838                 rstate->lrd[j].next    = &rstate->lrd[j];
18839                 rstate->lrd[j].prev    = &rstate->lrd[j];
18840                 rstate->lrd[j].def     = ins;
18841                 rstate->lrd[j].orig_id = ins->id;
18842                 ins->id = j;
18843
18844                 j++;
18845                 ins = ins->next;
18846         } while(ins != first);
18847         rstate->ranges = i;
18848
18849         /* Make a second pass to handle achitecture specific register
18850          * constraints.
18851          */
18852         ins = first;
18853         do {
18854                 int zlhs, zrhs, i, j;
18855                 if (ins->id > rstate->defs) {
18856                         internal_error(state, ins, "bad id");
18857                 }
18858
18859                 /* Walk through the template of ins and coalesce live ranges */
18860                 zlhs = ins->lhs;
18861                 if ((zlhs == 0) && triple_is_def(state, ins)) {
18862                         zlhs = 1;
18863                 }
18864                 zrhs = ins->rhs;
18865
18866                 if (state->compiler->debug & DEBUG_COALESCING2) {
18867                         fprintf(state->errout, "mandatory coalesce: %p %d %d\n",
18868                                 ins, zlhs, zrhs);
18869                 }
18870
18871                 for(i = 0; i < zlhs; i++) {
18872                         struct reg_info linfo;
18873                         struct live_range_def *lhs;
18874                         linfo = arch_reg_lhs(state, ins, i);
18875                         if (linfo.reg < MAX_REGISTERS) {
18876                                 continue;
18877                         }
18878                         if (triple_is_def(state, ins)) {
18879                                 lhs = &rstate->lrd[ins->id];
18880                         } else {
18881                                 lhs = &rstate->lrd[LHS(ins, i)->id];
18882                         }
18883
18884                         if (state->compiler->debug & DEBUG_COALESCING2) {
18885                                 fprintf(state->errout, "coalesce lhs(%d): %p %d\n",
18886                                         i, lhs, linfo.reg);
18887                         }
18888
18889                         for(j = 0; j < zrhs; j++) {
18890                                 struct reg_info rinfo;
18891                                 struct live_range_def *rhs;
18892                                 rinfo = arch_reg_rhs(state, ins, j);
18893                                 if (rinfo.reg < MAX_REGISTERS) {
18894                                         continue;
18895                                 }
18896                                 rhs = &rstate->lrd[RHS(ins, j)->id];
18897
18898                                 if (state->compiler->debug & DEBUG_COALESCING2) {
18899                                         fprintf(state->errout, "coalesce rhs(%d): %p %d\n",
18900                                                 j, rhs, rinfo.reg);
18901                                 }
18902
18903                                 if (rinfo.reg == linfo.reg) {
18904                                         coalesce_ranges(state, rstate,
18905                                                 lhs->lr, rhs->lr);
18906                                 }
18907                         }
18908                 }
18909                 ins = ins->next;
18910         } while(ins != first);
18911 }
18912
18913 static void graph_ins(
18914         struct compile_state *state,
18915         struct reg_block *blocks, struct triple_reg_set *live,
18916         struct reg_block *rb, struct triple *ins, void *arg)
18917 {
18918         struct reg_state *rstate = arg;
18919         struct live_range *def;
18920         struct triple_reg_set *entry;
18921
18922         /* If the triple is not a definition
18923          * we do not have a definition to add to
18924          * the interference graph.
18925          */
18926         if (!triple_is_def(state, ins)) {
18927                 return;
18928         }
18929         def = rstate->lrd[ins->id].lr;
18930
18931         /* Create an edge between ins and everything that is
18932          * alive, unless the live_range cannot share
18933          * a physical register with ins.
18934          */
18935         for(entry = live; entry; entry = entry->next) {
18936                 struct live_range *lr;
18937                 if ((entry->member->id < 0) || (entry->member->id > rstate->defs)) {
18938                         internal_error(state, 0, "bad entry?");
18939                 }
18940                 lr = rstate->lrd[entry->member->id].lr;
18941                 if (def == lr) {
18942                         continue;
18943                 }
18944                 if (!arch_regcm_intersect(def->classes, lr->classes)) {
18945                         continue;
18946                 }
18947                 add_live_edge(rstate, def, lr);
18948         }
18949         return;
18950 }
18951
18952 #if DEBUG_CONSISTENCY > 1
18953 static struct live_range *get_verify_live_range(
18954         struct compile_state *state, struct reg_state *rstate, struct triple *ins)
18955 {
18956         struct live_range *lr;
18957         struct live_range_def *lrd;
18958         int ins_found;
18959         if ((ins->id < 0) || (ins->id > rstate->defs)) {
18960                 internal_error(state, ins, "bad ins?");
18961         }
18962         lr = rstate->lrd[ins->id].lr;
18963         ins_found = 0;
18964         lrd = lr->defs;
18965         do {
18966                 if (lrd->def == ins) {
18967                         ins_found = 1;
18968                 }
18969                 lrd = lrd->next;
18970         } while(lrd != lr->defs);
18971         if (!ins_found) {
18972                 internal_error(state, ins, "ins not in live range");
18973         }
18974         return lr;
18975 }
18976
18977 static void verify_graph_ins(
18978         struct compile_state *state,
18979         struct reg_block *blocks, struct triple_reg_set *live,
18980         struct reg_block *rb, struct triple *ins, void *arg)
18981 {
18982         struct reg_state *rstate = arg;
18983         struct triple_reg_set *entry1, *entry2;
18984
18985
18986         /* Compare live against edges and make certain the code is working */
18987         for(entry1 = live; entry1; entry1 = entry1->next) {
18988                 struct live_range *lr1;
18989                 lr1 = get_verify_live_range(state, rstate, entry1->member);
18990                 for(entry2 = live; entry2; entry2 = entry2->next) {
18991                         struct live_range *lr2;
18992                         struct live_range_edge *edge2;
18993                         int lr1_found;
18994                         int lr2_degree;
18995                         if (entry2 == entry1) {
18996                                 continue;
18997                         }
18998                         lr2 = get_verify_live_range(state, rstate, entry2->member);
18999                         if (lr1 == lr2) {
19000                                 internal_error(state, entry2->member,
19001                                         "live range with 2 values simultaneously alive");
19002                         }
19003                         if (!arch_regcm_intersect(lr1->classes, lr2->classes)) {
19004                                 continue;
19005                         }
19006                         if (!interfere(rstate, lr1, lr2)) {
19007                                 internal_error(state, entry2->member,
19008                                         "edges don't interfere?");
19009                         }
19010
19011                         lr1_found = 0;
19012                         lr2_degree = 0;
19013                         for(edge2 = lr2->edges; edge2; edge2 = edge2->next) {
19014                                 lr2_degree++;
19015                                 if (edge2->node == lr1) {
19016                                         lr1_found = 1;
19017                                 }
19018                         }
19019                         if (lr2_degree != lr2->degree) {
19020                                 internal_error(state, entry2->member,
19021                                         "computed degree: %d does not match reported degree: %d\n",
19022                                         lr2_degree, lr2->degree);
19023                         }
19024                         if (!lr1_found) {
19025                                 internal_error(state, entry2->member, "missing edge");
19026                         }
19027                 }
19028         }
19029         return;
19030 }
19031 #endif
19032
19033 static void print_interference_ins(
19034         struct compile_state *state,
19035         struct reg_block *blocks, struct triple_reg_set *live,
19036         struct reg_block *rb, struct triple *ins, void *arg)
19037 {
19038         struct reg_state *rstate = arg;
19039         struct live_range *lr;
19040         unsigned id;
19041         FILE *fp = state->dbgout;
19042
19043         lr = rstate->lrd[ins->id].lr;
19044         id = ins->id;
19045         ins->id = rstate->lrd[id].orig_id;
19046         SET_REG(ins->id, lr->color);
19047         display_triple(state->dbgout, ins);
19048         ins->id = id;
19049
19050         if (lr->defs) {
19051                 struct live_range_def *lrd;
19052                 fprintf(fp, "       range:");
19053                 lrd = lr->defs;
19054                 do {
19055                         fprintf(fp, " %-10p", lrd->def);
19056                         lrd = lrd->next;
19057                 } while(lrd != lr->defs);
19058                 fprintf(fp, "\n");
19059         }
19060         if (live) {
19061                 struct triple_reg_set *entry;
19062                 fprintf(fp, "        live:");
19063                 for(entry = live; entry; entry = entry->next) {
19064                         fprintf(fp, " %-10p", entry->member);
19065                 }
19066                 fprintf(fp, "\n");
19067         }
19068         if (lr->edges) {
19069                 struct live_range_edge *entry;
19070                 fprintf(fp, "       edges:");
19071                 for(entry = lr->edges; entry; entry = entry->next) {
19072                         struct live_range_def *lrd;
19073                         lrd = entry->node->defs;
19074                         do {
19075                                 fprintf(fp, " %-10p", lrd->def);
19076                                 lrd = lrd->next;
19077                         } while(lrd != entry->node->defs);
19078                         fprintf(fp, "|");
19079                 }
19080                 fprintf(fp, "\n");
19081         }
19082         if (triple_is_branch(state, ins)) {
19083                 fprintf(fp, "\n");
19084         }
19085         return;
19086 }
19087
19088 static int coalesce_live_ranges(
19089         struct compile_state *state, struct reg_state *rstate)
19090 {
19091         /* At the point where a value is moved from one
19092          * register to another that value requires two
19093          * registers, thus increasing register pressure.
19094          * Live range coaleescing reduces the register
19095          * pressure by keeping a value in one register
19096          * longer.
19097          *
19098          * In the case of a phi function all paths leading
19099          * into it must be allocated to the same register
19100          * otherwise the phi function may not be removed.
19101          *
19102          * Forcing a value to stay in a single register
19103          * for an extended period of time does have
19104          * limitations when applied to non homogenous
19105          * register pool.
19106          *
19107          * The two cases I have identified are:
19108          * 1) Two forced register assignments may
19109          *    collide.
19110          * 2) Registers may go unused because they
19111          *    are only good for storing the value
19112          *    and not manipulating it.
19113          *
19114          * Because of this I need to split live ranges,
19115          * even outside of the context of coalesced live
19116          * ranges.  The need to split live ranges does
19117          * impose some constraints on live range coalescing.
19118          *
19119          * - Live ranges may not be coalesced across phi
19120          *   functions.  This creates a 2 headed live
19121          *   range that cannot be sanely split.
19122          *
19123          * - phi functions (coalesced in initialize_live_ranges)
19124          *   are handled as pre split live ranges so we will
19125          *   never attempt to split them.
19126          */
19127         int coalesced;
19128         int i;
19129
19130         coalesced = 0;
19131         for(i = 0; i <= rstate->ranges; i++) {
19132                 struct live_range *lr1;
19133                 struct live_range_def *lrd1;
19134                 lr1 = &rstate->lr[i];
19135                 if (!lr1->defs) {
19136                         continue;
19137                 }
19138                 lrd1 = live_range_end(state, lr1, 0);
19139                 for(; lrd1; lrd1 = live_range_end(state, lr1, lrd1)) {
19140                         struct triple_set *set;
19141                         if (lrd1->def->op != OP_COPY) {
19142                                 continue;
19143                         }
19144                         /* Skip copies that are the result of a live range split. */
19145                         if (lrd1->orig_id & TRIPLE_FLAG_POST_SPLIT) {
19146                                 continue;
19147                         }
19148                         for(set = lrd1->def->use; set; set = set->next) {
19149                                 struct live_range_def *lrd2;
19150                                 struct live_range *lr2, *res;
19151
19152                                 lrd2 = &rstate->lrd[set->member->id];
19153
19154                                 /* Don't coalesce with instructions
19155                                  * that are the result of a live range
19156                                  * split.
19157                                  */
19158                                 if (lrd2->orig_id & TRIPLE_FLAG_PRE_SPLIT) {
19159                                         continue;
19160                                 }
19161                                 lr2 = rstate->lrd[set->member->id].lr;
19162                                 if (lr1 == lr2) {
19163                                         continue;
19164                                 }
19165                                 if ((lr1->color != lr2->color) &&
19166                                         (lr1->color != REG_UNSET) &&
19167                                         (lr2->color != REG_UNSET)) {
19168                                         continue;
19169                                 }
19170                                 if ((lr1->classes & lr2->classes) == 0) {
19171                                         continue;
19172                                 }
19173
19174                                 if (interfere(rstate, lr1, lr2)) {
19175                                         continue;
19176                                 }
19177
19178                                 res = coalesce_ranges(state, rstate, lr1, lr2);
19179                                 coalesced += 1;
19180                                 if (res != lr1) {
19181                                         goto next;
19182                                 }
19183                         }
19184                 }
19185         next:
19186                 ;
19187         }
19188         return coalesced;
19189 }
19190
19191
19192 static void fix_coalesce_conflicts(struct compile_state *state,
19193         struct reg_block *blocks, struct triple_reg_set *live,
19194         struct reg_block *rb, struct triple *ins, void *arg)
19195 {
19196         int *conflicts = arg;
19197         int zlhs, zrhs, i, j;
19198
19199         /* See if we have a mandatory coalesce operation between
19200          * a lhs and a rhs value.  If so and the rhs value is also
19201          * alive then this triple needs to be pre copied.  Otherwise
19202          * we would have two definitions in the same live range simultaneously
19203          * alive.
19204          */
19205         zlhs = ins->lhs;
19206         if ((zlhs == 0) && triple_is_def(state, ins)) {
19207                 zlhs = 1;
19208         }
19209         zrhs = ins->rhs;
19210         for(i = 0; i < zlhs; i++) {
19211                 struct reg_info linfo;
19212                 linfo = arch_reg_lhs(state, ins, i);
19213                 if (linfo.reg < MAX_REGISTERS) {
19214                         continue;
19215                 }
19216                 for(j = 0; j < zrhs; j++) {
19217                         struct reg_info rinfo;
19218                         struct triple *rhs;
19219                         struct triple_reg_set *set;
19220                         int found;
19221                         found = 0;
19222                         rinfo = arch_reg_rhs(state, ins, j);
19223                         if (rinfo.reg != linfo.reg) {
19224                                 continue;
19225                         }
19226                         rhs = RHS(ins, j);
19227                         for(set = live; set && !found; set = set->next) {
19228                                 if (set->member == rhs) {
19229                                         found = 1;
19230                                 }
19231                         }
19232                         if (found) {
19233                                 struct triple *copy;
19234                                 copy = pre_copy(state, ins, j);
19235                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19236                                 (*conflicts)++;
19237                         }
19238                 }
19239         }
19240         return;
19241 }
19242
19243 static int correct_coalesce_conflicts(
19244         struct compile_state *state, struct reg_block *blocks)
19245 {
19246         int conflicts;
19247         conflicts = 0;
19248         walk_variable_lifetimes(state, &state->bb, blocks,
19249                 fix_coalesce_conflicts, &conflicts);
19250         return conflicts;
19251 }
19252
19253 static void replace_set_use(struct compile_state *state,
19254         struct triple_reg_set *head, struct triple *orig, struct triple *new)
19255 {
19256         struct triple_reg_set *set;
19257         for(set = head; set; set = set->next) {
19258                 if (set->member == orig) {
19259                         set->member = new;
19260                 }
19261         }
19262 }
19263
19264 static void replace_block_use(struct compile_state *state,
19265         struct reg_block *blocks, struct triple *orig, struct triple *new)
19266 {
19267         int i;
19268 #if DEBUG_ROMCC_WARNINGS
19269 #warning "WISHLIST visit just those blocks that need it *"
19270 #endif
19271         for(i = 1; i <= state->bb.last_vertex; i++) {
19272                 struct reg_block *rb;
19273                 rb = &blocks[i];
19274                 replace_set_use(state, rb->in, orig, new);
19275                 replace_set_use(state, rb->out, orig, new);
19276         }
19277 }
19278
19279 static void color_instructions(struct compile_state *state)
19280 {
19281         struct triple *ins, *first;
19282         first = state->first;
19283         ins = first;
19284         do {
19285                 if (triple_is_def(state, ins)) {
19286                         struct reg_info info;
19287                         info = find_lhs_color(state, ins, 0);
19288                         if (info.reg >= MAX_REGISTERS) {
19289                                 info.reg = REG_UNSET;
19290                         }
19291                         SET_INFO(ins->id, info);
19292                 }
19293                 ins = ins->next;
19294         } while(ins != first);
19295 }
19296
19297 static struct reg_info read_lhs_color(
19298         struct compile_state *state, struct triple *ins, int index)
19299 {
19300         struct reg_info info;
19301         if ((index == 0) && triple_is_def(state, ins)) {
19302                 info.reg   = ID_REG(ins->id);
19303                 info.regcm = ID_REGCM(ins->id);
19304         }
19305         else if (index < ins->lhs) {
19306                 info = read_lhs_color(state, LHS(ins, index), 0);
19307         }
19308         else {
19309                 internal_error(state, ins, "Bad lhs %d", index);
19310                 info.reg = REG_UNSET;
19311                 info.regcm = 0;
19312         }
19313         return info;
19314 }
19315
19316 static struct triple *resolve_tangle(
19317         struct compile_state *state, struct triple *tangle)
19318 {
19319         struct reg_info info, uinfo;
19320         struct triple_set *set, *next;
19321         struct triple *copy;
19322
19323 #if DEBUG_ROMCC_WARNINGS
19324 #warning "WISHLIST recalculate all affected instructions colors"
19325 #endif
19326         info = find_lhs_color(state, tangle, 0);
19327         for(set = tangle->use; set; set = next) {
19328                 struct triple *user;
19329                 int i, zrhs;
19330                 next = set->next;
19331                 user = set->member;
19332                 zrhs = user->rhs;
19333                 for(i = 0; i < zrhs; i++) {
19334                         if (RHS(user, i) != tangle) {
19335                                 continue;
19336                         }
19337                         uinfo = find_rhs_post_color(state, user, i);
19338                         if (uinfo.reg == info.reg) {
19339                                 copy = pre_copy(state, user, i);
19340                                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19341                                 SET_INFO(copy->id, uinfo);
19342                         }
19343                 }
19344         }
19345         copy = 0;
19346         uinfo = find_lhs_pre_color(state, tangle, 0);
19347         if (uinfo.reg == info.reg) {
19348                 struct reg_info linfo;
19349                 copy = post_copy(state, tangle);
19350                 copy->id |= TRIPLE_FLAG_PRE_SPLIT;
19351                 linfo = find_lhs_color(state, copy, 0);
19352                 SET_INFO(copy->id, linfo);
19353         }
19354         info = find_lhs_color(state, tangle, 0);
19355         SET_INFO(tangle->id, info);
19356
19357         return copy;
19358 }
19359
19360
19361 static void fix_tangles(struct compile_state *state,
19362         struct reg_block *blocks, struct triple_reg_set *live,
19363         struct reg_block *rb, struct triple *ins, void *arg)
19364 {
19365         int *tangles = arg;
19366         struct triple *tangle;
19367         do {
19368                 char used[MAX_REGISTERS];
19369                 struct triple_reg_set *set;
19370                 tangle = 0;
19371
19372                 /* Find out which registers have multiple uses at this point */
19373                 memset(used, 0, sizeof(used));
19374                 for(set = live; set; set = set->next) {
19375                         struct reg_info info;
19376                         info = read_lhs_color(state, set->member, 0);
19377                         if (info.reg == REG_UNSET) {
19378                                 continue;
19379                         }
19380                         reg_inc_used(state, used, info.reg);
19381                 }
19382
19383                 /* Now find the least dominated definition of a register in
19384                  * conflict I have seen so far.
19385                  */
19386                 for(set = live; set; set = set->next) {
19387                         struct reg_info info;
19388                         info = read_lhs_color(state, set->member, 0);
19389                         if (used[info.reg] < 2) {
19390                                 continue;
19391                         }
19392                         /* Changing copies that feed into phi functions
19393                          * is incorrect.
19394                          */
19395                         if (set->member->use &&
19396                                 (set->member->use->member->op == OP_PHI)) {
19397                                 continue;
19398                         }
19399                         if (!tangle || tdominates(state, set->member, tangle)) {
19400                                 tangle = set->member;
19401                         }
19402                 }
19403                 /* If I have found a tangle resolve it */
19404                 if (tangle) {
19405                         struct triple *post_copy;
19406                         (*tangles)++;
19407                         post_copy = resolve_tangle(state, tangle);
19408                         if (post_copy) {
19409                                 replace_block_use(state, blocks, tangle, post_copy);
19410                         }
19411                         if (post_copy && (tangle != ins)) {
19412                                 replace_set_use(state, live, tangle, post_copy);
19413                         }
19414                 }
19415         } while(tangle);
19416         return;
19417 }
19418
19419 static int correct_tangles(
19420         struct compile_state *state, struct reg_block *blocks)
19421 {
19422         int tangles;
19423         tangles = 0;
19424         color_instructions(state);
19425         walk_variable_lifetimes(state, &state->bb, blocks,
19426                 fix_tangles, &tangles);
19427         return tangles;
19428 }
19429
19430
19431 static void ids_from_rstate(struct compile_state *state, struct reg_state *rstate);
19432 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate);
19433
19434 struct triple *find_constrained_def(
19435         struct compile_state *state, struct live_range *range, struct triple *constrained)
19436 {
19437         struct live_range_def *lrd, *lrd_next;
19438         lrd_next = range->defs;
19439         do {
19440                 struct reg_info info;
19441                 unsigned regcm;
19442
19443                 lrd = lrd_next;
19444                 lrd_next = lrd->next;
19445
19446                 regcm = arch_type_to_regcm(state, lrd->def->type);
19447                 info = find_lhs_color(state, lrd->def, 0);
19448                 regcm      = arch_regcm_reg_normalize(state, regcm);
19449                 info.regcm = arch_regcm_reg_normalize(state, info.regcm);
19450                 /* If the 2 register class masks are equal then
19451                  * the current register class is not constrained.
19452                  */
19453                 if (regcm == info.regcm) {
19454                         continue;
19455                 }
19456
19457                 /* If there is just one use.
19458                  * That use cannot accept a larger register class.
19459                  * There are no intervening definitions except
19460                  * definitions that feed into that use.
19461                  * Then a triple is not constrained.
19462                  * FIXME handle this case!
19463                  */
19464 #if DEBUG_ROMCC_WARNINGS
19465 #warning "FIXME ignore cases that cannot be fixed (a definition followed by a use)"
19466 #endif
19467
19468
19469                 /* Of the constrained live ranges deal with the
19470                  * least dominated one first.
19471                  */
19472                 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19473                         fprintf(state->errout, "canidate: %p %-8s regcm: %x %x\n",
19474                                 lrd->def, tops(lrd->def->op), regcm, info.regcm);
19475                 }
19476                 if (!constrained ||
19477                         tdominates(state, lrd->def, constrained))
19478                 {
19479                         constrained = lrd->def;
19480                 }
19481         } while(lrd_next != range->defs);
19482         return constrained;
19483 }
19484
19485 static int split_constrained_ranges(
19486         struct compile_state *state, struct reg_state *rstate,
19487         struct live_range *range)
19488 {
19489         /* Walk through the edges in conflict and our current live
19490          * range, and find definitions that are more severly constrained
19491          * than they type of data they contain require.
19492          *
19493          * Then pick one of those ranges and relax the constraints.
19494          */
19495         struct live_range_edge *edge;
19496         struct triple *constrained;
19497
19498         constrained = 0;
19499         for(edge = range->edges; edge; edge = edge->next) {
19500                 constrained = find_constrained_def(state, edge->node, constrained);
19501         }
19502 #if DEBUG_ROMCC_WARNINGS
19503 #warning "FIXME should I call find_constrained_def here only if no previous constrained def was found?"
19504 #endif
19505         if (!constrained) {
19506                 constrained = find_constrained_def(state, range, constrained);
19507         }
19508
19509         if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19510                 fprintf(state->errout, "constrained: ");
19511                 display_triple(state->errout, constrained);
19512         }
19513         if (constrained) {
19514                 ids_from_rstate(state, rstate);
19515                 cleanup_rstate(state, rstate);
19516                 resolve_tangle(state, constrained);
19517         }
19518         return !!constrained;
19519 }
19520
19521 static int split_ranges(
19522         struct compile_state *state, struct reg_state *rstate,
19523         char *used, struct live_range *range)
19524 {
19525         int split;
19526         if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
19527                 fprintf(state->errout, "split_ranges %d %s %p\n",
19528                         rstate->passes, tops(range->defs->def->op), range->defs->def);
19529         }
19530         if ((range->color == REG_UNNEEDED) ||
19531                 (rstate->passes >= rstate->max_passes)) {
19532                 return 0;
19533         }
19534         split = split_constrained_ranges(state, rstate, range);
19535
19536         /* Ideally I would split the live range that will not be used
19537          * for the longest period of time in hopes that this will
19538          * (a) allow me to spill a register or
19539          * (b) allow me to place a value in another register.
19540          *
19541          * So far I don't have a test case for this, the resolving
19542          * of mandatory constraints has solved all of my
19543          * know issues.  So I have choosen not to write any
19544          * code until I cat get a better feel for cases where
19545          * it would be useful to have.
19546          *
19547          */
19548 #if DEBUG_ROMCC_WARNINGS
19549 #warning "WISHLIST implement live range splitting..."
19550 #endif
19551
19552         if (!split && (state->compiler->debug & DEBUG_RANGE_CONFLICTS2)) {
19553                 FILE *fp = state->errout;
19554                 print_interference_blocks(state, rstate, fp, 0);
19555                 print_dominators(state, fp, &state->bb);
19556         }
19557         return split;
19558 }
19559
19560 static FILE *cgdebug_fp(struct compile_state *state)
19561 {
19562         FILE *fp;
19563         fp = 0;
19564         if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH2)) {
19565                 fp = state->errout;
19566         }
19567         if (!fp && (state->compiler->debug & DEBUG_COLOR_GRAPH)) {
19568                 fp = state->dbgout;
19569         }
19570         return fp;
19571 }
19572
19573 static void cgdebug_printf(struct compile_state *state, const char *fmt, ...)
19574 {
19575         FILE *fp;
19576         fp = cgdebug_fp(state);
19577         if (fp) {
19578                 va_list args;
19579                 va_start(args, fmt);
19580                 vfprintf(fp, fmt, args);
19581                 va_end(args);
19582         }
19583 }
19584
19585 static void cgdebug_flush(struct compile_state *state)
19586 {
19587         FILE *fp;
19588         fp = cgdebug_fp(state);
19589         if (fp) {
19590                 fflush(fp);
19591         }
19592 }
19593
19594 static void cgdebug_loc(struct compile_state *state, struct triple *ins)
19595 {
19596         FILE *fp;
19597         fp = cgdebug_fp(state);
19598         if (fp) {
19599                 loc(fp, state, ins);
19600         }
19601 }
19602
19603 static int select_free_color(struct compile_state *state,
19604         struct reg_state *rstate, struct live_range *range)
19605 {
19606         struct triple_set *entry;
19607         struct live_range_def *lrd;
19608         struct live_range_def *phi;
19609         struct live_range_edge *edge;
19610         char used[MAX_REGISTERS];
19611         struct triple **expr;
19612
19613         /* Instead of doing just the trivial color select here I try
19614          * a few extra things because a good color selection will help reduce
19615          * copies.
19616          */
19617
19618         /* Find the registers currently in use */
19619         memset(used, 0, sizeof(used));
19620         for(edge = range->edges; edge; edge = edge->next) {
19621                 if (edge->node->color == REG_UNSET) {
19622                         continue;
19623                 }
19624                 reg_fill_used(state, used, edge->node->color);
19625         }
19626
19627         if (state->compiler->debug & DEBUG_COLOR_GRAPH2) {
19628                 int i;
19629                 i = 0;
19630                 for(edge = range->edges; edge; edge = edge->next) {
19631                         i++;
19632                 }
19633                 cgdebug_printf(state, "\n%s edges: %d",
19634                         tops(range->defs->def->op), i);
19635                 cgdebug_loc(state, range->defs->def);
19636                 cgdebug_printf(state, "\n");
19637                 for(i = 0; i < MAX_REGISTERS; i++) {
19638                         if (used[i]) {
19639                                 cgdebug_printf(state, "used: %s\n",
19640                                         arch_reg_str(i));
19641                         }
19642                 }
19643         }
19644
19645         /* If a color is already assigned see if it will work */
19646         if (range->color != REG_UNSET) {
19647                 struct live_range_def *lrd;
19648                 if (!used[range->color]) {
19649                         return 1;
19650                 }
19651                 for(edge = range->edges; edge; edge = edge->next) {
19652                         if (edge->node->color != range->color) {
19653                                 continue;
19654                         }
19655                         warning(state, edge->node->defs->def, "edge: ");
19656                         lrd = edge->node->defs;
19657                         do {
19658                                 warning(state, lrd->def, " %p %s",
19659                                         lrd->def, tops(lrd->def->op));
19660                                 lrd = lrd->next;
19661                         } while(lrd != edge->node->defs);
19662                 }
19663                 lrd = range->defs;
19664                 warning(state, range->defs->def, "def: ");
19665                 do {
19666                         warning(state, lrd->def, " %p %s",
19667                                 lrd->def, tops(lrd->def->op));
19668                         lrd = lrd->next;
19669                 } while(lrd != range->defs);
19670                 internal_error(state, range->defs->def,
19671                         "live range with already used color %s",
19672                         arch_reg_str(range->color));
19673         }
19674
19675         /* If I feed into an expression reuse it's color.
19676          * This should help remove copies in the case of 2 register instructions
19677          * and phi functions.
19678          */
19679         phi = 0;
19680         lrd = live_range_end(state, range, 0);
19681         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_end(state, range, lrd)) {
19682                 entry = lrd->def->use;
19683                 for(;(range->color == REG_UNSET) && entry; entry = entry->next) {
19684                         struct live_range_def *insd;
19685                         unsigned regcm;
19686                         insd = &rstate->lrd[entry->member->id];
19687                         if (insd->lr->defs == 0) {
19688                                 continue;
19689                         }
19690                         if (!phi && (insd->def->op == OP_PHI) &&
19691                                 !interfere(rstate, range, insd->lr)) {
19692                                 phi = insd;
19693                         }
19694                         if (insd->lr->color == REG_UNSET) {
19695                                 continue;
19696                         }
19697                         regcm = insd->lr->classes;
19698                         if (((regcm & range->classes) == 0) ||
19699                                 (used[insd->lr->color])) {
19700                                 continue;
19701                         }
19702                         if (interfere(rstate, range, insd->lr)) {
19703                                 continue;
19704                         }
19705                         range->color = insd->lr->color;
19706                 }
19707         }
19708         /* If I feed into a phi function reuse it's color or the color
19709          * of something else that feeds into the phi function.
19710          */
19711         if (phi) {
19712                 if (phi->lr->color != REG_UNSET) {
19713                         if (used[phi->lr->color]) {
19714                                 range->color = phi->lr->color;
19715                         }
19716                 }
19717                 else {
19718                         expr = triple_rhs(state, phi->def, 0);
19719                         for(; expr; expr = triple_rhs(state, phi->def, expr)) {
19720                                 struct live_range *lr;
19721                                 unsigned regcm;
19722                                 if (!*expr) {
19723                                         continue;
19724                                 }
19725                                 lr = rstate->lrd[(*expr)->id].lr;
19726                                 if (lr->color == REG_UNSET) {
19727                                         continue;
19728                                 }
19729                                 regcm = lr->classes;
19730                                 if (((regcm & range->classes) == 0) ||
19731                                         (used[lr->color])) {
19732                                         continue;
19733                                 }
19734                                 if (interfere(rstate, range, lr)) {
19735                                         continue;
19736                                 }
19737                                 range->color = lr->color;
19738                         }
19739                 }
19740         }
19741         /* If I don't interfere with a rhs node reuse it's color */
19742         lrd = live_range_head(state, range, 0);
19743         for(; (range->color == REG_UNSET) && lrd ; lrd = live_range_head(state, range, lrd)) {
19744                 expr = triple_rhs(state, lrd->def, 0);
19745                 for(; expr; expr = triple_rhs(state, lrd->def, expr)) {
19746                         struct live_range *lr;
19747                         unsigned regcm;
19748                         if (!*expr) {
19749                                 continue;
19750                         }
19751                         lr = rstate->lrd[(*expr)->id].lr;
19752                         if (lr->color == REG_UNSET) {
19753                                 continue;
19754                         }
19755                         regcm = lr->classes;
19756                         if (((regcm & range->classes) == 0) ||
19757                                 (used[lr->color])) {
19758                                 continue;
19759                         }
19760                         if (interfere(rstate, range, lr)) {
19761                                 continue;
19762                         }
19763                         range->color = lr->color;
19764                         break;
19765                 }
19766         }
19767         /* If I have not opportunitically picked a useful color
19768          * pick the first color that is free.
19769          */
19770         if (range->color == REG_UNSET) {
19771                 range->color =
19772                         arch_select_free_register(state, used, range->classes);
19773         }
19774         if (range->color == REG_UNSET) {
19775                 struct live_range_def *lrd;
19776                 int i;
19777                 if (split_ranges(state, rstate, used, range)) {
19778                         return 0;
19779                 }
19780                 for(edge = range->edges; edge; edge = edge->next) {
19781                         warning(state, edge->node->defs->def, "edge reg %s",
19782                                 arch_reg_str(edge->node->color));
19783                         lrd = edge->node->defs;
19784                         do {
19785                                 warning(state, lrd->def, " %s %p",
19786                                         tops(lrd->def->op), lrd->def);
19787                                 lrd = lrd->next;
19788                         } while(lrd != edge->node->defs);
19789                 }
19790                 warning(state, range->defs->def, "range: ");
19791                 lrd = range->defs;
19792                 do {
19793                         warning(state, lrd->def, " %s %p",
19794                                 tops(lrd->def->op), lrd->def);
19795                         lrd = lrd->next;
19796                 } while(lrd != range->defs);
19797
19798                 warning(state, range->defs->def, "classes: %x",
19799                         range->classes);
19800                 for(i = 0; i < MAX_REGISTERS; i++) {
19801                         if (used[i]) {
19802                                 warning(state, range->defs->def, "used: %s",
19803                                         arch_reg_str(i));
19804                         }
19805                 }
19806                 error(state, range->defs->def, "too few registers");
19807         }
19808         range->classes &= arch_reg_regcm(state, range->color);
19809         if ((range->color == REG_UNSET) || (range->classes == 0)) {
19810                 internal_error(state, range->defs->def, "select_free_color did not?");
19811         }
19812         return 1;
19813 }
19814
19815 static int color_graph(struct compile_state *state, struct reg_state *rstate)
19816 {
19817         int colored;
19818         struct live_range_edge *edge;
19819         struct live_range *range;
19820         if (rstate->low) {
19821                 cgdebug_printf(state, "Lo: ");
19822                 range = rstate->low;
19823                 if (*range->group_prev != range) {
19824                         internal_error(state, 0, "lo: *prev != range?");
19825                 }
19826                 *range->group_prev = range->group_next;
19827                 if (range->group_next) {
19828                         range->group_next->group_prev = range->group_prev;
19829                 }
19830                 if (&range->group_next == rstate->low_tail) {
19831                         rstate->low_tail = range->group_prev;
19832                 }
19833                 if (rstate->low == range) {
19834                         internal_error(state, 0, "low: next != prev?");
19835                 }
19836         }
19837         else if (rstate->high) {
19838                 cgdebug_printf(state, "Hi: ");
19839                 range = rstate->high;
19840                 if (*range->group_prev != range) {
19841                         internal_error(state, 0, "hi: *prev != range?");
19842                 }
19843                 *range->group_prev = range->group_next;
19844                 if (range->group_next) {
19845                         range->group_next->group_prev = range->group_prev;
19846                 }
19847                 if (&range->group_next == rstate->high_tail) {
19848                         rstate->high_tail = range->group_prev;
19849                 }
19850                 if (rstate->high == range) {
19851                         internal_error(state, 0, "high: next != prev?");
19852                 }
19853         }
19854         else {
19855                 return 1;
19856         }
19857         cgdebug_printf(state, " %d\n", range - rstate->lr);
19858         range->group_prev = 0;
19859         for(edge = range->edges; edge; edge = edge->next) {
19860                 struct live_range *node;
19861                 node = edge->node;
19862                 /* Move nodes from the high to the low list */
19863                 if (node->group_prev && (node->color == REG_UNSET) &&
19864                         (node->degree == regc_max_size(state, node->classes))) {
19865                         if (*node->group_prev != node) {
19866                                 internal_error(state, 0, "move: *prev != node?");
19867                         }
19868                         *node->group_prev = node->group_next;
19869                         if (node->group_next) {
19870                                 node->group_next->group_prev = node->group_prev;
19871                         }
19872                         if (&node->group_next == rstate->high_tail) {
19873                                 rstate->high_tail = node->group_prev;
19874                         }
19875                         cgdebug_printf(state, "Moving...%d to low\n", node - rstate->lr);
19876                         node->group_prev  = rstate->low_tail;
19877                         node->group_next  = 0;
19878                         *rstate->low_tail = node;
19879                         rstate->low_tail  = &node->group_next;
19880                         if (*node->group_prev != node) {
19881                                 internal_error(state, 0, "move2: *prev != node?");
19882                         }
19883                 }
19884                 node->degree -= 1;
19885         }
19886         colored = color_graph(state, rstate);
19887         if (colored) {
19888                 cgdebug_printf(state, "Coloring %d @", range - rstate->lr);
19889                 cgdebug_loc(state, range->defs->def);
19890                 cgdebug_flush(state);
19891                 colored = select_free_color(state, rstate, range);
19892                 if (colored) {
19893                         cgdebug_printf(state, " %s\n", arch_reg_str(range->color));
19894                 }
19895         }
19896         return colored;
19897 }
19898
19899 static void verify_colors(struct compile_state *state, struct reg_state *rstate)
19900 {
19901         struct live_range *lr;
19902         struct live_range_edge *edge;
19903         struct triple *ins, *first;
19904         char used[MAX_REGISTERS];
19905         first = state->first;
19906         ins = first;
19907         do {
19908                 if (triple_is_def(state, ins)) {
19909                         if ((ins->id < 0) || (ins->id > rstate->defs)) {
19910                                 internal_error(state, ins,
19911                                         "triple without a live range def");
19912                         }
19913                         lr = rstate->lrd[ins->id].lr;
19914                         if (lr->color == REG_UNSET) {
19915                                 internal_error(state, ins,
19916                                         "triple without a color");
19917                         }
19918                         /* Find the registers used by the edges */
19919                         memset(used, 0, sizeof(used));
19920                         for(edge = lr->edges; edge; edge = edge->next) {
19921                                 if (edge->node->color == REG_UNSET) {
19922                                         internal_error(state, 0,
19923                                                 "live range without a color");
19924                         }
19925                                 reg_fill_used(state, used, edge->node->color);
19926                         }
19927                         if (used[lr->color]) {
19928                                 internal_error(state, ins,
19929                                         "triple with already used color");
19930                         }
19931                 }
19932                 ins = ins->next;
19933         } while(ins != first);
19934 }
19935
19936 static void color_triples(struct compile_state *state, struct reg_state *rstate)
19937 {
19938         struct live_range_def *lrd;
19939         struct live_range *lr;
19940         struct triple *first, *ins;
19941         first = state->first;
19942         ins = first;
19943         do {
19944                 if ((ins->id < 0) || (ins->id > rstate->defs)) {
19945                         internal_error(state, ins,
19946                                 "triple without a live range");
19947                 }
19948                 lrd = &rstate->lrd[ins->id];
19949                 lr = lrd->lr;
19950                 ins->id = lrd->orig_id;
19951                 SET_REG(ins->id, lr->color);
19952                 ins = ins->next;
19953         } while (ins != first);
19954 }
19955
19956 static struct live_range *merge_sort_lr(
19957         struct live_range *first, struct live_range *last)
19958 {
19959         struct live_range *mid, *join, **join_tail, *pick;
19960         size_t size;
19961         size = (last - first) + 1;
19962         if (size >= 2) {
19963                 mid = first + size/2;
19964                 first = merge_sort_lr(first, mid -1);
19965                 mid   = merge_sort_lr(mid, last);
19966
19967                 join = 0;
19968                 join_tail = &join;
19969                 /* merge the two lists */
19970                 while(first && mid) {
19971                         if ((first->degree < mid->degree) ||
19972                                 ((first->degree == mid->degree) &&
19973                                         (first->length < mid->length))) {
19974                                 pick = first;
19975                                 first = first->group_next;
19976                                 if (first) {
19977                                         first->group_prev = 0;
19978                                 }
19979                         }
19980                         else {
19981                                 pick = mid;
19982                                 mid = mid->group_next;
19983                                 if (mid) {
19984                                         mid->group_prev = 0;
19985                                 }
19986                         }
19987                         pick->group_next = 0;
19988                         pick->group_prev = join_tail;
19989                         *join_tail = pick;
19990                         join_tail = &pick->group_next;
19991                 }
19992                 /* Splice the remaining list */
19993                 pick = (first)? first : mid;
19994                 *join_tail = pick;
19995                 if (pick) {
19996                         pick->group_prev = join_tail;
19997                 }
19998         }
19999         else {
20000                 if (!first->defs) {
20001                         first = 0;
20002                 }
20003                 join = first;
20004         }
20005         return join;
20006 }
20007
20008 static void ids_from_rstate(struct compile_state *state,
20009         struct reg_state *rstate)
20010 {
20011         struct triple *ins, *first;
20012         if (!rstate->defs) {
20013                 return;
20014         }
20015         /* Display the graph if desired */
20016         if (state->compiler->debug & DEBUG_INTERFERENCE) {
20017                 FILE *fp = state->dbgout;
20018                 print_interference_blocks(state, rstate, fp, 0);
20019                 print_control_flow(state, fp, &state->bb);
20020                 fflush(fp);
20021         }
20022         first = state->first;
20023         ins = first;
20024         do {
20025                 if (ins->id) {
20026                         struct live_range_def *lrd;
20027                         lrd = &rstate->lrd[ins->id];
20028                         ins->id = lrd->orig_id;
20029                 }
20030                 ins = ins->next;
20031         } while(ins != first);
20032 }
20033
20034 static void cleanup_live_edges(struct reg_state *rstate)
20035 {
20036         int i;
20037         /* Free the edges on each node */
20038         for(i = 1; i <= rstate->ranges; i++) {
20039                 remove_live_edges(rstate, &rstate->lr[i]);
20040         }
20041 }
20042
20043 static void cleanup_rstate(struct compile_state *state, struct reg_state *rstate)
20044 {
20045         cleanup_live_edges(rstate);
20046         xfree(rstate->lrd);
20047         xfree(rstate->lr);
20048
20049         /* Free the variable lifetime information */
20050         if (rstate->blocks) {
20051                 free_variable_lifetimes(state, &state->bb, rstate->blocks);
20052         }
20053         rstate->defs = 0;
20054         rstate->ranges = 0;
20055         rstate->lrd = 0;
20056         rstate->lr = 0;
20057         rstate->blocks = 0;
20058 }
20059
20060 static void verify_consistency(struct compile_state *state);
20061 static void allocate_registers(struct compile_state *state)
20062 {
20063         struct reg_state rstate;
20064         int colored;
20065
20066         /* Clear out the reg_state */
20067         memset(&rstate, 0, sizeof(rstate));
20068         rstate.max_passes = state->compiler->max_allocation_passes;
20069
20070         do {
20071                 struct live_range **point, **next;
20072                 int tangles;
20073                 int coalesced;
20074
20075                 if (state->compiler->debug & DEBUG_RANGE_CONFLICTS) {
20076                         FILE *fp = state->errout;
20077                         fprintf(fp, "pass: %d\n", rstate.passes);
20078                         fflush(fp);
20079                 }
20080
20081                 /* Restore ids */
20082                 ids_from_rstate(state, &rstate);
20083
20084                 /* Cleanup the temporary data structures */
20085                 cleanup_rstate(state, &rstate);
20086
20087                 /* Compute the variable lifetimes */
20088                 rstate.blocks = compute_variable_lifetimes(state, &state->bb);
20089
20090                 /* Fix invalid mandatory live range coalesce conflicts */
20091                 correct_coalesce_conflicts(state, rstate.blocks);
20092
20093                 /* Fix two simultaneous uses of the same register.
20094                  * In a few pathlogical cases a partial untangle moves
20095                  * the tangle to a part of the graph we won't revisit.
20096                  * So we keep looping until we have no more tangle fixes
20097                  * to apply.
20098                  */
20099                 do {
20100                         tangles = correct_tangles(state, rstate.blocks);
20101                 } while(tangles);
20102
20103
20104                 print_blocks(state, "resolve_tangles", state->dbgout);
20105                 verify_consistency(state);
20106
20107                 /* Allocate and initialize the live ranges */
20108                 initialize_live_ranges(state, &rstate);
20109
20110                 /* Note currently doing coalescing in a loop appears to
20111                  * buys me nothing.  The code is left this way in case
20112                  * there is some value in it.  Or if a future bugfix
20113                  * yields some benefit.
20114                  */
20115                 do {
20116                         if (state->compiler->debug & DEBUG_COALESCING) {
20117                                 fprintf(state->errout, "coalescing\n");
20118                         }
20119
20120                         /* Remove any previous live edge calculations */
20121                         cleanup_live_edges(&rstate);
20122
20123                         /* Compute the interference graph */
20124                         walk_variable_lifetimes(
20125                                 state, &state->bb, rstate.blocks,
20126                                 graph_ins, &rstate);
20127
20128                         /* Display the interference graph if desired */
20129                         if (state->compiler->debug & DEBUG_INTERFERENCE) {
20130                                 print_interference_blocks(state, &rstate, state->dbgout, 1);
20131                                 fprintf(state->dbgout, "\nlive variables by instruction\n");
20132                                 walk_variable_lifetimes(
20133                                         state, &state->bb, rstate.blocks,
20134                                         print_interference_ins, &rstate);
20135                         }
20136
20137                         coalesced = coalesce_live_ranges(state, &rstate);
20138
20139                         if (state->compiler->debug & DEBUG_COALESCING) {
20140                                 fprintf(state->errout, "coalesced: %d\n", coalesced);
20141                         }
20142                 } while(coalesced);
20143
20144 #if DEBUG_CONSISTENCY > 1
20145 # if 0
20146                 fprintf(state->errout, "verify_graph_ins...\n");
20147 # endif
20148                 /* Verify the interference graph */
20149                 walk_variable_lifetimes(
20150                         state, &state->bb, rstate.blocks,
20151                         verify_graph_ins, &rstate);
20152 # if 0
20153                 fprintf(state->errout, "verify_graph_ins done\n");
20154 #endif
20155 #endif
20156
20157                 /* Build the groups low and high.  But with the nodes
20158                  * first sorted by degree order.
20159                  */
20160                 rstate.low_tail  = &rstate.low;
20161                 rstate.high_tail = &rstate.high;
20162                 rstate.high = merge_sort_lr(&rstate.lr[1], &rstate.lr[rstate.ranges]);
20163                 if (rstate.high) {
20164                         rstate.high->group_prev = &rstate.high;
20165                 }
20166                 for(point = &rstate.high; *point; point = &(*point)->group_next)
20167                         ;
20168                 rstate.high_tail = point;
20169                 /* Walk through the high list and move everything that needs
20170                  * to be onto low.
20171                  */
20172                 for(point = &rstate.high; *point; point = next) {
20173                         struct live_range *range;
20174                         next = &(*point)->group_next;
20175                         range = *point;
20176
20177                         /* If it has a low degree or it already has a color
20178                          * place the node in low.
20179                          */
20180                         if ((range->degree < regc_max_size(state, range->classes)) ||
20181                                 (range->color != REG_UNSET)) {
20182                                 cgdebug_printf(state, "Lo: %5d degree %5d%s\n",
20183                                         range - rstate.lr, range->degree,
20184                                         (range->color != REG_UNSET) ? " (colored)": "");
20185                                 *range->group_prev = range->group_next;
20186                                 if (range->group_next) {
20187                                         range->group_next->group_prev = range->group_prev;
20188                                 }
20189                                 if (&range->group_next == rstate.high_tail) {
20190                                         rstate.high_tail = range->group_prev;
20191                                 }
20192                                 range->group_prev  = rstate.low_tail;
20193                                 range->group_next  = 0;
20194                                 *rstate.low_tail   = range;
20195                                 rstate.low_tail    = &range->group_next;
20196                                 next = point;
20197                         }
20198                         else {
20199                                 cgdebug_printf(state, "hi: %5d degree %5d%s\n",
20200                                         range - rstate.lr, range->degree,
20201                                         (range->color != REG_UNSET) ? " (colored)": "");
20202                         }
20203                 }
20204                 /* Color the live_ranges */
20205                 colored = color_graph(state, &rstate);
20206                 rstate.passes++;
20207         } while (!colored);
20208
20209         /* Verify the graph was properly colored */
20210         verify_colors(state, &rstate);
20211
20212         /* Move the colors from the graph to the triples */
20213         color_triples(state, &rstate);
20214
20215         /* Cleanup the temporary data structures */
20216         cleanup_rstate(state, &rstate);
20217
20218         /* Display the new graph */
20219         print_blocks(state, __func__, state->dbgout);
20220 }
20221
20222 /* Sparce Conditional Constant Propogation
20223  * =========================================
20224  */
20225 struct ssa_edge;
20226 struct flow_block;
20227 struct lattice_node {
20228         unsigned old_id;
20229         struct triple *def;
20230         struct ssa_edge *out;
20231         struct flow_block *fblock;
20232         struct triple *val;
20233         /* lattice high   val == def
20234          * lattice const  is_const(val)
20235          * lattice low    other
20236          */
20237 };
20238 struct ssa_edge {
20239         struct lattice_node *src;
20240         struct lattice_node *dst;
20241         struct ssa_edge *work_next;
20242         struct ssa_edge *work_prev;
20243         struct ssa_edge *out_next;
20244 };
20245 struct flow_edge {
20246         struct flow_block *src;
20247         struct flow_block *dst;
20248         struct flow_edge *work_next;
20249         struct flow_edge *work_prev;
20250         struct flow_edge *in_next;
20251         struct flow_edge *out_next;
20252         int executable;
20253 };
20254 #define MAX_FLOW_BLOCK_EDGES 3
20255 struct flow_block {
20256         struct block *block;
20257         struct flow_edge *in;
20258         struct flow_edge *out;
20259         struct flow_edge *edges;
20260 };
20261
20262 struct scc_state {
20263         int ins_count;
20264         struct lattice_node *lattice;
20265         struct ssa_edge     *ssa_edges;
20266         struct flow_block   *flow_blocks;
20267         struct flow_edge    *flow_work_list;
20268         struct ssa_edge     *ssa_work_list;
20269 };
20270
20271
20272 static int is_scc_const(struct compile_state *state, struct triple *ins)
20273 {
20274         return ins && (triple_is_ubranch(state, ins) || is_const(ins));
20275 }
20276
20277 static int is_lattice_hi(struct compile_state *state, struct lattice_node *lnode)
20278 {
20279         return !is_scc_const(state, lnode->val) && (lnode->val == lnode->def);
20280 }
20281
20282 static int is_lattice_const(struct compile_state *state, struct lattice_node *lnode)
20283 {
20284         return is_scc_const(state, lnode->val);
20285 }
20286
20287 static int is_lattice_lo(struct compile_state *state, struct lattice_node *lnode)
20288 {
20289         return (lnode->val != lnode->def) && !is_scc_const(state, lnode->val);
20290 }
20291
20292 static void scc_add_fedge(struct compile_state *state, struct scc_state *scc,
20293         struct flow_edge *fedge)
20294 {
20295         if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20296                 fprintf(state->errout, "adding fedge: %p (%4d -> %5d)\n",
20297                         fedge,
20298                         fedge->src->block?fedge->src->block->last->id: 0,
20299                         fedge->dst->block?fedge->dst->block->first->id: 0);
20300         }
20301         if ((fedge == scc->flow_work_list) ||
20302                 (fedge->work_next != fedge) ||
20303                 (fedge->work_prev != fedge)) {
20304
20305                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20306                         fprintf(state->errout, "dupped fedge: %p\n",
20307                                 fedge);
20308                 }
20309                 return;
20310         }
20311         if (!scc->flow_work_list) {
20312                 scc->flow_work_list = fedge;
20313                 fedge->work_next = fedge->work_prev = fedge;
20314         }
20315         else {
20316                 struct flow_edge *ftail;
20317                 ftail = scc->flow_work_list->work_prev;
20318                 fedge->work_next = ftail->work_next;
20319                 fedge->work_prev = ftail;
20320                 fedge->work_next->work_prev = fedge;
20321                 fedge->work_prev->work_next = fedge;
20322         }
20323 }
20324
20325 static struct flow_edge *scc_next_fedge(
20326         struct compile_state *state, struct scc_state *scc)
20327 {
20328         struct flow_edge *fedge;
20329         fedge = scc->flow_work_list;
20330         if (fedge) {
20331                 fedge->work_next->work_prev = fedge->work_prev;
20332                 fedge->work_prev->work_next = fedge->work_next;
20333                 if (fedge->work_next != fedge) {
20334                         scc->flow_work_list = fedge->work_next;
20335                 } else {
20336                         scc->flow_work_list = 0;
20337                 }
20338                 fedge->work_next = fedge->work_prev = fedge;
20339         }
20340         return fedge;
20341 }
20342
20343 static void scc_add_sedge(struct compile_state *state, struct scc_state *scc,
20344         struct ssa_edge *sedge)
20345 {
20346         if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20347                 fprintf(state->errout, "adding sedge: %5ld (%4d -> %5d)\n",
20348                         (long)(sedge - scc->ssa_edges),
20349                         sedge->src->def->id,
20350                         sedge->dst->def->id);
20351         }
20352         if ((sedge == scc->ssa_work_list) ||
20353                 (sedge->work_next != sedge) ||
20354                 (sedge->work_prev != sedge)) {
20355
20356                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM2) {
20357                         fprintf(state->errout, "dupped sedge: %5ld\n",
20358                                 (long)(sedge - scc->ssa_edges));
20359                 }
20360                 return;
20361         }
20362         if (!scc->ssa_work_list) {
20363                 scc->ssa_work_list = sedge;
20364                 sedge->work_next = sedge->work_prev = sedge;
20365         }
20366         else {
20367                 struct ssa_edge *stail;
20368                 stail = scc->ssa_work_list->work_prev;
20369                 sedge->work_next = stail->work_next;
20370                 sedge->work_prev = stail;
20371                 sedge->work_next->work_prev = sedge;
20372                 sedge->work_prev->work_next = sedge;
20373         }
20374 }
20375
20376 static struct ssa_edge *scc_next_sedge(
20377         struct compile_state *state, struct scc_state *scc)
20378 {
20379         struct ssa_edge *sedge;
20380         sedge = scc->ssa_work_list;
20381         if (sedge) {
20382                 sedge->work_next->work_prev = sedge->work_prev;
20383                 sedge->work_prev->work_next = sedge->work_next;
20384                 if (sedge->work_next != sedge) {
20385                         scc->ssa_work_list = sedge->work_next;
20386                 } else {
20387                         scc->ssa_work_list = 0;
20388                 }
20389                 sedge->work_next = sedge->work_prev = sedge;
20390         }
20391         return sedge;
20392 }
20393
20394 static void initialize_scc_state(
20395         struct compile_state *state, struct scc_state *scc)
20396 {
20397         int ins_count, ssa_edge_count;
20398         int ins_index, ssa_edge_index, fblock_index;
20399         struct triple *first, *ins;
20400         struct block *block;
20401         struct flow_block *fblock;
20402
20403         memset(scc, 0, sizeof(*scc));
20404
20405         /* Inialize pass zero find out how much memory we need */
20406         first = state->first;
20407         ins = first;
20408         ins_count = ssa_edge_count = 0;
20409         do {
20410                 struct triple_set *edge;
20411                 ins_count += 1;
20412                 for(edge = ins->use; edge; edge = edge->next) {
20413                         ssa_edge_count++;
20414                 }
20415                 ins = ins->next;
20416         } while(ins != first);
20417         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20418                 fprintf(state->errout, "ins_count: %d ssa_edge_count: %d vertex_count: %d\n",
20419                         ins_count, ssa_edge_count, state->bb.last_vertex);
20420         }
20421         scc->ins_count   = ins_count;
20422         scc->lattice     =
20423                 xcmalloc(sizeof(*scc->lattice)*(ins_count + 1), "lattice");
20424         scc->ssa_edges   =
20425                 xcmalloc(sizeof(*scc->ssa_edges)*(ssa_edge_count + 1), "ssa_edges");
20426         scc->flow_blocks =
20427                 xcmalloc(sizeof(*scc->flow_blocks)*(state->bb.last_vertex + 1),
20428                         "flow_blocks");
20429
20430         /* Initialize pass one collect up the nodes */
20431         fblock = 0;
20432         block = 0;
20433         ins_index = ssa_edge_index = fblock_index = 0;
20434         ins = first;
20435         do {
20436                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20437                         block = ins->u.block;
20438                         if (!block) {
20439                                 internal_error(state, ins, "label without block");
20440                         }
20441                         fblock_index += 1;
20442                         block->vertex = fblock_index;
20443                         fblock = &scc->flow_blocks[fblock_index];
20444                         fblock->block = block;
20445                         fblock->edges = xcmalloc(sizeof(*fblock->edges)*block->edge_count,
20446                                 "flow_edges");
20447                 }
20448                 {
20449                         struct lattice_node *lnode;
20450                         ins_index += 1;
20451                         lnode = &scc->lattice[ins_index];
20452                         lnode->def = ins;
20453                         lnode->out = 0;
20454                         lnode->fblock = fblock;
20455                         lnode->val = ins; /* LATTICE HIGH */
20456                         if (lnode->val->op == OP_UNKNOWNVAL) {
20457                                 lnode->val = 0; /* LATTICE LOW by definition */
20458                         }
20459                         lnode->old_id = ins->id;
20460                         ins->id = ins_index;
20461                 }
20462                 ins = ins->next;
20463         } while(ins != first);
20464         /* Initialize pass two collect up the edges */
20465         block = 0;
20466         fblock = 0;
20467         ins = first;
20468         do {
20469                 {
20470                         struct triple_set *edge;
20471                         struct ssa_edge **stail;
20472                         struct lattice_node *lnode;
20473                         lnode = &scc->lattice[ins->id];
20474                         lnode->out = 0;
20475                         stail = &lnode->out;
20476                         for(edge = ins->use; edge; edge = edge->next) {
20477                                 struct ssa_edge *sedge;
20478                                 ssa_edge_index += 1;
20479                                 sedge = &scc->ssa_edges[ssa_edge_index];
20480                                 *stail = sedge;
20481                                 stail = &sedge->out_next;
20482                                 sedge->src = lnode;
20483                                 sedge->dst = &scc->lattice[edge->member->id];
20484                                 sedge->work_next = sedge->work_prev = sedge;
20485                                 sedge->out_next = 0;
20486                         }
20487                 }
20488                 if ((ins->op == OP_LABEL) && (block != ins->u.block)) {
20489                         struct flow_edge *fedge, **ftail;
20490                         struct block_set *bedge;
20491                         block = ins->u.block;
20492                         fblock = &scc->flow_blocks[block->vertex];
20493                         fblock->in = 0;
20494                         fblock->out = 0;
20495                         ftail = &fblock->out;
20496
20497                         fedge = fblock->edges;
20498                         bedge = block->edges;
20499                         for(; bedge; bedge = bedge->next, fedge++) {
20500                                 fedge->dst = &scc->flow_blocks[bedge->member->vertex];
20501                                 if (fedge->dst->block != bedge->member) {
20502                                         internal_error(state, 0, "block mismatch");
20503                                 }
20504                                 *ftail = fedge;
20505                                 ftail = &fedge->out_next;
20506                                 fedge->out_next = 0;
20507                         }
20508                         for(fedge = fblock->out; fedge; fedge = fedge->out_next) {
20509                                 fedge->src = fblock;
20510                                 fedge->work_next = fedge->work_prev = fedge;
20511                                 fedge->executable = 0;
20512                         }
20513                 }
20514                 ins = ins->next;
20515         } while (ins != first);
20516         block = 0;
20517         fblock = 0;
20518         ins = first;
20519         do {
20520                 if ((ins->op  == OP_LABEL) && (block != ins->u.block)) {
20521                         struct flow_edge **ftail;
20522                         struct block_set *bedge;
20523                         block = ins->u.block;
20524                         fblock = &scc->flow_blocks[block->vertex];
20525                         ftail = &fblock->in;
20526                         for(bedge = block->use; bedge; bedge = bedge->next) {
20527                                 struct block *src_block;
20528                                 struct flow_block *sfblock;
20529                                 struct flow_edge *sfedge;
20530                                 src_block = bedge->member;
20531                                 sfblock = &scc->flow_blocks[src_block->vertex];
20532                                 for(sfedge = sfblock->out; sfedge; sfedge = sfedge->out_next) {
20533                                         if (sfedge->dst == fblock) {
20534                                                 break;
20535                                         }
20536                                 }
20537                                 if (!sfedge) {
20538                                         internal_error(state, 0, "edge mismatch");
20539                                 }
20540                                 *ftail = sfedge;
20541                                 ftail = &sfedge->in_next;
20542                                 sfedge->in_next = 0;
20543                         }
20544                 }
20545                 ins = ins->next;
20546         } while(ins != first);
20547         /* Setup a dummy block 0 as a node above the start node */
20548         {
20549                 struct flow_block *fblock, *dst;
20550                 struct flow_edge *fedge;
20551                 fblock = &scc->flow_blocks[0];
20552                 fblock->block = 0;
20553                 fblock->edges = xcmalloc(sizeof(*fblock->edges)*1, "flow_edges");
20554                 fblock->in = 0;
20555                 fblock->out = fblock->edges;
20556                 dst = &scc->flow_blocks[state->bb.first_block->vertex];
20557                 fedge = fblock->edges;
20558                 fedge->src        = fblock;
20559                 fedge->dst        = dst;
20560                 fedge->work_next  = fedge;
20561                 fedge->work_prev  = fedge;
20562                 fedge->in_next    = fedge->dst->in;
20563                 fedge->out_next   = 0;
20564                 fedge->executable = 0;
20565                 fedge->dst->in = fedge;
20566
20567                 /* Initialize the work lists */
20568                 scc->flow_work_list = 0;
20569                 scc->ssa_work_list  = 0;
20570                 scc_add_fedge(state, scc, fedge);
20571         }
20572         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20573                 fprintf(state->errout, "ins_index: %d ssa_edge_index: %d fblock_index: %d\n",
20574                         ins_index, ssa_edge_index, fblock_index);
20575         }
20576 }
20577
20578
20579 static void free_scc_state(
20580         struct compile_state *state, struct scc_state *scc)
20581 {
20582         int i;
20583         for(i = 0; i < state->bb.last_vertex + 1; i++) {
20584                 struct flow_block *fblock;
20585                 fblock = &scc->flow_blocks[i];
20586                 if (fblock->edges) {
20587                         xfree(fblock->edges);
20588                         fblock->edges = 0;
20589                 }
20590         }
20591         xfree(scc->flow_blocks);
20592         xfree(scc->ssa_edges);
20593         xfree(scc->lattice);
20594
20595 }
20596
20597 static struct lattice_node *triple_to_lattice(
20598         struct compile_state *state, struct scc_state *scc, struct triple *ins)
20599 {
20600         if (ins->id <= 0) {
20601                 internal_error(state, ins, "bad id");
20602         }
20603         return &scc->lattice[ins->id];
20604 }
20605
20606 static struct triple *preserve_lval(
20607         struct compile_state *state, struct lattice_node *lnode)
20608 {
20609         struct triple *old;
20610         /* Preserve the original value */
20611         if (lnode->val) {
20612                 old = dup_triple(state, lnode->val);
20613                 if (lnode->val != lnode->def) {
20614                         xfree(lnode->val);
20615                 }
20616                 lnode->val = 0;
20617         } else {
20618                 old = 0;
20619         }
20620         return old;
20621 }
20622
20623 static int lval_changed(struct compile_state *state,
20624         struct triple *old, struct lattice_node *lnode)
20625 {
20626         int changed;
20627         /* See if the lattice value has changed */
20628         changed = 1;
20629         if (!old && !lnode->val) {
20630                 changed = 0;
20631         }
20632         if (changed &&
20633                 lnode->val && old &&
20634                 (memcmp(lnode->val->param, old->param,
20635                         TRIPLE_SIZE(lnode->val) * sizeof(lnode->val->param[0])) == 0) &&
20636                 (memcmp(&lnode->val->u, &old->u, sizeof(old->u)) == 0)) {
20637                 changed = 0;
20638         }
20639         if (old) {
20640                 xfree(old);
20641         }
20642         return changed;
20643
20644 }
20645
20646 static void scc_debug_lnode(
20647         struct compile_state *state, struct scc_state *scc,
20648         struct lattice_node *lnode, int changed)
20649 {
20650         if ((state->compiler->debug & DEBUG_SCC_TRANSFORM2) && lnode->val) {
20651                 display_triple_changes(state->errout, lnode->val, lnode->def);
20652         }
20653         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20654                 FILE *fp = state->errout;
20655                 struct triple *val, **expr;
20656                 val = lnode->val? lnode->val : lnode->def;
20657                 fprintf(fp, "%p %s %3d %10s (",
20658                         lnode->def,
20659                         ((lnode->def->op == OP_PHI)? "phi: ": "expr:"),
20660                         lnode->def->id,
20661                         tops(lnode->def->op));
20662                 expr = triple_rhs(state, lnode->def, 0);
20663                 for(;expr;expr = triple_rhs(state, lnode->def, expr)) {
20664                         if (*expr) {
20665                                 fprintf(fp, " %d", (*expr)->id);
20666                         }
20667                 }
20668                 if (val->op == OP_INTCONST) {
20669                         fprintf(fp, " <0x%08lx>", (unsigned long)(val->u.cval));
20670                 }
20671                 fprintf(fp, " ) -> %s %s\n",
20672                         (is_lattice_hi(state, lnode)? "hi":
20673                                 is_lattice_const(state, lnode)? "const" : "lo"),
20674                         changed? "changed" : ""
20675                         );
20676         }
20677 }
20678
20679 static int compute_lnode_val(struct compile_state *state, struct scc_state *scc,
20680         struct lattice_node *lnode)
20681 {
20682         int changed;
20683         struct triple *old, *scratch;
20684         struct triple **dexpr, **vexpr;
20685         int count, i;
20686
20687         /* Store the original value */
20688         old = preserve_lval(state, lnode);
20689
20690         /* Reinitialize the value */
20691         lnode->val = scratch = dup_triple(state, lnode->def);
20692         scratch->id = lnode->old_id;
20693         scratch->next     = scratch;
20694         scratch->prev     = scratch;
20695         scratch->use      = 0;
20696
20697         count = TRIPLE_SIZE(scratch);
20698         for(i = 0; i < count; i++) {
20699                 dexpr = &lnode->def->param[i];
20700                 vexpr = &scratch->param[i];
20701                 *vexpr = *dexpr;
20702                 if (((i < TRIPLE_MISC_OFF(scratch)) ||
20703                         (i >= TRIPLE_TARG_OFF(scratch))) &&
20704                         *dexpr) {
20705                         struct lattice_node *tmp;
20706                         tmp = triple_to_lattice(state, scc, *dexpr);
20707                         *vexpr = (tmp->val)? tmp->val : tmp->def;
20708                 }
20709         }
20710         if (triple_is_branch(state, scratch)) {
20711                 scratch->next = lnode->def->next;
20712         }
20713         /* Recompute the value */
20714 #if DEBUG_ROMCC_WARNINGS
20715 #warning "FIXME see if simplify does anything bad"
20716 #endif
20717         /* So far it looks like only the strength reduction
20718          * optimization are things I need to worry about.
20719          */
20720         simplify(state, scratch);
20721         /* Cleanup my value */
20722         if (scratch->use) {
20723                 internal_error(state, lnode->def, "scratch used?");
20724         }
20725         if ((scratch->prev != scratch) ||
20726                 ((scratch->next != scratch) &&
20727                         (!triple_is_branch(state, lnode->def) ||
20728                                 (scratch->next != lnode->def->next)))) {
20729                 internal_error(state, lnode->def, "scratch in list?");
20730         }
20731         /* undo any uses... */
20732         count = TRIPLE_SIZE(scratch);
20733         for(i = 0; i < count; i++) {
20734                 vexpr = &scratch->param[i];
20735                 if (*vexpr) {
20736                         unuse_triple(*vexpr, scratch);
20737                 }
20738         }
20739         if (lnode->val->op == OP_UNKNOWNVAL) {
20740                 lnode->val = 0; /* Lattice low by definition */
20741         }
20742         /* Find the case when I am lattice high */
20743         if (lnode->val &&
20744                 (lnode->val->op == lnode->def->op) &&
20745                 (memcmp(lnode->val->param, lnode->def->param,
20746                         count * sizeof(lnode->val->param[0])) == 0) &&
20747                 (memcmp(&lnode->val->u, &lnode->def->u, sizeof(lnode->def->u)) == 0)) {
20748                 lnode->val = lnode->def;
20749         }
20750         /* Only allow lattice high when all of my inputs
20751          * are also lattice high.  Occassionally I can
20752          * have constants with a lattice low input, so
20753          * I do not need to check that case.
20754          */
20755         if (is_lattice_hi(state, lnode)) {
20756                 struct lattice_node *tmp;
20757                 int rhs;
20758                 rhs = lnode->val->rhs;
20759                 for(i = 0; i < rhs; i++) {
20760                         tmp = triple_to_lattice(state, scc, RHS(lnode->val, i));
20761                         if (!is_lattice_hi(state, tmp)) {
20762                                 lnode->val = 0;
20763                                 break;
20764                         }
20765                 }
20766         }
20767         /* Find the cases that are always lattice lo */
20768         if (lnode->val &&
20769                 triple_is_def(state, lnode->val) &&
20770                 !triple_is_pure(state, lnode->val, lnode->old_id)) {
20771                 lnode->val = 0;
20772         }
20773         /* See if the lattice value has changed */
20774         changed = lval_changed(state, old, lnode);
20775         /* See if this value should not change */
20776         if ((lnode->val != lnode->def) &&
20777                 ((      !triple_is_def(state, lnode->def)  &&
20778                         !triple_is_cbranch(state, lnode->def)) ||
20779                         (lnode->def->op == OP_PIECE))) {
20780 #if DEBUG_ROMCC_WARNINGS
20781 #warning "FIXME constant propogate through expressions with multiple left hand sides"
20782 #endif
20783                 if (changed) {
20784                         internal_warning(state, lnode->def, "non def changes value?");
20785                 }
20786                 lnode->val = 0;
20787         }
20788
20789         /* See if we need to free the scratch value */
20790         if (lnode->val != scratch) {
20791                 xfree(scratch);
20792         }
20793
20794         return changed;
20795 }
20796
20797
20798 static void scc_visit_cbranch(struct compile_state *state, struct scc_state *scc,
20799         struct lattice_node *lnode)
20800 {
20801         struct lattice_node *cond;
20802         struct flow_edge *left, *right;
20803         int changed;
20804
20805         /* Update the branch value */
20806         changed = compute_lnode_val(state, scc, lnode);
20807         scc_debug_lnode(state, scc, lnode, changed);
20808
20809         /* This only applies to conditional branches */
20810         if (!triple_is_cbranch(state, lnode->def)) {
20811                 internal_error(state, lnode->def, "not a conditional branch");
20812         }
20813
20814         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20815                 struct flow_edge *fedge;
20816                 FILE *fp = state->errout;
20817                 fprintf(fp, "%s: %d (",
20818                         tops(lnode->def->op),
20819                         lnode->def->id);
20820
20821                 for(fedge = lnode->fblock->out; fedge; fedge = fedge->out_next) {
20822                         fprintf(fp, " %d", fedge->dst->block->vertex);
20823                 }
20824                 fprintf(fp, " )");
20825                 if (lnode->def->rhs > 0) {
20826                         fprintf(fp, " <- %d",
20827                                 RHS(lnode->def, 0)->id);
20828                 }
20829                 fprintf(fp, "\n");
20830         }
20831         cond = triple_to_lattice(state, scc, RHS(lnode->def,0));
20832         for(left = cond->fblock->out; left; left = left->out_next) {
20833                 if (left->dst->block->first == lnode->def->next) {
20834                         break;
20835                 }
20836         }
20837         if (!left) {
20838                 internal_error(state, lnode->def, "Cannot find left branch edge");
20839         }
20840         for(right = cond->fblock->out; right; right = right->out_next) {
20841                 if (right->dst->block->first == TARG(lnode->def, 0)) {
20842                         break;
20843                 }
20844         }
20845         if (!right) {
20846                 internal_error(state, lnode->def, "Cannot find right branch edge");
20847         }
20848         /* I should only come here if the controlling expressions value
20849          * has changed, which means it must be either a constant or lo.
20850          */
20851         if (is_lattice_hi(state, cond)) {
20852                 internal_error(state, cond->def, "condition high?");
20853                 return;
20854         }
20855         if (is_lattice_lo(state, cond)) {
20856                 scc_add_fedge(state, scc, left);
20857                 scc_add_fedge(state, scc, right);
20858         }
20859         else if (cond->val->u.cval) {
20860                 scc_add_fedge(state, scc, right);
20861         } else {
20862                 scc_add_fedge(state, scc, left);
20863         }
20864
20865 }
20866
20867
20868 static void scc_add_sedge_dst(struct compile_state *state,
20869         struct scc_state *scc, struct ssa_edge *sedge)
20870 {
20871         if (triple_is_cbranch(state, sedge->dst->def)) {
20872                 scc_visit_cbranch(state, scc, sedge->dst);
20873         }
20874         else if (triple_is_def(state, sedge->dst->def)) {
20875                 scc_add_sedge(state, scc, sedge);
20876         }
20877 }
20878
20879 static void scc_visit_phi(struct compile_state *state, struct scc_state *scc,
20880         struct lattice_node *lnode)
20881 {
20882         struct lattice_node *tmp;
20883         struct triple **slot, *old;
20884         struct flow_edge *fedge;
20885         int changed;
20886         int index;
20887         if (lnode->def->op != OP_PHI) {
20888                 internal_error(state, lnode->def, "not phi");
20889         }
20890         /* Store the original value */
20891         old = preserve_lval(state, lnode);
20892
20893         /* default to lattice high */
20894         lnode->val = lnode->def;
20895         slot = &RHS(lnode->def, 0);
20896         index = 0;
20897         for(fedge = lnode->fblock->in; fedge; index++, fedge = fedge->in_next) {
20898                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20899                         fprintf(state->errout, "Examining edge: %d vertex: %d executable: %d\n",
20900                                 index,
20901                                 fedge->dst->block->vertex,
20902                                 fedge->executable
20903                                 );
20904                 }
20905                 if (!fedge->executable) {
20906                         continue;
20907                 }
20908                 if (!slot[index]) {
20909                         internal_error(state, lnode->def, "no phi value");
20910                 }
20911                 tmp = triple_to_lattice(state, scc, slot[index]);
20912                 /* meet(X, lattice low) = lattice low */
20913                 if (is_lattice_lo(state, tmp)) {
20914                         lnode->val = 0;
20915                 }
20916                 /* meet(X, lattice high) = X */
20917                 else if (is_lattice_hi(state, tmp)) {
20918                         lnode->val = lnode->val;
20919                 }
20920                 /* meet(lattice high, X) = X */
20921                 else if (is_lattice_hi(state, lnode)) {
20922                         lnode->val = dup_triple(state, tmp->val);
20923                         /* Only change the type if necessary */
20924                         if (!is_subset_type(lnode->def->type, tmp->val->type)) {
20925                                 lnode->val->type = lnode->def->type;
20926                         }
20927                 }
20928                 /* meet(const, const) = const or lattice low */
20929                 else if (!constants_equal(state, lnode->val, tmp->val)) {
20930                         lnode->val = 0;
20931                 }
20932
20933                 /* meet(lattice low, X) = lattice low */
20934                 if (is_lattice_lo(state, lnode)) {
20935                         lnode->val = 0;
20936                         break;
20937                 }
20938         }
20939         changed = lval_changed(state, old, lnode);
20940         scc_debug_lnode(state, scc, lnode, changed);
20941
20942         /* If the lattice value has changed update the work lists. */
20943         if (changed) {
20944                 struct ssa_edge *sedge;
20945                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20946                         scc_add_sedge_dst(state, scc, sedge);
20947                 }
20948         }
20949 }
20950
20951
20952 static void scc_visit_expr(struct compile_state *state, struct scc_state *scc,
20953         struct lattice_node *lnode)
20954 {
20955         int changed;
20956
20957         if (!triple_is_def(state, lnode->def)) {
20958                 internal_warning(state, lnode->def, "not visiting an expression?");
20959         }
20960         changed = compute_lnode_val(state, scc, lnode);
20961         scc_debug_lnode(state, scc, lnode, changed);
20962
20963         if (changed) {
20964                 struct ssa_edge *sedge;
20965                 for(sedge = lnode->out; sedge; sedge = sedge->out_next) {
20966                         scc_add_sedge_dst(state, scc, sedge);
20967                 }
20968         }
20969 }
20970
20971 static void scc_writeback_values(
20972         struct compile_state *state, struct scc_state *scc)
20973 {
20974         struct triple *first, *ins;
20975         first = state->first;
20976         ins = first;
20977         do {
20978                 struct lattice_node *lnode;
20979                 lnode = triple_to_lattice(state, scc, ins);
20980                 if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
20981                         if (is_lattice_hi(state, lnode) &&
20982                                 (lnode->val->op != OP_NOOP))
20983                         {
20984                                 struct flow_edge *fedge;
20985                                 int executable;
20986                                 executable = 0;
20987                                 for(fedge = lnode->fblock->in;
20988                                     !executable && fedge; fedge = fedge->in_next) {
20989                                         executable |= fedge->executable;
20990                                 }
20991                                 if (executable) {
20992                                         internal_warning(state, lnode->def,
20993                                                 "lattice node %d %s->%s still high?",
20994                                                 ins->id,
20995                                                 tops(lnode->def->op),
20996                                                 tops(lnode->val->op));
20997                                 }
20998                         }
20999                 }
21000
21001                 /* Restore id */
21002                 ins->id = lnode->old_id;
21003                 if (lnode->val && (lnode->val != ins)) {
21004                         /* See if it something I know how to write back */
21005                         switch(lnode->val->op) {
21006                         case OP_INTCONST:
21007                                 mkconst(state, ins, lnode->val->u.cval);
21008                                 break;
21009                         case OP_ADDRCONST:
21010                                 mkaddr_const(state, ins,
21011                                         MISC(lnode->val, 0), lnode->val->u.cval);
21012                                 break;
21013                         default:
21014                                 /* By default don't copy the changes,
21015                                  * recompute them in place instead.
21016                                  */
21017                                 simplify(state, ins);
21018                                 break;
21019                         }
21020                         if (is_const(lnode->val) &&
21021                                 !constants_equal(state, lnode->val, ins)) {
21022                                 internal_error(state, 0, "constants not equal");
21023                         }
21024                         /* Free the lattice nodes */
21025                         xfree(lnode->val);
21026                         lnode->val = 0;
21027                 }
21028                 ins = ins->next;
21029         } while(ins != first);
21030 }
21031
21032 static void scc_transform(struct compile_state *state)
21033 {
21034         struct scc_state scc;
21035         if (!(state->compiler->flags & COMPILER_SCC_TRANSFORM)) {
21036                 return;
21037         }
21038
21039         initialize_scc_state(state, &scc);
21040
21041         while(scc.flow_work_list || scc.ssa_work_list) {
21042                 struct flow_edge *fedge;
21043                 struct ssa_edge *sedge;
21044                 struct flow_edge *fptr;
21045                 while((fedge = scc_next_fedge(state, &scc))) {
21046                         struct block *block;
21047                         struct triple *ptr;
21048                         struct flow_block *fblock;
21049                         int reps;
21050                         int done;
21051                         if (fedge->executable) {
21052                                 continue;
21053                         }
21054                         if (!fedge->dst) {
21055                                 internal_error(state, 0, "fedge without dst");
21056                         }
21057                         if (!fedge->src) {
21058                                 internal_error(state, 0, "fedge without src");
21059                         }
21060                         fedge->executable = 1;
21061                         fblock = fedge->dst;
21062                         block = fblock->block;
21063                         reps = 0;
21064                         for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21065                                 if (fptr->executable) {
21066                                         reps++;
21067                                 }
21068                         }
21069
21070                         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21071                                 fprintf(state->errout, "vertex: %d reps: %d\n",
21072                                         block->vertex, reps);
21073                         }
21074
21075                         done = 0;
21076                         for(ptr = block->first; !done; ptr = ptr->next) {
21077                                 struct lattice_node *lnode;
21078                                 done = (ptr == block->last);
21079                                 lnode = &scc.lattice[ptr->id];
21080                                 if (ptr->op == OP_PHI) {
21081                                         scc_visit_phi(state, &scc, lnode);
21082                                 }
21083                                 else if ((reps == 1) && triple_is_def(state, ptr))
21084                                 {
21085                                         scc_visit_expr(state, &scc, lnode);
21086                                 }
21087                         }
21088                         /* Add unconditional branch edges */
21089                         if (!triple_is_cbranch(state, fblock->block->last)) {
21090                                 struct flow_edge *out;
21091                                 for(out = fblock->out; out; out = out->out_next) {
21092                                         scc_add_fedge(state, &scc, out);
21093                                 }
21094                         }
21095                 }
21096                 while((sedge = scc_next_sedge(state, &scc))) {
21097                         struct lattice_node *lnode;
21098                         struct flow_block *fblock;
21099                         lnode = sedge->dst;
21100                         fblock = lnode->fblock;
21101
21102                         if (state->compiler->debug & DEBUG_SCC_TRANSFORM) {
21103                                 fprintf(state->errout, "sedge: %5ld (%5d -> %5d)\n",
21104                                         (unsigned long)sedge - (unsigned long)scc.ssa_edges,
21105                                         sedge->src->def->id,
21106                                         sedge->dst->def->id);
21107                         }
21108
21109                         if (lnode->def->op == OP_PHI) {
21110                                 scc_visit_phi(state, &scc, lnode);
21111                         }
21112                         else {
21113                                 for(fptr = fblock->in; fptr; fptr = fptr->in_next) {
21114                                         if (fptr->executable) {
21115                                                 break;
21116                                         }
21117                                 }
21118                                 if (fptr) {
21119                                         scc_visit_expr(state, &scc, lnode);
21120                                 }
21121                         }
21122                 }
21123         }
21124
21125         scc_writeback_values(state, &scc);
21126         free_scc_state(state, &scc);
21127         rebuild_ssa_form(state);
21128
21129         print_blocks(state, __func__, state->dbgout);
21130 }
21131
21132
21133 static void transform_to_arch_instructions(struct compile_state *state)
21134 {
21135         struct triple *ins, *first;
21136         first = state->first;
21137         ins = first;
21138         do {
21139                 ins = transform_to_arch_instruction(state, ins);
21140         } while(ins != first);
21141
21142         print_blocks(state, __func__, state->dbgout);
21143 }
21144
21145 #if DEBUG_CONSISTENCY
21146 static void verify_uses(struct compile_state *state)
21147 {
21148         struct triple *first, *ins;
21149         struct triple_set *set;
21150         first = state->first;
21151         ins = first;
21152         do {
21153                 struct triple **expr;
21154                 expr = triple_rhs(state, ins, 0);
21155                 for(; expr; expr = triple_rhs(state, ins, expr)) {
21156                         struct triple *rhs;
21157                         rhs = *expr;
21158                         for(set = rhs?rhs->use:0; set; set = set->next) {
21159                                 if (set->member == ins) {
21160                                         break;
21161                                 }
21162                         }
21163                         if (!set) {
21164                                 internal_error(state, ins, "rhs not used");
21165                         }
21166                 }
21167                 expr = triple_lhs(state, ins, 0);
21168                 for(; expr; expr = triple_lhs(state, ins, expr)) {
21169                         struct triple *lhs;
21170                         lhs = *expr;
21171                         for(set =  lhs?lhs->use:0; set; set = set->next) {
21172                                 if (set->member == ins) {
21173                                         break;
21174                                 }
21175                         }
21176                         if (!set) {
21177                                 internal_error(state, ins, "lhs not used");
21178                         }
21179                 }
21180                 expr = triple_misc(state, ins, 0);
21181                 if (ins->op != OP_PHI) {
21182                         for(; expr; expr = triple_targ(state, ins, expr)) {
21183                                 struct triple *misc;
21184                                 misc = *expr;
21185                                 for(set = misc?misc->use:0; set; set = set->next) {
21186                                         if (set->member == ins) {
21187                                                 break;
21188                                         }
21189                                 }
21190                                 if (!set) {
21191                                         internal_error(state, ins, "misc not used");
21192                                 }
21193                         }
21194                 }
21195                 if (!triple_is_ret(state, ins)) {
21196                         expr = triple_targ(state, ins, 0);
21197                         for(; expr; expr = triple_targ(state, ins, expr)) {
21198                                 struct triple *targ;
21199                                 targ = *expr;
21200                                 for(set = targ?targ->use:0; set; set = set->next) {
21201                                         if (set->member == ins) {
21202                                                 break;
21203                                         }
21204                                 }
21205                                 if (!set) {
21206                                         internal_error(state, ins, "targ not used");
21207                                 }
21208                         }
21209                 }
21210                 ins = ins->next;
21211         } while(ins != first);
21212
21213 }
21214 static void verify_blocks_present(struct compile_state *state)
21215 {
21216         struct triple *first, *ins;
21217         if (!state->bb.first_block) {
21218                 return;
21219         }
21220         first = state->first;
21221         ins = first;
21222         do {
21223                 valid_ins(state, ins);
21224                 if (triple_stores_block(state, ins)) {
21225                         if (!ins->u.block) {
21226                                 internal_error(state, ins,
21227                                         "%p not in a block?", ins);
21228                         }
21229                 }
21230                 ins = ins->next;
21231         } while(ins != first);
21232
21233
21234 }
21235
21236 static int edge_present(struct compile_state *state, struct block *block, struct triple *edge)
21237 {
21238         struct block_set *bedge;
21239         struct block *targ;
21240         targ = block_of_triple(state, edge);
21241         for(bedge = block->edges; bedge; bedge = bedge->next) {
21242                 if (bedge->member == targ) {
21243                         return 1;
21244                 }
21245         }
21246         return 0;
21247 }
21248
21249 static void verify_blocks(struct compile_state *state)
21250 {
21251         struct triple *ins;
21252         struct block *block;
21253         int blocks;
21254         block = state->bb.first_block;
21255         if (!block) {
21256                 return;
21257         }
21258         blocks = 0;
21259         do {
21260                 int users;
21261                 struct block_set *user, *edge;
21262                 blocks++;
21263                 for(ins = block->first; ins != block->last->next; ins = ins->next) {
21264                         if (triple_stores_block(state, ins) && (ins->u.block != block)) {
21265                                 internal_error(state, ins, "inconsitent block specified");
21266                         }
21267                         valid_ins(state, ins);
21268                 }
21269                 users = 0;
21270                 for(user = block->use; user; user = user->next) {
21271                         users++;
21272                         if (!user->member->first) {
21273                                 internal_error(state, block->first, "user is empty");
21274                         }
21275                         if ((block == state->bb.last_block) &&
21276                                 (user->member == state->bb.first_block)) {
21277                                 continue;
21278                         }
21279                         for(edge = user->member->edges; edge; edge = edge->next) {
21280                                 if (edge->member == block) {
21281                                         break;
21282                                 }
21283                         }
21284                         if (!edge) {
21285                                 internal_error(state, user->member->first,
21286                                         "user does not use block");
21287                         }
21288                 }
21289                 if (triple_is_branch(state, block->last)) {
21290                         struct triple **expr;
21291                         expr = triple_edge_targ(state, block->last, 0);
21292                         for(;expr; expr = triple_edge_targ(state, block->last, expr)) {
21293                                 if (*expr && !edge_present(state, block, *expr)) {
21294                                         internal_error(state, block->last, "no edge to targ");
21295                                 }
21296                         }
21297                 }
21298                 if (!triple_is_ubranch(state, block->last) &&
21299                         (block != state->bb.last_block) &&
21300                         !edge_present(state, block, block->last->next)) {
21301                         internal_error(state, block->last, "no edge to block->last->next");
21302                 }
21303                 for(edge = block->edges; edge; edge = edge->next) {
21304                         for(user = edge->member->use; user; user = user->next) {
21305                                 if (user->member == block) {
21306                                         break;
21307                                 }
21308                         }
21309                         if (!user || user->member != block) {
21310                                 internal_error(state, block->first,
21311                                         "block does not use edge");
21312                         }
21313                         if (!edge->member->first) {
21314                                 internal_error(state, block->first, "edge block is empty");
21315                         }
21316                 }
21317                 if (block->users != users) {
21318                         internal_error(state, block->first,
21319                                 "computed users %d != stored users %d",
21320                                 users, block->users);
21321                 }
21322                 if (!triple_stores_block(state, block->last->next)) {
21323                         internal_error(state, block->last->next,
21324                                 "cannot find next block");
21325                 }
21326                 block = block->last->next->u.block;
21327                 if (!block) {
21328                         internal_error(state, block->last->next,
21329                                 "bad next block");
21330                 }
21331         } while(block != state->bb.first_block);
21332         if (blocks != state->bb.last_vertex) {
21333                 internal_error(state, 0, "computed blocks: %d != stored blocks %d",
21334                         blocks, state->bb.last_vertex);
21335         }
21336 }
21337
21338 static void verify_domination(struct compile_state *state)
21339 {
21340         struct triple *first, *ins;
21341         struct triple_set *set;
21342         if (!state->bb.first_block) {
21343                 return;
21344         }
21345
21346         first = state->first;
21347         ins = first;
21348         do {
21349                 for(set = ins->use; set; set = set->next) {
21350                         struct triple **slot;
21351                         struct triple *use_point;
21352                         int i, zrhs;
21353                         use_point = 0;
21354                         zrhs = set->member->rhs;
21355                         slot = &RHS(set->member, 0);
21356                         /* See if the use is on the right hand side */
21357                         for(i = 0; i < zrhs; i++) {
21358                                 if (slot[i] == ins) {
21359                                         break;
21360                                 }
21361                         }
21362                         if (i < zrhs) {
21363                                 use_point = set->member;
21364                                 if (set->member->op == OP_PHI) {
21365                                         struct block_set *bset;
21366                                         int edge;
21367                                         bset = set->member->u.block->use;
21368                                         for(edge = 0; bset && (edge < i); edge++) {
21369                                                 bset = bset->next;
21370                                         }
21371                                         if (!bset) {
21372                                                 internal_error(state, set->member,
21373                                                         "no edge for phi rhs %d", i);
21374                                         }
21375                                         use_point = bset->member->last;
21376                                 }
21377                         }
21378                         if (use_point &&
21379                                 !tdominates(state, ins, use_point)) {
21380                                 if (is_const(ins)) {
21381                                         internal_warning(state, ins,
21382                                         "non dominated rhs use point %p?", use_point);
21383                                 }
21384                                 else {
21385                                         internal_error(state, ins,
21386                                                 "non dominated rhs use point %p?", use_point);
21387                                 }
21388                         }
21389                 }
21390                 ins = ins->next;
21391         } while(ins != first);
21392 }
21393
21394 static void verify_rhs(struct compile_state *state)
21395 {
21396         struct triple *first, *ins;
21397         first = state->first;
21398         ins = first;
21399         do {
21400                 struct triple **slot;
21401                 int zrhs, i;
21402                 zrhs = ins->rhs;
21403                 slot = &RHS(ins, 0);
21404                 for(i = 0; i < zrhs; i++) {
21405                         if (slot[i] == 0) {
21406                                 internal_error(state, ins,
21407                                         "missing rhs %d on %s",
21408                                         i, tops(ins->op));
21409                         }
21410                         if ((ins->op != OP_PHI) && (slot[i] == ins)) {
21411                                 internal_error(state, ins,
21412                                         "ins == rhs[%d] on %s",
21413                                         i, tops(ins->op));
21414                         }
21415                 }
21416                 ins = ins->next;
21417         } while(ins != first);
21418 }
21419
21420 static void verify_piece(struct compile_state *state)
21421 {
21422         struct triple *first, *ins;
21423         first = state->first;
21424         ins = first;
21425         do {
21426                 struct triple *ptr;
21427                 int lhs, i;
21428                 lhs = ins->lhs;
21429                 for(ptr = ins->next, i = 0; i < lhs; i++, ptr = ptr->next) {
21430                         if (ptr != LHS(ins, i)) {
21431                                 internal_error(state, ins, "malformed lhs on %s",
21432                                         tops(ins->op));
21433                         }
21434                         if (ptr->op != OP_PIECE) {
21435                                 internal_error(state, ins, "bad lhs op %s at %d on %s",
21436                                         tops(ptr->op), i, tops(ins->op));
21437                         }
21438                         if (ptr->u.cval != i) {
21439                                 internal_error(state, ins, "bad u.cval of %d %d expected",
21440                                         ptr->u.cval, i);
21441                         }
21442                 }
21443                 ins = ins->next;
21444         } while(ins != first);
21445 }
21446
21447 static void verify_ins_colors(struct compile_state *state)
21448 {
21449         struct triple *first, *ins;
21450
21451         first = state->first;
21452         ins = first;
21453         do {
21454                 ins = ins->next;
21455         } while(ins != first);
21456 }
21457
21458 static void verify_unknown(struct compile_state *state)
21459 {
21460         struct triple *first, *ins;
21461         if (    (unknown_triple.next != &unknown_triple) ||
21462                 (unknown_triple.prev != &unknown_triple) ||
21463 #if 0
21464                 (unknown_triple.use != 0) ||
21465 #endif
21466                 (unknown_triple.op != OP_UNKNOWNVAL) ||
21467                 (unknown_triple.lhs != 0) ||
21468                 (unknown_triple.rhs != 0) ||
21469                 (unknown_triple.misc != 0) ||
21470                 (unknown_triple.targ != 0) ||
21471                 (unknown_triple.template_id != 0) ||
21472                 (unknown_triple.id != -1) ||
21473                 (unknown_triple.type != &unknown_type) ||
21474                 (unknown_triple.occurance != &dummy_occurance) ||
21475                 (unknown_triple.param[0] != 0) ||
21476                 (unknown_triple.param[1] != 0)) {
21477                 internal_error(state, &unknown_triple, "unknown_triple corrupted!");
21478         }
21479         if (    (dummy_occurance.count != 2) ||
21480                 (strcmp(dummy_occurance.filename, __FILE__) != 0) ||
21481                 (strcmp(dummy_occurance.function, "") != 0) ||
21482                 (dummy_occurance.col != 0) ||
21483                 (dummy_occurance.parent != 0)) {
21484                 internal_error(state, &unknown_triple, "dummy_occurance corrupted!");
21485         }
21486         if (    (unknown_type.type != TYPE_UNKNOWN)) {
21487                 internal_error(state, &unknown_triple, "unknown_type corrupted!");
21488         }
21489         first = state->first;
21490         ins = first;
21491         do {
21492                 int params, i;
21493                 if (ins == &unknown_triple) {
21494                         internal_error(state, ins, "unknown triple in list");
21495                 }
21496                 params = TRIPLE_SIZE(ins);
21497                 for(i = 0; i < params; i++) {
21498                         if (ins->param[i] == &unknown_triple) {
21499                                 internal_error(state, ins, "unknown triple used!");
21500                         }
21501                 }
21502                 ins = ins->next;
21503         } while(ins != first);
21504 }
21505
21506 static void verify_types(struct compile_state *state)
21507 {
21508         struct triple *first, *ins;
21509         first = state->first;
21510         ins = first;
21511         do {
21512                 struct type *invalid;
21513                 invalid = invalid_type(state, ins->type);
21514                 if (invalid) {
21515                         FILE *fp = state->errout;
21516                         fprintf(fp, "type: ");
21517                         name_of(fp, ins->type);
21518                         fprintf(fp, "\n");
21519                         fprintf(fp, "invalid type: ");
21520                         name_of(fp, invalid);
21521                         fprintf(fp, "\n");
21522                         internal_error(state, ins, "invalid ins type");
21523                 }
21524         } while(ins != first);
21525 }
21526
21527 static void verify_copy(struct compile_state *state)
21528 {
21529         struct triple *first, *ins, *next;
21530         first = state->first;
21531         next = ins = first;
21532         do {
21533                 ins = next;
21534                 next = ins->next;
21535                 if (ins->op != OP_COPY) {
21536                         continue;
21537                 }
21538                 if (!equiv_types(ins->type, RHS(ins, 0)->type)) {
21539                         FILE *fp = state->errout;
21540                         fprintf(fp, "src type: ");
21541                         name_of(fp, RHS(ins, 0)->type);
21542                         fprintf(fp, "\n");
21543                         fprintf(fp, "dst type: ");
21544                         name_of(fp, ins->type);
21545                         fprintf(fp, "\n");
21546                         internal_error(state, ins, "type mismatch in copy");
21547                 }
21548         } while(next != first);
21549 }
21550
21551 static void verify_consistency(struct compile_state *state)
21552 {
21553         verify_unknown(state);
21554         verify_uses(state);
21555         verify_blocks_present(state);
21556         verify_blocks(state);
21557         verify_domination(state);
21558         verify_rhs(state);
21559         verify_piece(state);
21560         verify_ins_colors(state);
21561         verify_types(state);
21562         verify_copy(state);
21563         if (state->compiler->debug & DEBUG_VERIFICATION) {
21564                 fprintf(state->dbgout, "consistency verified\n");
21565         }
21566 }
21567 #else
21568 static void verify_consistency(struct compile_state *state) {}
21569 #endif /* DEBUG_CONSISTENCY */
21570
21571 static void optimize(struct compile_state *state)
21572 {
21573         /* Join all of the functions into one giant function */
21574         join_functions(state);
21575
21576         /* Dump what the instruction graph intially looks like */
21577         print_triples(state);
21578
21579         /* Replace structures with simpler data types */
21580         decompose_compound_types(state);
21581         print_triples(state);
21582
21583         verify_consistency(state);
21584         /* Analyze the intermediate code */
21585         state->bb.first = state->first;
21586         analyze_basic_blocks(state, &state->bb);
21587
21588         /* Transform the code to ssa form. */
21589         /*
21590          * The transformation to ssa form puts a phi function
21591          * on each of edge of a dominance frontier where that
21592          * phi function might be needed.  At -O2 if we don't
21593          * eleminate the excess phi functions we can get an
21594          * exponential code size growth.  So I kill the extra
21595          * phi functions early and I kill them often.
21596          */
21597         transform_to_ssa_form(state);
21598         verify_consistency(state);
21599
21600         /* Remove dead code */
21601         eliminate_inefectual_code(state);
21602         verify_consistency(state);
21603
21604         /* Do strength reduction and simple constant optimizations */
21605         simplify_all(state);
21606         verify_consistency(state);
21607         /* Propogate constants throughout the code */
21608         scc_transform(state);
21609         verify_consistency(state);
21610 #if DEBUG_ROMCC_WARNINGS
21611 #warning "WISHLIST implement single use constants (least possible register pressure)"
21612 #warning "WISHLIST implement induction variable elimination"
21613 #endif
21614         /* Select architecture instructions and an initial partial
21615          * coloring based on architecture constraints.
21616          */
21617         transform_to_arch_instructions(state);
21618         verify_consistency(state);
21619
21620         /* Remove dead code */
21621         eliminate_inefectual_code(state);
21622         verify_consistency(state);
21623
21624         /* Color all of the variables to see if they will fit in registers */
21625         insert_copies_to_phi(state);
21626         verify_consistency(state);
21627
21628         insert_mandatory_copies(state);
21629         verify_consistency(state);
21630
21631         allocate_registers(state);
21632         verify_consistency(state);
21633
21634         /* Remove the optimization information.
21635          * This is more to check for memory consistency than to free memory.
21636          */
21637         free_basic_blocks(state, &state->bb);
21638 }
21639
21640 static void print_op_asm(struct compile_state *state,
21641         struct triple *ins, FILE *fp)
21642 {
21643         struct asm_info *info;
21644         const char *ptr;
21645         unsigned lhs, rhs, i;
21646         info = ins->u.ainfo;
21647         lhs = ins->lhs;
21648         rhs = ins->rhs;
21649         /* Don't count the clobbers in lhs */
21650         for(i = 0; i < lhs; i++) {
21651                 if (LHS(ins, i)->type == &void_type) {
21652                         break;
21653                 }
21654         }
21655         lhs = i;
21656         fprintf(fp, "#ASM\n");
21657         fputc('\t', fp);
21658         for(ptr = info->str; *ptr; ptr++) {
21659                 char *next;
21660                 unsigned long param;
21661                 struct triple *piece;
21662                 if (*ptr != '%') {
21663                         fputc(*ptr, fp);
21664                         continue;
21665                 }
21666                 ptr++;
21667                 if (*ptr == '%') {
21668                         fputc('%', fp);
21669                         continue;
21670                 }
21671                 param = strtoul(ptr, &next, 10);
21672                 if (ptr == next) {
21673                         error(state, ins, "Invalid asm template");
21674                 }
21675                 if (param >= (lhs + rhs)) {
21676                         error(state, ins, "Invalid param %%%u in asm template",
21677                                 param);
21678                 }
21679                 piece = (param < lhs)? LHS(ins, param) : RHS(ins, param - lhs);
21680                 fprintf(fp, "%s",
21681                         arch_reg_str(ID_REG(piece->id)));
21682                 ptr = next -1;
21683         }
21684         fprintf(fp, "\n#NOT ASM\n");
21685 }
21686
21687
21688 /* Only use the low x86 byte registers.  This allows me
21689  * allocate the entire register when a byte register is used.
21690  */
21691 #define X86_4_8BIT_GPRS 1
21692
21693 /* x86 featrues */
21694 #define X86_MMX_REGS  (1<<0)
21695 #define X86_XMM_REGS  (1<<1)
21696 #define X86_NOOP_COPY (1<<2)
21697
21698 /* The x86 register classes */
21699 #define REGC_FLAGS       0
21700 #define REGC_GPR8        1
21701 #define REGC_GPR16       2
21702 #define REGC_GPR32       3
21703 #define REGC_DIVIDEND64  4
21704 #define REGC_DIVIDEND32  5
21705 #define REGC_MMX         6
21706 #define REGC_XMM         7
21707 #define REGC_GPR32_8     8
21708 #define REGC_GPR16_8     9
21709 #define REGC_GPR8_LO    10
21710 #define REGC_IMM32      11
21711 #define REGC_IMM16      12
21712 #define REGC_IMM8       13
21713 #define LAST_REGC  REGC_IMM8
21714 #if LAST_REGC >= MAX_REGC
21715 #error "MAX_REGC is to low"
21716 #endif
21717
21718 /* Register class masks */
21719 #define REGCM_FLAGS      (1 << REGC_FLAGS)
21720 #define REGCM_GPR8       (1 << REGC_GPR8)
21721 #define REGCM_GPR16      (1 << REGC_GPR16)
21722 #define REGCM_GPR32      (1 << REGC_GPR32)
21723 #define REGCM_DIVIDEND64 (1 << REGC_DIVIDEND64)
21724 #define REGCM_DIVIDEND32 (1 << REGC_DIVIDEND32)
21725 #define REGCM_MMX        (1 << REGC_MMX)
21726 #define REGCM_XMM        (1 << REGC_XMM)
21727 #define REGCM_GPR32_8    (1 << REGC_GPR32_8)
21728 #define REGCM_GPR16_8    (1 << REGC_GPR16_8)
21729 #define REGCM_GPR8_LO    (1 << REGC_GPR8_LO)
21730 #define REGCM_IMM32      (1 << REGC_IMM32)
21731 #define REGCM_IMM16      (1 << REGC_IMM16)
21732 #define REGCM_IMM8       (1 << REGC_IMM8)
21733 #define REGCM_ALL        ((1 << (LAST_REGC + 1)) - 1)
21734 #define REGCM_IMMALL    (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)
21735
21736 /* The x86 registers */
21737 #define REG_EFLAGS  2
21738 #define REGC_FLAGS_FIRST REG_EFLAGS
21739 #define REGC_FLAGS_LAST  REG_EFLAGS
21740 #define REG_AL      3
21741 #define REG_BL      4
21742 #define REG_CL      5
21743 #define REG_DL      6
21744 #define REG_AH      7
21745 #define REG_BH      8
21746 #define REG_CH      9
21747 #define REG_DH      10
21748 #define REGC_GPR8_LO_FIRST REG_AL
21749 #define REGC_GPR8_LO_LAST  REG_DL
21750 #define REGC_GPR8_FIRST  REG_AL
21751 #define REGC_GPR8_LAST   REG_DH
21752 #define REG_AX     11
21753 #define REG_BX     12
21754 #define REG_CX     13
21755 #define REG_DX     14
21756 #define REG_SI     15
21757 #define REG_DI     16
21758 #define REG_BP     17
21759 #define REG_SP     18
21760 #define REGC_GPR16_FIRST REG_AX
21761 #define REGC_GPR16_LAST  REG_SP
21762 #define REG_EAX    19
21763 #define REG_EBX    20
21764 #define REG_ECX    21
21765 #define REG_EDX    22
21766 #define REG_ESI    23
21767 #define REG_EDI    24
21768 #define REG_EBP    25
21769 #define REG_ESP    26
21770 #define REGC_GPR32_FIRST REG_EAX
21771 #define REGC_GPR32_LAST  REG_ESP
21772 #define REG_EDXEAX 27
21773 #define REGC_DIVIDEND64_FIRST REG_EDXEAX
21774 #define REGC_DIVIDEND64_LAST  REG_EDXEAX
21775 #define REG_DXAX   28
21776 #define REGC_DIVIDEND32_FIRST REG_DXAX
21777 #define REGC_DIVIDEND32_LAST  REG_DXAX
21778 #define REG_MMX0   29
21779 #define REG_MMX1   30
21780 #define REG_MMX2   31
21781 #define REG_MMX3   32
21782 #define REG_MMX4   33
21783 #define REG_MMX5   34
21784 #define REG_MMX6   35
21785 #define REG_MMX7   36
21786 #define REGC_MMX_FIRST REG_MMX0
21787 #define REGC_MMX_LAST  REG_MMX7
21788 #define REG_XMM0   37
21789 #define REG_XMM1   38
21790 #define REG_XMM2   39
21791 #define REG_XMM3   40
21792 #define REG_XMM4   41
21793 #define REG_XMM5   42
21794 #define REG_XMM6   43
21795 #define REG_XMM7   44
21796 #define REGC_XMM_FIRST REG_XMM0
21797 #define REGC_XMM_LAST  REG_XMM7
21798
21799 #if DEBUG_ROMCC_WARNINGS
21800 #warning "WISHLIST figure out how to use pinsrw and pextrw to better use extended regs"
21801 #endif
21802
21803 #define LAST_REG   REG_XMM7
21804
21805 #define REGC_GPR32_8_FIRST REG_EAX
21806 #define REGC_GPR32_8_LAST  REG_EDX
21807 #define REGC_GPR16_8_FIRST REG_AX
21808 #define REGC_GPR16_8_LAST  REG_DX
21809
21810 #define REGC_IMM8_FIRST    -1
21811 #define REGC_IMM8_LAST     -1
21812 #define REGC_IMM16_FIRST   -2
21813 #define REGC_IMM16_LAST    -1
21814 #define REGC_IMM32_FIRST   -4
21815 #define REGC_IMM32_LAST    -1
21816
21817 #if LAST_REG >= MAX_REGISTERS
21818 #error "MAX_REGISTERS to low"
21819 #endif
21820
21821
21822 static unsigned regc_size[LAST_REGC +1] = {
21823         [REGC_FLAGS]      = REGC_FLAGS_LAST      - REGC_FLAGS_FIRST + 1,
21824         [REGC_GPR8]       = REGC_GPR8_LAST       - REGC_GPR8_FIRST + 1,
21825         [REGC_GPR16]      = REGC_GPR16_LAST      - REGC_GPR16_FIRST + 1,
21826         [REGC_GPR32]      = REGC_GPR32_LAST      - REGC_GPR32_FIRST + 1,
21827         [REGC_DIVIDEND64] = REGC_DIVIDEND64_LAST - REGC_DIVIDEND64_FIRST + 1,
21828         [REGC_DIVIDEND32] = REGC_DIVIDEND32_LAST - REGC_DIVIDEND32_FIRST + 1,
21829         [REGC_MMX]        = REGC_MMX_LAST        - REGC_MMX_FIRST + 1,
21830         [REGC_XMM]        = REGC_XMM_LAST        - REGC_XMM_FIRST + 1,
21831         [REGC_GPR32_8]    = REGC_GPR32_8_LAST    - REGC_GPR32_8_FIRST + 1,
21832         [REGC_GPR16_8]    = REGC_GPR16_8_LAST    - REGC_GPR16_8_FIRST + 1,
21833         [REGC_GPR8_LO]    = REGC_GPR8_LO_LAST    - REGC_GPR8_LO_FIRST + 1,
21834         [REGC_IMM32]      = 0,
21835         [REGC_IMM16]      = 0,
21836         [REGC_IMM8]       = 0,
21837 };
21838
21839 static const struct {
21840         int first, last;
21841 } regcm_bound[LAST_REGC + 1] = {
21842         [REGC_FLAGS]      = { REGC_FLAGS_FIRST,      REGC_FLAGS_LAST },
21843         [REGC_GPR8]       = { REGC_GPR8_FIRST,       REGC_GPR8_LAST },
21844         [REGC_GPR16]      = { REGC_GPR16_FIRST,      REGC_GPR16_LAST },
21845         [REGC_GPR32]      = { REGC_GPR32_FIRST,      REGC_GPR32_LAST },
21846         [REGC_DIVIDEND64] = { REGC_DIVIDEND64_FIRST, REGC_DIVIDEND64_LAST },
21847         [REGC_DIVIDEND32] = { REGC_DIVIDEND32_FIRST, REGC_DIVIDEND32_LAST },
21848         [REGC_MMX]        = { REGC_MMX_FIRST,        REGC_MMX_LAST },
21849         [REGC_XMM]        = { REGC_XMM_FIRST,        REGC_XMM_LAST },
21850         [REGC_GPR32_8]    = { REGC_GPR32_8_FIRST,    REGC_GPR32_8_LAST },
21851         [REGC_GPR16_8]    = { REGC_GPR16_8_FIRST,    REGC_GPR16_8_LAST },
21852         [REGC_GPR8_LO]    = { REGC_GPR8_LO_FIRST,    REGC_GPR8_LO_LAST },
21853         [REGC_IMM32]      = { REGC_IMM32_FIRST,      REGC_IMM32_LAST },
21854         [REGC_IMM16]      = { REGC_IMM16_FIRST,      REGC_IMM16_LAST },
21855         [REGC_IMM8]       = { REGC_IMM8_FIRST,       REGC_IMM8_LAST },
21856 };
21857
21858 #if ARCH_INPUT_REGS != 4
21859 #error ARCH_INPUT_REGS size mismatch
21860 #endif
21861 static const struct reg_info arch_input_regs[ARCH_INPUT_REGS] = {
21862         { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21863         { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21864         { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21865         { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21866 };
21867
21868 #if ARCH_OUTPUT_REGS != 4
21869 #error ARCH_INPUT_REGS size mismatch
21870 #endif
21871 static const struct reg_info arch_output_regs[ARCH_OUTPUT_REGS] = {
21872         { .reg = REG_EAX, .regcm = REGCM_GPR32 },
21873         { .reg = REG_EBX, .regcm = REGCM_GPR32 },
21874         { .reg = REG_ECX, .regcm = REGCM_GPR32 },
21875         { .reg = REG_EDX, .regcm = REGCM_GPR32 },
21876 };
21877
21878 static void init_arch_state(struct arch_state *arch)
21879 {
21880         memset(arch, 0, sizeof(*arch));
21881         arch->features = 0;
21882 }
21883
21884 static const struct compiler_flag arch_flags[] = {
21885         { "mmx",       X86_MMX_REGS },
21886         { "sse",       X86_XMM_REGS },
21887         { "noop-copy", X86_NOOP_COPY },
21888         { 0,     0 },
21889 };
21890 static const struct compiler_flag arch_cpus[] = {
21891         { "i386", 0 },
21892         { "p2",   X86_MMX_REGS },
21893         { "p3",   X86_MMX_REGS | X86_XMM_REGS },
21894         { "p4",   X86_MMX_REGS | X86_XMM_REGS },
21895         { "k7",   X86_MMX_REGS },
21896         { "k8",   X86_MMX_REGS | X86_XMM_REGS },
21897         { "c3",   X86_MMX_REGS },
21898         { "c3-2", X86_MMX_REGS | X86_XMM_REGS }, /* Nehemiah */
21899         {  0,     0 }
21900 };
21901 static int arch_encode_flag(struct arch_state *arch, const char *flag)
21902 {
21903         int result;
21904         int act;
21905
21906         act = 1;
21907         result = -1;
21908         if (strncmp(flag, "no-", 3) == 0) {
21909                 flag += 3;
21910                 act = 0;
21911         }
21912         if (act && strncmp(flag, "cpu=", 4) == 0) {
21913                 flag += 4;
21914                 result = set_flag(arch_cpus, &arch->features, 1, flag);
21915         }
21916         else {
21917                 result = set_flag(arch_flags, &arch->features, act, flag);
21918         }
21919         return result;
21920 }
21921
21922 static void arch_usage(FILE *fp)
21923 {
21924         flag_usage(fp, arch_flags, "-m", "-mno-");
21925         flag_usage(fp, arch_cpus, "-mcpu=", 0);
21926 }
21927
21928 static unsigned arch_regc_size(struct compile_state *state, int class)
21929 {
21930         if ((class < 0) || (class > LAST_REGC)) {
21931                 return 0;
21932         }
21933         return regc_size[class];
21934 }
21935
21936 static int arch_regcm_intersect(unsigned regcm1, unsigned regcm2)
21937 {
21938         /* See if two register classes may have overlapping registers */
21939         unsigned gpr_mask = REGCM_GPR8 | REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
21940                 REGCM_GPR32_8 | REGCM_GPR32 |
21941                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64;
21942
21943         /* Special case for the immediates */
21944         if ((regcm1 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21945                 ((regcm1 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0) &&
21946                 (regcm2 & (REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) &&
21947                 ((regcm2 & ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8)) == 0)) {
21948                 return 0;
21949         }
21950         return (regcm1 & regcm2) ||
21951                 ((regcm1 & gpr_mask) && (regcm2 & gpr_mask));
21952 }
21953
21954 static void arch_reg_equivs(
21955         struct compile_state *state, unsigned *equiv, int reg)
21956 {
21957         if ((reg < 0) || (reg > LAST_REG)) {
21958                 internal_error(state, 0, "invalid register");
21959         }
21960         *equiv++ = reg;
21961         switch(reg) {
21962         case REG_AL:
21963 #if X86_4_8BIT_GPRS
21964                 *equiv++ = REG_AH;
21965 #endif
21966                 *equiv++ = REG_AX;
21967                 *equiv++ = REG_EAX;
21968                 *equiv++ = REG_DXAX;
21969                 *equiv++ = REG_EDXEAX;
21970                 break;
21971         case REG_AH:
21972 #if X86_4_8BIT_GPRS
21973                 *equiv++ = REG_AL;
21974 #endif
21975                 *equiv++ = REG_AX;
21976                 *equiv++ = REG_EAX;
21977                 *equiv++ = REG_DXAX;
21978                 *equiv++ = REG_EDXEAX;
21979                 break;
21980         case REG_BL:
21981 #if X86_4_8BIT_GPRS
21982                 *equiv++ = REG_BH;
21983 #endif
21984                 *equiv++ = REG_BX;
21985                 *equiv++ = REG_EBX;
21986                 break;
21987
21988         case REG_BH:
21989 #if X86_4_8BIT_GPRS
21990                 *equiv++ = REG_BL;
21991 #endif
21992                 *equiv++ = REG_BX;
21993                 *equiv++ = REG_EBX;
21994                 break;
21995         case REG_CL:
21996 #if X86_4_8BIT_GPRS
21997                 *equiv++ = REG_CH;
21998 #endif
21999                 *equiv++ = REG_CX;
22000                 *equiv++ = REG_ECX;
22001                 break;
22002
22003         case REG_CH:
22004 #if X86_4_8BIT_GPRS
22005                 *equiv++ = REG_CL;
22006 #endif
22007                 *equiv++ = REG_CX;
22008                 *equiv++ = REG_ECX;
22009                 break;
22010         case REG_DL:
22011 #if X86_4_8BIT_GPRS
22012                 *equiv++ = REG_DH;
22013 #endif
22014                 *equiv++ = REG_DX;
22015                 *equiv++ = REG_EDX;
22016                 *equiv++ = REG_DXAX;
22017                 *equiv++ = REG_EDXEAX;
22018                 break;
22019         case REG_DH:
22020 #if X86_4_8BIT_GPRS
22021                 *equiv++ = REG_DL;
22022 #endif
22023                 *equiv++ = REG_DX;
22024                 *equiv++ = REG_EDX;
22025                 *equiv++ = REG_DXAX;
22026                 *equiv++ = REG_EDXEAX;
22027                 break;
22028         case REG_AX:
22029                 *equiv++ = REG_AL;
22030                 *equiv++ = REG_AH;
22031                 *equiv++ = REG_EAX;
22032                 *equiv++ = REG_DXAX;
22033                 *equiv++ = REG_EDXEAX;
22034                 break;
22035         case REG_BX:
22036                 *equiv++ = REG_BL;
22037                 *equiv++ = REG_BH;
22038                 *equiv++ = REG_EBX;
22039                 break;
22040         case REG_CX:
22041                 *equiv++ = REG_CL;
22042                 *equiv++ = REG_CH;
22043                 *equiv++ = REG_ECX;
22044                 break;
22045         case REG_DX:
22046                 *equiv++ = REG_DL;
22047                 *equiv++ = REG_DH;
22048                 *equiv++ = REG_EDX;
22049                 *equiv++ = REG_DXAX;
22050                 *equiv++ = REG_EDXEAX;
22051                 break;
22052         case REG_SI:
22053                 *equiv++ = REG_ESI;
22054                 break;
22055         case REG_DI:
22056                 *equiv++ = REG_EDI;
22057                 break;
22058         case REG_BP:
22059                 *equiv++ = REG_EBP;
22060                 break;
22061         case REG_SP:
22062                 *equiv++ = REG_ESP;
22063                 break;
22064         case REG_EAX:
22065                 *equiv++ = REG_AL;
22066                 *equiv++ = REG_AH;
22067                 *equiv++ = REG_AX;
22068                 *equiv++ = REG_DXAX;
22069                 *equiv++ = REG_EDXEAX;
22070                 break;
22071         case REG_EBX:
22072                 *equiv++ = REG_BL;
22073                 *equiv++ = REG_BH;
22074                 *equiv++ = REG_BX;
22075                 break;
22076         case REG_ECX:
22077                 *equiv++ = REG_CL;
22078                 *equiv++ = REG_CH;
22079                 *equiv++ = REG_CX;
22080                 break;
22081         case REG_EDX:
22082                 *equiv++ = REG_DL;
22083                 *equiv++ = REG_DH;
22084                 *equiv++ = REG_DX;
22085                 *equiv++ = REG_DXAX;
22086                 *equiv++ = REG_EDXEAX;
22087                 break;
22088         case REG_ESI:
22089                 *equiv++ = REG_SI;
22090                 break;
22091         case REG_EDI:
22092                 *equiv++ = REG_DI;
22093                 break;
22094         case REG_EBP:
22095                 *equiv++ = REG_BP;
22096                 break;
22097         case REG_ESP:
22098                 *equiv++ = REG_SP;
22099                 break;
22100         case REG_DXAX:
22101                 *equiv++ = REG_AL;
22102                 *equiv++ = REG_AH;
22103                 *equiv++ = REG_DL;
22104                 *equiv++ = REG_DH;
22105                 *equiv++ = REG_AX;
22106                 *equiv++ = REG_DX;
22107                 *equiv++ = REG_EAX;
22108                 *equiv++ = REG_EDX;
22109                 *equiv++ = REG_EDXEAX;
22110                 break;
22111         case REG_EDXEAX:
22112                 *equiv++ = REG_AL;
22113                 *equiv++ = REG_AH;
22114                 *equiv++ = REG_DL;
22115                 *equiv++ = REG_DH;
22116                 *equiv++ = REG_AX;
22117                 *equiv++ = REG_DX;
22118                 *equiv++ = REG_EAX;
22119                 *equiv++ = REG_EDX;
22120                 *equiv++ = REG_DXAX;
22121                 break;
22122         }
22123         *equiv++ = REG_UNSET;
22124 }
22125
22126 static unsigned arch_avail_mask(struct compile_state *state)
22127 {
22128         unsigned avail_mask;
22129         /* REGCM_GPR8 is not available */
22130         avail_mask = REGCM_GPR8_LO | REGCM_GPR16_8 | REGCM_GPR16 |
22131                 REGCM_GPR32 | REGCM_GPR32_8 |
22132                 REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22133                 REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 | REGCM_FLAGS;
22134         if (state->arch->features & X86_MMX_REGS) {
22135                 avail_mask |= REGCM_MMX;
22136         }
22137         if (state->arch->features & X86_XMM_REGS) {
22138                 avail_mask |= REGCM_XMM;
22139         }
22140         return avail_mask;
22141 }
22142
22143 static unsigned arch_regcm_normalize(struct compile_state *state, unsigned regcm)
22144 {
22145         unsigned mask, result;
22146         int class, class2;
22147         result = regcm;
22148
22149         for(class = 0, mask = 1; mask; mask <<= 1, class++) {
22150                 if ((result & mask) == 0) {
22151                         continue;
22152                 }
22153                 if (class > LAST_REGC) {
22154                         result &= ~mask;
22155                 }
22156                 for(class2 = 0; class2 <= LAST_REGC; class2++) {
22157                         if ((regcm_bound[class2].first >= regcm_bound[class].first) &&
22158                                 (regcm_bound[class2].last <= regcm_bound[class].last)) {
22159                                 result |= (1 << class2);
22160                         }
22161                 }
22162         }
22163         result &= arch_avail_mask(state);
22164         return result;
22165 }
22166
22167 static unsigned arch_regcm_reg_normalize(struct compile_state *state, unsigned regcm)
22168 {
22169         /* Like arch_regcm_normalize except immediate register classes are excluded */
22170         regcm = arch_regcm_normalize(state, regcm);
22171         /* Remove the immediate register classes */
22172         regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
22173         return regcm;
22174
22175 }
22176
22177 static unsigned arch_reg_regcm(struct compile_state *state, int reg)
22178 {
22179         unsigned mask;
22180         int class;
22181         mask = 0;
22182         for(class = 0; class <= LAST_REGC; class++) {
22183                 if ((reg >= regcm_bound[class].first) &&
22184                         (reg <= regcm_bound[class].last)) {
22185                         mask |= (1 << class);
22186                 }
22187         }
22188         if (!mask) {
22189                 internal_error(state, 0, "reg %d not in any class", reg);
22190         }
22191         return mask;
22192 }
22193
22194 static struct reg_info arch_reg_constraint(
22195         struct compile_state *state, struct type *type, const char *constraint)
22196 {
22197         static const struct {
22198                 char class;
22199                 unsigned int mask;
22200                 unsigned int reg;
22201         } constraints[] = {
22202                 { 'r', REGCM_GPR32,   REG_UNSET },
22203                 { 'g', REGCM_GPR32,   REG_UNSET },
22204                 { 'p', REGCM_GPR32,   REG_UNSET },
22205                 { 'q', REGCM_GPR8_LO, REG_UNSET },
22206                 { 'Q', REGCM_GPR32_8, REG_UNSET },
22207                 { 'x', REGCM_XMM,     REG_UNSET },
22208                 { 'y', REGCM_MMX,     REG_UNSET },
22209                 { 'a', REGCM_GPR32,   REG_EAX },
22210                 { 'b', REGCM_GPR32,   REG_EBX },
22211                 { 'c', REGCM_GPR32,   REG_ECX },
22212                 { 'd', REGCM_GPR32,   REG_EDX },
22213                 { 'D', REGCM_GPR32,   REG_EDI },
22214                 { 'S', REGCM_GPR32,   REG_ESI },
22215                 { '\0', 0, REG_UNSET },
22216         };
22217         unsigned int regcm;
22218         unsigned int mask, reg;
22219         struct reg_info result;
22220         const char *ptr;
22221         regcm = arch_type_to_regcm(state, type);
22222         reg = REG_UNSET;
22223         mask = 0;
22224         for(ptr = constraint; *ptr; ptr++) {
22225                 int i;
22226                 if (*ptr ==  ' ') {
22227                         continue;
22228                 }
22229                 for(i = 0; constraints[i].class != '\0'; i++) {
22230                         if (constraints[i].class == *ptr) {
22231                                 break;
22232                         }
22233                 }
22234                 if (constraints[i].class == '\0') {
22235                         error(state, 0, "invalid register constraint ``%c''", *ptr);
22236                         break;
22237                 }
22238                 if ((constraints[i].mask & regcm) == 0) {
22239                         error(state, 0, "invalid register class %c specified",
22240                                 *ptr);
22241                 }
22242                 mask |= constraints[i].mask;
22243                 if (constraints[i].reg != REG_UNSET) {
22244                         if ((reg != REG_UNSET) && (reg != constraints[i].reg)) {
22245                                 error(state, 0, "Only one register may be specified");
22246                         }
22247                         reg = constraints[i].reg;
22248                 }
22249         }
22250         result.reg = reg;
22251         result.regcm = mask;
22252         return result;
22253 }
22254
22255 static struct reg_info arch_reg_clobber(
22256         struct compile_state *state, const char *clobber)
22257 {
22258         struct reg_info result;
22259         if (strcmp(clobber, "memory") == 0) {
22260                 result.reg = REG_UNSET;
22261                 result.regcm = 0;
22262         }
22263         else if (strcmp(clobber, "eax") == 0) {
22264                 result.reg = REG_EAX;
22265                 result.regcm = REGCM_GPR32;
22266         }
22267         else if (strcmp(clobber, "ebx") == 0) {
22268                 result.reg = REG_EBX;
22269                 result.regcm = REGCM_GPR32;
22270         }
22271         else if (strcmp(clobber, "ecx") == 0) {
22272                 result.reg = REG_ECX;
22273                 result.regcm = REGCM_GPR32;
22274         }
22275         else if (strcmp(clobber, "edx") == 0) {
22276                 result.reg = REG_EDX;
22277                 result.regcm = REGCM_GPR32;
22278         }
22279         else if (strcmp(clobber, "esi") == 0) {
22280                 result.reg = REG_ESI;
22281                 result.regcm = REGCM_GPR32;
22282         }
22283         else if (strcmp(clobber, "edi") == 0) {
22284                 result.reg = REG_EDI;
22285                 result.regcm = REGCM_GPR32;
22286         }
22287         else if (strcmp(clobber, "ebp") == 0) {
22288                 result.reg = REG_EBP;
22289                 result.regcm = REGCM_GPR32;
22290         }
22291         else if (strcmp(clobber, "esp") == 0) {
22292                 result.reg = REG_ESP;
22293                 result.regcm = REGCM_GPR32;
22294         }
22295         else if (strcmp(clobber, "cc") == 0) {
22296                 result.reg = REG_EFLAGS;
22297                 result.regcm = REGCM_FLAGS;
22298         }
22299         else if ((strncmp(clobber, "xmm", 3) == 0)  &&
22300                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22301                 result.reg = REG_XMM0 + octdigval(clobber[3]);
22302                 result.regcm = REGCM_XMM;
22303         }
22304         else if ((strncmp(clobber, "mm", 2) == 0) &&
22305                 octdigitp(clobber[3]) && (clobber[4] == '\0')) {
22306                 result.reg = REG_MMX0 + octdigval(clobber[3]);
22307                 result.regcm = REGCM_MMX;
22308         }
22309         else {
22310                 error(state, 0, "unknown register name `%s' in asm",
22311                         clobber);
22312                 result.reg = REG_UNSET;
22313                 result.regcm = 0;
22314         }
22315         return result;
22316 }
22317
22318 static int do_select_reg(struct compile_state *state,
22319         char *used, int reg, unsigned classes)
22320 {
22321         unsigned mask;
22322         if (used[reg]) {
22323                 return REG_UNSET;
22324         }
22325         mask = arch_reg_regcm(state, reg);
22326         return (classes & mask) ? reg : REG_UNSET;
22327 }
22328
22329 static int arch_select_free_register(
22330         struct compile_state *state, char *used, int classes)
22331 {
22332         /* Live ranges with the most neighbors are colored first.
22333          *
22334          * Generally it does not matter which colors are given
22335          * as the register allocator attempts to color live ranges
22336          * in an order where you are guaranteed not to run out of colors.
22337          *
22338          * Occasionally the register allocator cannot find an order
22339          * of register selection that will find a free color.  To
22340          * increase the odds the register allocator will work when
22341          * it guesses first give out registers from register classes
22342          * least likely to run out of registers.
22343          *
22344          */
22345         int i, reg;
22346         reg = REG_UNSET;
22347         for(i = REGC_XMM_FIRST; (reg == REG_UNSET) && (i <= REGC_XMM_LAST); i++) {
22348                 reg = do_select_reg(state, used, i, classes);
22349         }
22350         for(i = REGC_MMX_FIRST; (reg == REG_UNSET) && (i <= REGC_MMX_LAST); i++) {
22351                 reg = do_select_reg(state, used, i, classes);
22352         }
22353         for(i = REGC_GPR32_LAST; (reg == REG_UNSET) && (i >= REGC_GPR32_FIRST); i--) {
22354                 reg = do_select_reg(state, used, i, classes);
22355         }
22356         for(i = REGC_GPR16_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR16_LAST); i++) {
22357                 reg = do_select_reg(state, used, i, classes);
22358         }
22359         for(i = REGC_GPR8_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LAST); i++) {
22360                 reg = do_select_reg(state, used, i, classes);
22361         }
22362         for(i = REGC_GPR8_LO_FIRST; (reg == REG_UNSET) && (i <= REGC_GPR8_LO_LAST); i++) {
22363                 reg = do_select_reg(state, used, i, classes);
22364         }
22365         for(i = REGC_DIVIDEND32_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND32_LAST); i++) {
22366                 reg = do_select_reg(state, used, i, classes);
22367         }
22368         for(i = REGC_DIVIDEND64_FIRST; (reg == REG_UNSET) && (i <= REGC_DIVIDEND64_LAST); i++) {
22369                 reg = do_select_reg(state, used, i, classes);
22370         }
22371         for(i = REGC_FLAGS_FIRST; (reg == REG_UNSET) && (i <= REGC_FLAGS_LAST); i++) {
22372                 reg = do_select_reg(state, used, i, classes);
22373         }
22374         return reg;
22375 }
22376
22377
22378 static unsigned arch_type_to_regcm(struct compile_state *state, struct type *type)
22379 {
22380
22381 #if DEBUG_ROMCC_WARNINGS
22382 #warning "FIXME force types smaller (if legal) before I get here"
22383 #endif
22384         unsigned mask;
22385         mask = 0;
22386         switch(type->type & TYPE_MASK) {
22387         case TYPE_ARRAY:
22388         case TYPE_VOID:
22389                 mask = 0;
22390                 break;
22391         case TYPE_CHAR:
22392         case TYPE_UCHAR:
22393                 mask = REGCM_GPR8 | REGCM_GPR8_LO |
22394                         REGCM_GPR16 | REGCM_GPR16_8 |
22395                         REGCM_GPR32 | REGCM_GPR32_8 |
22396                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22397                         REGCM_MMX | REGCM_XMM |
22398                         REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8;
22399                 break;
22400         case TYPE_SHORT:
22401         case TYPE_USHORT:
22402                 mask =  REGCM_GPR16 | REGCM_GPR16_8 |
22403                         REGCM_GPR32 | REGCM_GPR32_8 |
22404                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22405                         REGCM_MMX | REGCM_XMM |
22406                         REGCM_IMM32 | REGCM_IMM16;
22407                 break;
22408         case TYPE_ENUM:
22409         case TYPE_INT:
22410         case TYPE_UINT:
22411         case TYPE_LONG:
22412         case TYPE_ULONG:
22413         case TYPE_POINTER:
22414                 mask =  REGCM_GPR32 | REGCM_GPR32_8 |
22415                         REGCM_DIVIDEND32 | REGCM_DIVIDEND64 |
22416                         REGCM_MMX | REGCM_XMM |
22417                         REGCM_IMM32;
22418                 break;
22419         case TYPE_JOIN:
22420         case TYPE_UNION:
22421                 mask = arch_type_to_regcm(state, type->left);
22422                 break;
22423         case TYPE_OVERLAP:
22424                 mask = arch_type_to_regcm(state, type->left) &
22425                         arch_type_to_regcm(state, type->right);
22426                 break;
22427         case TYPE_BITFIELD:
22428                 mask = arch_type_to_regcm(state, type->left);
22429                 break;
22430         default:
22431                 fprintf(state->errout, "type: ");
22432                 name_of(state->errout, type);
22433                 fprintf(state->errout, "\n");
22434                 internal_error(state, 0, "no register class for type");
22435                 break;
22436         }
22437         mask = arch_regcm_normalize(state, mask);
22438         return mask;
22439 }
22440
22441 static int is_imm32(struct triple *imm)
22442 {
22443         // second condition commented out to prevent compiler warning:
22444         // imm->u.cval is always 32bit unsigned, so the comparison is
22445         // always true.
22446         return ((imm->op == OP_INTCONST) /* && (imm->u.cval <= 0xffffffffUL) */ ) ||
22447                 (imm->op == OP_ADDRCONST);
22448
22449 }
22450 static int is_imm16(struct triple *imm)
22451 {
22452         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xffff));
22453 }
22454 static int is_imm8(struct triple *imm)
22455 {
22456         return ((imm->op == OP_INTCONST) && (imm->u.cval <= 0xff));
22457 }
22458
22459 static int get_imm32(struct triple *ins, struct triple **expr)
22460 {
22461         struct triple *imm;
22462         imm = *expr;
22463         while(imm->op == OP_COPY) {
22464                 imm = RHS(imm, 0);
22465         }
22466         if (!is_imm32(imm)) {
22467                 return 0;
22468         }
22469         unuse_triple(*expr, ins);
22470         use_triple(imm, ins);
22471         *expr = imm;
22472         return 1;
22473 }
22474
22475 static int get_imm8(struct triple *ins, struct triple **expr)
22476 {
22477         struct triple *imm;
22478         imm = *expr;
22479         while(imm->op == OP_COPY) {
22480                 imm = RHS(imm, 0);
22481         }
22482         if (!is_imm8(imm)) {
22483                 return 0;
22484         }
22485         unuse_triple(*expr, ins);
22486         use_triple(imm, ins);
22487         *expr = imm;
22488         return 1;
22489 }
22490
22491 #define TEMPLATE_NOP           0
22492 #define TEMPLATE_INTCONST8     1
22493 #define TEMPLATE_INTCONST32    2
22494 #define TEMPLATE_UNKNOWNVAL    3
22495 #define TEMPLATE_COPY8_REG     5
22496 #define TEMPLATE_COPY16_REG    6
22497 #define TEMPLATE_COPY32_REG    7
22498 #define TEMPLATE_COPY_IMM8     8
22499 #define TEMPLATE_COPY_IMM16    9
22500 #define TEMPLATE_COPY_IMM32   10
22501 #define TEMPLATE_PHI8         11
22502 #define TEMPLATE_PHI16        12
22503 #define TEMPLATE_PHI32        13
22504 #define TEMPLATE_STORE8       14
22505 #define TEMPLATE_STORE16      15
22506 #define TEMPLATE_STORE32      16
22507 #define TEMPLATE_LOAD8        17
22508 #define TEMPLATE_LOAD16       18
22509 #define TEMPLATE_LOAD32       19
22510 #define TEMPLATE_BINARY8_REG  20
22511 #define TEMPLATE_BINARY16_REG 21
22512 #define TEMPLATE_BINARY32_REG 22
22513 #define TEMPLATE_BINARY8_IMM  23
22514 #define TEMPLATE_BINARY16_IMM 24
22515 #define TEMPLATE_BINARY32_IMM 25
22516 #define TEMPLATE_SL8_CL       26
22517 #define TEMPLATE_SL16_CL      27
22518 #define TEMPLATE_SL32_CL      28
22519 #define TEMPLATE_SL8_IMM      29
22520 #define TEMPLATE_SL16_IMM     30
22521 #define TEMPLATE_SL32_IMM     31
22522 #define TEMPLATE_UNARY8       32
22523 #define TEMPLATE_UNARY16      33
22524 #define TEMPLATE_UNARY32      34
22525 #define TEMPLATE_CMP8_REG     35
22526 #define TEMPLATE_CMP16_REG    36
22527 #define TEMPLATE_CMP32_REG    37
22528 #define TEMPLATE_CMP8_IMM     38
22529 #define TEMPLATE_CMP16_IMM    39
22530 #define TEMPLATE_CMP32_IMM    40
22531 #define TEMPLATE_TEST8        41
22532 #define TEMPLATE_TEST16       42
22533 #define TEMPLATE_TEST32       43
22534 #define TEMPLATE_SET          44
22535 #define TEMPLATE_JMP          45
22536 #define TEMPLATE_RET          46
22537 #define TEMPLATE_INB_DX       47
22538 #define TEMPLATE_INB_IMM      48
22539 #define TEMPLATE_INW_DX       49
22540 #define TEMPLATE_INW_IMM      50
22541 #define TEMPLATE_INL_DX       51
22542 #define TEMPLATE_INL_IMM      52
22543 #define TEMPLATE_OUTB_DX      53
22544 #define TEMPLATE_OUTB_IMM     54
22545 #define TEMPLATE_OUTW_DX      55
22546 #define TEMPLATE_OUTW_IMM     56
22547 #define TEMPLATE_OUTL_DX      57
22548 #define TEMPLATE_OUTL_IMM     58
22549 #define TEMPLATE_BSF          59
22550 #define TEMPLATE_RDMSR        60
22551 #define TEMPLATE_WRMSR        61
22552 #define TEMPLATE_UMUL8        62
22553 #define TEMPLATE_UMUL16       63
22554 #define TEMPLATE_UMUL32       64
22555 #define TEMPLATE_DIV8         65
22556 #define TEMPLATE_DIV16        66
22557 #define TEMPLATE_DIV32        67
22558 #define LAST_TEMPLATE       TEMPLATE_DIV32
22559 #if LAST_TEMPLATE >= MAX_TEMPLATES
22560 #error "MAX_TEMPLATES to low"
22561 #endif
22562
22563 #define COPY8_REGCM     (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO | REGCM_MMX | REGCM_XMM)
22564 #define COPY16_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_GPR16 | REGCM_MMX | REGCM_XMM)
22565 #define COPY32_REGCM    (REGCM_DIVIDEND64 | REGCM_DIVIDEND32 | REGCM_GPR32 | REGCM_MMX | REGCM_XMM)
22566
22567
22568 static struct ins_template templates[] = {
22569         [TEMPLATE_NOP]      = {
22570                 .lhs = {
22571                         [ 0] = { REG_UNNEEDED, REGCM_IMMALL },
22572                         [ 1] = { REG_UNNEEDED, REGCM_IMMALL },
22573                         [ 2] = { REG_UNNEEDED, REGCM_IMMALL },
22574                         [ 3] = { REG_UNNEEDED, REGCM_IMMALL },
22575                         [ 4] = { REG_UNNEEDED, REGCM_IMMALL },
22576                         [ 5] = { REG_UNNEEDED, REGCM_IMMALL },
22577                         [ 6] = { REG_UNNEEDED, REGCM_IMMALL },
22578                         [ 7] = { REG_UNNEEDED, REGCM_IMMALL },
22579                         [ 8] = { REG_UNNEEDED, REGCM_IMMALL },
22580                         [ 9] = { REG_UNNEEDED, REGCM_IMMALL },
22581                         [10] = { REG_UNNEEDED, REGCM_IMMALL },
22582                         [11] = { REG_UNNEEDED, REGCM_IMMALL },
22583                         [12] = { REG_UNNEEDED, REGCM_IMMALL },
22584                         [13] = { REG_UNNEEDED, REGCM_IMMALL },
22585                         [14] = { REG_UNNEEDED, REGCM_IMMALL },
22586                         [15] = { REG_UNNEEDED, REGCM_IMMALL },
22587                         [16] = { REG_UNNEEDED, REGCM_IMMALL },
22588                         [17] = { REG_UNNEEDED, REGCM_IMMALL },
22589                         [18] = { REG_UNNEEDED, REGCM_IMMALL },
22590                         [19] = { REG_UNNEEDED, REGCM_IMMALL },
22591                         [20] = { REG_UNNEEDED, REGCM_IMMALL },
22592                         [21] = { REG_UNNEEDED, REGCM_IMMALL },
22593                         [22] = { REG_UNNEEDED, REGCM_IMMALL },
22594                         [23] = { REG_UNNEEDED, REGCM_IMMALL },
22595                         [24] = { REG_UNNEEDED, REGCM_IMMALL },
22596                         [25] = { REG_UNNEEDED, REGCM_IMMALL },
22597                         [26] = { REG_UNNEEDED, REGCM_IMMALL },
22598                         [27] = { REG_UNNEEDED, REGCM_IMMALL },
22599                         [28] = { REG_UNNEEDED, REGCM_IMMALL },
22600                         [29] = { REG_UNNEEDED, REGCM_IMMALL },
22601                         [30] = { REG_UNNEEDED, REGCM_IMMALL },
22602                         [31] = { REG_UNNEEDED, REGCM_IMMALL },
22603                         [32] = { REG_UNNEEDED, REGCM_IMMALL },
22604                         [33] = { REG_UNNEEDED, REGCM_IMMALL },
22605                         [34] = { REG_UNNEEDED, REGCM_IMMALL },
22606                         [35] = { REG_UNNEEDED, REGCM_IMMALL },
22607                         [36] = { REG_UNNEEDED, REGCM_IMMALL },
22608                         [37] = { REG_UNNEEDED, REGCM_IMMALL },
22609                         [38] = { REG_UNNEEDED, REGCM_IMMALL },
22610                         [39] = { REG_UNNEEDED, REGCM_IMMALL },
22611                         [40] = { REG_UNNEEDED, REGCM_IMMALL },
22612                         [41] = { REG_UNNEEDED, REGCM_IMMALL },
22613                         [42] = { REG_UNNEEDED, REGCM_IMMALL },
22614                         [43] = { REG_UNNEEDED, REGCM_IMMALL },
22615                         [44] = { REG_UNNEEDED, REGCM_IMMALL },
22616                         [45] = { REG_UNNEEDED, REGCM_IMMALL },
22617                         [46] = { REG_UNNEEDED, REGCM_IMMALL },
22618                         [47] = { REG_UNNEEDED, REGCM_IMMALL },
22619                         [48] = { REG_UNNEEDED, REGCM_IMMALL },
22620                         [49] = { REG_UNNEEDED, REGCM_IMMALL },
22621                         [50] = { REG_UNNEEDED, REGCM_IMMALL },
22622                         [51] = { REG_UNNEEDED, REGCM_IMMALL },
22623                         [52] = { REG_UNNEEDED, REGCM_IMMALL },
22624                         [53] = { REG_UNNEEDED, REGCM_IMMALL },
22625                         [54] = { REG_UNNEEDED, REGCM_IMMALL },
22626                         [55] = { REG_UNNEEDED, REGCM_IMMALL },
22627                         [56] = { REG_UNNEEDED, REGCM_IMMALL },
22628                         [57] = { REG_UNNEEDED, REGCM_IMMALL },
22629                         [58] = { REG_UNNEEDED, REGCM_IMMALL },
22630                         [59] = { REG_UNNEEDED, REGCM_IMMALL },
22631                         [60] = { REG_UNNEEDED, REGCM_IMMALL },
22632                         [61] = { REG_UNNEEDED, REGCM_IMMALL },
22633                         [62] = { REG_UNNEEDED, REGCM_IMMALL },
22634                         [63] = { REG_UNNEEDED, REGCM_IMMALL },
22635                 },
22636         },
22637         [TEMPLATE_INTCONST8] = {
22638                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22639         },
22640         [TEMPLATE_INTCONST32] = {
22641                 .lhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 } },
22642         },
22643         [TEMPLATE_UNKNOWNVAL] = {
22644                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22645         },
22646         [TEMPLATE_COPY8_REG] = {
22647                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22648                 .rhs = { [0] = { REG_UNSET, COPY8_REGCM }  },
22649         },
22650         [TEMPLATE_COPY16_REG] = {
22651                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22652                 .rhs = { [0] = { REG_UNSET, COPY16_REGCM }  },
22653         },
22654         [TEMPLATE_COPY32_REG] = {
22655                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22656                 .rhs = { [0] = { REG_UNSET, COPY32_REGCM }  },
22657         },
22658         [TEMPLATE_COPY_IMM8] = {
22659                 .lhs = { [0] = { REG_UNSET, COPY8_REGCM } },
22660                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22661         },
22662         [TEMPLATE_COPY_IMM16] = {
22663                 .lhs = { [0] = { REG_UNSET, COPY16_REGCM } },
22664                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM16 | REGCM_IMM8 } },
22665         },
22666         [TEMPLATE_COPY_IMM32] = {
22667                 .lhs = { [0] = { REG_UNSET, COPY32_REGCM } },
22668                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8 } },
22669         },
22670         [TEMPLATE_PHI8] = {
22671                 .lhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22672                 .rhs = { [0] = { REG_VIRT0, COPY8_REGCM } },
22673         },
22674         [TEMPLATE_PHI16] = {
22675                 .lhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22676                 .rhs = { [0] = { REG_VIRT0, COPY16_REGCM } },
22677         },
22678         [TEMPLATE_PHI32] = {
22679                 .lhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22680                 .rhs = { [0] = { REG_VIRT0, COPY32_REGCM } },
22681         },
22682         [TEMPLATE_STORE8] = {
22683                 .rhs = {
22684                         [0] = { REG_UNSET, REGCM_GPR32 },
22685                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22686                 },
22687         },
22688         [TEMPLATE_STORE16] = {
22689                 .rhs = {
22690                         [0] = { REG_UNSET, REGCM_GPR32 },
22691                         [1] = { REG_UNSET, REGCM_GPR16 },
22692                 },
22693         },
22694         [TEMPLATE_STORE32] = {
22695                 .rhs = {
22696                         [0] = { REG_UNSET, REGCM_GPR32 },
22697                         [1] = { REG_UNSET, REGCM_GPR32 },
22698                 },
22699         },
22700         [TEMPLATE_LOAD8] = {
22701                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22702                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22703         },
22704         [TEMPLATE_LOAD16] = {
22705                 .lhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22706                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22707         },
22708         [TEMPLATE_LOAD32] = {
22709                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22710                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22711         },
22712         [TEMPLATE_BINARY8_REG] = {
22713                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22714                 .rhs = {
22715                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
22716                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22717                 },
22718         },
22719         [TEMPLATE_BINARY16_REG] = {
22720                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22721                 .rhs = {
22722                         [0] = { REG_VIRT0, REGCM_GPR16 },
22723                         [1] = { REG_UNSET, REGCM_GPR16 },
22724                 },
22725         },
22726         [TEMPLATE_BINARY32_REG] = {
22727                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22728                 .rhs = {
22729                         [0] = { REG_VIRT0, REGCM_GPR32 },
22730                         [1] = { REG_UNSET, REGCM_GPR32 },
22731                 },
22732         },
22733         [TEMPLATE_BINARY8_IMM] = {
22734                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22735                 .rhs = {
22736                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
22737                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22738                 },
22739         },
22740         [TEMPLATE_BINARY16_IMM] = {
22741                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22742                 .rhs = {
22743                         [0] = { REG_VIRT0,    REGCM_GPR16 },
22744                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
22745                 },
22746         },
22747         [TEMPLATE_BINARY32_IMM] = {
22748                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22749                 .rhs = {
22750                         [0] = { REG_VIRT0,    REGCM_GPR32 },
22751                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
22752                 },
22753         },
22754         [TEMPLATE_SL8_CL] = {
22755                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22756                 .rhs = {
22757                         [0] = { REG_VIRT0, REGCM_GPR8_LO },
22758                         [1] = { REG_CL, REGCM_GPR8_LO },
22759                 },
22760         },
22761         [TEMPLATE_SL16_CL] = {
22762                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22763                 .rhs = {
22764                         [0] = { REG_VIRT0, REGCM_GPR16 },
22765                         [1] = { REG_CL, REGCM_GPR8_LO },
22766                 },
22767         },
22768         [TEMPLATE_SL32_CL] = {
22769                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22770                 .rhs = {
22771                         [0] = { REG_VIRT0, REGCM_GPR32 },
22772                         [1] = { REG_CL, REGCM_GPR8_LO },
22773                 },
22774         },
22775         [TEMPLATE_SL8_IMM] = {
22776                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22777                 .rhs = {
22778                         [0] = { REG_VIRT0,    REGCM_GPR8_LO },
22779                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22780                 },
22781         },
22782         [TEMPLATE_SL16_IMM] = {
22783                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22784                 .rhs = {
22785                         [0] = { REG_VIRT0,    REGCM_GPR16 },
22786                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22787                 },
22788         },
22789         [TEMPLATE_SL32_IMM] = {
22790                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22791                 .rhs = {
22792                         [0] = { REG_VIRT0,    REGCM_GPR32 },
22793                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22794                 },
22795         },
22796         [TEMPLATE_UNARY8] = {
22797                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22798                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR8_LO } },
22799         },
22800         [TEMPLATE_UNARY16] = {
22801                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22802                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR16 } },
22803         },
22804         [TEMPLATE_UNARY32] = {
22805                 .lhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22806                 .rhs = { [0] = { REG_VIRT0, REGCM_GPR32 } },
22807         },
22808         [TEMPLATE_CMP8_REG] = {
22809                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22810                 .rhs = {
22811                         [0] = { REG_UNSET, REGCM_GPR8_LO },
22812                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22813                 },
22814         },
22815         [TEMPLATE_CMP16_REG] = {
22816                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22817                 .rhs = {
22818                         [0] = { REG_UNSET, REGCM_GPR16 },
22819                         [1] = { REG_UNSET, REGCM_GPR16 },
22820                 },
22821         },
22822         [TEMPLATE_CMP32_REG] = {
22823                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22824                 .rhs = {
22825                         [0] = { REG_UNSET, REGCM_GPR32 },
22826                         [1] = { REG_UNSET, REGCM_GPR32 },
22827                 },
22828         },
22829         [TEMPLATE_CMP8_IMM] = {
22830                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22831                 .rhs = {
22832                         [0] = { REG_UNSET, REGCM_GPR8_LO },
22833                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22834                 },
22835         },
22836         [TEMPLATE_CMP16_IMM] = {
22837                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22838                 .rhs = {
22839                         [0] = { REG_UNSET, REGCM_GPR16 },
22840                         [1] = { REG_UNNEEDED, REGCM_IMM16 },
22841                 },
22842         },
22843         [TEMPLATE_CMP32_IMM] = {
22844                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22845                 .rhs = {
22846                         [0] = { REG_UNSET, REGCM_GPR32 },
22847                         [1] = { REG_UNNEEDED, REGCM_IMM32 },
22848                 },
22849         },
22850         [TEMPLATE_TEST8] = {
22851                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22852                 .rhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22853         },
22854         [TEMPLATE_TEST16] = {
22855                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22856                 .rhs = { [0] = { REG_UNSET, REGCM_GPR16 } },
22857         },
22858         [TEMPLATE_TEST32] = {
22859                 .lhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22860                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22861         },
22862         [TEMPLATE_SET] = {
22863                 .lhs = { [0] = { REG_UNSET, REGCM_GPR8_LO } },
22864                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22865         },
22866         [TEMPLATE_JMP] = {
22867                 .rhs = { [0] = { REG_EFLAGS, REGCM_FLAGS } },
22868         },
22869         [TEMPLATE_RET] = {
22870                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22871         },
22872         [TEMPLATE_INB_DX] = {
22873                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },
22874                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22875         },
22876         [TEMPLATE_INB_IMM] = {
22877                 .lhs = { [0] = { REG_AL,  REGCM_GPR8_LO } },
22878                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22879         },
22880         [TEMPLATE_INW_DX]  = {
22881                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } },
22882                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22883         },
22884         [TEMPLATE_INW_IMM] = {
22885                 .lhs = { [0] = { REG_AX,  REGCM_GPR16 } },
22886                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22887         },
22888         [TEMPLATE_INL_DX]  = {
22889                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22890                 .rhs = { [0] = { REG_DX, REGCM_GPR16 } },
22891         },
22892         [TEMPLATE_INL_IMM] = {
22893                 .lhs = { [0] = { REG_EAX, REGCM_GPR32 } },
22894                 .rhs = { [0] = { REG_UNNEEDED, REGCM_IMM8 } },
22895         },
22896         [TEMPLATE_OUTB_DX] = {
22897                 .rhs = {
22898                         [0] = { REG_AL,  REGCM_GPR8_LO },
22899                         [1] = { REG_DX, REGCM_GPR16 },
22900                 },
22901         },
22902         [TEMPLATE_OUTB_IMM] = {
22903                 .rhs = {
22904                         [0] = { REG_AL,  REGCM_GPR8_LO },
22905                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22906                 },
22907         },
22908         [TEMPLATE_OUTW_DX] = {
22909                 .rhs = {
22910                         [0] = { REG_AX,  REGCM_GPR16 },
22911                         [1] = { REG_DX, REGCM_GPR16 },
22912                 },
22913         },
22914         [TEMPLATE_OUTW_IMM] = {
22915                 .rhs = {
22916                         [0] = { REG_AX,  REGCM_GPR16 },
22917                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22918                 },
22919         },
22920         [TEMPLATE_OUTL_DX] = {
22921                 .rhs = {
22922                         [0] = { REG_EAX, REGCM_GPR32 },
22923                         [1] = { REG_DX, REGCM_GPR16 },
22924                 },
22925         },
22926         [TEMPLATE_OUTL_IMM] = {
22927                 .rhs = {
22928                         [0] = { REG_EAX, REGCM_GPR32 },
22929                         [1] = { REG_UNNEEDED, REGCM_IMM8 },
22930                 },
22931         },
22932         [TEMPLATE_BSF] = {
22933                 .lhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22934                 .rhs = { [0] = { REG_UNSET, REGCM_GPR32 } },
22935         },
22936         [TEMPLATE_RDMSR] = {
22937                 .lhs = {
22938                         [0] = { REG_EAX, REGCM_GPR32 },
22939                         [1] = { REG_EDX, REGCM_GPR32 },
22940                 },
22941                 .rhs = { [0] = { REG_ECX, REGCM_GPR32 } },
22942         },
22943         [TEMPLATE_WRMSR] = {
22944                 .rhs = {
22945                         [0] = { REG_ECX, REGCM_GPR32 },
22946                         [1] = { REG_EAX, REGCM_GPR32 },
22947                         [2] = { REG_EDX, REGCM_GPR32 },
22948                 },
22949         },
22950         [TEMPLATE_UMUL8] = {
22951                 .lhs = { [0] = { REG_AX, REGCM_GPR16 } },
22952                 .rhs = {
22953                         [0] = { REG_AL, REGCM_GPR8_LO },
22954                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22955                 },
22956         },
22957         [TEMPLATE_UMUL16] = {
22958                 .lhs = { [0] = { REG_DXAX, REGCM_DIVIDEND32 } },
22959                 .rhs = {
22960                         [0] = { REG_AX, REGCM_GPR16 },
22961                         [1] = { REG_UNSET, REGCM_GPR16 },
22962                 },
22963         },
22964         [TEMPLATE_UMUL32] = {
22965                 .lhs = { [0] = { REG_EDXEAX, REGCM_DIVIDEND64 } },
22966                 .rhs = {
22967                         [0] = { REG_EAX, REGCM_GPR32 },
22968                         [1] = { REG_UNSET, REGCM_GPR32 },
22969                 },
22970         },
22971         [TEMPLATE_DIV8] = {
22972                 .lhs = {
22973                         [0] = { REG_AL, REGCM_GPR8_LO },
22974                         [1] = { REG_AH, REGCM_GPR8 },
22975                 },
22976                 .rhs = {
22977                         [0] = { REG_AX, REGCM_GPR16 },
22978                         [1] = { REG_UNSET, REGCM_GPR8_LO },
22979                 },
22980         },
22981         [TEMPLATE_DIV16] = {
22982                 .lhs = {
22983                         [0] = { REG_AX, REGCM_GPR16 },
22984                         [1] = { REG_DX, REGCM_GPR16 },
22985                 },
22986                 .rhs = {
22987                         [0] = { REG_DXAX, REGCM_DIVIDEND32 },
22988                         [1] = { REG_UNSET, REGCM_GPR16 },
22989                 },
22990         },
22991         [TEMPLATE_DIV32] = {
22992                 .lhs = {
22993                         [0] = { REG_EAX, REGCM_GPR32 },
22994                         [1] = { REG_EDX, REGCM_GPR32 },
22995                 },
22996                 .rhs = {
22997                         [0] = { REG_EDXEAX, REGCM_DIVIDEND64 },
22998                         [1] = { REG_UNSET, REGCM_GPR32 },
22999                 },
23000         },
23001 };
23002
23003 static void fixup_branch(struct compile_state *state,
23004         struct triple *branch, int jmp_op, int cmp_op, struct type *cmp_type,
23005         struct triple *left, struct triple *right)
23006 {
23007         struct triple *test;
23008         if (!left) {
23009                 internal_error(state, branch, "no branch test?");
23010         }
23011         test = pre_triple(state, branch,
23012                 cmp_op, cmp_type, left, right);
23013         test->template_id = TEMPLATE_TEST32;
23014         if (cmp_op == OP_CMP) {
23015                 test->template_id = TEMPLATE_CMP32_REG;
23016                 if (get_imm32(test, &RHS(test, 1))) {
23017                         test->template_id = TEMPLATE_CMP32_IMM;
23018                 }
23019         }
23020         use_triple(RHS(test, 0), test);
23021         use_triple(RHS(test, 1), test);
23022         unuse_triple(RHS(branch, 0), branch);
23023         RHS(branch, 0) = test;
23024         branch->op = jmp_op;
23025         branch->template_id = TEMPLATE_JMP;
23026         use_triple(RHS(branch, 0), branch);
23027 }
23028
23029 static void fixup_branches(struct compile_state *state,
23030         struct triple *cmp, struct triple *use, int jmp_op)
23031 {
23032         struct triple_set *entry, *next;
23033         for(entry = use->use; entry; entry = next) {
23034                 next = entry->next;
23035                 if (entry->member->op == OP_COPY) {
23036                         fixup_branches(state, cmp, entry->member, jmp_op);
23037                 }
23038                 else if (entry->member->op == OP_CBRANCH) {
23039                         struct triple *branch;
23040                         struct triple *left, *right;
23041                         left = right = 0;
23042                         left = RHS(cmp, 0);
23043                         if (cmp->rhs > 1) {
23044                                 right = RHS(cmp, 1);
23045                         }
23046                         branch = entry->member;
23047                         fixup_branch(state, branch, jmp_op,
23048                                 cmp->op, cmp->type, left, right);
23049                 }
23050         }
23051 }
23052
23053 static void bool_cmp(struct compile_state *state,
23054         struct triple *ins, int cmp_op, int jmp_op, int set_op)
23055 {
23056         struct triple_set *entry, *next;
23057         struct triple *set, *convert;
23058
23059         /* Put a barrier up before the cmp which preceeds the
23060          * copy instruction.  If a set actually occurs this gives
23061          * us a chance to move variables in registers out of the way.
23062          */
23063
23064         /* Modify the comparison operator */
23065         ins->op = cmp_op;
23066         ins->template_id = TEMPLATE_TEST32;
23067         if (cmp_op == OP_CMP) {
23068                 ins->template_id = TEMPLATE_CMP32_REG;
23069                 if (get_imm32(ins, &RHS(ins, 1))) {
23070                         ins->template_id =  TEMPLATE_CMP32_IMM;
23071                 }
23072         }
23073         /* Generate the instruction sequence that will transform the
23074          * result of the comparison into a logical value.
23075          */
23076         set = post_triple(state, ins, set_op, &uchar_type, ins, 0);
23077         use_triple(ins, set);
23078         set->template_id = TEMPLATE_SET;
23079
23080         convert = set;
23081         if (!equiv_types(ins->type, set->type)) {
23082                 convert = post_triple(state, set, OP_CONVERT, ins->type, set, 0);
23083                 use_triple(set, convert);
23084                 convert->template_id = TEMPLATE_COPY32_REG;
23085         }
23086
23087         for(entry = ins->use; entry; entry = next) {
23088                 next = entry->next;
23089                 if (entry->member == set) {
23090                         continue;
23091                 }
23092                 replace_rhs_use(state, ins, convert, entry->member);
23093         }
23094         fixup_branches(state, ins, convert, jmp_op);
23095 }
23096
23097 struct reg_info arch_reg_lhs(struct compile_state *state, struct triple *ins, int index)
23098 {
23099         struct ins_template *template;
23100         struct reg_info result;
23101         int zlhs;
23102         if (ins->op == OP_PIECE) {
23103                 index = ins->u.cval;
23104                 ins = MISC(ins, 0);
23105         }
23106         zlhs = ins->lhs;
23107         if (triple_is_def(state, ins)) {
23108                 zlhs = 1;
23109         }
23110         if (index >= zlhs) {
23111                 internal_error(state, ins, "index %d out of range for %s",
23112                         index, tops(ins->op));
23113         }
23114         switch(ins->op) {
23115         case OP_ASM:
23116                 template = &ins->u.ainfo->tmpl;
23117                 break;
23118         default:
23119                 if (ins->template_id > LAST_TEMPLATE) {
23120                         internal_error(state, ins, "bad template number %d",
23121                                 ins->template_id);
23122                 }
23123                 template = &templates[ins->template_id];
23124                 break;
23125         }
23126         result = template->lhs[index];
23127         result.regcm = arch_regcm_normalize(state, result.regcm);
23128         if (result.reg != REG_UNNEEDED) {
23129                 result.regcm &= ~(REGCM_IMM32 | REGCM_IMM16 | REGCM_IMM8);
23130         }
23131         if (result.regcm == 0) {
23132                 internal_error(state, ins, "lhs %d regcm == 0", index);
23133         }
23134         return result;
23135 }
23136
23137 struct reg_info arch_reg_rhs(struct compile_state *state, struct triple *ins, int index)
23138 {
23139         struct reg_info result;
23140         struct ins_template *template;
23141         if ((index > ins->rhs) ||
23142                 (ins->op == OP_PIECE)) {
23143                 internal_error(state, ins, "index %d out of range for %s\n",
23144                         index, tops(ins->op));
23145         }
23146         switch(ins->op) {
23147         case OP_ASM:
23148                 template = &ins->u.ainfo->tmpl;
23149                 break;
23150         case OP_PHI:
23151                 index = 0;
23152                 /* Fall through */
23153         default:
23154                 if (ins->template_id > LAST_TEMPLATE) {
23155                         internal_error(state, ins, "bad template number %d",
23156                                 ins->template_id);
23157                 }
23158                 template = &templates[ins->template_id];
23159                 break;
23160         }
23161         result = template->rhs[index];
23162         result.regcm = arch_regcm_normalize(state, result.regcm);
23163         if (result.regcm == 0) {
23164                 internal_error(state, ins, "rhs %d regcm == 0", index);
23165         }
23166         return result;
23167 }
23168
23169 static struct triple *mod_div(struct compile_state *state,
23170         struct triple *ins, int div_op, int index)
23171 {
23172         struct triple *div, *piece1;
23173
23174         /* Generate the appropriate division instruction */
23175         div = post_triple(state, ins, div_op, ins->type, 0, 0);
23176         RHS(div, 0) = RHS(ins, 0);
23177         RHS(div, 1) = RHS(ins, 1);
23178         piece1 = LHS(div, 1);
23179         div->template_id  = TEMPLATE_DIV32;
23180         use_triple(RHS(div, 0), div);
23181         use_triple(RHS(div, 1), div);
23182         use_triple(LHS(div, 0), div);
23183         use_triple(LHS(div, 1), div);
23184
23185         /* Replate uses of ins with the appropriate piece of the div */
23186         propogate_use(state, ins, LHS(div, index));
23187         release_triple(state, ins);
23188
23189         /* Return the address of the next instruction */
23190         return piece1->next;
23191 }
23192
23193 static int noop_adecl(struct triple *adecl)
23194 {
23195         struct triple_set *use;
23196         /* It's a noop if it doesn't specify stoorage */
23197         if (adecl->lhs == 0) {
23198                 return 1;
23199         }
23200         /* Is the adecl used? If not it's a noop */
23201         for(use = adecl->use; use ; use = use->next) {
23202                 if ((use->member->op != OP_PIECE) ||
23203                         (MISC(use->member, 0) != adecl)) {
23204                         return 0;
23205                 }
23206         }
23207         return 1;
23208 }
23209
23210 static struct triple *x86_deposit(struct compile_state *state, struct triple *ins)
23211 {
23212         struct triple *mask, *nmask, *shift;
23213         struct triple *val, *val_mask, *val_shift;
23214         struct triple *targ, *targ_mask;
23215         struct triple *new;
23216         ulong_t the_mask, the_nmask;
23217
23218         targ = RHS(ins, 0);
23219         val = RHS(ins, 1);
23220
23221         /* Get constant for the mask value */
23222         the_mask = 1;
23223         the_mask <<= ins->u.bitfield.size;
23224         the_mask -= 1;
23225         the_mask <<= ins->u.bitfield.offset;
23226         mask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23227         mask->u.cval = the_mask;
23228
23229         /* Get the inverted mask value */
23230         the_nmask = ~the_mask;
23231         nmask = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23232         nmask->u.cval = the_nmask;
23233
23234         /* Get constant for the shift value */
23235         shift = pre_triple(state, ins, OP_INTCONST, &uint_type, 0, 0);
23236         shift->u.cval = ins->u.bitfield.offset;
23237
23238         /* Shift and mask the source value */
23239         val_shift = val;
23240         if (shift->u.cval != 0) {
23241                 val_shift = pre_triple(state, ins, OP_SL, val->type, val, shift);
23242                 use_triple(val, val_shift);
23243                 use_triple(shift, val_shift);
23244         }
23245         val_mask = val_shift;
23246         if (is_signed(val->type)) {
23247                 val_mask = pre_triple(state, ins, OP_AND, val->type, val_shift, mask);
23248                 use_triple(val_shift, val_mask);
23249                 use_triple(mask, val_mask);
23250         }
23251
23252         /* Mask the target value */
23253         targ_mask = pre_triple(state, ins, OP_AND, targ->type, targ, nmask);
23254         use_triple(targ, targ_mask);
23255         use_triple(nmask, targ_mask);
23256
23257         /* Now combined them together */
23258         new = pre_triple(state, ins, OP_OR, targ->type, targ_mask, val_mask);
23259         use_triple(targ_mask, new);
23260         use_triple(val_mask, new);
23261
23262         /* Move all of the users over to the new expression */
23263         propogate_use(state, ins, new);
23264
23265         /* Delete the original triple */
23266         release_triple(state, ins);
23267
23268         /* Restart the transformation at mask */
23269         return mask;
23270 }
23271
23272 static struct triple *x86_extract(struct compile_state *state, struct triple *ins)
23273 {
23274         struct triple *mask, *shift;
23275         struct triple *val, *val_mask, *val_shift;
23276         ulong_t the_mask;
23277
23278         val = RHS(ins, 0);
23279
23280         /* Get constant for the mask value */
23281         the_mask = 1;
23282         the_mask <<= ins->u.bitfield.size;
23283         the_mask -= 1;
23284         mask = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23285         mask->u.cval = the_mask;
23286
23287         /* Get constant for the right shift value */
23288         shift = pre_triple(state, ins, OP_INTCONST, &int_type, 0, 0);
23289         shift->u.cval = ins->u.bitfield.offset;
23290
23291         /* Shift arithmetic right, to correct the sign */
23292         val_shift = val;
23293         if (shift->u.cval != 0) {
23294                 int op;
23295                 if (ins->op == OP_SEXTRACT) {
23296                         op = OP_SSR;
23297                 } else {
23298                         op = OP_USR;
23299                 }
23300                 val_shift = pre_triple(state, ins, op, val->type, val, shift);
23301                 use_triple(val, val_shift);
23302                 use_triple(shift, val_shift);
23303         }
23304
23305         /* Finally mask the value */
23306         val_mask = pre_triple(state, ins, OP_AND, ins->type, val_shift, mask);
23307         use_triple(val_shift, val_mask);
23308         use_triple(mask,      val_mask);
23309
23310         /* Move all of the users over to the new expression */
23311         propogate_use(state, ins, val_mask);
23312
23313         /* Release the original instruction */
23314         release_triple(state, ins);
23315
23316         return mask;
23317
23318 }
23319
23320 static struct triple *transform_to_arch_instruction(
23321         struct compile_state *state, struct triple *ins)
23322 {
23323         /* Transform from generic 3 address instructions
23324          * to archtecture specific instructions.
23325          * And apply architecture specific constraints to instructions.
23326          * Copies are inserted to preserve the register flexibility
23327          * of 3 address instructions.
23328          */
23329         struct triple *next, *value;
23330         size_t size;
23331         next = ins->next;
23332         switch(ins->op) {
23333         case OP_INTCONST:
23334                 ins->template_id = TEMPLATE_INTCONST32;
23335                 if (ins->u.cval < 256) {
23336                         ins->template_id = TEMPLATE_INTCONST8;
23337                 }
23338                 break;
23339         case OP_ADDRCONST:
23340                 ins->template_id = TEMPLATE_INTCONST32;
23341                 break;
23342         case OP_UNKNOWNVAL:
23343                 ins->template_id = TEMPLATE_UNKNOWNVAL;
23344                 break;
23345         case OP_NOOP:
23346         case OP_SDECL:
23347         case OP_BLOBCONST:
23348         case OP_LABEL:
23349                 ins->template_id = TEMPLATE_NOP;
23350                 break;
23351         case OP_COPY:
23352         case OP_CONVERT:
23353                 size = size_of(state, ins->type);
23354                 value = RHS(ins, 0);
23355                 if (is_imm8(value) && (size <= SIZEOF_I8)) {
23356                         ins->template_id = TEMPLATE_COPY_IMM8;
23357                 }
23358                 else if (is_imm16(value) && (size <= SIZEOF_I16)) {
23359                         ins->template_id = TEMPLATE_COPY_IMM16;
23360                 }
23361                 else if (is_imm32(value) && (size <= SIZEOF_I32)) {
23362                         ins->template_id = TEMPLATE_COPY_IMM32;
23363                 }
23364                 else if (is_const(value)) {
23365                         internal_error(state, ins, "bad constant passed to copy");
23366                 }
23367                 else if (size <= SIZEOF_I8) {
23368                         ins->template_id = TEMPLATE_COPY8_REG;
23369                 }
23370                 else if (size <= SIZEOF_I16) {
23371                         ins->template_id = TEMPLATE_COPY16_REG;
23372                 }
23373                 else if (size <= SIZEOF_I32) {
23374                         ins->template_id = TEMPLATE_COPY32_REG;
23375                 }
23376                 else {
23377                         internal_error(state, ins, "bad type passed to copy");
23378                 }
23379                 break;
23380         case OP_PHI:
23381                 size = size_of(state, ins->type);
23382                 if (size <= SIZEOF_I8) {
23383                         ins->template_id = TEMPLATE_PHI8;
23384                 }
23385                 else if (size <= SIZEOF_I16) {
23386                         ins->template_id = TEMPLATE_PHI16;
23387                 }
23388                 else if (size <= SIZEOF_I32) {
23389                         ins->template_id = TEMPLATE_PHI32;
23390                 }
23391                 else {
23392                         internal_error(state, ins, "bad type passed to phi");
23393                 }
23394                 break;
23395         case OP_ADECL:
23396                 /* Adecls should always be treated as dead code and
23397                  * removed.  If we are not optimizing they may linger.
23398                  */
23399                 if (!noop_adecl(ins)) {
23400                         internal_error(state, ins, "adecl remains?");
23401                 }
23402                 ins->template_id = TEMPLATE_NOP;
23403                 next = after_lhs(state, ins);
23404                 break;
23405         case OP_STORE:
23406                 switch(ins->type->type & TYPE_MASK) {
23407                 case TYPE_CHAR:    case TYPE_UCHAR:
23408                         ins->template_id = TEMPLATE_STORE8;
23409                         break;
23410                 case TYPE_SHORT:   case TYPE_USHORT:
23411                         ins->template_id = TEMPLATE_STORE16;
23412                         break;
23413                 case TYPE_INT:     case TYPE_UINT:
23414                 case TYPE_LONG:    case TYPE_ULONG:
23415                 case TYPE_POINTER:
23416                         ins->template_id = TEMPLATE_STORE32;
23417                         break;
23418                 default:
23419                         internal_error(state, ins, "unknown type in store");
23420                         break;
23421                 }
23422                 break;
23423         case OP_LOAD:
23424                 switch(ins->type->type & TYPE_MASK) {
23425                 case TYPE_CHAR:   case TYPE_UCHAR:
23426                 case TYPE_SHORT:  case TYPE_USHORT:
23427                 case TYPE_INT:    case TYPE_UINT:
23428                 case TYPE_LONG:   case TYPE_ULONG:
23429                 case TYPE_POINTER:
23430                         break;
23431                 default:
23432                         internal_error(state, ins, "unknown type in load");
23433                         break;
23434                 }
23435                 ins->template_id = TEMPLATE_LOAD32;
23436                 break;
23437         case OP_ADD:
23438         case OP_SUB:
23439         case OP_AND:
23440         case OP_XOR:
23441         case OP_OR:
23442         case OP_SMUL:
23443                 ins->template_id = TEMPLATE_BINARY32_REG;
23444                 if (get_imm32(ins, &RHS(ins, 1))) {
23445                         ins->template_id = TEMPLATE_BINARY32_IMM;
23446                 }
23447                 break;
23448         case OP_SDIVT:
23449         case OP_UDIVT:
23450                 ins->template_id = TEMPLATE_DIV32;
23451                 next = after_lhs(state, ins);
23452                 break;
23453         case OP_UMUL:
23454                 ins->template_id = TEMPLATE_UMUL32;
23455                 break;
23456         case OP_UDIV:
23457                 next = mod_div(state, ins, OP_UDIVT, 0);
23458                 break;
23459         case OP_SDIV:
23460                 next = mod_div(state, ins, OP_SDIVT, 0);
23461                 break;
23462         case OP_UMOD:
23463                 next = mod_div(state, ins, OP_UDIVT, 1);
23464                 break;
23465         case OP_SMOD:
23466                 next = mod_div(state, ins, OP_SDIVT, 1);
23467                 break;
23468         case OP_SL:
23469         case OP_SSR:
23470         case OP_USR:
23471                 ins->template_id = TEMPLATE_SL32_CL;
23472                 if (get_imm8(ins, &RHS(ins, 1))) {
23473                         ins->template_id = TEMPLATE_SL32_IMM;
23474                 } else if (size_of(state, RHS(ins, 1)->type) > SIZEOF_CHAR) {
23475                         typed_pre_copy(state, &uchar_type, ins, 1);
23476                 }
23477                 break;
23478         case OP_INVERT:
23479         case OP_NEG:
23480                 ins->template_id = TEMPLATE_UNARY32;
23481                 break;
23482         case OP_EQ:
23483                 bool_cmp(state, ins, OP_CMP, OP_JMP_EQ, OP_SET_EQ);
23484                 break;
23485         case OP_NOTEQ:
23486                 bool_cmp(state, ins, OP_CMP, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23487                 break;
23488         case OP_SLESS:
23489                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESS, OP_SET_SLESS);
23490                 break;
23491         case OP_ULESS:
23492                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESS, OP_SET_ULESS);
23493                 break;
23494         case OP_SMORE:
23495                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMORE, OP_SET_SMORE);
23496                 break;
23497         case OP_UMORE:
23498                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMORE, OP_SET_UMORE);
23499                 break;
23500         case OP_SLESSEQ:
23501                 bool_cmp(state, ins, OP_CMP, OP_JMP_SLESSEQ, OP_SET_SLESSEQ);
23502                 break;
23503         case OP_ULESSEQ:
23504                 bool_cmp(state, ins, OP_CMP, OP_JMP_ULESSEQ, OP_SET_ULESSEQ);
23505                 break;
23506         case OP_SMOREEQ:
23507                 bool_cmp(state, ins, OP_CMP, OP_JMP_SMOREEQ, OP_SET_SMOREEQ);
23508                 break;
23509         case OP_UMOREEQ:
23510                 bool_cmp(state, ins, OP_CMP, OP_JMP_UMOREEQ, OP_SET_UMOREEQ);
23511                 break;
23512         case OP_LTRUE:
23513                 bool_cmp(state, ins, OP_TEST, OP_JMP_NOTEQ, OP_SET_NOTEQ);
23514                 break;
23515         case OP_LFALSE:
23516                 bool_cmp(state, ins, OP_TEST, OP_JMP_EQ, OP_SET_EQ);
23517                 break;
23518         case OP_BRANCH:
23519                 ins->op = OP_JMP;
23520                 ins->template_id = TEMPLATE_NOP;
23521                 break;
23522         case OP_CBRANCH:
23523                 fixup_branch(state, ins, OP_JMP_NOTEQ, OP_TEST,
23524                         RHS(ins, 0)->type, RHS(ins, 0), 0);
23525                 break;
23526         case OP_CALL:
23527                 ins->template_id = TEMPLATE_NOP;
23528                 break;
23529         case OP_RET:
23530                 ins->template_id = TEMPLATE_RET;
23531                 break;
23532         case OP_INB:
23533         case OP_INW:
23534         case OP_INL:
23535                 switch(ins->op) {
23536                 case OP_INB: ins->template_id = TEMPLATE_INB_DX; break;
23537                 case OP_INW: ins->template_id = TEMPLATE_INW_DX; break;
23538                 case OP_INL: ins->template_id = TEMPLATE_INL_DX; break;
23539                 }
23540                 if (get_imm8(ins, &RHS(ins, 0))) {
23541                         ins->template_id += 1;
23542                 }
23543                 break;
23544         case OP_OUTB:
23545         case OP_OUTW:
23546         case OP_OUTL:
23547                 switch(ins->op) {
23548                 case OP_OUTB: ins->template_id = TEMPLATE_OUTB_DX; break;
23549                 case OP_OUTW: ins->template_id = TEMPLATE_OUTW_DX; break;
23550                 case OP_OUTL: ins->template_id = TEMPLATE_OUTL_DX; break;
23551                 }
23552                 if (get_imm8(ins, &RHS(ins, 1))) {
23553                         ins->template_id += 1;
23554                 }
23555                 break;
23556         case OP_BSF:
23557         case OP_BSR:
23558                 ins->template_id = TEMPLATE_BSF;
23559                 break;
23560         case OP_RDMSR:
23561                 ins->template_id = TEMPLATE_RDMSR;
23562                 next = after_lhs(state, ins);
23563                 break;
23564         case OP_WRMSR:
23565                 ins->template_id = TEMPLATE_WRMSR;
23566                 break;
23567         case OP_HLT:
23568                 ins->template_id = TEMPLATE_NOP;
23569                 break;
23570         case OP_ASM:
23571                 ins->template_id = TEMPLATE_NOP;
23572                 next = after_lhs(state, ins);
23573                 break;
23574                 /* Already transformed instructions */
23575         case OP_TEST:
23576                 ins->template_id = TEMPLATE_TEST32;
23577                 break;
23578         case OP_CMP:
23579                 ins->template_id = TEMPLATE_CMP32_REG;
23580                 if (get_imm32(ins, &RHS(ins, 1))) {
23581                         ins->template_id = TEMPLATE_CMP32_IMM;
23582                 }
23583                 break;
23584         case OP_JMP:
23585                 ins->template_id = TEMPLATE_NOP;
23586                 break;
23587         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
23588         case OP_JMP_SLESS:   case OP_JMP_ULESS:
23589         case OP_JMP_SMORE:   case OP_JMP_UMORE:
23590         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
23591         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
23592                 ins->template_id = TEMPLATE_JMP;
23593                 break;
23594         case OP_SET_EQ:      case OP_SET_NOTEQ:
23595         case OP_SET_SLESS:   case OP_SET_ULESS:
23596         case OP_SET_SMORE:   case OP_SET_UMORE:
23597         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
23598         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
23599                 ins->template_id = TEMPLATE_SET;
23600                 break;
23601         case OP_DEPOSIT:
23602                 next = x86_deposit(state, ins);
23603                 break;
23604         case OP_SEXTRACT:
23605         case OP_UEXTRACT:
23606                 next = x86_extract(state, ins);
23607                 break;
23608                 /* Unhandled instructions */
23609         case OP_PIECE:
23610         default:
23611                 internal_error(state, ins, "unhandled ins: %d %s",
23612                         ins->op, tops(ins->op));
23613                 break;
23614         }
23615         return next;
23616 }
23617
23618 static long next_label(struct compile_state *state)
23619 {
23620         static long label_counter = 1000;
23621         return ++label_counter;
23622 }
23623 static void generate_local_labels(struct compile_state *state)
23624 {
23625         struct triple *first, *label;
23626         first = state->first;
23627         label = first;
23628         do {
23629                 if ((label->op == OP_LABEL) ||
23630                         (label->op == OP_SDECL)) {
23631                         if (label->use) {
23632                                 label->u.cval = next_label(state);
23633                         } else {
23634                                 label->u.cval = 0;
23635                         }
23636
23637                 }
23638                 label = label->next;
23639         } while(label != first);
23640 }
23641
23642 static int check_reg(struct compile_state *state,
23643         struct triple *triple, int classes)
23644 {
23645         unsigned mask;
23646         int reg;
23647         reg = ID_REG(triple->id);
23648         if (reg == REG_UNSET) {
23649                 internal_error(state, triple, "register not set");
23650         }
23651         mask = arch_reg_regcm(state, reg);
23652         if (!(classes & mask)) {
23653                 internal_error(state, triple, "reg %d in wrong class",
23654                         reg);
23655         }
23656         return reg;
23657 }
23658
23659
23660 #if REG_XMM7 != 44
23661 #error "Registers have renumberd fix arch_reg_str"
23662 #endif
23663 static const char *arch_regs[] = {
23664         "%unset",
23665         "%unneeded",
23666         "%eflags",
23667         "%al", "%bl", "%cl", "%dl", "%ah", "%bh", "%ch", "%dh",
23668         "%ax", "%bx", "%cx", "%dx", "%si", "%di", "%bp", "%sp",
23669         "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi", "%ebp", "%esp",
23670         "%edx:%eax",
23671         "%dx:%ax",
23672         "%mm0", "%mm1", "%mm2", "%mm3", "%mm4", "%mm5", "%mm6", "%mm7",
23673         "%xmm0", "%xmm1", "%xmm2", "%xmm3",
23674         "%xmm4", "%xmm5", "%xmm6", "%xmm7",
23675 };
23676 static const char *arch_reg_str(int reg)
23677 {
23678         if (!((reg >= REG_EFLAGS) && (reg <= REG_XMM7))) {
23679                 reg = 0;
23680         }
23681         return arch_regs[reg];
23682 }
23683
23684 static const char *reg(struct compile_state *state, struct triple *triple,
23685         int classes)
23686 {
23687         int reg;
23688         reg = check_reg(state, triple, classes);
23689         return arch_reg_str(reg);
23690 }
23691
23692 static int arch_reg_size(int reg)
23693 {
23694         int size;
23695         size = 0;
23696         if (reg == REG_EFLAGS) {
23697                 size = 32;
23698         }
23699         else if ((reg >= REG_AL) && (reg <= REG_DH)) {
23700                 size = 8;
23701         }
23702         else if ((reg >= REG_AX) && (reg <= REG_SP)) {
23703                 size = 16;
23704         }
23705         else if ((reg >= REG_EAX) && (reg <= REG_ESP)) {
23706                 size = 32;
23707         }
23708         else if (reg == REG_EDXEAX) {
23709                 size = 64;
23710         }
23711         else if (reg == REG_DXAX) {
23712                 size = 32;
23713         }
23714         else if ((reg >= REG_MMX0) && (reg <= REG_MMX7)) {
23715                 size = 64;
23716         }
23717         else if ((reg >= REG_XMM0) && (reg <= REG_XMM7)) {
23718                 size = 128;
23719         }
23720         return size;
23721 }
23722
23723 static int reg_size(struct compile_state *state, struct triple *ins)
23724 {
23725         int reg;
23726         reg = ID_REG(ins->id);
23727         if (reg == REG_UNSET) {
23728                 internal_error(state, ins, "register not set");
23729         }
23730         return arch_reg_size(reg);
23731 }
23732
23733
23734
23735 const char *type_suffix(struct compile_state *state, struct type *type)
23736 {
23737         const char *suffix;
23738         switch(size_of(state, type)) {
23739         case SIZEOF_I8:  suffix = "b"; break;
23740         case SIZEOF_I16: suffix = "w"; break;
23741         case SIZEOF_I32: suffix = "l"; break;
23742         default:
23743                 internal_error(state, 0, "unknown suffix");
23744                 suffix = 0;
23745                 break;
23746         }
23747         return suffix;
23748 }
23749
23750 static void print_const_val(
23751         struct compile_state *state, struct triple *ins, FILE *fp)
23752 {
23753         switch(ins->op) {
23754         case OP_INTCONST:
23755                 fprintf(fp, " $%ld ",
23756                         (long)(ins->u.cval));
23757                 break;
23758         case OP_ADDRCONST:
23759                 if ((MISC(ins, 0)->op != OP_SDECL) &&
23760                         (MISC(ins, 0)->op != OP_LABEL))
23761                 {
23762                         internal_error(state, ins, "bad base for addrconst");
23763                 }
23764                 if (MISC(ins, 0)->u.cval <= 0) {
23765                         internal_error(state, ins, "unlabeled constant");
23766                 }
23767                 fprintf(fp, " $L%s%lu+%lu ",
23768                         state->compiler->label_prefix,
23769                         (unsigned long)(MISC(ins, 0)->u.cval),
23770                         (unsigned long)(ins->u.cval));
23771                 break;
23772         default:
23773                 internal_error(state, ins, "unknown constant type");
23774                 break;
23775         }
23776 }
23777
23778 static void print_const(struct compile_state *state,
23779         struct triple *ins, FILE *fp)
23780 {
23781         switch(ins->op) {
23782         case OP_INTCONST:
23783                 switch(ins->type->type & TYPE_MASK) {
23784                 case TYPE_CHAR:
23785                 case TYPE_UCHAR:
23786                         fprintf(fp, ".byte 0x%02lx\n",
23787                                 (unsigned long)(ins->u.cval));
23788                         break;
23789                 case TYPE_SHORT:
23790                 case TYPE_USHORT:
23791                         fprintf(fp, ".short 0x%04lx\n",
23792                                 (unsigned long)(ins->u.cval));
23793                         break;
23794                 case TYPE_INT:
23795                 case TYPE_UINT:
23796                 case TYPE_LONG:
23797                 case TYPE_ULONG:
23798                 case TYPE_POINTER:
23799                         fprintf(fp, ".int %lu\n",
23800                                 (unsigned long)(ins->u.cval));
23801                         break;
23802                 default:
23803                         fprintf(state->errout, "type: ");
23804                         name_of(state->errout, ins->type);
23805                         fprintf(state->errout, "\n");
23806                         internal_error(state, ins, "Unknown constant type. Val: %lu",
23807                                 (unsigned long)(ins->u.cval));
23808                 }
23809
23810                 break;
23811         case OP_ADDRCONST:
23812                 if ((MISC(ins, 0)->op != OP_SDECL) &&
23813                         (MISC(ins, 0)->op != OP_LABEL)) {
23814                         internal_error(state, ins, "bad base for addrconst");
23815                 }
23816                 if (MISC(ins, 0)->u.cval <= 0) {
23817                         internal_error(state, ins, "unlabeled constant");
23818                 }
23819                 fprintf(fp, ".int L%s%lu+%lu\n",
23820                         state->compiler->label_prefix,
23821                         (unsigned long)(MISC(ins, 0)->u.cval),
23822                         (unsigned long)(ins->u.cval));
23823                 break;
23824         case OP_BLOBCONST:
23825         {
23826                 unsigned char *blob;
23827                 size_t size, i;
23828                 size = size_of_in_bytes(state, ins->type);
23829                 blob = ins->u.blob;
23830                 for(i = 0; i < size; i++) {
23831                         fprintf(fp, ".byte 0x%02x\n",
23832                                 blob[i]);
23833                 }
23834                 break;
23835         }
23836         default:
23837                 internal_error(state, ins, "Unknown constant type");
23838                 break;
23839         }
23840 }
23841
23842 #define TEXT_SECTION ".rom.text"
23843 #define DATA_SECTION ".rom.data"
23844
23845 static long get_const_pool_ref(
23846         struct compile_state *state, struct triple *ins, size_t size, FILE *fp)
23847 {
23848         size_t fill_bytes;
23849         long ref;
23850         ref = next_label(state);
23851         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
23852         fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
23853         fprintf(fp, "L%s%lu:\n", state->compiler->label_prefix, ref);
23854         print_const(state, ins, fp);
23855         fill_bytes = bits_to_bytes(size - size_of(state, ins->type));
23856         if (fill_bytes) {
23857                 fprintf(fp, ".fill %ld, 1, 0\n", (long int)fill_bytes);
23858         }
23859         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
23860         return ref;
23861 }
23862
23863 static long get_mask_pool_ref(
23864         struct compile_state *state, struct triple *ins, unsigned long mask, FILE *fp)
23865 {
23866         long ref;
23867         if (mask == 0xff) {
23868                 ref = 1;
23869         }
23870         else if (mask == 0xffff) {
23871                 ref = 2;
23872         }
23873         else {
23874                 ref = 0;
23875                 internal_error(state, ins, "unhandled mask value");
23876         }
23877         return ref;
23878 }
23879
23880 static void print_binary_op(struct compile_state *state,
23881         const char *op, struct triple *ins, FILE *fp)
23882 {
23883         unsigned mask;
23884         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23885         if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23886                 internal_error(state, ins, "invalid register assignment");
23887         }
23888         if (is_const(RHS(ins, 1))) {
23889                 fprintf(fp, "\t%s ", op);
23890                 print_const_val(state, RHS(ins, 1), fp);
23891                 fprintf(fp, ", %s\n",
23892                         reg(state, RHS(ins, 0), mask));
23893         }
23894         else {
23895                 unsigned lmask, rmask;
23896                 int lreg, rreg;
23897                 lreg = check_reg(state, RHS(ins, 0), mask);
23898                 rreg = check_reg(state, RHS(ins, 1), mask);
23899                 lmask = arch_reg_regcm(state, lreg);
23900                 rmask = arch_reg_regcm(state, rreg);
23901                 mask = lmask & rmask;
23902                 fprintf(fp, "\t%s %s, %s\n",
23903                         op,
23904                         reg(state, RHS(ins, 1), mask),
23905                         reg(state, RHS(ins, 0), mask));
23906         }
23907 }
23908 static void print_unary_op(struct compile_state *state,
23909         const char *op, struct triple *ins, FILE *fp)
23910 {
23911         unsigned mask;
23912         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23913         fprintf(fp, "\t%s %s\n",
23914                 op,
23915                 reg(state, RHS(ins, 0), mask));
23916 }
23917
23918 static void print_op_shift(struct compile_state *state,
23919         const char *op, struct triple *ins, FILE *fp)
23920 {
23921         unsigned mask;
23922         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
23923         if (ID_REG(RHS(ins, 0)->id) != ID_REG(ins->id)) {
23924                 internal_error(state, ins, "invalid register assignment");
23925         }
23926         if (is_const(RHS(ins, 1))) {
23927                 fprintf(fp, "\t%s ", op);
23928                 print_const_val(state, RHS(ins, 1), fp);
23929                 fprintf(fp, ", %s\n",
23930                         reg(state, RHS(ins, 0), mask));
23931         }
23932         else {
23933                 fprintf(fp, "\t%s %s, %s\n",
23934                         op,
23935                         reg(state, RHS(ins, 1), REGCM_GPR8_LO),
23936                         reg(state, RHS(ins, 0), mask));
23937         }
23938 }
23939
23940 static void print_op_in(struct compile_state *state, struct triple *ins, FILE *fp)
23941 {
23942         const char *op;
23943         int mask;
23944         int dreg;
23945         mask = 0;
23946         switch(ins->op) {
23947         case OP_INB: op = "inb", mask = REGCM_GPR8_LO; break;
23948         case OP_INW: op = "inw", mask = REGCM_GPR16; break;
23949         case OP_INL: op = "inl", mask = REGCM_GPR32; break;
23950         default:
23951                 internal_error(state, ins, "not an in operation");
23952                 op = 0;
23953                 break;
23954         }
23955         dreg = check_reg(state, ins, mask);
23956         if (!reg_is_reg(state, dreg, REG_EAX)) {
23957                 internal_error(state, ins, "dst != %%eax");
23958         }
23959         if (is_const(RHS(ins, 0))) {
23960                 fprintf(fp, "\t%s ", op);
23961                 print_const_val(state, RHS(ins, 0), fp);
23962                 fprintf(fp, ", %s\n",
23963                         reg(state, ins, mask));
23964         }
23965         else {
23966                 int addr_reg;
23967                 addr_reg = check_reg(state, RHS(ins, 0), REGCM_GPR16);
23968                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
23969                         internal_error(state, ins, "src != %%dx");
23970                 }
23971                 fprintf(fp, "\t%s %s, %s\n",
23972                         op,
23973                         reg(state, RHS(ins, 0), REGCM_GPR16),
23974                         reg(state, ins, mask));
23975         }
23976 }
23977
23978 static void print_op_out(struct compile_state *state, struct triple *ins, FILE *fp)
23979 {
23980         const char *op;
23981         int mask;
23982         int lreg;
23983         mask = 0;
23984         switch(ins->op) {
23985         case OP_OUTB: op = "outb", mask = REGCM_GPR8_LO; break;
23986         case OP_OUTW: op = "outw", mask = REGCM_GPR16; break;
23987         case OP_OUTL: op = "outl", mask = REGCM_GPR32; break;
23988         default:
23989                 internal_error(state, ins, "not an out operation");
23990                 op = 0;
23991                 break;
23992         }
23993         lreg = check_reg(state, RHS(ins, 0), mask);
23994         if (!reg_is_reg(state, lreg, REG_EAX)) {
23995                 internal_error(state, ins, "src != %%eax");
23996         }
23997         if (is_const(RHS(ins, 1))) {
23998                 fprintf(fp, "\t%s %s,",
23999                         op, reg(state, RHS(ins, 0), mask));
24000                 print_const_val(state, RHS(ins, 1), fp);
24001                 fprintf(fp, "\n");
24002         }
24003         else {
24004                 int addr_reg;
24005                 addr_reg = check_reg(state, RHS(ins, 1), REGCM_GPR16);
24006                 if (!reg_is_reg(state, addr_reg, REG_DX)) {
24007                         internal_error(state, ins, "dst != %%dx");
24008                 }
24009                 fprintf(fp, "\t%s %s, %s\n",
24010                         op,
24011                         reg(state, RHS(ins, 0), mask),
24012                         reg(state, RHS(ins, 1), REGCM_GPR16));
24013         }
24014 }
24015
24016 static void print_op_move(struct compile_state *state,
24017         struct triple *ins, FILE *fp)
24018 {
24019         /* op_move is complex because there are many types
24020          * of registers we can move between.
24021          * Because OP_COPY will be introduced in arbitrary locations
24022          * OP_COPY must not affect flags.
24023          * OP_CONVERT can change the flags and it is the only operation
24024          * where it is expected the types in the registers can change.
24025          */
24026         int omit_copy = 1; /* Is it o.k. to omit a noop copy? */
24027         struct triple *dst, *src;
24028         if (state->arch->features & X86_NOOP_COPY) {
24029                 omit_copy = 0;
24030         }
24031         if ((ins->op == OP_COPY) || (ins->op == OP_CONVERT)) {
24032                 src = RHS(ins, 0);
24033                 dst = ins;
24034         }
24035         else {
24036                 internal_error(state, ins, "unknown move operation");
24037                 src = dst = 0;
24038         }
24039         if (reg_size(state, dst) < size_of(state, dst->type)) {
24040                 internal_error(state, ins, "Invalid destination register");
24041         }
24042         if (!equiv_types(src->type, dst->type) && (dst->op == OP_COPY)) {
24043                 fprintf(state->errout, "src type: ");
24044                 name_of(state->errout, src->type);
24045                 fprintf(state->errout, "\n");
24046                 fprintf(state->errout, "dst type: ");
24047                 name_of(state->errout, dst->type);
24048                 fprintf(state->errout, "\n");
24049                 internal_error(state, ins, "Type mismatch for OP_COPY");
24050         }
24051
24052         if (!is_const(src)) {
24053                 int src_reg, dst_reg;
24054                 int src_regcm, dst_regcm;
24055                 src_reg   = ID_REG(src->id);
24056                 dst_reg   = ID_REG(dst->id);
24057                 src_regcm = arch_reg_regcm(state, src_reg);
24058                 dst_regcm = arch_reg_regcm(state, dst_reg);
24059                 /* If the class is the same just move the register */
24060                 if (src_regcm & dst_regcm &
24061                         (REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32)) {
24062                         if ((src_reg != dst_reg) || !omit_copy) {
24063                                 fprintf(fp, "\tmov %s, %s\n",
24064                                         reg(state, src, src_regcm),
24065                                         reg(state, dst, dst_regcm));
24066                         }
24067                 }
24068                 /* Move 32bit to 16bit */
24069                 else if ((src_regcm & REGCM_GPR32) &&
24070                         (dst_regcm & REGCM_GPR16)) {
24071                         src_reg = (src_reg - REGC_GPR32_FIRST) + REGC_GPR16_FIRST;
24072                         if ((src_reg != dst_reg) || !omit_copy) {
24073                                 fprintf(fp, "\tmovw %s, %s\n",
24074                                         arch_reg_str(src_reg),
24075                                         arch_reg_str(dst_reg));
24076                         }
24077                 }
24078                 /* Move from 32bit gprs to 16bit gprs */
24079                 else if ((src_regcm & REGCM_GPR32) &&
24080                         (dst_regcm & REGCM_GPR16)) {
24081                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24082                         if ((src_reg != dst_reg) || !omit_copy) {
24083                                 fprintf(fp, "\tmov %s, %s\n",
24084                                         arch_reg_str(src_reg),
24085                                         arch_reg_str(dst_reg));
24086                         }
24087                 }
24088                 /* Move 32bit to 8bit */
24089                 else if ((src_regcm & REGCM_GPR32_8) &&
24090                         (dst_regcm & REGCM_GPR8_LO))
24091                 {
24092                         src_reg = (src_reg - REGC_GPR32_8_FIRST) + REGC_GPR8_FIRST;
24093                         if ((src_reg != dst_reg) || !omit_copy) {
24094                                 fprintf(fp, "\tmovb %s, %s\n",
24095                                         arch_reg_str(src_reg),
24096                                         arch_reg_str(dst_reg));
24097                         }
24098                 }
24099                 /* Move 16bit to 8bit */
24100                 else if ((src_regcm & REGCM_GPR16_8) &&
24101                         (dst_regcm & REGCM_GPR8_LO))
24102                 {
24103                         src_reg = (src_reg - REGC_GPR16_8_FIRST) + REGC_GPR8_FIRST;
24104                         if ((src_reg != dst_reg) || !omit_copy) {
24105                                 fprintf(fp, "\tmovb %s, %s\n",
24106                                         arch_reg_str(src_reg),
24107                                         arch_reg_str(dst_reg));
24108                         }
24109                 }
24110                 /* Move 8/16bit to 16/32bit */
24111                 else if ((src_regcm & (REGCM_GPR8_LO | REGCM_GPR16)) &&
24112                         (dst_regcm & (REGCM_GPR16 | REGCM_GPR32))) {
24113                         const char *op;
24114                         op = is_signed(src->type)? "movsx": "movzx";
24115                         fprintf(fp, "\t%s %s, %s\n",
24116                                 op,
24117                                 reg(state, src, src_regcm),
24118                                 reg(state, dst, dst_regcm));
24119                 }
24120                 /* Move between sse registers */
24121                 else if ((src_regcm & dst_regcm & REGCM_XMM)) {
24122                         if ((src_reg != dst_reg) || !omit_copy) {
24123                                 fprintf(fp, "\tmovdqa %s, %s\n",
24124                                         reg(state, src, src_regcm),
24125                                         reg(state, dst, dst_regcm));
24126                         }
24127                 }
24128                 /* Move between mmx registers */
24129                 else if ((src_regcm & dst_regcm & REGCM_MMX)) {
24130                         if ((src_reg != dst_reg) || !omit_copy) {
24131                                 fprintf(fp, "\tmovq %s, %s\n",
24132                                         reg(state, src, src_regcm),
24133                                         reg(state, dst, dst_regcm));
24134                         }
24135                 }
24136                 /* Move from sse to mmx registers */
24137                 else if ((src_regcm & REGCM_XMM) && (dst_regcm & REGCM_MMX)) {
24138                         fprintf(fp, "\tmovdq2q %s, %s\n",
24139                                 reg(state, src, src_regcm),
24140                                 reg(state, dst, dst_regcm));
24141                 }
24142                 /* Move from mmx to sse registers */
24143                 else if ((src_regcm & REGCM_MMX) && (dst_regcm & REGCM_XMM)) {
24144                         fprintf(fp, "\tmovq2dq %s, %s\n",
24145                                 reg(state, src, src_regcm),
24146                                 reg(state, dst, dst_regcm));
24147                 }
24148                 /* Move between 32bit gprs & mmx/sse registers */
24149                 else if ((src_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM)) &&
24150                         (dst_regcm & (REGCM_GPR32 | REGCM_MMX | REGCM_XMM))) {
24151                         fprintf(fp, "\tmovd %s, %s\n",
24152                                 reg(state, src, src_regcm),
24153                                 reg(state, dst, dst_regcm));
24154                 }
24155                 /* Move from 16bit gprs &  mmx/sse registers */
24156                 else if ((src_regcm & REGCM_GPR16) &&
24157                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24158                         const char *op;
24159                         int mid_reg;
24160                         op = is_signed(src->type)? "movsx":"movzx";
24161                         mid_reg = (src_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24162                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24163                                 op,
24164                                 arch_reg_str(src_reg),
24165                                 arch_reg_str(mid_reg),
24166                                 arch_reg_str(mid_reg),
24167                                 arch_reg_str(dst_reg));
24168                 }
24169                 /* Move from mmx/sse registers to 16bit gprs */
24170                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24171                         (dst_regcm & REGCM_GPR16)) {
24172                         dst_reg = (dst_reg - REGC_GPR16_FIRST) + REGC_GPR32_FIRST;
24173                         fprintf(fp, "\tmovd %s, %s\n",
24174                                 arch_reg_str(src_reg),
24175                                 arch_reg_str(dst_reg));
24176                 }
24177                 /* Move from gpr to 64bit dividend */
24178                 else if ((src_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))  &&
24179                         (dst_regcm & REGCM_DIVIDEND64)) {
24180                         const char *extend;
24181                         extend = is_signed(src->type)? "cltd":"movl $0, %edx";
24182                         fprintf(fp, "\tmov %s, %%eax\n\t%s\n",
24183                                 arch_reg_str(src_reg),
24184                                 extend);
24185                 }
24186                 /* Move from 64bit gpr to gpr */
24187                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24188                         (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO))) {
24189                         if (dst_regcm & REGCM_GPR32) {
24190                                 src_reg = REG_EAX;
24191                         }
24192                         else if (dst_regcm & REGCM_GPR16) {
24193                                 src_reg = REG_AX;
24194                         }
24195                         else if (dst_regcm & REGCM_GPR8_LO) {
24196                                 src_reg = REG_AL;
24197                         }
24198                         fprintf(fp, "\tmov %s, %s\n",
24199                                 arch_reg_str(src_reg),
24200                                 arch_reg_str(dst_reg));
24201                 }
24202                 /* Move from mmx/sse registers to 64bit gpr */
24203                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24204                         (dst_regcm & REGCM_DIVIDEND64)) {
24205                         const char *extend;
24206                         extend = is_signed(src->type)? "cltd": "movl $0, %edx";
24207                         fprintf(fp, "\tmovd %s, %%eax\n\t%s\n",
24208                                 arch_reg_str(src_reg),
24209                                 extend);
24210                 }
24211                 /* Move from 64bit gpr to mmx/sse register */
24212                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24213                         (dst_regcm & (REGCM_XMM | REGCM_MMX))) {
24214                         fprintf(fp, "\tmovd %%eax, %s\n",
24215                                 arch_reg_str(dst_reg));
24216                 }
24217 #if X86_4_8BIT_GPRS
24218                 /* Move from 8bit gprs to  mmx/sse registers */
24219                 else if ((src_regcm & REGCM_GPR8_LO) && (src_reg <= REG_DL) &&
24220                         (dst_regcm & (REGCM_MMX | REGCM_XMM))) {
24221                         const char *op;
24222                         int mid_reg;
24223                         op = is_signed(src->type)? "movsx":"movzx";
24224                         mid_reg = (src_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24225                         fprintf(fp, "\t%s %s, %s\n\tmovd %s, %s\n",
24226                                 op,
24227                                 reg(state, src, src_regcm),
24228                                 arch_reg_str(mid_reg),
24229                                 arch_reg_str(mid_reg),
24230                                 reg(state, dst, dst_regcm));
24231                 }
24232                 /* Move from mmx/sse registers and 8bit gprs */
24233                 else if ((src_regcm & (REGCM_MMX | REGCM_XMM)) &&
24234                         (dst_regcm & REGCM_GPR8_LO) && (dst_reg <= REG_DL)) {
24235                         int mid_reg;
24236                         mid_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24237                         fprintf(fp, "\tmovd %s, %s\n",
24238                                 reg(state, src, src_regcm),
24239                                 arch_reg_str(mid_reg));
24240                 }
24241                 /* Move from 32bit gprs to 8bit gprs */
24242                 else if ((src_regcm & REGCM_GPR32) &&
24243                         (dst_regcm & REGCM_GPR8_LO)) {
24244                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR32_FIRST;
24245                         if ((src_reg != dst_reg) || !omit_copy) {
24246                                 fprintf(fp, "\tmov %s, %s\n",
24247                                         arch_reg_str(src_reg),
24248                                         arch_reg_str(dst_reg));
24249                         }
24250                 }
24251                 /* Move from 16bit gprs to 8bit gprs */
24252                 else if ((src_regcm & REGCM_GPR16) &&
24253                         (dst_regcm & REGCM_GPR8_LO)) {
24254                         dst_reg = (dst_reg - REGC_GPR8_FIRST) + REGC_GPR16_FIRST;
24255                         if ((src_reg != dst_reg) || !omit_copy) {
24256                                 fprintf(fp, "\tmov %s, %s\n",
24257                                         arch_reg_str(src_reg),
24258                                         arch_reg_str(dst_reg));
24259                         }
24260                 }
24261 #endif /* X86_4_8BIT_GPRS */
24262                 /* Move from %eax:%edx to %eax:%edx */
24263                 else if ((src_regcm & REGCM_DIVIDEND64) &&
24264                         (dst_regcm & REGCM_DIVIDEND64) &&
24265                         (src_reg == dst_reg)) {
24266                         if (!omit_copy) {
24267                                 fprintf(fp, "\t/*mov %s, %s*/\n",
24268                                         arch_reg_str(src_reg),
24269                                         arch_reg_str(dst_reg));
24270                         }
24271                 }
24272                 else {
24273                         if ((src_regcm & ~REGCM_FLAGS) == 0) {
24274                                 internal_error(state, ins, "attempt to copy from %%eflags!");
24275                         }
24276                         internal_error(state, ins, "unknown copy type");
24277                 }
24278         }
24279         else {
24280                 size_t dst_size;
24281                 int dst_reg;
24282                 int dst_regcm;
24283                 dst_size = size_of(state, dst->type);
24284                 dst_reg = ID_REG(dst->id);
24285                 dst_regcm = arch_reg_regcm(state, dst_reg);
24286                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24287                         fprintf(fp, "\tmov ");
24288                         print_const_val(state, src, fp);
24289                         fprintf(fp, ", %s\n",
24290                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24291                 }
24292                 else if (dst_regcm & REGCM_DIVIDEND64) {
24293                         if (dst_size > SIZEOF_I32) {
24294                                 internal_error(state, ins, "%dbit constant...", dst_size);
24295                         }
24296                         fprintf(fp, "\tmov $0, %%edx\n");
24297                         fprintf(fp, "\tmov ");
24298                         print_const_val(state, src, fp);
24299                         fprintf(fp, ", %%eax\n");
24300                 }
24301                 else if (dst_regcm & REGCM_DIVIDEND32) {
24302                         if (dst_size > SIZEOF_I16) {
24303                                 internal_error(state, ins, "%dbit constant...", dst_size);
24304                         }
24305                         fprintf(fp, "\tmov $0, %%dx\n");
24306                         fprintf(fp, "\tmov ");
24307                         print_const_val(state, src, fp);
24308                         fprintf(fp, ", %%ax");
24309                 }
24310                 else if (dst_regcm & (REGCM_XMM | REGCM_MMX)) {
24311                         long ref;
24312                         if (dst_size > SIZEOF_I32) {
24313                                 internal_error(state, ins, "%d bit constant...", dst_size);
24314                         }
24315                         ref = get_const_pool_ref(state, src, SIZEOF_I32, fp);
24316                         fprintf(fp, "\tmovd L%s%lu, %s\n",
24317                                 state->compiler->label_prefix, ref,
24318                                 reg(state, dst, (REGCM_XMM | REGCM_MMX)));
24319                 }
24320                 else {
24321                         internal_error(state, ins, "unknown copy immediate type");
24322                 }
24323         }
24324         /* Leave now if this is not a type conversion */
24325         if (ins->op != OP_CONVERT) {
24326                 return;
24327         }
24328         /* Now make certain I have not logically overflowed the destination */
24329         if ((size_of(state, src->type) > size_of(state, dst->type)) &&
24330                 (size_of(state, dst->type) < reg_size(state, dst)))
24331         {
24332                 unsigned long mask;
24333                 int dst_reg;
24334                 int dst_regcm;
24335                 if (size_of(state, dst->type) >= 32) {
24336                         fprintf(state->errout, "dst type: ");
24337                         name_of(state->errout, dst->type);
24338                         fprintf(state->errout, "\n");
24339                         internal_error(state, dst, "unhandled dst type size");
24340                 }
24341                 mask = 1;
24342                 mask <<= size_of(state, dst->type);
24343                 mask -= 1;
24344
24345                 dst_reg = ID_REG(dst->id);
24346                 dst_regcm = arch_reg_regcm(state, dst_reg);
24347
24348                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24349                         fprintf(fp, "\tand $0x%lx, %s\n",
24350                                 mask, reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24351                 }
24352                 else if (dst_regcm & REGCM_MMX) {
24353                         long ref;
24354                         ref = get_mask_pool_ref(state, dst, mask, fp);
24355                         fprintf(fp, "\tpand L%s%lu, %s\n",
24356                                 state->compiler->label_prefix, ref,
24357                                 reg(state, dst, REGCM_MMX));
24358                 }
24359                 else if (dst_regcm & REGCM_XMM) {
24360                         long ref;
24361                         ref = get_mask_pool_ref(state, dst, mask, fp);
24362                         fprintf(fp, "\tpand L%s%lu, %s\n",
24363                                 state->compiler->label_prefix, ref,
24364                                 reg(state, dst, REGCM_XMM));
24365                 }
24366                 else {
24367                         fprintf(state->errout, "dst type: ");
24368                         name_of(state->errout, dst->type);
24369                         fprintf(state->errout, "\n");
24370                         fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24371                         internal_error(state, dst, "failed to trunc value: mask %lx", mask);
24372                 }
24373         }
24374         /* Make certain I am properly sign extended */
24375         if ((size_of(state, src->type) < size_of(state, dst->type)) &&
24376                 (is_signed(src->type)))
24377         {
24378                 int reg_bits, shift_bits;
24379                 int dst_reg;
24380                 int dst_regcm;
24381
24382                 reg_bits = reg_size(state, dst);
24383                 if (reg_bits > 32) {
24384                         reg_bits = 32;
24385                 }
24386                 shift_bits = reg_bits - size_of(state, src->type);
24387                 dst_reg = ID_REG(dst->id);
24388                 dst_regcm = arch_reg_regcm(state, dst_reg);
24389
24390                 if (shift_bits < 0) {
24391                         internal_error(state, dst, "negative shift?");
24392                 }
24393
24394                 if (dst_regcm & (REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO)) {
24395                         fprintf(fp, "\tshl $%d, %s\n",
24396                                 shift_bits,
24397                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24398                         fprintf(fp, "\tsar $%d, %s\n",
24399                                 shift_bits,
24400                                 reg(state, dst, REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO));
24401                 }
24402                 else if (dst_regcm & (REGCM_MMX | REGCM_XMM)) {
24403                         fprintf(fp, "\tpslld $%d, %s\n",
24404                                 shift_bits,
24405                                 reg(state, dst, REGCM_MMX | REGCM_XMM));
24406                         fprintf(fp, "\tpsrad $%d, %s\n",
24407                                 shift_bits,
24408                                 reg(state, dst, REGCM_MMX | REGCM_XMM));
24409                 }
24410                 else {
24411                         fprintf(state->errout, "dst type: ");
24412                         name_of(state->errout, dst->type);
24413                         fprintf(state->errout, "\n");
24414                         fprintf(state->errout, "dst: %s\n", reg(state, dst, REGCM_ALL));
24415                         internal_error(state, dst, "failed to signed extend value");
24416                 }
24417         }
24418 }
24419
24420 static void print_op_load(struct compile_state *state,
24421         struct triple *ins, FILE *fp)
24422 {
24423         struct triple *dst, *src;
24424         const char *op;
24425         dst = ins;
24426         src = RHS(ins, 0);
24427         if (is_const(src) || is_const(dst)) {
24428                 internal_error(state, ins, "unknown load operation");
24429         }
24430         switch(ins->type->type & TYPE_MASK) {
24431         case TYPE_CHAR:   op = "movsbl"; break;
24432         case TYPE_UCHAR:  op = "movzbl"; break;
24433         case TYPE_SHORT:  op = "movswl"; break;
24434         case TYPE_USHORT: op = "movzwl"; break;
24435         case TYPE_INT:    case TYPE_UINT:
24436         case TYPE_LONG:   case TYPE_ULONG:
24437         case TYPE_POINTER:
24438                 op = "movl";
24439                 break;
24440         default:
24441                 internal_error(state, ins, "unknown type in load");
24442                 op = "<invalid opcode>";
24443                 break;
24444         }
24445         fprintf(fp, "\t%s (%s), %s\n",
24446                 op,
24447                 reg(state, src, REGCM_GPR32),
24448                 reg(state, dst, REGCM_GPR32));
24449 }
24450
24451
24452 static void print_op_store(struct compile_state *state,
24453         struct triple *ins, FILE *fp)
24454 {
24455         struct triple *dst, *src;
24456         dst = RHS(ins, 0);
24457         src = RHS(ins, 1);
24458         if (is_const(src) && (src->op == OP_INTCONST)) {
24459                 long_t value;
24460                 value = (long_t)(src->u.cval);
24461                 fprintf(fp, "\tmov%s $%ld, (%s)\n",
24462                         type_suffix(state, src->type),
24463                         (long)(value),
24464                         reg(state, dst, REGCM_GPR32));
24465         }
24466         else if (is_const(dst) && (dst->op == OP_INTCONST)) {
24467                 fprintf(fp, "\tmov%s %s, 0x%08lx\n",
24468                         type_suffix(state, src->type),
24469                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24470                         (unsigned long)(dst->u.cval));
24471         }
24472         else {
24473                 if (is_const(src) || is_const(dst)) {
24474                         internal_error(state, ins, "unknown store operation");
24475                 }
24476                 fprintf(fp, "\tmov%s %s, (%s)\n",
24477                         type_suffix(state, src->type),
24478                         reg(state, src, REGCM_GPR8_LO | REGCM_GPR16 | REGCM_GPR32),
24479                         reg(state, dst, REGCM_GPR32));
24480         }
24481
24482
24483 }
24484
24485 static void print_op_smul(struct compile_state *state,
24486         struct triple *ins, FILE *fp)
24487 {
24488         if (!is_const(RHS(ins, 1))) {
24489                 fprintf(fp, "\timul %s, %s\n",
24490                         reg(state, RHS(ins, 1), REGCM_GPR32),
24491                         reg(state, RHS(ins, 0), REGCM_GPR32));
24492         }
24493         else {
24494                 fprintf(fp, "\timul ");
24495                 print_const_val(state, RHS(ins, 1), fp);
24496                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), REGCM_GPR32));
24497         }
24498 }
24499
24500 static void print_op_cmp(struct compile_state *state,
24501         struct triple *ins, FILE *fp)
24502 {
24503         unsigned mask;
24504         int dreg;
24505         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24506         dreg = check_reg(state, ins, REGCM_FLAGS);
24507         if (!reg_is_reg(state, dreg, REG_EFLAGS)) {
24508                 internal_error(state, ins, "bad dest register for cmp");
24509         }
24510         if (is_const(RHS(ins, 1))) {
24511                 fprintf(fp, "\tcmp ");
24512                 print_const_val(state, RHS(ins, 1), fp);
24513                 fprintf(fp, ", %s\n", reg(state, RHS(ins, 0), mask));
24514         }
24515         else {
24516                 unsigned lmask, rmask;
24517                 int lreg, rreg;
24518                 lreg = check_reg(state, RHS(ins, 0), mask);
24519                 rreg = check_reg(state, RHS(ins, 1), mask);
24520                 lmask = arch_reg_regcm(state, lreg);
24521                 rmask = arch_reg_regcm(state, rreg);
24522                 mask = lmask & rmask;
24523                 fprintf(fp, "\tcmp %s, %s\n",
24524                         reg(state, RHS(ins, 1), mask),
24525                         reg(state, RHS(ins, 0), mask));
24526         }
24527 }
24528
24529 static void print_op_test(struct compile_state *state,
24530         struct triple *ins, FILE *fp)
24531 {
24532         unsigned mask;
24533         mask = REGCM_GPR32 | REGCM_GPR16 | REGCM_GPR8_LO;
24534         fprintf(fp, "\ttest %s, %s\n",
24535                 reg(state, RHS(ins, 0), mask),
24536                 reg(state, RHS(ins, 0), mask));
24537 }
24538
24539 static void print_op_branch(struct compile_state *state,
24540         struct triple *branch, FILE *fp)
24541 {
24542         const char *bop = "j";
24543         if ((branch->op == OP_JMP) || (branch->op == OP_CALL)) {
24544                 if (branch->rhs != 0) {
24545                         internal_error(state, branch, "jmp with condition?");
24546                 }
24547                 bop = "jmp";
24548         }
24549         else {
24550                 struct triple *ptr;
24551                 if (branch->rhs != 1) {
24552                         internal_error(state, branch, "jmpcc without condition?");
24553                 }
24554                 check_reg(state, RHS(branch, 0), REGCM_FLAGS);
24555                 if ((RHS(branch, 0)->op != OP_CMP) &&
24556                         (RHS(branch, 0)->op != OP_TEST)) {
24557                         internal_error(state, branch, "bad branch test");
24558                 }
24559 #if DEBUG_ROMCC_WARNINGS
24560 #warning "FIXME I have observed instructions between the test and branch instructions"
24561 #endif
24562                 ptr = RHS(branch, 0);
24563                 for(ptr = RHS(branch, 0)->next; ptr != branch; ptr = ptr->next) {
24564                         if (ptr->op != OP_COPY) {
24565                                 internal_error(state, branch, "branch does not follow test");
24566                         }
24567                 }
24568                 switch(branch->op) {
24569                 case OP_JMP_EQ:       bop = "jz";  break;
24570                 case OP_JMP_NOTEQ:    bop = "jnz"; break;
24571                 case OP_JMP_SLESS:    bop = "jl";  break;
24572                 case OP_JMP_ULESS:    bop = "jb";  break;
24573                 case OP_JMP_SMORE:    bop = "jg";  break;
24574                 case OP_JMP_UMORE:    bop = "ja";  break;
24575                 case OP_JMP_SLESSEQ:  bop = "jle"; break;
24576                 case OP_JMP_ULESSEQ:  bop = "jbe"; break;
24577                 case OP_JMP_SMOREEQ:  bop = "jge"; break;
24578                 case OP_JMP_UMOREEQ:  bop = "jae"; break;
24579                 default:
24580                         internal_error(state, branch, "Invalid branch op");
24581                         break;
24582                 }
24583
24584         }
24585 #if 1
24586         if (branch->op == OP_CALL) {
24587                 fprintf(fp, "\t/* call */\n");
24588         }
24589 #endif
24590         fprintf(fp, "\t%s L%s%lu\n",
24591                 bop,
24592                 state->compiler->label_prefix,
24593                 (unsigned long)(TARG(branch, 0)->u.cval));
24594 }
24595
24596 static void print_op_ret(struct compile_state *state,
24597         struct triple *branch, FILE *fp)
24598 {
24599         fprintf(fp, "\tjmp *%s\n",
24600                 reg(state, RHS(branch, 0), REGCM_GPR32));
24601 }
24602
24603 static void print_op_set(struct compile_state *state,
24604         struct triple *set, FILE *fp)
24605 {
24606         const char *sop = "set";
24607         if (set->rhs != 1) {
24608                 internal_error(state, set, "setcc without condition?");
24609         }
24610         check_reg(state, RHS(set, 0), REGCM_FLAGS);
24611         if ((RHS(set, 0)->op != OP_CMP) &&
24612                 (RHS(set, 0)->op != OP_TEST)) {
24613                 internal_error(state, set, "bad set test");
24614         }
24615         if (RHS(set, 0)->next != set) {
24616                 internal_error(state, set, "set does not follow test");
24617         }
24618         switch(set->op) {
24619         case OP_SET_EQ:       sop = "setz";  break;
24620         case OP_SET_NOTEQ:    sop = "setnz"; break;
24621         case OP_SET_SLESS:    sop = "setl";  break;
24622         case OP_SET_ULESS:    sop = "setb";  break;
24623         case OP_SET_SMORE:    sop = "setg";  break;
24624         case OP_SET_UMORE:    sop = "seta";  break;
24625         case OP_SET_SLESSEQ:  sop = "setle"; break;
24626         case OP_SET_ULESSEQ:  sop = "setbe"; break;
24627         case OP_SET_SMOREEQ:  sop = "setge"; break;
24628         case OP_SET_UMOREEQ:  sop = "setae"; break;
24629         default:
24630                 internal_error(state, set, "Invalid set op");
24631                 break;
24632         }
24633         fprintf(fp, "\t%s %s\n",
24634                 sop, reg(state, set, REGCM_GPR8_LO));
24635 }
24636
24637 static void print_op_bit_scan(struct compile_state *state,
24638         struct triple *ins, FILE *fp)
24639 {
24640         const char *op;
24641         switch(ins->op) {
24642         case OP_BSF: op = "bsf"; break;
24643         case OP_BSR: op = "bsr"; break;
24644         default:
24645                 internal_error(state, ins, "unknown bit scan");
24646                 op = 0;
24647                 break;
24648         }
24649         fprintf(fp,
24650                 "\t%s %s, %s\n"
24651                 "\tjnz 1f\n"
24652                 "\tmovl $-1, %s\n"
24653                 "1:\n",
24654                 op,
24655                 reg(state, RHS(ins, 0), REGCM_GPR32),
24656                 reg(state, ins, REGCM_GPR32),
24657                 reg(state, ins, REGCM_GPR32));
24658 }
24659
24660
24661 static void print_sdecl(struct compile_state *state,
24662         struct triple *ins, FILE *fp)
24663 {
24664         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24665         fprintf(fp, ".balign %ld\n", (long int)align_of_in_bytes(state, ins->type));
24666         fprintf(fp, "L%s%lu:\n",
24667                 state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24668         print_const(state, MISC(ins, 0), fp);
24669         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24670
24671 }
24672
24673 static void print_instruction(struct compile_state *state,
24674         struct triple *ins, FILE *fp)
24675 {
24676         /* Assumption: after I have exted the register allocator
24677          * everything is in a valid register.
24678          */
24679         switch(ins->op) {
24680         case OP_ASM:
24681                 print_op_asm(state, ins, fp);
24682                 break;
24683         case OP_ADD:    print_binary_op(state, "add", ins, fp); break;
24684         case OP_SUB:    print_binary_op(state, "sub", ins, fp); break;
24685         case OP_AND:    print_binary_op(state, "and", ins, fp); break;
24686         case OP_XOR:    print_binary_op(state, "xor", ins, fp); break;
24687         case OP_OR:     print_binary_op(state, "or",  ins, fp); break;
24688         case OP_SL:     print_op_shift(state, "shl", ins, fp); break;
24689         case OP_USR:    print_op_shift(state, "shr", ins, fp); break;
24690         case OP_SSR:    print_op_shift(state, "sar", ins, fp); break;
24691         case OP_POS:    break;
24692         case OP_NEG:    print_unary_op(state, "neg", ins, fp); break;
24693         case OP_INVERT: print_unary_op(state, "not", ins, fp); break;
24694         case OP_NOOP:
24695         case OP_INTCONST:
24696         case OP_ADDRCONST:
24697         case OP_BLOBCONST:
24698                 /* Don't generate anything here for constants */
24699         case OP_PHI:
24700                 /* Don't generate anything for variable declarations. */
24701                 break;
24702         case OP_UNKNOWNVAL:
24703                 fprintf(fp, " /* unknown %s */\n",
24704                         reg(state, ins, REGCM_ALL));
24705                 break;
24706         case OP_SDECL:
24707                 print_sdecl(state, ins, fp);
24708                 break;
24709         case OP_COPY:
24710         case OP_CONVERT:
24711                 print_op_move(state, ins, fp);
24712                 break;
24713         case OP_LOAD:
24714                 print_op_load(state, ins, fp);
24715                 break;
24716         case OP_STORE:
24717                 print_op_store(state, ins, fp);
24718                 break;
24719         case OP_SMUL:
24720                 print_op_smul(state, ins, fp);
24721                 break;
24722         case OP_CMP:    print_op_cmp(state, ins, fp); break;
24723         case OP_TEST:   print_op_test(state, ins, fp); break;
24724         case OP_JMP:
24725         case OP_JMP_EQ:      case OP_JMP_NOTEQ:
24726         case OP_JMP_SLESS:   case OP_JMP_ULESS:
24727         case OP_JMP_SMORE:   case OP_JMP_UMORE:
24728         case OP_JMP_SLESSEQ: case OP_JMP_ULESSEQ:
24729         case OP_JMP_SMOREEQ: case OP_JMP_UMOREEQ:
24730         case OP_CALL:
24731                 print_op_branch(state, ins, fp);
24732                 break;
24733         case OP_RET:
24734                 print_op_ret(state, ins, fp);
24735                 break;
24736         case OP_SET_EQ:      case OP_SET_NOTEQ:
24737         case OP_SET_SLESS:   case OP_SET_ULESS:
24738         case OP_SET_SMORE:   case OP_SET_UMORE:
24739         case OP_SET_SLESSEQ: case OP_SET_ULESSEQ:
24740         case OP_SET_SMOREEQ: case OP_SET_UMOREEQ:
24741                 print_op_set(state, ins, fp);
24742                 break;
24743         case OP_INB:  case OP_INW:  case OP_INL:
24744                 print_op_in(state, ins, fp);
24745                 break;
24746         case OP_OUTB: case OP_OUTW: case OP_OUTL:
24747                 print_op_out(state, ins, fp);
24748                 break;
24749         case OP_BSF:
24750         case OP_BSR:
24751                 print_op_bit_scan(state, ins, fp);
24752                 break;
24753         case OP_RDMSR:
24754                 after_lhs(state, ins);
24755                 fprintf(fp, "\trdmsr\n");
24756                 break;
24757         case OP_WRMSR:
24758                 fprintf(fp, "\twrmsr\n");
24759                 break;
24760         case OP_HLT:
24761                 fprintf(fp, "\thlt\n");
24762                 break;
24763         case OP_SDIVT:
24764                 fprintf(fp, "\tidiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24765                 break;
24766         case OP_UDIVT:
24767                 fprintf(fp, "\tdiv %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24768                 break;
24769         case OP_UMUL:
24770                 fprintf(fp, "\tmul %s\n", reg(state, RHS(ins, 1), REGCM_GPR32));
24771                 break;
24772         case OP_LABEL:
24773                 if (!ins->use) {
24774                         return;
24775                 }
24776                 fprintf(fp, "L%s%lu:\n",
24777                         state->compiler->label_prefix, (unsigned long)(ins->u.cval));
24778                 break;
24779         case OP_ADECL:
24780                 /* Ignore adecls with no registers error otherwise */
24781                 if (!noop_adecl(ins)) {
24782                         internal_error(state, ins, "adecl remains?");
24783                 }
24784                 break;
24785                 /* Ignore OP_PIECE */
24786         case OP_PIECE:
24787                 break;
24788                 /* Operations that should never get here */
24789         case OP_SDIV: case OP_UDIV:
24790         case OP_SMOD: case OP_UMOD:
24791         case OP_LTRUE:   case OP_LFALSE:  case OP_EQ:      case OP_NOTEQ:
24792         case OP_SLESS:   case OP_ULESS:   case OP_SMORE:   case OP_UMORE:
24793         case OP_SLESSEQ: case OP_ULESSEQ: case OP_SMOREEQ: case OP_UMOREEQ:
24794         default:
24795                 internal_error(state, ins, "unknown op: %d %s",
24796                         ins->op, tops(ins->op));
24797                 break;
24798         }
24799 }
24800
24801 static void print_instructions(struct compile_state *state)
24802 {
24803         struct triple *first, *ins;
24804         int print_location;
24805         struct occurance *last_occurance;
24806         FILE *fp;
24807         int max_inline_depth;
24808         max_inline_depth = 0;
24809         print_location = 1;
24810         last_occurance = 0;
24811         fp = state->output;
24812         /* Masks for common sizes */
24813         fprintf(fp, ".section \"" DATA_SECTION "\"\n");
24814         fprintf(fp, ".balign 16\n");
24815         fprintf(fp, "L%s1:\n", state->compiler->label_prefix);
24816         fprintf(fp, ".int 0xff, 0, 0, 0\n");
24817         fprintf(fp, "L%s2:\n", state->compiler->label_prefix);
24818         fprintf(fp, ".int 0xffff, 0, 0, 0\n");
24819         fprintf(fp, ".section \"" TEXT_SECTION "\"\n");
24820         first = state->first;
24821         ins = first;
24822         do {
24823                 if (print_location &&
24824                         last_occurance != ins->occurance) {
24825                         if (!ins->occurance->parent) {
24826                                 fprintf(fp, "\t/* %s,%s:%d.%d */\n",
24827                                         ins->occurance->function?ins->occurance->function:"(null)",
24828                                         ins->occurance->filename?ins->occurance->filename:"(null)",
24829                                         ins->occurance->line,
24830                                         ins->occurance->col);
24831                         }
24832                         else {
24833                                 struct occurance *ptr;
24834                                 int inline_depth;
24835                                 fprintf(fp, "\t/*\n");
24836                                 inline_depth = 0;
24837                                 for(ptr = ins->occurance; ptr; ptr = ptr->parent) {
24838                                         inline_depth++;
24839                                         fprintf(fp, "\t * %s,%s:%d.%d\n",
24840                                                 ptr->function,
24841                                                 ptr->filename,
24842                                                 ptr->line,
24843                                                 ptr->col);
24844                                 }
24845                                 fprintf(fp, "\t */\n");
24846                                 if (inline_depth > max_inline_depth) {
24847                                         max_inline_depth = inline_depth;
24848                                 }
24849                         }
24850                         if (last_occurance) {
24851                                 put_occurance(last_occurance);
24852                         }
24853                         get_occurance(ins->occurance);
24854                         last_occurance = ins->occurance;
24855                 }
24856
24857                 print_instruction(state, ins, fp);
24858                 ins = ins->next;
24859         } while(ins != first);
24860         if (print_location) {
24861                 fprintf(fp, "/* max inline depth %d */\n",
24862                         max_inline_depth);
24863         }
24864 }
24865
24866 static void generate_code(struct compile_state *state)
24867 {
24868         generate_local_labels(state);
24869         print_instructions(state);
24870
24871 }
24872
24873 static void print_preprocessed_tokens(struct compile_state *state)
24874 {
24875         int tok;
24876         FILE *fp;
24877         int line;
24878         const char *filename;
24879         fp = state->output;
24880         filename = 0;
24881         line = 0;
24882         for(;;) {
24883                 struct file_state *file;
24884                 struct token *tk;
24885                 const char *token_str;
24886                 tok = peek(state);
24887                 if (tok == TOK_EOF) {
24888                         break;
24889                 }
24890                 tk = eat(state, tok);
24891                 token_str =
24892                         tk->ident ? tk->ident->name :
24893                         tk->str_len ? tk->val.str :
24894                         tokens[tk->tok];
24895
24896                 file = state->file;
24897                 while(file->macro && file->prev) {
24898                         file = file->prev;
24899                 }
24900                 if (!file->macro &&
24901                         ((file->line != line) || (file->basename != filename)))
24902                 {
24903                         int i, col;
24904                         if ((file->basename == filename) &&
24905                                 (line < file->line)) {
24906                                 while(line < file->line) {
24907                                         fprintf(fp, "\n");
24908                                         line++;
24909                                 }
24910                         }
24911                         else {
24912                                 fprintf(fp, "\n#line %d \"%s\"\n",
24913                                         file->line, file->basename);
24914                         }
24915                         line = file->line;
24916                         filename = file->basename;
24917                         col = get_col(file) - strlen(token_str);
24918                         for(i = 0; i < col; i++) {
24919                                 fprintf(fp, " ");
24920                         }
24921                 }
24922
24923                 fprintf(fp, "%s ", token_str);
24924
24925                 if (state->compiler->debug & DEBUG_TOKENS) {
24926                         loc(state->dbgout, state, 0);
24927                         fprintf(state->dbgout, "%s <- `%s'\n",
24928                                 tokens[tok], token_str);
24929                 }
24930         }
24931 }
24932
24933 static void compile(const char *filename,
24934         struct compiler_state *compiler, struct arch_state *arch)
24935 {
24936         int i;
24937         struct compile_state state;
24938         struct triple *ptr;
24939         struct filelist *includes = include_filelist;
24940         memset(&state, 0, sizeof(state));
24941         state.compiler = compiler;
24942         state.arch     = arch;
24943         state.file = 0;
24944         for(i = 0; i < sizeof(state.token)/sizeof(state.token[0]); i++) {
24945                 memset(&state.token[i], 0, sizeof(state.token[i]));
24946                 state.token[i].tok = -1;
24947         }
24948         /* Remember the output descriptors */
24949         state.errout = stderr;
24950         state.dbgout = stdout;
24951         /* Remember the output filename */
24952         if ((state.compiler->flags & COMPILER_PP_ONLY) && (strcmp("auto.inc",state.compiler->ofilename) == 0)) {
24953                 state.output    = stdout;
24954         } else {
24955                 state.output    = fopen(state.compiler->ofilename, "w");
24956                 if (!state.output) {
24957                         error(&state, 0, "Cannot open output file %s\n",
24958                                 state.compiler->ofilename);
24959                 }
24960         }
24961         /* Make certain a good cleanup happens */
24962         exit_state = &state;
24963         atexit(exit_cleanup);
24964
24965         /* Prep the preprocessor */
24966         state.if_depth = 0;
24967         memset(state.if_bytes, 0, sizeof(state.if_bytes));
24968         /* register the C keywords */
24969         register_keywords(&state);
24970         /* register the keywords the macro preprocessor knows */
24971         register_macro_keywords(&state);
24972         /* generate some builtin macros */
24973         register_builtin_macros(&state);
24974         /* Memorize where some special keywords are. */
24975         state.i_switch        = lookup(&state, "switch", 6);
24976         state.i_case          = lookup(&state, "case", 4);
24977         state.i_continue      = lookup(&state, "continue", 8);
24978         state.i_break         = lookup(&state, "break", 5);
24979         state.i_default       = lookup(&state, "default", 7);
24980         state.i_return        = lookup(&state, "return", 6);
24981         /* Memorize where predefined macros are. */
24982         state.i___VA_ARGS__   = lookup(&state, "__VA_ARGS__", 11);
24983         state.i___FILE__      = lookup(&state, "__FILE__", 8);
24984         state.i___LINE__      = lookup(&state, "__LINE__", 8);
24985         /* Memorize where predefined identifiers are. */
24986         state.i___func__      = lookup(&state, "__func__", 8);
24987         /* Memorize where some attribute keywords are. */
24988         state.i_noinline      = lookup(&state, "noinline", 8);
24989         state.i_always_inline = lookup(&state, "always_inline", 13);
24990         state.i_noreturn      = lookup(&state, "noreturn", 8);
24991
24992         /* Process the command line macros */
24993         process_cmdline_macros(&state);
24994
24995         /* Allocate beginning bounding labels for the function list */
24996         state.first = label(&state);
24997         state.first->id |= TRIPLE_FLAG_VOLATILE;
24998         use_triple(state.first, state.first);
24999         ptr = label(&state);
25000         ptr->id |= TRIPLE_FLAG_VOLATILE;
25001         use_triple(ptr, ptr);
25002         flatten(&state, state.first, ptr);
25003
25004         /* Allocate a label for the pool of global variables */
25005         state.global_pool = label(&state);
25006         state.global_pool->id |= TRIPLE_FLAG_VOLATILE;
25007         flatten(&state, state.first, state.global_pool);
25008
25009         /* Enter the globl definition scope */
25010         start_scope(&state);
25011         register_builtins(&state);
25012
25013         compile_file(&state, filename, 1);
25014
25015         while (includes) {
25016                 compile_file(&state, includes->filename, 1);
25017                 includes=includes->next;
25018         }
25019
25020         /* Stop if all we want is preprocessor output */
25021         if (state.compiler->flags & COMPILER_PP_ONLY) {
25022                 print_preprocessed_tokens(&state);
25023                 return;
25024         }
25025
25026         decls(&state);
25027
25028         /* Exit the global definition scope */
25029         end_scope(&state);
25030
25031         /* Now that basic compilation has happened
25032          * optimize the intermediate code
25033          */
25034         optimize(&state);
25035
25036         generate_code(&state);
25037         if (state.compiler->debug) {
25038                 fprintf(state.errout, "done\n");
25039         }
25040         exit_state = 0;
25041 }
25042
25043 static void version(FILE *fp)
25044 {
25045         fprintf(fp, "romcc " VERSION " released " RELEASE_DATE "\n");
25046 }
25047
25048 static void usage(void)
25049 {
25050         FILE *fp = stdout;
25051         version(fp);
25052         fprintf(fp,
25053                 "\nUsage: romcc [options] <source>.c\n"
25054                 "Compile a C source file generating a binary that does not implicilty use RAM\n"
25055                 "Options: \n"
25056                 "-o <output file name>\n"
25057                 "-f<option>            Specify a generic compiler option\n"
25058                 "-m<option>            Specify a arch dependent option\n"
25059                 "--                    Specify this is the last option\n"
25060                 "\nGeneric compiler options:\n"
25061         );
25062         compiler_usage(fp);
25063         fprintf(fp,
25064                 "\nArchitecture compiler options:\n"
25065         );
25066         arch_usage(fp);
25067         fprintf(fp,
25068                 "\n"
25069         );
25070 }
25071
25072 static void arg_error(char *fmt, ...)
25073 {
25074         va_list args;
25075         va_start(args, fmt);
25076         vfprintf(stderr, fmt, args);
25077         va_end(args);
25078         usage();
25079         exit(1);
25080 }
25081
25082 int main(int argc, char **argv)
25083 {
25084         const char *filename;
25085         struct compiler_state compiler;
25086         struct arch_state arch;
25087         int all_opts;
25088
25089
25090         /* I don't want any surprises */
25091         setlocale(LC_ALL, "C");
25092
25093         init_compiler_state(&compiler);
25094         init_arch_state(&arch);
25095         filename = 0;
25096         all_opts = 0;
25097         while(argc > 1) {
25098                 if (!all_opts && (strcmp(argv[1], "-o") == 0) && (argc > 2)) {
25099                         compiler.ofilename = argv[2];
25100                         argv += 2;
25101                         argc -= 2;
25102                 }
25103                 else if (!all_opts && argv[1][0] == '-') {
25104                         int result;
25105                         result = -1;
25106                         if (strcmp(argv[1], "--") == 0) {
25107                                 result = 0;
25108                                 all_opts = 1;
25109                         }
25110                         else if (strncmp(argv[1], "-E", 2) == 0) {
25111                                 result = compiler_encode_flag(&compiler, argv[1]);
25112                         }
25113                         else if (strncmp(argv[1], "-O", 2) == 0) {
25114                                 result = compiler_encode_flag(&compiler, argv[1]);
25115                         }
25116                         else if (strncmp(argv[1], "-I", 2) == 0) {
25117                                 result = compiler_encode_flag(&compiler, argv[1]);
25118                         }
25119                         else if (strncmp(argv[1], "-D", 2) == 0) {
25120                                 result = compiler_encode_flag(&compiler, argv[1]);
25121                         }
25122                         else if (strncmp(argv[1], "-U", 2) == 0) {
25123                                 result = compiler_encode_flag(&compiler, argv[1]);
25124                         }
25125                         else if (strncmp(argv[1], "--label-prefix=", 15) == 0) {
25126                                 result = compiler_encode_flag(&compiler, argv[1]+2);
25127                         }
25128                         else if (strncmp(argv[1], "-f", 2) == 0) {
25129                                 result = compiler_encode_flag(&compiler, argv[1]+2);
25130                         }
25131                         else if (strncmp(argv[1], "-m", 2) == 0) {
25132                                 result = arch_encode_flag(&arch, argv[1]+2);
25133                         }
25134                         else if (strncmp(argv[1], "-c", 2) == 0) {
25135                                 result = 0;
25136                         }
25137                         else if (strncmp(argv[1], "-S", 2) == 0) {
25138                                 result = 0;
25139                         }
25140                         else if (strncmp(argv[1], "-include", 10) == 0) {
25141                                 struct filelist *old_head = include_filelist;
25142                                 include_filelist = malloc(sizeof(struct filelist));
25143                                 if (!include_filelist) {
25144                                         die("Out of memory.\n");
25145                                 }
25146                                 argv++;
25147                                 argc--;
25148                                 include_filelist->filename = strdup(argv[1]);
25149                                 include_filelist->next = old_head;
25150                                 result = 0;
25151                         }
25152                         if (result < 0) {
25153                                 arg_error("Invalid option specified: %s\n",
25154                                         argv[1]);
25155                         }
25156                         argv++;
25157                         argc--;
25158                 }
25159                 else {
25160                         if (filename) {
25161                                 arg_error("Only one filename may be specified\n");
25162                         }
25163                         filename = argv[1];
25164                         argv++;
25165                         argc--;
25166                 }
25167         }
25168         if (!filename) {
25169                 arg_error("No filename specified\n");
25170         }
25171         compile(filename, &compiler, &arch);
25172
25173         return 0;
25174 }