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