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         if (! buf) {
47                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
48         }
49         else {
50                 memset(buf, 0, SNPRINTF_BUF_LEN);
51         }
52
53         switch(get_ia32_op_type(n)) {
54                 case ia32_Normal:
55                         if (get_ia32_cnst(n)) {
56                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %s", n, get_ia32_cnst(n));
57                         }
58                         else {
59                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %4S", n, n);
60                         }
61                         break;
62                 case ia32_AddrModeS:
63                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D, %s", n, ia32_emit_am(n));
64                         break;
65                 case ia32_AddrModeD:
66                         if (get_ia32_cnst(n)) {
67                                 lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %s", ia32_emit_am(n), get_ia32_cnst(n));
68                         }
69                         else {
70                                 if (is_ia32_St(n)) {
71                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %3S", ia32_emit_am(n), n);
72                                 }
73                                 else {
74                                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%s, %4S", ia32_emit_am(n), n);
75                                 }
76                         }
77                         break;
78                 default:
79                         assert(0 && "unsupported op type");
80         }
81
82         return buf;
83 }
84
85 /**
86  * Emits registers and/or address mode of a unary operation.
87  */
88 char *ia32_emit_unop(const ir_node *n) {
89         static char *buf = NULL;
90
91         if (! buf) {
92                 buf = xcalloc(1, SNPRINTF_BUF_LEN);
93         }
94         else {
95                 memset(buf, 0, SNPRINTF_BUF_LEN);
96         }
97
98         switch(get_ia32_op_type(n)) {
99                 case ia32_Normal:
100                         lc_esnprintf(ia32_get_arg_env(), buf, SNPRINTF_BUF_LEN, "%1D", n);
101                         break;
102                 case ia32_am_Dest:
103                         snprintf(buf, SNPRINTF_BUF_LEN, ia32_emit_am(n));
104                         break;
105                 default:
106                         assert(0 && "unsupported op type");
107         }
108
109         return buf;
110 }
111
112 /**
113  * Emits adressmode.
114  */
115 char *ia32_emit_am(const ir_node *n) {
116         ia32_am_flavour_t am_flav    = get_ia32_am_flavour(n);
117         int               had_output = 0;
118         char             *s;
119         int               size;
120         static struct obstack *obst  = NULL;
121
122         if (! obst) {
123                 obst = xcalloc(1, sizeof(*obst));
124         }
125         else {
126                 obstack_free(obst, NULL);
127         }
128
129         /* obstack_free with NULL results in an uninitialized obstack */
130         obstack_init(obst);
131
132         obstack_printf(obst, "[");
133
134         if (am_flav & ia32_B) {
135                 lc_eoprintf(ia32_get_arg_env(), obst, "%1S", n);
136                 had_output = 1;
137         }
138
139         if (am_flav & ia32_I) {
140                 if (had_output) {
141                         obstack_printf(obst, "+");
142                 }
143
144                 lc_eoprintf(ia32_get_arg_env(), obst, "%2S", n);
145
146                 if (am_flav & ia32_S) {
147                         obstack_printf(obst, "*%d", 1 << get_ia32_am_scale(n));
148                 }
149
150                 had_output = 1;
151         }
152
153         if (am_flav & ia32_O) {
154                 obstack_printf(obst, get_ia32_am_offs(n));
155         }
156
157         obstack_printf(obst, "] ");
158
159         size        = obstack_object_size(obst);
160         s           = obstack_finish(obst);
161         s[size - 1] = '\0';
162
163         return s;
164 }
165
166 /*************************************************************
167  *             _       _    __   _          _
168  *            (_)     | |  / _| | |        | |
169  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
170  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
171  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
172  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
173  * | |                                       | |
174  * |_|                                       |_|
175  *************************************************************/
176
177 /* We always pass the ir_node which is a pointer. */
178 static int ia32_get_arg_type(const lc_arg_occ_t *occ) {
179         return lc_arg_type_ptr;
180 }
181
182
183 /**
184  * Returns the register at in position pos.
185  */
186 static const arch_register_t *get_in_reg(const ir_node *irn, int pos) {
187         ir_node                *op;
188         const arch_register_t  *reg = NULL;
189
190         assert(get_irn_arity(irn) > pos && "Invalid IN position");
191
192         /* The out register of the operator at position pos is the
193            in register we need. */
194         op = get_irn_n(irn, pos);
195
196         reg = arch_get_irn_register(arch_env, op);
197
198         assert(reg && "no in register found");
199         return reg;
200 }
201
202 /**
203  * Returns the register at out position pos.
204  */
205 static const arch_register_t *get_out_reg(const ir_node *irn, int pos) {
206         ir_node                *proj;
207         const arch_register_t  *reg = NULL;
208
209         assert(get_irn_n_edges(irn) > pos && "Invalid OUT position");
210
211         /* 1st case: irn is not of mode_T, so it has only                 */
212         /*           one OUT register -> good                             */
213         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
214         /*           Proj with the corresponding projnum for the register */
215
216         if (get_irn_mode(irn) != mode_T) {
217                 reg = arch_get_irn_register(arch_env, irn);
218         }
219         else if (is_ia32_irn(irn)) {
220                 reg = get_ia32_out_reg(irn, pos);
221         }
222         else {
223                 const ir_edge_t *edge;
224
225                 foreach_out_edge(irn, edge) {
226                         proj = get_edge_src_irn(edge);
227                         assert(is_Proj(proj) && "non-Proj from mode_T node");
228                         if (get_Proj_proj(proj) == pos) {
229                                 reg = arch_get_irn_register(arch_env, proj);
230                                 break;
231                         }
232                 }
233         }
234
235         assert(reg && "no out register found");
236         return reg;
237 }
238
239 /**
240  * Returns the number of the in register at position pos.
241  */
242 int get_ia32_reg_nr(ir_node *irn, int pos, int in_out) {
243         const arch_register_t *reg;
244
245         if (in_out == 1) {
246                 reg = get_in_reg(irn, pos);
247         }
248         else {
249                 reg = get_out_reg(irn, pos);
250         }
251
252         return arch_register_get_index(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 (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 %2S, %1S\t\t\t/* CondJmp(%+F, %+F) */\n", irn, irn,
492                                                                                                                                         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 %C, %1S\t\t\t/* CondJmp_i(%+F) */\n", irn, irn, get_irn_n(irn, 0));
503         finish_CondJmp(F, irn);
504 }
505
506
507
508 /*********************************************************
509  *                 _ _       _
510  *                (_) |     (_)
511  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
512  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
513  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
514  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
515  *                         _/ |               | |
516  *                        |__/                |_|
517  *********************************************************/
518
519 /* jump table entry (target and corresponding number) */
520 typedef struct _branch_t {
521         ir_node *target;
522         int      value;
523 } branch_t;
524
525 /* jump table for switch generation */
526 typedef struct _jmp_tbl_t {
527         ir_node  *defProj;         /**< default target */
528         int       min_value;       /**< smallest switch case */
529         int       max_value;       /**< largest switch case */
530         int       num_branches;    /**< number of jumps */
531         char     *label;           /**< label of the jump table */
532         branch_t *branches;        /**< jump array */
533 } jmp_tbl_t;
534
535 /**
536  * Compare two variables of type branch_t. Used to sort all switch cases
537  */
538 static int ia32_cmp_branch_t(const void *a, const void *b) {
539         branch_t *b1 = (branch_t *)a;
540         branch_t *b2 = (branch_t *)b;
541
542         if (b1->value <= b2->value)
543                 return -1;
544         else
545                 return 1;
546 }
547
548 /**
549  * Emits code for a SwitchJmp (creates a jump table if
550  * possible otherwise a cmp-jmp cascade). Port from
551  * cggg ia32 backend
552  */
553 void emit_ia32_SwitchJmp(const ir_node *irn, emit_env_t *emit_env) {
554         unsigned long       interval;
555         char                buf[SNPRINTF_BUF_LEN];
556         int                 last_value, i, pn, do_jmp_tbl = 1;
557         jmp_tbl_t           tbl;
558         ir_node            *proj;
559         const ir_edge_t    *edge;
560         const lc_arg_env_t *env = ia32_get_arg_env();
561         FILE               *F   = emit_env->out;
562
563         /* fill the table structure */
564         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
565         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, "JMPTBL_");
566         tbl.defProj      = NULL;
567         tbl.num_branches = get_irn_n_edges(irn);
568         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
569         tbl.min_value    = INT_MAX;
570         tbl.max_value    = INT_MIN;
571
572         i = 0;
573         /* go over all proj's and collect them */
574         foreach_out_edge(irn, edge) {
575                 proj = get_edge_src_irn(edge);
576                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
577
578                 pn = get_Proj_proj(proj);
579
580                 /* create branch entry */
581                 tbl.branches[i].target = proj;
582                 tbl.branches[i].value  = pn;
583
584                 tbl.min_value = pn < tbl.min_value ? pn : tbl.min_value;
585                 tbl.max_value = pn > tbl.max_value ? pn : tbl.max_value;
586
587                 /* check for default proj */
588                 if (pn == get_ia32_pncode(irn)) {
589                         assert(tbl.defProj == NULL && "found two defProjs at SwitchJmp");
590                         tbl.defProj = proj;
591                 }
592
593                 i++;
594         }
595
596         /* sort the branches by their number */
597         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
598
599         /* two-complement's magic make this work without overflow */
600         interval = tbl.max_value - tbl.min_value;
601
602         /* check value interval */
603         if (interval > 16 * 1024) {
604                 do_jmp_tbl = 0;
605         }
606
607         /* check ratio of value interval to number of branches */
608         if ((float)(interval + 1) / (float)tbl.num_branches > 8.0) {
609                 do_jmp_tbl = 0;
610         }
611
612         if (do_jmp_tbl) {
613                 /* emit the table */
614                 if (tbl.min_value != 0) {
615                         lc_efprintf(env, F, "\tcmpl %lu, -%d(%1S)\t\t/* first switch value is not 0 */\n",
616                                 interval, tbl.min_value, irn);
617                 }
618                 else {
619                         lc_efprintf(env, F, "\tcmpl %lu, %1S\t\t\t/* compare for switch */\n", interval, irn);
620                 }
621
622                 fprintf(F, "\tja %s\t\t\t/* default jump if out of range  */\n", get_cfop_target(tbl.defProj, buf));
623
624                 if (tbl.num_branches > 1) {
625                         /* create table */
626
627                         lc_efprintf(env, F, "\tjmp *%s(,%1S,4)\t\t/* get jump table entry as target */\n", tbl.label, irn);
628
629                         fprintf(F, "\t.section\t.rodata\t\t/* start jump table */\n");
630                         fprintf(F, "\t.align 4\n");
631
632                         fprintf(F, "%s:\n", tbl.label);
633                         fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[0].target, buf), tbl.branches[0].value);
634
635                         last_value = tbl.branches[0].value;
636                         for (i = 1; i < tbl.num_branches; ++i) {
637                                 while (++last_value < tbl.branches[i].value) {
638                                         fprintf(F, "\t.long %s\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
639                                 }
640                                 fprintf(F, "\t.long %s\t\t\t/* case %d */\n", get_cfop_target(tbl.branches[i].target, buf), last_value);
641                         }
642
643                         fprintf(F, "\t.text\t\t\t\t/* end of jump table */\n");
644                 }
645                 else {
646                         /* one jump is enough */
647                         fprintf(F, "\tjmp %s\t\t/* only one case given */\n", get_cfop_target(tbl.branches[0].target, buf));
648                 }
649         }
650         else { // no jump table
651                 for (i = 0; i < tbl.num_branches; ++i) {
652                         lc_efprintf(env, F, "\tcmpl %d, %1S\t\t\t/* case %d */\n", tbl.branches[i].value, irn, i);
653                         fprintf(F, "\tje %s\n", get_cfop_target(tbl.branches[i].target, buf));
654                 }
655
656                 fprintf(F, "\tjmp %s\t\t\t/* default case */\n", get_cfop_target(tbl.defProj, buf));
657         }
658
659         if (tbl.label)
660                 free(tbl.label);
661         if (tbl.branches)
662                 free(tbl.branches);
663 }
664
665 /**
666  * Emits code for a unconditional jump.
667  */
668 void emit_Jmp(const ir_node *irn, emit_env_t *env) {
669         FILE *F = env->out;
670
671         char buf[SNPRINTF_BUF_LEN];
672         ir_fprintf(F, "\tjmp %s\t\t\t/* Jmp(%+F) */\n", get_cfop_target(irn, buf), get_irn_link(irn));
673 }
674
675
676
677 /****************************
678  *                  _
679  *                 (_)
680  *  _ __  _ __ ___  _  ___
681  * | '_ \| '__/ _ \| |/ __|
682  * | |_) | | | (_) | |\__ \
683  * | .__/|_|  \___/| ||___/
684  * | |            _/ |
685  * |_|           |__/
686  ****************************/
687
688 /**
689  * Emits code for a proj -> node
690  */
691 void emit_Proj(const ir_node *irn, emit_env_t *env) {
692         ir_node *pred = get_Proj_pred(irn);
693
694         if (get_irn_op(pred) == op_Start) {
695                 switch(get_Proj_proj(irn)) {
696                         case pn_Start_X_initial_exec:
697                                 emit_Jmp(irn, env);
698                                 break;
699                         default:
700                                 break;
701                 }
702         }
703 }
704
705 /**********************************
706  *   _____                  ____
707  *  / ____|                |  _ \
708  * | |     ___  _ __  _   _| |_) |
709  * | |    / _ \| '_ \| | | |  _ <
710  * | |___| (_) | |_) | |_| | |_) |
711  *  \_____\___/| .__/ \__, |____/
712  *             | |     __/ |
713  *             |_|    |___/
714  **********************************/
715
716 static void emit_CopyB_prolog(FILE *F, int rem, int size) {
717         fprintf(F, "\t/* memcopy %d bytes*/\n", size);
718         fprintf(F, "\tcld\t\t\t\t/* copy direction forward*/\n");
719
720         switch(rem) {
721                 case 1:
722                         fprintf(F, "\tmovsb\t\t\t\t/* memcopy remainder 1 */\n");
723                         break;
724                 case 2:
725                         fprintf(F, "\tmovsw\t\t\t\t/* memcopy remainder 2 */\n");
726                         break;
727                 case 3:
728                         fprintf(F, "\tmovsb\t\t\t\t/* memcopy remainder 3 */\n");
729                         fprintf(F, "\tmovsw\t\t\t\t/* memcopy remainder 3 */\n");
730                         break;
731         }
732 }
733
734 void emit_ia32_CopyB(const ir_node *irn, emit_env_t *emit_env) {
735         FILE   *F    = emit_env->out;
736         tarval *tv   = get_ia32_Immop_tarval(irn);
737         int     rem  = get_tarval_long(tv);
738         int     size = get_tarval_long(get_ia32_Immop_tarval(get_irn_n(irn, 2)));
739
740         emit_CopyB_prolog(F, rem, size);
741
742         fprintf(F, "\trep movsd\t\t\t\t/* memcopy */\n");
743 }
744
745 void emit_ia32_CopyB_i(const ir_node *irn, emit_env_t *emit_env) {
746         tarval *tv   = get_ia32_Immop_tarval(irn);
747         int     size = get_tarval_long(tv);
748         FILE   *F    = emit_env->out;
749
750         emit_CopyB_prolog(F, size & 0x3, size);
751
752         size >>= 2;
753         while (size--) {
754                 fprintf(F, "\tmovsd\t\t\t\t/* memcopy unrolled */\n");
755         }
756 }
757
758
759
760 /*******************************************
761  *  _                          _
762  * | |                        | |
763  * | |__   ___ _ __   ___   __| | ___  ___
764  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
765  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
766  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
767  *
768  *******************************************/
769
770 void emit_be_Call(const ir_node *irn, emit_env_t *emit_env) {
771         FILE *F = emit_env->out;
772
773         lc_efprintf(ia32_get_arg_env(), F, "\tcall %3S\t\t\t/* %+F(%+F) (be_Call) */\n", irn, irn, get_irn_n(irn, 2));
774 }
775
776 void emit_be_IncSP(const ir_node *irn, emit_env_t *emit_env) {
777         FILE          *F    = emit_env->out;
778         unsigned       offs = be_get_IncSP_offset(irn);
779         be_stack_dir_t dir  = be_get_IncSP_direction(irn);
780
781         if (offs) {
782                 lc_efprintf(ia32_get_arg_env(), F, "\tadd %1S,%s%u\t\t\t/* %+F (IncSP) */\n", irn,
783                         (dir == be_stack_dir_along) ? " -" : " ", offs, irn);
784         }
785         else {
786                 fprintf(F, "\t\t\t\t\t/* omitted IncSP with 0 */\n");
787         }
788 }
789
790 void emit_be_AddSP(const ir_node *irn, emit_env_t *emit_env) {
791         FILE *F = emit_env->out;
792         lc_efprintf(ia32_get_arg_env(), F, "\tadd %1D, %1S\t\t\t/* %+F (AddSP) */\n", irn, irn, irn);
793 }
794
795
796
797 /***********************************************************************************
798  *                  _          __                                             _
799  *                 (_)        / _|                                           | |
800  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
801  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
802  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
803  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
804  *
805  ***********************************************************************************/
806
807 /**
808  * Enters the emitter functions for handled nodes into the generic
809  * pointer of an opcode.
810  */
811 static void ia32_register_emitters(void) {
812
813 #define IA32_EMIT(a) op_ia32_##a->ops.generic = (op_func)emit_ia32_##a
814 #define EMIT(a)      op_##a->ops.generic = (op_func)emit_##a
815 #define BE_EMIT(a)   op_be_##a->ops.generic = (op_func)emit_be_##a
816
817         /* first clear the generic function pointer for all ops */
818         clear_irp_opcodes_generic_func();
819
820         /* register all emitter functions defined in spec */
821         ia32_register_spec_emitters();
822
823         /* other ia32 emitter functions */
824         IA32_EMIT(CondJmp);
825         IA32_EMIT(SwitchJmp);
826         IA32_EMIT(CopyB);
827         IA32_EMIT(CopyB_i);
828
829         /* benode emitter */
830         BE_EMIT(Call);
831         BE_EMIT(IncSP);
832         // BE_EMIT(AddSP);
833
834         /* firm emitter */
835         EMIT(Jmp);
836         EMIT(Proj);
837
838 #undef IA32_EMIT
839 #undef BE_EMIT
840 #undef EMIT
841 }
842
843 /**
844  * Emits code for a node.
845  */
846 static void ia32_emit_node(const ir_node *irn, void *env) {
847         emit_env_t        *emit_env = env;
848         firm_dbg_module_t *mod      = emit_env->mod;
849         FILE              *F        = emit_env->out;
850         ir_op             *op       = get_irn_op(irn);
851
852         DBG((mod, LEVEL_1, "emitting code for %+F\n", irn));
853
854         if (op->ops.generic) {
855                 void (*emit)(const ir_node *, void *) = (void (*)(const ir_node *, void *))op->ops.generic;
856                 (*emit)(irn, env);
857         }
858         else {
859                 ir_fprintf(F, "\t\t\t\t\t/* %+F */\n", irn);
860         }
861 }
862
863 /**
864  * Walks over the nodes in a block connected by scheduling edges
865  * and emits code for each node.
866  */
867 static void ia32_gen_block(ir_node *block, void *env) {
868         const ir_node *irn;
869
870         if (! is_Block(block))
871                 return;
872
873         fprintf(((emit_env_t *)env)->out, "BLOCK_%ld:\n", get_irn_node_nr(block));
874         sched_foreach(block, irn) {
875                 ia32_emit_node(irn, env);
876         }
877 }
878
879
880 /**
881  * Emits code for function start.
882  */
883 static void ia32_emit_func_prolog(FILE *F, ir_graph *irg) {
884         const char *irg_name = get_entity_name(get_irg_entity(irg));
885
886         fprintf(F, "\t.text\n");
887         fprintf(F, ".globl %s\n", irg_name);
888         fprintf(F, "\t.type\t%s, @function\n", irg_name);
889         fprintf(F, "%s:\n", irg_name);
890 }
891
892 /**
893  * Emits code for function end
894  */
895 static void ia32_emit_func_epilog(FILE *F, ir_graph *irg) {
896         const char *irg_name = get_entity_name(get_irg_entity(irg));
897
898         fprintf(F, "\tret\n");
899         fprintf(F, "\t.size\t%s, .-%s\n\n", irg_name, irg_name);
900 }
901
902 /**
903  * Sets labels for control flow nodes (jump target)
904  * TODO: Jump optimization
905  */
906 static void ia32_gen_labels(ir_node *block, void *env) {
907         ir_node *pred;
908         int n = get_Block_n_cfgpreds(block);
909
910         for (n--; n >= 0; n--) {
911                 pred = get_Block_cfgpred(block, n);
912                 set_irn_link(pred, block);
913         }
914 }
915
916 /**
917  * Main driver. Emits the code for one routine.
918  */
919 void ia32_gen_routine(FILE *F, ir_graph *irg, const ia32_code_gen_t *cg) {
920         emit_env_t emit_env;
921
922         emit_env.mod      = firm_dbg_register("ir.be.codegen.ia32");
923         emit_env.out      = F;
924         emit_env.arch_env = cg->arch_env;
925         emit_env.cg       = cg;
926
927         /* set the global arch_env (needed by print hooks) */
928         arch_env = cg->arch_env;
929
930         ia32_register_emitters();
931
932         ia32_emit_func_prolog(F, irg);
933         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &emit_env);
934         irg_walk_blkwise_graph(irg, NULL, ia32_gen_block, &emit_env);
935         ia32_emit_func_epilog(F, irg);
936 }