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