fixed AM optimization
[libfirm] / ir / be / ia32 / ia32_emitter.c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4
5 #include <limits.h>
6
7 #include "xmalloc.h"
8 #include "tv.h"
9 #include "iredges.h"
10 #include "debug.h"
11 #include "irgwalk.h"
12 #include "irprintf.h"
13 #include "irop_t.h"
14 #include "irargs_t.h"
15
16 #include "../besched.h"
17
18 #include "ia32_emitter.h"
19 #include "gen_ia32_emitter.h"
20 #include "ia32_nodes_attr.h"
21 #include "ia32_new_nodes.h"
22 #include "ia32_map_regs.h"
23
24 #ifdef obstack_chunk_alloc
25 # undef obstack_chunk_alloc
26 # define obstack_chunk_alloc xmalloc
27 #else
28 # define obstack_chunk_alloc xmalloc
29 # define obstack_chunk_free free
30 #endif
31
32 #define SNPRINTF_BUF_LEN 128
33
34 static const arch_env_t *arch_env = NULL;
35
36 char *ia32_emit_binop(const ir_node *n) {
37         static char *buf = NULL;
38
39         if (! buf) {
40                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
41         }
42         else {
43                 memset(buf, 0, SNPRINTF_BUF_LEN);
44         }
45
46         switch(get_ia32_op_type(n)) {
47                 case ia32_Normal:
48                         if (get_ia32_cnst(n)) {
49                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %s", n, get_ia32_cnst(n));
50                         }
51                         else {
52                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %4S", n, n);
53                         }
54                         break;
55                 case ia32_am_Source:
56                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %s", n, ia32_emit_am(n));
57                         break;
58                 case ia32_am_Dest:
59                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %4S", ia32_emit_am(n), n);
60                         break;
61                 default:
62                         assert(0 && "unsupported op type");
63         }
64
65         return buf;
66 }
67
68 char *ia32_emit_unop(const ir_node *n) {
69         static char *buf = NULL;
70
71         if (! buf) {
72                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
73         }
74         else {
75                 memset(buf, 0, SNPRINTF_BUF_LEN);
76         }
77
78         switch(get_ia32_op_type(n)) {
79                 case ia32_Normal:
80                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D", n);
81                         break;
82                 case ia32_am_Dest:
83                         snprintf(buf, SNPRINTF_BUF_LEN, ia32_emit_am(n));
84                         break;
85                 default:
86                         assert(0 && "unsupported op type");
87         }
88
89         return buf;
90 }
91
92 char *ia32_emit_am(const ir_node *n) {
93         ia32_am_flavour_t am_flav    = get_ia32_am_flavour(n);
94         int               had_output = 0;
95         char             *s;
96         int               size;
97         static struct obstack *obst  = NULL;
98
99         if (! obst) {
100                 obst = xcalloc(1, sizeof(*obst));
101         }
102         else {
103                 obstack_free(obst, NULL);
104         }
105
106         /* obstack_free with NULL results in an uninitialized obstack */
107         obstack_init(obst);
108
109         obstack_printf(obst, "[");
110
111         if (am_flav & ia32_B) {
112                 lc_eoprintf(ia32_get_arg_env(), obst, "%1S", n);
113                 had_output = 1;
114         }
115
116         if (am_flav & ia32_I) {
117                 if (had_output) {
118                         obstack_printf(obst, "+");
119                 }
120
121                 lc_eoprintf(ia32_get_arg_env(), obst, "%2S", n);
122
123                 if (am_flav & ia32_S) {
124                         obstack_printf(obst, "*%d", get_ia32_am_scale(n));
125                 }
126
127                 had_output = 1;
128         }
129
130         if (am_flav & ia32_O) {
131                 obstack_printf(obst, get_ia32_am_offs(n));
132         }
133
134         obstack_printf(obst, "] ");
135
136         size        = obstack_object_size(obst);
137         s           = obstack_finish(obst);
138         s[size - 1] = '\0';
139
140         return s;
141 }
142
143 /*************************************************************
144  *             _       _    __   _          _
145  *            (_)     | |  / _| | |        | |
146  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
147  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
148  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
149  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
150  * | |                                       | |
151  * |_|                                       |_|
152  *************************************************************/
153
154 /* We always pass the ir_node which is a pointer. */
155 static int ia32_get_arg_type(const lc_arg_occ_t *occ) {
156         return lc_arg_type_ptr;
157 }
158
159
160 /**
161  * Returns the register at in position pos.
162  */
163 static const arch_register_t *get_in_reg(ir_node *irn, int pos) {
164         ir_node                *op;
165         const arch_register_t  *reg = NULL;
166
167         assert(get_irn_arity(irn) > pos && "Invalid IN position");
168
169         /* The out register of the operator at position pos is the
170            in register we need. */
171         op = get_irn_n(irn, pos);
172
173         reg = arch_get_irn_register(arch_env, op);
174
175         assert(reg && "no in register found");
176         return reg;
177 }
178
179 /**
180  * Returns the register at out position pos.
181  */
182 static const arch_register_t *get_out_reg(ir_node *irn, int pos) {
183         ir_node                *proj;
184         const arch_register_t  *reg = NULL;
185
186         assert(get_irn_n_edges(irn) > pos && "Invalid OUT position");
187
188         /* 1st case: irn is not of mode_T, so it has only                 */
189         /*           one OUT register -> good                             */
190         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
191         /*           Proj with the corresponding projnum for the register */
192
193         if (get_irn_mode(irn) != mode_T) {
194                 reg = arch_get_irn_register(arch_env, irn);
195         }
196         else if (is_ia32_irn(irn)) {
197                 reg = get_ia32_out_reg(irn, pos);
198         }
199         else {
200                 const ir_edge_t *edge;
201
202                 foreach_out_edge(irn, edge) {
203                         proj = get_edge_src_irn(edge);
204                         assert(is_Proj(proj) && "non-Proj from mode_T node");
205                         if (get_Proj_proj(proj) == pos) {
206                                 reg = arch_get_irn_register(arch_env, proj);
207                                 break;
208                         }
209                 }
210         }
211
212         assert(reg && "no out register found");
213         return reg;
214 }
215
216 /**
217  * Returns the number of the in register at position pos.
218  */
219 int get_ia32_reg_nr(ir_node *irn, int pos, int in_out) {
220         const arch_register_t *reg;
221
222         if (in_out == 1) {
223                 reg = get_in_reg(irn, pos);
224         }
225         else {
226                 reg = get_out_reg(irn, pos);
227         }
228
229         return arch_register_get_index(reg);
230 }
231
232 /**
233  * Returns the name of the in register at position pos.
234  */
235 const char *get_ia32_reg_name(ir_node *irn, int pos, int in_out) {
236         const arch_register_t *reg;
237
238         if (in_out == 1) {
239                 reg = get_in_reg(irn, pos);
240         }
241         else {
242                 reg = get_out_reg(irn, pos);
243         }
244
245         return arch_register_get_name(reg);
246 }
247
248 /**
249  * Get the register name for a node.
250  */
251 static int ia32_get_reg_name(lc_appendable_t *app,
252     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
253 {
254         const char *buf;
255         ir_node    *X  = arg->v_ptr;
256         int         nr = occ->width - 1;
257
258         if (!X)
259                 return lc_arg_append(app, occ, "(null)", 6);
260
261         if (occ->conversion == 'S') {
262                 buf = get_ia32_reg_name(X, nr, 1);
263         }
264         else { /* 'D' */
265                 buf = get_ia32_reg_name(X, nr, 0);
266         }
267
268         lc_appendable_chadd(app, '%');
269         return lc_arg_append(app, occ, buf, strlen(buf));
270 }
271
272 /**
273  * Returns the tarval or offset of an ia32 as a string.
274  */
275 static int ia32_const_to_str(lc_appendable_t *app,
276     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
277 {
278         const char *buf;
279         ir_node    *X = arg->v_ptr;
280
281         if (!X)
282                 return lc_arg_append(app, occ, "(null)", 6);
283
284         if (occ->conversion == 'C') {
285                 buf = get_ia32_cnst(X);
286         }
287         else { /* 'O' */
288                 buf = get_ia32_am_offs(X);
289         }
290
291         return lc_arg_append(app, occ, buf, strlen(buf));
292 }
293
294 /**
295  * Determines the SSE suffix depending on the mode.
296  */
297 static int ia32_get_mode_suffix(lc_appendable_t *app,
298     const lc_arg_occ_t *occ, const lc_arg_value_t *arg)
299 {
300         ir_node *X = arg->v_ptr;
301
302         if (!X)
303                 return lc_arg_append(app, occ, "(null)", 6);
304
305         if (get_mode_size_bits(get_irn_mode(X)) == 32)
306                 return lc_appendable_chadd(app, 's');
307         else
308                 return lc_appendable_chadd(app, 'd');
309 }
310
311 /**
312  * Return the ia32 printf arg environment.
313  * We use the firm environment with some additional handlers.
314  */
315 const lc_arg_env_t *ia32_get_arg_env(void) {
316         static lc_arg_env_t *env = NULL;
317
318         static const lc_arg_handler_t ia32_reg_handler   = { ia32_get_arg_type, ia32_get_reg_name };
319         static const lc_arg_handler_t ia32_const_handler = { ia32_get_arg_type, ia32_const_to_str };
320         static const lc_arg_handler_t ia32_mode_handler  = { ia32_get_arg_type, ia32_get_mode_suffix };
321
322         if(env == NULL) {
323                 /* extend the firm printer */
324                 env = firm_get_arg_env();
325                         //lc_arg_new_env();
326
327                 lc_arg_register(env, "ia32:sreg", 'S', &ia32_reg_handler);
328                 lc_arg_register(env, "ia32:dreg", 'D', &ia32_reg_handler);
329                 lc_arg_register(env, "ia32:cnst", 'C', &ia32_const_handler);
330                 lc_arg_register(env, "ia32:offs", 'O', &ia32_const_handler);
331                 lc_arg_register(env, "ia32:mode", 'M', &ia32_mode_handler);
332         }
333
334         return env;
335 }
336
337 /**
338  * For 2-address code we need to make sure the first src reg is equal to dest reg.
339  */
340 void equalize_dest_src(FILE *F, ir_node *n) {
341         if (get_ia32_reg_nr(n, 0, 1) != get_ia32_reg_nr(n, 0, 0)) {
342                 if (get_irn_arity(n) > 1 && get_ia32_reg_nr(n, 1, 1) == get_ia32_reg_nr(n, 0, 0)) {
343                         if (! is_op_commutative(get_irn_op(n))) {
344                                 /* we only need to exchange for non-commutative ops */
345                                 lc_efprintf(ia32_get_arg_env(), F, "\txchg %1S, %2S\t\t\t/* xchg src1 <-> src2 for 2 address code */\n", n, n);
346                         }
347                 }
348                 else {
349                         lc_efprintf(ia32_get_arg_env(), F, "\tmovl %1S, %1D\t\t\t/* src -> dest for 2 address code */\n", n, n);
350                 }
351         }
352 }
353
354 /*
355  * Add a number to a prefix. This number will not be used a second time.
356  */
357 char *get_unique_label(char *buf, size_t buflen, const char *prefix) {
358         static unsigned long id = 0;
359         snprintf(buf, buflen, "%s%lu", prefix, ++id);
360         return buf;
361 }
362
363
364 /*************************************************
365  *                 _ _                         _
366  *                (_) |                       | |
367  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
368  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
369  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
370  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
371  *
372  *************************************************/
373
374 /*
375  * coding of conditions
376  */
377 struct cmp2conditon_t {
378         const char *name;
379         pn_Cmp      num;
380 };
381
382 /*
383  * positive conditions for signed compares
384  */
385 static const struct cmp2conditon_t cmp2condition_s[] = {
386   { NULL,              pn_Cmp_False },  /* always false */
387   { "e",               pn_Cmp_Eq },     /* == */
388   { "l",               pn_Cmp_Lt },     /* < */
389   { "le",              pn_Cmp_Le },     /* <= */
390   { "g",               pn_Cmp_Gt },     /* > */
391   { "ge",              pn_Cmp_Ge },     /* >= */
392   { "ne",              pn_Cmp_Lg },     /* != */
393   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
394   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
395   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
396   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
397   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
398   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
399   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
400   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
401   { NULL,              pn_Cmp_True },   /* always true */
402 };
403
404 /*
405  * positive conditions for unsigned compares
406  */
407 static const struct cmp2conditon_t cmp2condition_u[] = {
408   { NULL,              pn_Cmp_False },  /* always false */
409   { "e",               pn_Cmp_Eq },     /* == */
410   { "b",               pn_Cmp_Lt },     /* < */
411   { "be",              pn_Cmp_Le },     /* <= */
412   { "a",               pn_Cmp_Gt },     /* > */
413   { "ae",              pn_Cmp_Ge },     /* >= */
414   { "ne",              pn_Cmp_Lg },     /* != */
415   { "ordered",         pn_Cmp_Leg },    /* Floating point: ordered */
416   { "unordered",       pn_Cmp_Uo },     /* FLoting point: unordered */
417   { "unordered or ==", pn_Cmp_Ue },     /* Floating point: unordered or == */
418   { "unordered or <",  pn_Cmp_Ul },     /* Floating point: unordered or < */
419   { "unordered or <=", pn_Cmp_Ule },    /* Floating point: unordered or <= */
420   { "unordered or >",  pn_Cmp_Ug },     /* Floating point: unordered or > */
421   { "unordered or >=", pn_Cmp_Uge },    /* Floating point: unordered or >= */
422   { "unordered or !=", pn_Cmp_Ne },     /* Floating point: unordered or != */
423   { NULL,              pn_Cmp_True },   /* always true */
424 };
425
426 /*
427  * returns the condition code
428  */
429 static const char *get_cmp_suffix(int cmp_code, int unsigned_cmp)
430 {
431         assert(cmp2condition_s[cmp_code].num == cmp_code);
432         assert(cmp2condition_u[cmp_code].num == cmp_code);
433
434         return unsigned_cmp ? cmp2condition_u[cmp_code & 7].name : cmp2condition_s[cmp_code & 7].name;
435 }
436
437 /**
438  * Returns the target label for a control flow node.
439  */
440 static char *get_cfop_target(const ir_node *irn, char *buf) {
441         ir_node *bl = get_irn_link(irn);
442
443         snprintf(buf, SNPRINTF_BUF_LEN, "BLOCK_%ld", get_irn_node_nr(bl));
444         return buf;
445 }
446
447 /**
448  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
449  */
450 static void finish_CondJmp(FILE *F, ir_node *irn) {
451         const ir_node   *proj;
452         const ir_edge_t *edge;
453         char buf[SNPRINTF_BUF_LEN];
454
455         edge = get_irn_out_edge_first(irn);
456         proj = get_edge_src_irn(edge);
457         assert(is_Proj(proj) && "CondJmp with a non-Proj");
458
459         if (get_Proj_proj(proj) == 1) {
460                 fprintf(F, "\tj%s %s\t\t\t/* cmp(a, b) == TRUE */\n",
461                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
462                                         get_cfop_target(proj, buf));
463         }
464         else  {
465                 fprintf(F, "\tjn%s %s\t\t\t/* cmp(a, b) == FALSE */\n",
466                                         get_cmp_suffix(get_ia32_pncode(irn), !mode_is_signed(get_irn_mode(get_irn_n(irn, 0)))),
467                                         get_cfop_target(proj, buf));
468         }
469
470         edge = get_irn_out_edge_next(irn, edge);
471         if (edge) {
472                 proj = get_edge_src_irn(edge);
473                 assert(is_Proj(proj) && "CondJmp with a non-Proj");
474                 fprintf(F, "\tjmp %s\t\t\t/* otherwise */\n", get_cfop_target(proj, buf));
475         }
476 }
477
478 /**
479  * Emits code for conditional jump with two variables.
480  */
481 static void emit_ia32_CondJmp(ir_node *irn, emit_env_t *env) {
482         FILE *F = env->out;
483
484         lc_efprintf(ia32_get_arg_env(), F, "\tcmp %2S, %1S\t\t\t/* CondJmp(%+F, %+F) */\n", irn, irn,
485                                                                                                                                         get_irn_n(irn, 0), get_irn_n(irn, 1));
486         finish_CondJmp(F, irn);
487 }
488
489 /**
490  * Emits code for conditional jump with immediate.
491  */
492 void emit_ia32_CondJmp_i(ir_node *irn, emit_env_t *env) {
493         FILE *F = env->out;
494
495         lc_efprintf(ia32_get_arg_env(), F, "\tcmp %C, %1S\t\t\t/* CondJmp_i(%+F) */\n", irn, irn, get_irn_n(irn, 0));
496         finish_CondJmp(F, irn);
497 }
498
499
500
501 /*********************************************************
502  *                 _ _       _
503  *                (_) |     (_)
504  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
505  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
506  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
507  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
508  *                         _/ |               | |
509  *                        |__/                |_|
510  *********************************************************/
511
512 /* jump table entry (target and corresponding number) */
513 typedef struct _branch_t {
514         ir_node *target;
515         int      value;
516 } branch_t;
517
518 /* jump table for switch generation */
519 typedef struct _jmp_tbl_t {
520         ir_node  *defProj;         /**< default target */
521         int       min_value;       /**< smallest switch case */
522         int       max_value;       /**< largest switch case */
523         int       num_branches;    /**< number of jumps */
524         char     *label;           /**< label of the jump table */
525         branch_t *branches;        /**< jump array */
526 } jmp_tbl_t;
527
528 /**
529  * Compare two variables of type branch_t. Used to sort all switch cases
530  */
531 static int ia32_cmp_branch_t(const void *a, const void *b) {
532         branch_t *b1 = (branch_t *)a;
533         branch_t *b2 = (branch_t *)b;
534
535         if (b1->value <= b2->value)
536                 return -1;
537         else
538                 return 1;
539 }
540
541 /**
542  * Emits code for a SwitchJmp (creates a jump table if
543  * possible otherwise a cmp-jmp cascade). Port from
544  * cggg ia32 backend
545  */
546 void emit_ia32_SwitchJmp(const ir_node *irn, emit_env_t *emit_env) {
547         unsigned long       interval;
548         char                buf[SNPRINTF_BUF_LEN];
549         int                 last_value, i, pn, do_jmp_tbl = 1;
550         jmp_tbl_t           tbl;
551         ir_node            *proj;
552         const ir_edge_t    *edge;
553         const lc_arg_env_t *env = ia32_get_arg_env();
554         FILE               *F   = emit_env->out;
555
556         /* fill the table structure */
557         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
558         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
559         tbl.defProj      = NULL;
560         tbl.num_branches = get_irn_n_edges(irn);
561         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
562         tbl.min_value    = INT_MAX;
563         tbl.max_value    = INT_MIN;
564
565         i = 0;
566         /* go over all proj's and collect them */
567         foreach_out_edge(irn, edge) {
568                 proj = get_edge_src_irn(edge);
569                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
570
571                 pn = get_Proj_proj(proj);
572
573                 /* create branch entry */
574                 tbl.branches[i].target = proj;
575                 tbl.branches[i].value  = pn;
576
577                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
578                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
579
580                 /* check for default proj */
581                 if (pn == get_ia32_pncode(irn)) {
582                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
583                         tbl.defProj = proj;
584                 }
585
586                 i++;
587         }
588
589         /* sort the branches by their number */
590         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
591
592         /* two-complement's magic make this work without overflow */
593         interval = tbl.max_value - tbl.min_value;
594
595         /* check value interval */
596         if (interval > 16 * 1024) {
597                 do_jmp_tbl = 0;
598         }
599
600         /* check ratio of value interval to number of branches */
601         if ((float)(interval + 1) / (float)tbl.num_branches > 8.0) {
602                 do_jmp_tbl = 0;
603         }
604
605         if (do_jmp_tbl) {
606                 /* emit the table */
607                 if (tbl.min_value != 0) {
608                         fprintf(F, "\tcmpl %lu, -%d", interval, tbl.min_value);
609                         lc_efprintf(env, F, "(%1S)\t\t/* first switch value is not 0 */\n", irn);
610                 }
611                 else {
612                         fprintf(F, "\tcmpl %lu, ", interval);
613                         lc_efprintf(env, F, "%1S\t\t\t/* compare for switch */\n", irn);
614                 }
615
616                 fprintf(F, "\tja %s\t\t\t/* default jump if out of range  */\n", get_cfop_target(tbl.defProj, buf));
617
618                 if (tbl.num_branches > 1) {
619                         /* create table */
620
621                         //fprintf(F, "\tjmp *%s", tbl.label);
622                         lc_efprintf(env, F, "\tjmp *%s(,%1S,4)\t\t/* get jump table entry as target */\n", tbl.label, irn);
623
624                         fprintf(F, "\t.section\t.rodata\t\t/* start jump table */\n");
625                         fprintf(F, "\t.align 4\n");
626
627                         fprintf(F, "%s:\n", tbl.label);
628                         fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[0].target, buf), tbl.branches[0].value);
629
630                         last_value = tbl.branches[0].value;
631                         for (i = 1; i < tbl.num_branches; ++i) {
632                                 while (++last_value < tbl.branches[i].value) {
633                                         fprintf(F, "\t.long %s\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
634                                 }
635                                 fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[i].target, buf), last_value);
636                         }
637
638                         fprintf(F, "\t.text\t\t\t\t/* end of jump table */\n");
639                 }
640                 else {
641                         /* one jump is enough */
642                         fprintf(F, "\tjmp %s\t\t/* only one case given */\n", get_cfop_target(tbl.branches[0].target, buf));
643                 }
644         }
645         else { // no jump table
646                 for (i = 0; i < tbl.num_branches; ++i) {
647                         fprintf(F, "\tcmpl %d, ", tbl.branches[i].value);
648                         lc_efprintf(env, F, "%1S", irn);
649                         fprintf(F, "\t\t\t/* case %d */\n", tbl.branches[i].value);
650                         fprintf(F, "\tje %s\n", get_cfop_target(tbl.branches[i].target, buf));
651                 }
652
653                 fprintf(F, "\tjmp %s\t\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
654         }
655
656         if (tbl.label)
657                 free(tbl.label);
658         if (tbl.branches)
659                 free(tbl.branches);
660 }
661
662 /**
663  * Emits code for a unconditional jump.
664  */
665 void emit_Jmp(ir_node *irn, emit_env_t *env) {
666         FILE *F = env->out;
667
668         char buf[SNPRINTF_BUF_LEN];
669         ir_fprintf(F, "\tjmp %s\t\t\t/* Jmp(%+F) */\n", get_cfop_target(irn, buf), get_irn_link(irn));
670 }
671
672
673
674 /****************************
675  *                  _
676  *                 (_)
677  *  _ __  _ __ ___  _  ___
678  * | '_ \| '__/ _ \| |/ __|
679  * | |_) | | | (_) | |\__ \
680  * | .__/|_|  \___/| ||___/
681  * | |            _/ |
682  * |_|           |__/
683  ****************************/
684
685 /**
686  * Emits code for a proj -> node
687  */
688 void emit_Proj(ir_node *irn, emit_env_t *env) {
689         ir_node *pred = get_Proj_pred(irn);
690
691         if (get_irn_op(pred) == op_Start) {
692                 switch(get_Proj_proj(irn)) {
693                         case pn_Start_X_initial_exec:
694                                 emit_Jmp(irn, env);
695                                 break;
696                         default:
697                                 break;
698                 }
699         }
700 }
701
702 /********************
703  *   _____      _ _
704  *  / ____|    | | |
705  * | |     __ _| | |
706  * | |    / _` | | |
707  * | |___| (_| | | |
708  *  \_____\__,_|_|_|
709  *
710  ********************/
711
712 void emit_ia32_Call(ir_node *irn, emit_env_t *emit_env) {
713         int                 i, n      = get_irn_arity(irn);
714         int                 args_size = 0;
715         ir_node            *sync      = get_irn_n(irn, n - 1);
716         FILE               *F         = emit_env->out;
717         const lc_arg_env_t *env       = ia32_get_arg_env();
718
719         if (get_irn_op(sync) == op_Sync) {
720                 /* We have stack arguments */
721                 ir_node **args = get_Sync_preds_arr(sync);
722
723                 for (i = 0; i < get_Sync_n_preds(sync); i++) {
724                         ir_node *n = get_irn_n(args[i], 1);
725                         lc_efprintf(env, F, "\tpush %1D\t\t\t\t/* push %+F(%+F) on stack */\n", n, args[i], n);
726
727                         if (mode_is_float(get_irn_mode(n))) {
728                                 args_size += 4;
729                         }
730                         else {
731                                 args_size += 16;
732                         }
733                 }
734         }
735
736         lc_efprintf(env, F, "\tcall %C\t\t\t/* %+F */\n", irn, irn);
737
738         if (get_irn_op(sync) == op_Sync) {
739                 /* We had stack arguments: clear the stack */
740                 fprintf(F, "\tadd %d, ", args_size);
741                 if (emit_env->cg->has_alloca) {
742                         fprintf(F, "%%ebp");
743                 }
744                 else {
745                         fprintf(F, "%%esp");
746                 }
747                 fprintf(F, "\t\t\t\t/* clear stack after call */\n");
748         }
749 }
750
751
752
753 /**
754  * Emits code for Alloca (increase stack pointer, cpoy to destination)
755  */
756 void emit_Alloca(ir_node *irn, emit_env_t *emit_env, int is_imm) {
757         const lc_arg_env_t *env = ia32_get_arg_env();
758         FILE               *F   = emit_env->out;
759         char               *sp;
760
761         if (emit_env->cg->has_alloca) {
762                 sp = "%ebp";
763         }
764         else {
765                 sp = "%esp";
766         }
767
768
769         /* allocate the memory */
770         fprintf(F, "\tsub %s", sp);
771
772         if (is_imm) {
773                 lc_efprintf(env, F, "%C", irn);
774         }
775         else {
776                 lc_efprintf(env, F, "%1S", irn);
777         }
778
779         fprintf(F, "\t\t\t\t/* reserve memory on stack */\n");
780
781         /* copy the new stack pointer to destination register */
782         lc_efprintf(env, F, "\tmov %s, %1D\t\t\t/* copy stack pointer to destination */\n", sp, irn);
783 }
784
785 void emit_ia32_Alloca(ir_node *irn, emit_env_t *emit_env) {
786         emit_Alloca(irn, emit_env, 0);
787 }
788
789 void emit_ia32_Alloca_i(ir_node *irn, emit_env_t *emit_env) {
790         emit_Alloca(irn, emit_env, 1);
791 }
792
793
794 /***********************************************************************************
795  *                  _          __                                             _
796  *                 (_)        / _|                                           | |
797  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
798  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
799  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
800  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
801  *
802  ***********************************************************************************/
803
804 /**
805  * Emits code for a node.
806  */
807 void ia32_emit_node(ir_node *irn, void *env) {
808         emit_env_t *emit_env   = env;
809         firm_dbg_module_t *mod = emit_env->mod;
810         FILE              *F   = emit_env->out;
811
812         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
813
814 #define IA32_EMIT(a) if (is_ia32_##a(irn))               { emit_ia32_##a(irn, emit_env); return; }
815 #define EMIT(a)      if (get_irn_opcode(irn) == iro_##a) { emit_##a(irn, emit_env); return; }
816
817         /* generated int emitter functions */
818         IA32_EMIT(Const);
819
820         IA32_EMIT(Add);
821         IA32_EMIT(Sub);
822         IA32_EMIT(Minus);
823         IA32_EMIT(Inc);
824         IA32_EMIT(Dec);
825
826         IA32_EMIT(Max);
827         IA32_EMIT(Min);
828
829         IA32_EMIT(And);
830         IA32_EMIT(Or);
831         IA32_EMIT(Eor);
832         IA32_EMIT(Not);
833
834         IA32_EMIT(Shl);
835         IA32_EMIT(Shr);
836         IA32_EMIT(Shrs);
837         IA32_EMIT(RotL);
838         IA32_EMIT(RotR);
839
840         IA32_EMIT(Lea);
841
842         IA32_EMIT(Mul);
843
844         IA32_EMIT(Cdq);
845         IA32_EMIT(DivMod);
846
847         IA32_EMIT(Store);
848         IA32_EMIT(Load);
849
850         /* generated floating point emitter */
851         IA32_EMIT(fConst);
852
853         IA32_EMIT(fAdd);
854         IA32_EMIT(fSub);
855
856         IA32_EMIT(fMul);
857         IA32_EMIT(fDiv);
858
859         IA32_EMIT(fMin);
860         IA32_EMIT(fMax);
861
862         IA32_EMIT(fLoad);
863         IA32_EMIT(fStore);
864
865         /* other emitter functions */
866         IA32_EMIT(CondJmp);
867         IA32_EMIT(SwitchJmp);
868         IA32_EMIT(Call);
869
870         EMIT(Jmp);
871         EMIT(Proj);
872
873         ir_fprintf(F, "\t\t\t\t\t/* %+F */\n", irn);
874 }
875
876 /**
877  * Walks over the nodes in a block connected by scheduling edges
878  * and emits code for each node.
879  */
880 void ia32_gen_block(ir_node *block, void *env) {
881         ir_node *irn;
882
883         if (! is_Block(block))
884                 return;
885
886         fprintf(((emit_env_t *)env)->out, "BLOCK_%ld:\n", get_irn_node_nr(block));
887         sched_foreach(block, irn) {
888                 ia32_emit_node(irn, env);
889         }
890 }
891
892
893 /**
894  * Emits code for function start.
895  */
896 void ia32_emit_start(FILE *F, ir_graph *irg) {
897         const char *irg_name = get_entity_name(get_irg_entity(irg));
898
899         fprintf(F, "\t.text\n");
900         fprintf(F, ".globl %s\n", irg_name);
901         fprintf(F, "\t.type\t%s, @function\n", irg_name);
902         fprintf(F, "%s:\n", irg_name);
903 }
904
905 /**
906  * Emits code for function end
907  */
908 void ia32_emit_end(FILE *F, ir_graph *irg) {
909         const char *irg_name = get_entity_name(get_irg_entity(irg));
910
911         fprintf(F, "\tret\n");
912         fprintf(F, "\t.size\t%s, .-%s\n\n", irg_name, irg_name);
913 }
914
915 /**
916  * Sets labels for control flow nodes (jump target)
917  * TODO: Jump optimization
918  */
919 void ia32_gen_labels(ir_node *block, void *env) {
920         ir_node *pred;
921         int n = get_Block_n_cfgpreds(block);
922
923         for (n--; n >= 0; n--) {
924                 pred = get_Block_cfgpred(block, n);
925                 set_irn_link(pred, block);
926         }
927 }
928
929 /**
930  * Main driver
931  */
932 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
933         emit_env_t emit_env;
934
935         emit_env.mod      = firm_dbg_register("ir.be.codegen.ia32");
936         emit_env.out      = F;
937         emit_env.arch_env = cg->arch_env;
938         emit_env.cg       = cg;
939
940         /* set the global arch_env (needed by print hooks) */
941         arch_env = cg->arch_env;
942
943         ia32_emit_start(F, irg);
944         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
945         irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
946         ia32_emit_end(F, irg);
947 }