d377143b0af700954862016768d01af9254fa5f0
[libfirm] / ir / be / ia32 / ia32_emitter.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       This file implements the ia32 node emitter.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include <limits.h>
31
32 #include "xmalloc.h"
33 #include "tv.h"
34 #include "iredges.h"
35 #include "debug.h"
36 #include "irgwalk.h"
37 #include "irprintf.h"
38 #include "irop_t.h"
39 #include "irargs_t.h"
40 #include "irprog_t.h"
41 #include "iredges_t.h"
42 #include "execfreq.h"
43 #include "error.h"
44 #include "raw_bitset.h"
45 #include "dbginfo.h"
46
47 #include "../besched_t.h"
48 #include "../benode_t.h"
49 #include "../beabi.h"
50 #include "../be_dbgout.h"
51 #include "../beemitter.h"
52 #include "../begnuas.h"
53 #include "../beirg_t.h"
54 #include "../be_dbgout.h"
55
56 #include "ia32_emitter.h"
57 #include "gen_ia32_emitter.h"
58 #include "gen_ia32_regalloc_if.h"
59 #include "ia32_nodes_attr.h"
60 #include "ia32_new_nodes.h"
61 #include "ia32_map_regs.h"
62 #include "ia32_architecture.h"
63 #include "bearch_ia32_t.h"
64
65 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
66
67 #define BLOCK_PREFIX ".L"
68
69 #define SNPRINTF_BUF_LEN 128
70
71 static const arch_env_t *arch_env;
72 static const ia32_isa_t *isa;
73 static ia32_code_gen_t  *cg;
74 static int               do_pic;
75 static char              pic_base_label[128];
76 static ir_label_t        exc_label_id;
77
78 /** Return the next block in Block schedule */
79 static ir_node *get_prev_block_sched(const ir_node *block)
80 {
81         return get_irn_link(block);
82 }
83
84 static int is_fallthrough(const ir_node *cfgpred)
85 {
86         ir_node *pred;
87
88         if (!is_Proj(cfgpred))
89                 return 1;
90         pred = get_Proj_pred(cfgpred);
91         if (is_ia32_SwitchJmp(pred))
92                 return 0;
93
94         return 1;
95 }
96
97 static int block_needs_label(const ir_node *block)
98 {
99         int need_label = 1;
100         int  n_cfgpreds = get_Block_n_cfgpreds(block);
101
102         if (n_cfgpreds == 0) {
103                 need_label = 0;
104         } else if (n_cfgpreds == 1) {
105                 ir_node *cfgpred       = get_Block_cfgpred(block, 0);
106                 ir_node *cfgpred_block = get_nodes_block(cfgpred);
107
108                 if (get_prev_block_sched(block) == cfgpred_block
109                                 && is_fallthrough(cfgpred)) {
110                         need_label = 0;
111                 }
112         }
113
114         return need_label;
115 }
116
117 /**
118  * Returns the register at in position pos.
119  */
120 static const arch_register_t *get_in_reg(const ir_node *irn, int pos)
121 {
122         ir_node               *op;
123         const arch_register_t *reg = NULL;
124
125         assert(get_irn_arity(irn) > pos && "Invalid IN position");
126
127         /* The out register of the operator at position pos is the
128            in register we need. */
129         op = get_irn_n(irn, pos);
130
131         reg = arch_get_irn_register(arch_env, op);
132
133         assert(reg && "no in register found");
134
135         if (reg == &ia32_gp_regs[REG_GP_NOREG])
136                 panic("trying to emit noreg for %+F input %d", irn, pos);
137
138         /* in case of unknown register: just return a valid register */
139         if (reg == &ia32_gp_regs[REG_GP_UKNWN]) {
140                 const arch_register_req_t *req;
141
142                 /* ask for the requirements */
143                 req = arch_get_register_req(arch_env, irn, pos);
144
145                 if (arch_register_req_is(req, limited)) {
146                         /* in case of limited requirements: get the first allowed register */
147                         unsigned idx = rbitset_next(req->limited, 0, 1);
148                         reg = arch_register_for_index(req->cls, idx);
149                 } else {
150                         /* otherwise get first register in class */
151                         reg = arch_register_for_index(req->cls, 0);
152                 }
153         }
154
155         return reg;
156 }
157
158 /**
159  * Returns the register at out position pos.
160  */
161 static const arch_register_t *get_out_reg(const ir_node *irn, int pos)
162 {
163         ir_node               *proj;
164         const arch_register_t *reg = NULL;
165
166         /* 1st case: irn is not of mode_T, so it has only                 */
167         /*           one OUT register -> good                             */
168         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
169         /*           Proj with the corresponding projnum for the register */
170
171         if (get_irn_mode(irn) != mode_T) {
172                 assert(pos == 0);
173                 reg = arch_get_irn_register(arch_env, irn);
174         } else if (is_ia32_irn(irn)) {
175                 reg = get_ia32_out_reg(irn, pos);
176         } else {
177                 const ir_edge_t *edge;
178
179                 foreach_out_edge(irn, edge) {
180                         proj = get_edge_src_irn(edge);
181                         assert(is_Proj(proj) && "non-Proj from mode_T node");
182                         if (get_Proj_proj(proj) == pos) {
183                                 reg = arch_get_irn_register(arch_env, proj);
184                                 break;
185                         }
186                 }
187         }
188
189         assert(reg && "no out register found");
190         return reg;
191 }
192
193 /**
194  * Add a number to a prefix. This number will not be used a second time.
195  */
196 static char *get_unique_label(char *buf, size_t buflen, const char *prefix)
197 {
198         static unsigned long id = 0;
199         snprintf(buf, buflen, "%s%lu", prefix, ++id);
200         return buf;
201 }
202
203 /*************************************************************
204  *             _       _    __   _          _
205  *            (_)     | |  / _| | |        | |
206  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
207  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
208  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
209  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
210  * | |                                       | |
211  * |_|                                       |_|
212  *************************************************************/
213
214 static void emit_8bit_register(const arch_register_t *reg)
215 {
216         const char *reg_name = arch_register_get_name(reg);
217
218         be_emit_char('%');
219         be_emit_char(reg_name[1]);
220         be_emit_char('l');
221 }
222
223 static void emit_16bit_register(const arch_register_t *reg)
224 {
225         const char *reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
226
227         be_emit_char('%');
228         be_emit_string(reg_name);
229 }
230
231 static void emit_register(const arch_register_t *reg, const ir_mode *mode)
232 {
233         const char *reg_name;
234
235         if (mode != NULL) {
236                 int size = get_mode_size_bits(mode);
237                 switch (size) {
238                         case  8: emit_8bit_register(reg);  return;
239                         case 16: emit_16bit_register(reg); return;
240                 }
241                 assert(mode_is_float(mode) || size == 32);
242         }
243
244         reg_name = arch_register_get_name(reg);
245
246         be_emit_char('%');
247         be_emit_string(reg_name);
248 }
249
250 void ia32_emit_source_register(const ir_node *node, int pos)
251 {
252         const arch_register_t *reg = get_in_reg(node, pos);
253
254         emit_register(reg, NULL);
255 }
256
257 static void emit_ia32_Immediate(const ir_node *node);
258
259 void ia32_emit_8bit_source_register_or_immediate(const ir_node *node, int pos)
260 {
261         const arch_register_t *reg;
262         ir_node               *in = get_irn_n(node, pos);
263         if (is_ia32_Immediate(in)) {
264                 emit_ia32_Immediate(in);
265                 return;
266         }
267
268         reg = get_in_reg(node, pos);
269         emit_8bit_register(reg);
270 }
271
272 void ia32_emit_dest_register(const ir_node *node, int pos)
273 {
274         const arch_register_t *reg  = get_out_reg(node, pos);
275
276         emit_register(reg, NULL);
277 }
278
279 void ia32_emit_8bit_dest_register(const ir_node *node, int pos)
280 {
281         const arch_register_t *reg  = get_out_reg(node, pos);
282
283         emit_register(reg, mode_Bu);
284 }
285
286 void ia32_emit_x87_register(const ir_node *node, int pos)
287 {
288         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
289
290         assert(pos < 3);
291         be_emit_char('%');
292         be_emit_string(attr->x87[pos]->name);
293 }
294
295 static void ia32_emit_mode_suffix_mode(const ir_mode *mode)
296 {
297         if (mode_is_float(mode)) {
298                 switch(get_mode_size_bits(mode)) {
299                 case 32: be_emit_char('s'); return;
300                 case 64: be_emit_char('l'); return;
301                 case 80:
302                 case 96: be_emit_char('t'); return;
303                 }
304         } else {
305                 assert(mode_is_int(mode) || mode_is_reference(mode));
306                 switch(get_mode_size_bits(mode)) {
307                 /* gas docu says q is the suffix but gcc, objdump and icc use ll
308                  * apparently */
309                 case 64: be_emit_cstring("ll"); return;
310                 case 32: be_emit_char('l');     return;
311                 case 16: be_emit_char('w');     return;
312                 case 8:  be_emit_char('b');     return;
313                 }
314         }
315         panic("Can't output mode_suffix for %+F", mode);
316 }
317
318 void ia32_emit_mode_suffix(const ir_node *node)
319 {
320         ir_mode *mode = get_ia32_ls_mode(node);
321         if (mode == NULL)
322                 mode = mode_Iu;
323
324         ia32_emit_mode_suffix_mode(mode);
325 }
326
327 void ia32_emit_x87_mode_suffix(const ir_node *node)
328 {
329         /* we only need to emit the mode on address mode */
330         if (get_ia32_op_type(node) != ia32_Normal) {
331                 ir_mode *mode = get_ia32_ls_mode(node);
332                 assert(mode != NULL);
333                 ia32_emit_mode_suffix_mode(mode);
334         }
335 }
336
337 static char get_xmm_mode_suffix(ir_mode *mode)
338 {
339         assert(mode_is_float(mode));
340         switch(get_mode_size_bits(mode)) {
341         case 32: return 's';
342         case 64: return 'd';
343         default: panic("Invalid XMM mode");
344         }
345 }
346
347 void ia32_emit_xmm_mode_suffix(const ir_node *node)
348 {
349         ir_mode *mode = get_ia32_ls_mode(node);
350         assert(mode != NULL);
351         be_emit_char('s');
352         be_emit_char(get_xmm_mode_suffix(mode));
353 }
354
355 void ia32_emit_xmm_mode_suffix_s(const ir_node *node)
356 {
357         ir_mode *mode = get_ia32_ls_mode(node);
358         assert(mode != NULL);
359         be_emit_char(get_xmm_mode_suffix(mode));
360 }
361
362 void ia32_emit_extend_suffix(const ir_mode *mode)
363 {
364         if (get_mode_size_bits(mode) == 32)
365                 return;
366         be_emit_char(mode_is_signed(mode) ? 's' : 'z');
367 }
368
369 void ia32_emit_source_register_or_immediate(const ir_node *node, int pos)
370 {
371         ir_node *in = get_irn_n(node, pos);
372         if (is_ia32_Immediate(in)) {
373                 emit_ia32_Immediate(in);
374         } else {
375                 const ir_mode         *mode = get_ia32_ls_mode(node);
376                 const arch_register_t *reg  = get_in_reg(node, pos);
377                 emit_register(reg, mode);
378         }
379 }
380
381 /**
382  * Emits registers and/or address mode of a binary operation.
383  */
384 void ia32_emit_binop(const ir_node *node)
385 {
386         const ir_node         *right_op  = get_irn_n(node, n_ia32_binary_right);
387         const ir_mode         *mode      = get_ia32_ls_mode(node);
388         const arch_register_t *reg_left;
389
390         switch(get_ia32_op_type(node)) {
391         case ia32_Normal:
392                 reg_left = get_in_reg(node, n_ia32_binary_left);
393                 if (is_ia32_Immediate(right_op)) {
394                         emit_ia32_Immediate(right_op);
395                         be_emit_cstring(", ");
396                         emit_register(reg_left, mode);
397                         break;
398                 } else {
399                         const arch_register_t *reg_right
400                                 = get_in_reg(node, n_ia32_binary_right);
401                         emit_register(reg_right, mode);
402                         be_emit_cstring(", ");
403                         emit_register(reg_left, mode);
404                 }
405                 break;
406         case ia32_AddrModeS:
407                 if (is_ia32_Immediate(right_op)) {
408                         emit_ia32_Immediate(right_op);
409                         be_emit_cstring(", ");
410                         ia32_emit_am(node);
411                 } else {
412                         reg_left = get_in_reg(node, n_ia32_binary_left);
413                         ia32_emit_am(node);
414                         be_emit_cstring(", ");
415                         emit_register(reg_left, mode);
416                 }
417                 break;
418         case ia32_AddrModeD:
419                 panic("DestMode can't be output by %%binop anymore");
420                 break;
421         default:
422                 assert(0 && "unsupported op type");
423         }
424 }
425
426 /**
427  * Emits registers and/or address mode of a binary operation.
428  */
429 void ia32_emit_x87_binop(const ir_node *node)
430 {
431         switch(get_ia32_op_type(node)) {
432                 case ia32_Normal:
433                         {
434                                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
435                                 const arch_register_t *in1      = x87_attr->x87[0];
436                                 const arch_register_t *in2      = x87_attr->x87[1];
437                                 const arch_register_t *out      = x87_attr->x87[2];
438                                 const arch_register_t *in;
439
440                                 in  = out ? ((out == in2) ? in1 : in2) : in2;
441                                 out = out ? out : in1;
442
443                                 be_emit_char('%');
444                                 be_emit_string(arch_register_get_name(in));
445                                 be_emit_cstring(", %");
446                                 be_emit_string(arch_register_get_name(out));
447                         }
448                         break;
449                 case ia32_AddrModeS:
450                         ia32_emit_am(node);
451                         break;
452                 case ia32_AddrModeD:
453                 default:
454                         assert(0 && "unsupported op type");
455         }
456 }
457
458 /**
459  * Emits registers and/or address mode of a unary operation.
460  */
461 void ia32_emit_unop(const ir_node *node, int pos)
462 {
463         const ir_node *op;
464
465         switch(get_ia32_op_type(node)) {
466         case ia32_Normal:
467                 op = get_irn_n(node, pos);
468                 if (is_ia32_Immediate(op)) {
469                         emit_ia32_Immediate(op);
470                 } else {
471                         ia32_emit_source_register(node, pos);
472                 }
473                 break;
474         case ia32_AddrModeS:
475         case ia32_AddrModeD:
476                 ia32_emit_am(node);
477                 break;
478         default:
479                 assert(0 && "unsupported op type");
480         }
481 }
482
483 static void ia32_emit_entity(ir_entity *entity, int no_pic_adjust)
484 {
485         ident *id;
486
487         set_entity_backend_marked(entity, 1);
488         id = get_entity_ld_ident(entity);
489         be_emit_ident(id);
490
491         if (get_entity_owner(entity) == get_tls_type()) {
492                 if (get_entity_visibility(entity) == visibility_external_allocated) {
493                         be_emit_cstring("@INDNTPOFF");
494                 } else {
495                         be_emit_cstring("@NTPOFF");
496                 }
497         }
498
499         if (!no_pic_adjust && do_pic) {
500                 /* TODO: only do this when necessary */
501                 be_emit_char('-');
502                 be_emit_string(pic_base_label);
503         }
504 }
505
506 /**
507  * Emits address mode.
508  */
509 void ia32_emit_am(const ir_node *node)
510 {
511         ir_entity *ent       = get_ia32_am_sc(node);
512         int        offs      = get_ia32_am_offs_int(node);
513         ir_node   *base      = get_irn_n(node, n_ia32_base);
514         int        has_base  = !is_ia32_NoReg_GP(base);
515         ir_node   *index     = get_irn_n(node, n_ia32_index);
516         int        has_index = !is_ia32_NoReg_GP(index);
517
518         /* just to be sure... */
519         assert(!is_ia32_use_frame(node) || get_ia32_frame_ent(node) != NULL);
520
521         /* emit offset */
522         if (ent != NULL) {
523                 if (is_ia32_am_sc_sign(node))
524                         be_emit_char('-');
525                 ia32_emit_entity(ent, 0);
526         }
527
528         /* also handle special case if nothing is set */
529         if (offs != 0 || (ent == NULL && !has_base && !has_index)) {
530                 if (ent != NULL) {
531                         be_emit_irprintf("%+d", offs);
532                 } else {
533                         be_emit_irprintf("%d", offs);
534                 }
535         }
536
537         if (has_base || has_index) {
538                 be_emit_char('(');
539
540                 /* emit base */
541                 if (has_base) {
542                         const arch_register_t *reg = get_in_reg(node, n_ia32_base);
543                         emit_register(reg, NULL);
544                 }
545
546                 /* emit index + scale */
547                 if (has_index) {
548                         const arch_register_t *reg = get_in_reg(node, n_ia32_index);
549                         int scale;
550                         be_emit_char(',');
551                         emit_register(reg, NULL);
552
553                         scale = get_ia32_am_scale(node);
554                         if (scale > 0) {
555                                 be_emit_irprintf(",%d", 1 << scale);
556                         }
557                 }
558                 be_emit_char(')');
559         }
560 }
561
562 static void emit_ia32_IMul(const ir_node *node)
563 {
564         ir_node               *left    = get_irn_n(node, n_ia32_IMul_left);
565         const arch_register_t *out_reg = get_out_reg(node, pn_ia32_IMul_res);
566
567         be_emit_cstring("\timul");
568         ia32_emit_mode_suffix(node);
569         be_emit_char(' ');
570
571         ia32_emit_binop(node);
572
573         /* do we need the 3-address form? */
574         if (is_ia32_NoReg_GP(left) ||
575                         get_in_reg(node, n_ia32_IMul_left) != out_reg) {
576                 be_emit_cstring(", ");
577                 emit_register(out_reg, get_ia32_ls_mode(node));
578         }
579         be_emit_finish_line_gas(node);
580 }
581
582 /*************************************************
583  *                 _ _                         _
584  *                (_) |                       | |
585  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
586  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
587  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
588  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
589  *
590  *************************************************/
591
592 #undef IA32_DO_EMIT
593 #define IA32_DO_EMIT(irn) ia32_fprintf_format(F, irn, cmd_buf, cmnt_buf)
594
595 /*
596  * coding of conditions
597  */
598 struct cmp2conditon_t {
599         const char *name;
600         int         num;
601 };
602
603 /*
604  * positive conditions for signed compares
605  */
606 static const struct cmp2conditon_t cmp2condition_s[] = {
607         { NULL,              pn_Cmp_False },  /* always false */
608         { "e",               pn_Cmp_Eq },     /* == */
609         { "l",               pn_Cmp_Lt },     /* < */
610         { "le",              pn_Cmp_Le },     /* <= */
611         { "g",               pn_Cmp_Gt },     /* > */
612         { "ge",              pn_Cmp_Ge },     /* >= */
613         { "ne",              pn_Cmp_Lg },     /* != */
614         { NULL,              pn_Cmp_Leg},     /* always true */
615 };
616
617 /*
618  * positive conditions for unsigned compares
619  */
620 static const struct cmp2conditon_t cmp2condition_u[] = {
621         { NULL,              pn_Cmp_False },  /* always false */
622         { "e",               pn_Cmp_Eq },     /* == */
623         { "b",               pn_Cmp_Lt },     /* < */
624         { "be",              pn_Cmp_Le },     /* <= */
625         { "a",               pn_Cmp_Gt },     /* > */
626         { "ae",              pn_Cmp_Ge },     /* >= */
627         { "ne",              pn_Cmp_Lg },     /* != */
628         { NULL,              pn_Cmp_Leg },   /* always true  */
629 };
630
631 /**
632  * walks up a tree of copies/perms/spills/reloads to find the original value
633  * that is moved around
634  */
635 static ir_node *find_original_value(ir_node *node)
636 {
637         if (irn_visited(node))
638                 return NULL;
639
640         mark_irn_visited(node);
641         if (be_is_Copy(node)) {
642                 return find_original_value(be_get_Copy_op(node));
643         } else if (be_is_CopyKeep(node)) {
644                 return find_original_value(be_get_CopyKeep_op(node));
645         } else if (is_Proj(node)) {
646                 ir_node *pred = get_Proj_pred(node);
647                 if (be_is_Perm(pred)) {
648                         return find_original_value(get_irn_n(pred, get_Proj_proj(node)));
649                 } else if (be_is_MemPerm(pred)) {
650                         return find_original_value(get_irn_n(pred, get_Proj_proj(node) + 1));
651                 } else if (is_ia32_Load(pred)) {
652                         return find_original_value(get_irn_n(pred, n_ia32_Load_mem));
653                 } else {
654                         return node;
655                 }
656         } else if (is_ia32_Store(node)) {
657                 return find_original_value(get_irn_n(node, n_ia32_Store_val));
658         } else if (is_Phi(node)) {
659                 int i, arity;
660                 arity = get_irn_arity(node);
661                 for (i = 0; i < arity; ++i) {
662                         ir_node *in  = get_irn_n(node, i);
663                         ir_node *res = find_original_value(in);
664
665                         if (res != NULL)
666                                 return res;
667                 }
668                 return NULL;
669         } else {
670                 return node;
671         }
672 }
673
674 static int determine_final_pnc(const ir_node *node, int flags_pos,
675                                int pnc)
676 {
677         ir_node           *flags = get_irn_n(node, flags_pos);
678         const ia32_attr_t *flags_attr;
679         flags = skip_Proj(flags);
680
681         if (is_ia32_Sahf(flags)) {
682                 ir_node *cmp = get_irn_n(flags, n_ia32_Sahf_val);
683                 if (!(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
684                                 || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp))) {
685                         inc_irg_visited(current_ir_graph);
686                         cmp = find_original_value(cmp);
687                         assert(cmp != NULL);
688                         assert(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
689                                || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp));
690                 }
691
692                 flags_attr = get_ia32_attr_const(cmp);
693                 if (flags_attr->data.ins_permuted)
694                         pnc = get_mirrored_pnc(pnc);
695                 pnc |= ia32_pn_Cmp_float;
696         } else if (is_ia32_Ucomi(flags) || is_ia32_Fucomi(flags)
697                         || is_ia32_Fucompi(flags)) {
698                 flags_attr = get_ia32_attr_const(flags);
699
700                 if (flags_attr->data.ins_permuted)
701                         pnc = get_mirrored_pnc(pnc);
702                 pnc |= ia32_pn_Cmp_float;
703         } else {
704 #if 0
705                 assert(is_ia32_Cmp(flags) || is_ia32_Test(flags)
706                                 || is_ia32_Cmp8Bit(flags) || is_ia32_Test8Bit(flags));
707 #endif
708                 flags_attr = get_ia32_attr_const(flags);
709
710                 if (flags_attr->data.ins_permuted)
711                         pnc = get_mirrored_pnc(pnc);
712                 if (flags_attr->data.cmp_unsigned)
713                         pnc |= ia32_pn_Cmp_unsigned;
714         }
715
716         return pnc;
717 }
718
719 static void ia32_emit_cmp_suffix(int pnc)
720 {
721         const char        *str;
722
723         if ((pnc & ia32_pn_Cmp_float) || (pnc & ia32_pn_Cmp_unsigned)) {
724                 pnc = pnc & 7;
725                 assert(cmp2condition_u[pnc].num == pnc);
726                 str = cmp2condition_u[pnc].name;
727         } else {
728                 pnc = pnc & 7;
729                 assert(cmp2condition_s[pnc].num == pnc);
730                 str = cmp2condition_s[pnc].name;
731         }
732
733         be_emit_string(str);
734 }
735
736 void ia32_emit_cmp_suffix_node(const ir_node *node,
737                                int flags_pos)
738 {
739         const ia32_attr_t *attr = get_ia32_attr_const(node);
740
741         pn_Cmp pnc = get_ia32_condcode(node);
742
743         pnc = determine_final_pnc(node, flags_pos, pnc);
744         if (attr->data.ins_permuted) {
745                 if (pnc & ia32_pn_Cmp_float) {
746                         pnc = get_negated_pnc(pnc, mode_F);
747                 } else {
748                         pnc = get_negated_pnc(pnc, mode_Iu);
749                 }
750         }
751
752         ia32_emit_cmp_suffix(pnc);
753 }
754
755 /**
756  * Returns the target block for a control flow node.
757  */
758 static ir_node *get_cfop_target_block(const ir_node *irn)
759 {
760         assert(get_irn_mode(irn) == mode_X);
761         return get_irn_link(irn);
762 }
763
764 /**
765  * Emits a block label for the given block.
766  */
767 static void ia32_emit_block_name(const ir_node *block)
768 {
769         if (has_Block_label(block)) {
770                 be_emit_string(be_gas_block_label_prefix());
771                 be_emit_irprintf("%lu", get_Block_label(block));
772         } else {
773                 be_emit_cstring(BLOCK_PREFIX);
774                 be_emit_irprintf("%ld", get_irn_node_nr(block));
775         }
776 }
777
778 /**
779  * Emits an exception label for a given node.
780  */
781 static void ia32_emit_exc_label(const ir_node *node)
782 {
783         be_emit_string(be_gas_insn_label_prefix());
784         be_emit_irprintf("%lu", get_ia32_exc_label_id(node));
785 }
786
787 /**
788  * Emits the target label for a control flow node.
789  */
790 static void ia32_emit_cfop_target(const ir_node *node)
791 {
792         ir_node *block = get_cfop_target_block(node);
793
794         ia32_emit_block_name(block);
795 }
796
797 /**
798  * Returns the Proj with projection number proj and NOT mode_M
799  */
800 static ir_node *get_proj(const ir_node *node, long proj)
801 {
802         const ir_edge_t *edge;
803         ir_node         *src;
804
805         assert(get_irn_mode(node) == mode_T && "expected mode_T node");
806
807         foreach_out_edge(node, edge) {
808                 src = get_edge_src_irn(edge);
809
810                 assert(is_Proj(src) && "Proj expected");
811                 if (get_irn_mode(src) == mode_M)
812                         continue;
813
814                 if (get_Proj_proj(src) == proj)
815                         return src;
816         }
817         return NULL;
818 }
819
820 static int can_be_fallthrough(const ir_node *node)
821 {
822         ir_node *target_block = get_cfop_target_block(node);
823         ir_node *block        = get_nodes_block(node);
824         return get_prev_block_sched(target_block) == block;
825 }
826
827 /**
828  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
829  */
830 static void emit_ia32_Jcc(const ir_node *node)
831 {
832         int            need_parity_label = 0;
833         const ir_node *proj_true;
834         const ir_node *proj_false;
835         const ir_node *block;
836         pn_Cmp         pnc = get_ia32_condcode(node);
837
838         pnc = determine_final_pnc(node, 0, pnc);
839
840         /* get both Projs */
841         proj_true = get_proj(node, pn_ia32_Jcc_true);
842         assert(proj_true && "Jcc without true Proj");
843
844         proj_false = get_proj(node, pn_ia32_Jcc_false);
845         assert(proj_false && "Jcc without false Proj");
846
847         block      = get_nodes_block(node);
848
849         if (can_be_fallthrough(proj_true)) {
850                 /* exchange both proj's so the second one can be omitted */
851                 const ir_node *t = proj_true;
852
853                 proj_true  = proj_false;
854                 proj_false = t;
855                 if (pnc & ia32_pn_Cmp_float) {
856                         pnc = get_negated_pnc(pnc, mode_F);
857                 } else {
858                         pnc = get_negated_pnc(pnc, mode_Iu);
859                 }
860         }
861
862         if (pnc & ia32_pn_Cmp_float) {
863                 /* Some floating point comparisons require a test of the parity flag,
864                  * which indicates that the result is unordered */
865                 switch (pnc & 15) {
866                         case pn_Cmp_Uo: {
867                                 be_emit_cstring("\tjp ");
868                                 ia32_emit_cfop_target(proj_true);
869                                 be_emit_finish_line_gas(proj_true);
870                                 break;
871                         }
872
873                         case pn_Cmp_Leg:
874                                 be_emit_cstring("\tjnp ");
875                                 ia32_emit_cfop_target(proj_true);
876                                 be_emit_finish_line_gas(proj_true);
877                                 break;
878
879                         case pn_Cmp_Eq:
880                         case pn_Cmp_Lt:
881                         case pn_Cmp_Le:
882                                 /* we need a local label if the false proj is a fallthrough
883                                  * as the falseblock might have no label emitted then */
884                                 if (can_be_fallthrough(proj_false)) {
885                                         need_parity_label = 1;
886                                         be_emit_cstring("\tjp 1f");
887                                 } else {
888                                         be_emit_cstring("\tjp ");
889                                         ia32_emit_cfop_target(proj_false);
890                                 }
891                                 be_emit_finish_line_gas(proj_false);
892                                 goto emit_jcc;
893
894                         case pn_Cmp_Ug:
895                         case pn_Cmp_Uge:
896                         case pn_Cmp_Ne:
897                                 be_emit_cstring("\tjp ");
898                                 ia32_emit_cfop_target(proj_true);
899                                 be_emit_finish_line_gas(proj_true);
900                                 goto emit_jcc;
901
902                         default:
903                                 goto emit_jcc;
904                 }
905         } else {
906 emit_jcc:
907                 be_emit_cstring("\tj");
908                 ia32_emit_cmp_suffix(pnc);
909                 be_emit_char(' ');
910                 ia32_emit_cfop_target(proj_true);
911                 be_emit_finish_line_gas(proj_true);
912         }
913
914         if (need_parity_label) {
915                 be_emit_cstring("1:");
916                 be_emit_write_line();
917         }
918
919         /* the second Proj might be a fallthrough */
920         if (can_be_fallthrough(proj_false)) {
921                 be_emit_cstring("\t/* fallthrough to ");
922                 ia32_emit_cfop_target(proj_false);
923                 be_emit_cstring(" */");
924                 be_emit_finish_line_gas(proj_false);
925         } else {
926                 be_emit_cstring("\tjmp ");
927                 ia32_emit_cfop_target(proj_false);
928                 be_emit_finish_line_gas(proj_false);
929         }
930 }
931
932 static void emit_ia32_CMov(const ir_node *node)
933 {
934         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
935         int                    ins_permuted = attr->data.ins_permuted;
936         const arch_register_t *out          = arch_get_irn_register(arch_env, node);
937         pn_Cmp                 pnc          = get_ia32_condcode(node);
938         const arch_register_t *in_true;
939         const arch_register_t *in_false;
940
941         pnc = determine_final_pnc(node, n_ia32_CMov_eflags, pnc);
942
943         in_true  = arch_get_irn_register(arch_env,
944                                          get_irn_n(node, n_ia32_CMov_val_true));
945         in_false = arch_get_irn_register(arch_env,
946                                          get_irn_n(node, n_ia32_CMov_val_false));
947
948         /* should be same constraint fullfilled? */
949         if (out == in_false) {
950                 /* yes -> nothing to do */
951         } else if (out == in_true) {
952                 const arch_register_t *tmp;
953
954                 assert(get_ia32_op_type(node) == ia32_Normal);
955
956                 ins_permuted = !ins_permuted;
957
958                 tmp      = in_true;
959                 in_true  = in_false;
960                 in_false = tmp;
961         } else {
962                 /* we need a mov */
963                 be_emit_cstring("\tmovl ");
964                 emit_register(in_false, NULL);
965                 be_emit_cstring(", ");
966                 emit_register(out, NULL);
967                 be_emit_finish_line_gas(node);
968         }
969
970         if (ins_permuted) {
971                 if (pnc & ia32_pn_Cmp_float) {
972                         pnc = get_negated_pnc(pnc, mode_F);
973                 } else {
974                         pnc = get_negated_pnc(pnc, mode_Iu);
975                 }
976         }
977
978         /* TODO: handling of Nans isn't correct yet */
979
980         be_emit_cstring("\tcmov");
981         ia32_emit_cmp_suffix(pnc);
982         be_emit_char(' ');
983         if (get_ia32_op_type(node) == ia32_AddrModeS) {
984                 ia32_emit_am(node);
985         } else {
986                 emit_register(in_true, get_ia32_ls_mode(node));
987         }
988         be_emit_cstring(", ");
989         emit_register(out, get_ia32_ls_mode(node));
990         be_emit_finish_line_gas(node);
991 }
992
993 /*********************************************************
994  *                 _ _       _
995  *                (_) |     (_)
996  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
997  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
998  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
999  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
1000  *                         _/ |               | |
1001  *                        |__/                |_|
1002  *********************************************************/
1003
1004 /* jump table entry (target and corresponding number) */
1005 typedef struct _branch_t {
1006         ir_node *target;
1007         int      value;
1008 } branch_t;
1009
1010 /* jump table for switch generation */
1011 typedef struct _jmp_tbl_t {
1012         ir_node  *defProj;         /**< default target */
1013         long      min_value;       /**< smallest switch case */
1014         long      max_value;       /**< largest switch case */
1015         long      num_branches;    /**< number of jumps */
1016         char     *label;           /**< label of the jump table */
1017         branch_t *branches;        /**< jump array */
1018 } jmp_tbl_t;
1019
1020 /**
1021  * Compare two variables of type branch_t. Used to sort all switch cases
1022  */
1023 static int ia32_cmp_branch_t(const void *a, const void *b)
1024 {
1025         branch_t *b1 = (branch_t *)a;
1026         branch_t *b2 = (branch_t *)b;
1027
1028         if (b1->value <= b2->value)
1029                 return -1;
1030         else
1031                 return 1;
1032 }
1033
1034 /**
1035  * Emits code for a SwitchJmp (creates a jump table if
1036  * possible otherwise a cmp-jmp cascade). Port from
1037  * cggg ia32 backend
1038  */
1039 static void emit_ia32_SwitchJmp(const ir_node *node)
1040 {
1041         unsigned long       interval;
1042         int                 last_value, i;
1043         long                pnc;
1044         long                default_pn;
1045         jmp_tbl_t           tbl;
1046         ir_node            *proj;
1047         const ir_edge_t    *edge;
1048
1049         /* fill the table structure */
1050         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
1051         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, ".TBL_");
1052         tbl.defProj      = NULL;
1053         tbl.num_branches = get_irn_n_edges(node) - 1;
1054         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
1055         tbl.min_value    = INT_MAX;
1056         tbl.max_value    = INT_MIN;
1057
1058         default_pn = get_ia32_condcode(node);
1059         i = 0;
1060         /* go over all proj's and collect them */
1061         foreach_out_edge(node, edge) {
1062                 proj = get_edge_src_irn(edge);
1063                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1064
1065                 pnc = get_Proj_proj(proj);
1066
1067                 /* check for default proj */
1068                 if (pnc == default_pn) {
1069                         assert(tbl.defProj == NULL && "found two default Projs at SwitchJmp");
1070                         tbl.defProj = proj;
1071                 } else {
1072                         tbl.min_value = pnc < tbl.min_value ? pnc : tbl.min_value;
1073                         tbl.max_value = pnc > tbl.max_value ? pnc : tbl.max_value;
1074
1075                         /* create branch entry */
1076                         tbl.branches[i].target = proj;
1077                         tbl.branches[i].value  = pnc;
1078                         ++i;
1079                 }
1080
1081         }
1082         assert(i == tbl.num_branches);
1083
1084         /* sort the branches by their number */
1085         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
1086
1087         /* two-complement's magic make this work without overflow */
1088         interval = tbl.max_value - tbl.min_value;
1089
1090         /* emit the table */
1091         be_emit_cstring("\tcmpl $");
1092         be_emit_irprintf("%u, ", interval);
1093         ia32_emit_source_register(node, 0);
1094         be_emit_finish_line_gas(node);
1095
1096         be_emit_cstring("\tja ");
1097         ia32_emit_cfop_target(tbl.defProj);
1098         be_emit_finish_line_gas(node);
1099
1100         if (tbl.num_branches > 1) {
1101                 /* create table */
1102                 be_emit_cstring("\tjmp *");
1103                 be_emit_string(tbl.label);
1104                 be_emit_cstring("(,");
1105                 ia32_emit_source_register(node, 0);
1106                 be_emit_cstring(",4)");
1107                 be_emit_finish_line_gas(node);
1108
1109                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1110                 be_emit_cstring("\t.align 4\n");
1111                 be_emit_write_line();
1112
1113                 be_emit_string(tbl.label);
1114                 be_emit_cstring(":\n");
1115                 be_emit_write_line();
1116
1117                 be_emit_cstring(".long ");
1118                 ia32_emit_cfop_target(tbl.branches[0].target);
1119                 be_emit_finish_line_gas(NULL);
1120
1121                 last_value = tbl.branches[0].value;
1122                 for (i = 1; i < tbl.num_branches; ++i) {
1123                         while (++last_value < tbl.branches[i].value) {
1124                                 be_emit_cstring(".long ");
1125                                 ia32_emit_cfop_target(tbl.defProj);
1126                                 be_emit_finish_line_gas(NULL);
1127                         }
1128                         be_emit_cstring(".long ");
1129                         ia32_emit_cfop_target(tbl.branches[i].target);
1130                         be_emit_finish_line_gas(NULL);
1131                 }
1132                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1133         } else {
1134                 /* one jump is enough */
1135                 be_emit_cstring("\tjmp ");
1136                 ia32_emit_cfop_target(tbl.branches[0].target);
1137                 be_emit_finish_line_gas(node);
1138         }
1139
1140         if (tbl.label)
1141                 free(tbl.label);
1142         if (tbl.branches)
1143                 free(tbl.branches);
1144 }
1145
1146 /**
1147  * Emits code for a unconditional jump.
1148  */
1149 static void emit_Jmp(const ir_node *node)
1150 {
1151         ir_node *block;
1152
1153         /* for now, the code works for scheduled and non-schedules blocks */
1154         block = get_nodes_block(node);
1155
1156         /* we have a block schedule */
1157         if (can_be_fallthrough(node)) {
1158                 be_emit_cstring("\t/* fallthrough to ");
1159                 ia32_emit_cfop_target(node);
1160                 be_emit_cstring(" */");
1161         } else {
1162                 be_emit_cstring("\tjmp ");
1163                 ia32_emit_cfop_target(node);
1164         }
1165         be_emit_finish_line_gas(node);
1166 }
1167
1168 static void emit_ia32_Immediate(const ir_node *node)
1169 {
1170         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
1171
1172         be_emit_char('$');
1173         if (attr->symconst != NULL) {
1174                 if (attr->sc_sign)
1175                         be_emit_char('-');
1176                 ia32_emit_entity(attr->symconst, 0);
1177         }
1178         if (attr->symconst == NULL || attr->offset != 0) {
1179                 if (attr->symconst != NULL) {
1180                         be_emit_irprintf("%+d", attr->offset);
1181                 } else {
1182                         be_emit_irprintf("0x%X", attr->offset);
1183                 }
1184         }
1185 }
1186
1187 /**
1188  * Emit an inline assembler operand.
1189  *
1190  * @param node  the ia32_ASM node
1191  * @param s     points to the operand (a %c)
1192  *
1193  * @return  pointer to the first char in s NOT in the current operand
1194  */
1195 static const char* emit_asm_operand(const ir_node *node, const char *s)
1196 {
1197         const ia32_attr_t     *ia32_attr = get_ia32_attr_const(node);
1198         const ia32_asm_attr_t *attr      = CONST_CAST_IA32_ATTR(ia32_asm_attr_t,
1199                                                             ia32_attr);
1200         const arch_register_t *reg;
1201         const ia32_asm_reg_t  *asm_regs = attr->register_map;
1202         const ia32_asm_reg_t  *asm_reg;
1203         const char            *reg_name;
1204         char                   c;
1205         char                   modifier = 0;
1206         int                    num      = -1;
1207         int                    p;
1208
1209         assert(*s == '%');
1210         c = *(++s);
1211
1212         /* parse modifiers */
1213         switch(c) {
1214         case 0:
1215                 ir_fprintf(stderr, "Warning: asm text (%+F) ends with %\n", node);
1216                 be_emit_char('%');
1217                 return s + 1;
1218         case '%':
1219                 be_emit_char('%');
1220                 return s + 1;
1221         case 'w':
1222         case 'b':
1223         case 'h':
1224                 modifier = c;
1225                 ++s;
1226                 break;
1227         case '0':
1228         case '1':
1229         case '2':
1230         case '3':
1231         case '4':
1232         case '5':
1233         case '6':
1234         case '7':
1235         case '8':
1236         case '9':
1237                 break;
1238         default:
1239                 ir_fprintf(stderr, "Warning: asm text (%+F) contains unknown modifier "
1240                            "'%c' for asm op\n", node, c);
1241                 ++s;
1242                 break;
1243         }
1244
1245         /* parse number */
1246         sscanf(s, "%d%n", &num, &p);
1247         if (num < 0) {
1248                 ir_fprintf(stderr, "Warning: Couldn't parse assembler operand (%+F)\n",
1249                            node);
1250                 return s;
1251         } else {
1252                 s += p;
1253         }
1254
1255         if (num < 0 || num >= ARR_LEN(asm_regs)) {
1256                 ir_fprintf(stderr, "Error: Custom assembler references invalid "
1257                            "input/output (%+F)\n", node);
1258                 return s;
1259         }
1260         asm_reg = & asm_regs[num];
1261         assert(asm_reg->valid);
1262
1263         /* get register */
1264         if (asm_reg->use_input == 0) {
1265                 reg = get_out_reg(node, asm_reg->inout_pos);
1266         } else {
1267                 ir_node *pred = get_irn_n(node, asm_reg->inout_pos);
1268
1269                 /* might be an immediate value */
1270                 if (is_ia32_Immediate(pred)) {
1271                         emit_ia32_Immediate(pred);
1272                         return s;
1273                 }
1274                 reg = get_in_reg(node, asm_reg->inout_pos);
1275         }
1276         if (reg == NULL) {
1277                 ir_fprintf(stderr, "Warning: no register assigned for %d asm op "
1278                            "(%+F)\n", num, node);
1279                 return s;
1280         }
1281
1282         if (asm_reg->memory) {
1283                 be_emit_char('(');
1284         }
1285
1286         /* emit it */
1287         if (modifier != 0) {
1288                 be_emit_char('%');
1289                 switch(modifier) {
1290                 case 'b':
1291                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit, reg);
1292                         break;
1293                 case 'h':
1294                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit_high, reg);
1295                         break;
1296                 case 'w':
1297                         reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
1298                         break;
1299                 default:
1300                         panic("Invalid asm op modifier");
1301                 }
1302                 be_emit_string(reg_name);
1303         } else {
1304                 emit_register(reg, asm_reg->mode);
1305         }
1306
1307         if (asm_reg->memory) {
1308                 be_emit_char(')');
1309         }
1310
1311         return s;
1312 }
1313
1314 /**
1315  * Emits code for an ASM pseudo op.
1316  */
1317 static void emit_ia32_Asm(const ir_node *node)
1318 {
1319         const void            *gen_attr = get_irn_generic_attr_const(node);
1320         const ia32_asm_attr_t *attr
1321                 = CONST_CAST_IA32_ATTR(ia32_asm_attr_t, gen_attr);
1322         ident                 *asm_text = attr->asm_text;
1323         const char            *s        = get_id_str(asm_text);
1324
1325         be_emit_cstring("#APP\t");
1326         be_emit_finish_line_gas(node);
1327
1328         if (s[0] != '\t')
1329                 be_emit_char('\t');
1330
1331         while(*s != 0) {
1332                 if (*s == '%') {
1333                         s = emit_asm_operand(node, s);
1334                 } else {
1335                         be_emit_char(*s++);
1336                 }
1337         }
1338
1339         be_emit_char('\n');
1340         be_emit_write_line();
1341
1342         be_emit_cstring("#NO_APP\n");
1343         be_emit_write_line();
1344 }
1345
1346 /**********************************
1347  *   _____                  ____
1348  *  / ____|                |  _ \
1349  * | |     ___  _ __  _   _| |_) |
1350  * | |    / _ \| '_ \| | | |  _ <
1351  * | |___| (_) | |_) | |_| | |_) |
1352  *  \_____\___/| .__/ \__, |____/
1353  *             | |     __/ |
1354  *             |_|    |___/
1355  **********************************/
1356
1357 /**
1358  * Emit movsb/w instructions to make mov count divideable by 4
1359  */
1360 static void emit_CopyB_prolog(unsigned size)
1361 {
1362         be_emit_cstring("\tcld");
1363         be_emit_finish_line_gas(NULL);
1364
1365         switch (size) {
1366         case 1:
1367                 be_emit_cstring("\tmovsb");
1368                 be_emit_finish_line_gas(NULL);
1369                 break;
1370         case 2:
1371                 be_emit_cstring("\tmovsw");
1372                 be_emit_finish_line_gas(NULL);
1373                 break;
1374         case 3:
1375                 be_emit_cstring("\tmovsb");
1376                 be_emit_finish_line_gas(NULL);
1377                 be_emit_cstring("\tmovsw");
1378                 be_emit_finish_line_gas(NULL);
1379                 break;
1380         }
1381 }
1382
1383 /**
1384  * Emit rep movsd instruction for memcopy.
1385  */
1386 static void emit_ia32_CopyB(const ir_node *node)
1387 {
1388         unsigned size = get_ia32_copyb_size(node);
1389
1390         emit_CopyB_prolog(size);
1391
1392         be_emit_cstring("\trep movsd");
1393         be_emit_finish_line_gas(node);
1394 }
1395
1396 /**
1397  * Emits unrolled memcopy.
1398  */
1399 static void emit_ia32_CopyB_i(const ir_node *node)
1400 {
1401         unsigned size = get_ia32_copyb_size(node);
1402
1403         emit_CopyB_prolog(size & 0x3);
1404
1405         size >>= 2;
1406         while (size--) {
1407                 be_emit_cstring("\tmovsd");
1408                 be_emit_finish_line_gas(NULL);
1409         }
1410 }
1411
1412
1413
1414 /***************************
1415  *   _____
1416  *  / ____|
1417  * | |     ___  _ ____   __
1418  * | |    / _ \| '_ \ \ / /
1419  * | |___| (_) | | | \ V /
1420  *  \_____\___/|_| |_|\_/
1421  *
1422  ***************************/
1423
1424 /**
1425  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1426  */
1427 static void emit_ia32_Conv_with_FP(const ir_node *node)
1428 {
1429         ir_mode            *ls_mode = get_ia32_ls_mode(node);
1430         int                 ls_bits = get_mode_size_bits(ls_mode);
1431
1432         be_emit_cstring("\tcvt");
1433
1434         if (is_ia32_Conv_I2FP(node)) {
1435                 if (ls_bits == 32) {
1436                         be_emit_cstring("si2ss");
1437                 } else {
1438                         be_emit_cstring("si2sd");
1439                 }
1440         } else if (is_ia32_Conv_FP2I(node)) {
1441                 if (ls_bits == 32) {
1442                         be_emit_cstring("ss2si");
1443                 } else {
1444                         be_emit_cstring("sd2si");
1445                 }
1446         } else {
1447                 assert(is_ia32_Conv_FP2FP(node));
1448                 if (ls_bits == 32) {
1449                         be_emit_cstring("sd2ss");
1450                 } else {
1451                         be_emit_cstring("ss2sd");
1452                 }
1453         }
1454         be_emit_char(' ');
1455
1456         switch(get_ia32_op_type(node)) {
1457                 case ia32_Normal:
1458                         ia32_emit_source_register(node, n_ia32_unary_op);
1459                         break;
1460                 case ia32_AddrModeS:
1461                         ia32_emit_am(node);
1462                         break;
1463                 default:
1464                         assert(0 && "unsupported op type for Conv");
1465         }
1466         be_emit_cstring(", ");
1467         ia32_emit_dest_register(node, 0);
1468         be_emit_finish_line_gas(node);
1469 }
1470
1471 static void emit_ia32_Conv_I2FP(const ir_node *node)
1472 {
1473         emit_ia32_Conv_with_FP(node);
1474 }
1475
1476 static void emit_ia32_Conv_FP2I(const ir_node *node)
1477 {
1478         emit_ia32_Conv_with_FP(node);
1479 }
1480
1481 static void emit_ia32_Conv_FP2FP(const ir_node *node)
1482 {
1483         emit_ia32_Conv_with_FP(node);
1484 }
1485
1486 /**
1487  * Emits code for an Int conversion.
1488  */
1489 static void emit_ia32_Conv_I2I(const ir_node *node)
1490 {
1491         const char            *sign_suffix;
1492         ir_mode               *smaller_mode = get_ia32_ls_mode(node);
1493         int                    smaller_bits = get_mode_size_bits(smaller_mode);
1494         int                    signed_mode;
1495         const arch_register_t *in_reg, *out_reg;
1496
1497         assert(!mode_is_float(smaller_mode));
1498         assert(smaller_bits == 8 || smaller_bits == 16);
1499
1500         signed_mode = mode_is_signed(smaller_mode);
1501         sign_suffix = signed_mode ? "s" : "z";
1502
1503         out_reg = get_out_reg(node, 0);
1504
1505         switch(get_ia32_op_type(node)) {
1506                 case ia32_Normal:
1507                         in_reg  = get_in_reg(node, n_ia32_unary_op);
1508
1509                         if (in_reg  == &ia32_gp_regs[REG_EAX] &&
1510                                 out_reg == &ia32_gp_regs[REG_EAX] &&
1511                                 signed_mode &&
1512                                 smaller_bits == 16)
1513                         {
1514                                 /* argument and result are both in EAX and */
1515                                 /* signedness is ok: -> use the smaller cwtl opcode */
1516                                 be_emit_cstring("\tcwtl");
1517                         } else {
1518                                 be_emit_cstring("\tmov");
1519                                 be_emit_string(sign_suffix);
1520                                 ia32_emit_mode_suffix_mode(smaller_mode);
1521                                 be_emit_cstring("l ");
1522                                 emit_register(in_reg, smaller_mode);
1523                                 be_emit_cstring(", ");
1524                                 emit_register(out_reg, NULL);
1525                         }
1526                         break;
1527                 case ia32_AddrModeS: {
1528                         be_emit_cstring("\tmov");
1529                         be_emit_string(sign_suffix);
1530                         ia32_emit_mode_suffix_mode(smaller_mode);
1531                         be_emit_cstring("l ");
1532                         ia32_emit_am(node);
1533                         be_emit_cstring(", ");
1534                         emit_register(out_reg, NULL);
1535                         break;
1536                 }
1537                 default:
1538                         panic("unsupported op type for Conv");
1539         }
1540         be_emit_finish_line_gas(node);
1541 }
1542
1543
1544 /*******************************************
1545  *  _                          _
1546  * | |                        | |
1547  * | |__   ___ _ __   ___   __| | ___  ___
1548  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
1549  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
1550  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
1551  *
1552  *******************************************/
1553
1554 /**
1555  * Emits a backend call
1556  */
1557 static void emit_be_Call(const ir_node *node)
1558 {
1559         ir_entity *ent = be_Call_get_entity(node);
1560
1561         be_emit_cstring("\tcall ");
1562         if (ent) {
1563                 ia32_emit_entity(ent, 1);
1564         } else {
1565                 const arch_register_t *reg = get_in_reg(node, be_pos_Call_ptr);
1566                 be_emit_char('*');
1567                 emit_register(reg, NULL);
1568         }
1569         be_emit_finish_line_gas(node);
1570 }
1571
1572 /**
1573  * Emits code to increase stack pointer.
1574  */
1575 static void emit_be_IncSP(const ir_node *node)
1576 {
1577         int                    offs = be_get_IncSP_offset(node);
1578         const arch_register_t *reg  = arch_get_irn_register(arch_env, node);
1579
1580         if (offs == 0)
1581                 return;
1582
1583         if (offs > 0) {
1584                 be_emit_cstring("\tsubl $");
1585                 be_emit_irprintf("%u, ", offs);
1586                 emit_register(reg, NULL);
1587         } else {
1588                 be_emit_cstring("\taddl $");
1589                 be_emit_irprintf("%u, ", -offs);
1590                 emit_register(reg, NULL);
1591         }
1592         be_emit_finish_line_gas(node);
1593 }
1594
1595 /**
1596  * Emits code for Copy/CopyKeep.
1597  */
1598 static void Copy_emitter(const ir_node *node, const ir_node *op)
1599 {
1600         const arch_register_t *in  = arch_get_irn_register(arch_env, op);
1601         const arch_register_t *out = arch_get_irn_register(arch_env, node);
1602         ir_mode               *mode;
1603
1604         if (in == out) {
1605                 return;
1606         }
1607         if (is_unknown_reg(in))
1608                 return;
1609         /* copies of vf nodes aren't real... */
1610         if (arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
1611                 return;
1612
1613         mode = get_irn_mode(node);
1614         if (mode == mode_E) {
1615                 be_emit_cstring("\tmovsd ");
1616                 emit_register(in, NULL);
1617                 be_emit_cstring(", ");
1618                 emit_register(out, NULL);
1619         } else {
1620                 be_emit_cstring("\tmovl ");
1621                 emit_register(in, NULL);
1622                 be_emit_cstring(", ");
1623                 emit_register(out, NULL);
1624         }
1625         be_emit_finish_line_gas(node);
1626 }
1627
1628 static void emit_be_Copy(const ir_node *node)
1629 {
1630         Copy_emitter(node, be_get_Copy_op(node));
1631 }
1632
1633 static void emit_be_CopyKeep(const ir_node *node)
1634 {
1635         Copy_emitter(node, be_get_CopyKeep_op(node));
1636 }
1637
1638 /**
1639  * Emits code for exchange.
1640  */
1641 static void emit_be_Perm(const ir_node *node)
1642 {
1643         const arch_register_t *in0, *in1;
1644         const arch_register_class_t *cls0, *cls1;
1645
1646         in0 = arch_get_irn_register(arch_env, get_irn_n(node, 0));
1647         in1 = arch_get_irn_register(arch_env, get_irn_n(node, 1));
1648
1649         cls0 = arch_register_get_class(in0);
1650         cls1 = arch_register_get_class(in1);
1651
1652         assert(cls0 == cls1 && "Register class mismatch at Perm");
1653
1654         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
1655                 be_emit_cstring("\txchg ");
1656                 emit_register(in1, NULL);
1657                 be_emit_cstring(", ");
1658                 emit_register(in0, NULL);
1659                 be_emit_finish_line_gas(node);
1660         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
1661                 be_emit_cstring("\txorpd ");
1662                 emit_register(in1, NULL);
1663                 be_emit_cstring(", ");
1664                 emit_register(in0, NULL);
1665                 be_emit_finish_line_gas(NULL);
1666
1667                 be_emit_cstring("\txorpd ");
1668                 emit_register(in0, NULL);
1669                 be_emit_cstring(", ");
1670                 emit_register(in1, NULL);
1671                 be_emit_finish_line_gas(NULL);
1672
1673                 be_emit_cstring("\txorpd ");
1674                 emit_register(in1, NULL);
1675                 be_emit_cstring(", ");
1676                 emit_register(in0, NULL);
1677                 be_emit_finish_line_gas(node);
1678         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
1679                 /* is a NOP */
1680         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
1681                 /* is a NOP */
1682         } else {
1683                 panic("unexpected register class in be_Perm (%+F)", node);
1684         }
1685 }
1686
1687 /**
1688  * Emits code for Constant loading.
1689  */
1690 static void emit_ia32_Const(const ir_node *node)
1691 {
1692         be_emit_cstring("\tmovl ");
1693         emit_ia32_Immediate(node);
1694         be_emit_cstring(", ");
1695         ia32_emit_dest_register(node, 0);
1696
1697         be_emit_finish_line_gas(node);
1698 }
1699
1700 /**
1701  * Emits code to load the TLS base
1702  */
1703 static void emit_ia32_LdTls(const ir_node *node)
1704 {
1705         be_emit_cstring("\tmovl %gs:0, ");
1706         ia32_emit_dest_register(node, 0);
1707         be_emit_finish_line_gas(node);
1708 }
1709
1710 /* helper function for emit_ia32_Minus64Bit */
1711 static void emit_mov(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1712 {
1713         be_emit_cstring("\tmovl ");
1714         emit_register(src, NULL);
1715         be_emit_cstring(", ");
1716         emit_register(dst, NULL);
1717         be_emit_finish_line_gas(node);
1718 }
1719
1720 /* helper function for emit_ia32_Minus64Bit */
1721 static void emit_neg(const ir_node* node, const arch_register_t *reg)
1722 {
1723         be_emit_cstring("\tnegl ");
1724         emit_register(reg, NULL);
1725         be_emit_finish_line_gas(node);
1726 }
1727
1728 /* helper function for emit_ia32_Minus64Bit */
1729 static void emit_sbb0(const ir_node* node, const arch_register_t *reg)
1730 {
1731         be_emit_cstring("\tsbbl $0, ");
1732         emit_register(reg, NULL);
1733         be_emit_finish_line_gas(node);
1734 }
1735
1736 /* helper function for emit_ia32_Minus64Bit */
1737 static void emit_sbb(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1738 {
1739         be_emit_cstring("\tsbbl ");
1740         emit_register(src, NULL);
1741         be_emit_cstring(", ");
1742         emit_register(dst, NULL);
1743         be_emit_finish_line_gas(node);
1744 }
1745
1746 /* helper function for emit_ia32_Minus64Bit */
1747 static void emit_xchg(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1748 {
1749         be_emit_cstring("\txchgl ");
1750         emit_register(src, NULL);
1751         be_emit_cstring(", ");
1752         emit_register(dst, NULL);
1753         be_emit_finish_line_gas(node);
1754 }
1755
1756 /* helper function for emit_ia32_Minus64Bit */
1757 static void emit_zero(const ir_node* node, const arch_register_t *reg)
1758 {
1759         be_emit_cstring("\txorl ");
1760         emit_register(reg, NULL);
1761         be_emit_cstring(", ");
1762         emit_register(reg, NULL);
1763         be_emit_finish_line_gas(node);
1764 }
1765
1766 static void emit_ia32_Minus64Bit(const ir_node *node)
1767 {
1768         const arch_register_t *in_lo  = get_in_reg(node, 0);
1769         const arch_register_t *in_hi  = get_in_reg(node, 1);
1770         const arch_register_t *out_lo = get_out_reg(node, 0);
1771         const arch_register_t *out_hi = get_out_reg(node, 1);
1772
1773         if (out_lo == in_lo) {
1774                 if (out_hi != in_hi) {
1775                         /* a -> a, b -> d */
1776                         goto zero_neg;
1777                 } else {
1778                         /* a -> a, b -> b */
1779                         goto normal_neg;
1780                 }
1781         } else if (out_lo == in_hi) {
1782                 if (out_hi == in_lo) {
1783                         /* a -> b, b -> a */
1784                         emit_xchg(node, in_lo, in_hi);
1785                         goto normal_neg;
1786                 } else {
1787                         /* a -> b, b -> d */
1788                         emit_mov(node, in_hi, out_hi);
1789                         emit_mov(node, in_lo, out_lo);
1790                         goto normal_neg;
1791                 }
1792         } else {
1793                 if (out_hi == in_lo) {
1794                         /* a -> c, b -> a */
1795                         emit_mov(node, in_lo, out_lo);
1796                         goto zero_neg;
1797                 } else if (out_hi == in_hi) {
1798                         /* a -> c, b -> b */
1799                         emit_mov(node, in_lo, out_lo);
1800                         goto normal_neg;
1801                 } else {
1802                         /* a -> c, b -> d */
1803                         emit_mov(node, in_lo, out_lo);
1804                         goto zero_neg;
1805                 }
1806         }
1807
1808 normal_neg:
1809         emit_neg( node, out_hi);
1810         emit_neg( node, out_lo);
1811         emit_sbb0(node, out_hi);
1812         return;
1813
1814 zero_neg:
1815         emit_zero(node, out_hi);
1816         emit_neg( node, out_lo);
1817         emit_sbb( node, in_hi, out_hi);
1818 }
1819
1820 static void emit_ia32_GetEIP(const ir_node *node)
1821 {
1822         be_emit_cstring("\tcall ");
1823         be_emit_string(pic_base_label);
1824         be_emit_finish_line_gas(node);
1825
1826         be_emit_string(pic_base_label);
1827         be_emit_cstring(":\n");
1828         be_emit_write_line();
1829
1830         be_emit_cstring("\tpopl ");
1831         ia32_emit_dest_register(node, 0);
1832         be_emit_char('\n');
1833         be_emit_write_line();
1834 }
1835
1836 static void emit_be_Return(const ir_node *node)
1837 {
1838         unsigned pop;
1839         be_emit_cstring("\tret");
1840
1841         pop = be_Return_get_pop(node);
1842         if (pop > 0 || be_Return_get_emit_pop(node)) {
1843                 be_emit_irprintf(" $%d", pop);
1844         }
1845         be_emit_finish_line_gas(node);
1846 }
1847
1848 static void emit_Nothing(const ir_node *node)
1849 {
1850         (void) node;
1851 }
1852
1853
1854 /***********************************************************************************
1855  *                  _          __                                             _
1856  *                 (_)        / _|                                           | |
1857  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1858  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1859  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1860  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1861  *
1862  ***********************************************************************************/
1863
1864 /**
1865  * Enters the emitter functions for handled nodes into the generic
1866  * pointer of an opcode.
1867  */
1868 static void ia32_register_emitters(void)
1869 {
1870 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1871 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1872 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1873 #define IGN(a)                  op_##a->ops.generic = (op_func)emit_Nothing
1874 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1875 #define BE_IGN(a)               op_be_##a->ops.generic = (op_func)emit_Nothing
1876
1877         /* first clear the generic function pointer for all ops */
1878         clear_irp_opcodes_generic_func();
1879
1880         /* register all emitter functions defined in spec */
1881         ia32_register_spec_emitters();
1882
1883         /* other ia32 emitter functions */
1884         IA32_EMIT(Asm);
1885         IA32_EMIT(CMov);
1886         IA32_EMIT(IMul);
1887         IA32_EMIT(SwitchJmp);
1888         IA32_EMIT(CopyB);
1889         IA32_EMIT(CopyB_i);
1890         IA32_EMIT(Conv_I2FP);
1891         IA32_EMIT(Conv_FP2I);
1892         IA32_EMIT(Conv_FP2FP);
1893         IA32_EMIT(Conv_I2I);
1894         IA32_EMIT2(Conv_I2I8Bit, Conv_I2I);
1895         IA32_EMIT(Const);
1896         IA32_EMIT(LdTls);
1897         IA32_EMIT(Minus64Bit);
1898         IA32_EMIT(Jcc);
1899         IA32_EMIT(GetEIP);
1900
1901         /* benode emitter */
1902         BE_EMIT(Call);
1903         BE_EMIT(IncSP);
1904         BE_EMIT(Copy);
1905         BE_EMIT(CopyKeep);
1906         BE_EMIT(Perm);
1907         BE_EMIT(Return);
1908
1909         BE_IGN(RegParams);
1910         BE_IGN(Barrier);
1911         BE_IGN(Keep);
1912
1913         /* firm emitter */
1914         EMIT(Jmp);
1915         IGN(Proj);
1916         IGN(Phi);
1917         IGN(Start);
1918
1919 #undef BE_EMIT
1920 #undef EMIT
1921 #undef IGN
1922 #undef IA32_EMIT2
1923 #undef IA32_EMIT
1924 }
1925
1926 typedef void (*emit_func_ptr) (const ir_node *);
1927
1928 /**
1929  * Emits code for a node.
1930  */
1931 static void ia32_emit_node(ir_node *node)
1932 {
1933         ir_op *op = get_irn_op(node);
1934
1935         DBG((dbg, LEVEL_1, "emitting code for %+F\n", node));
1936
1937         if (is_ia32_irn(node) && get_ia32_exc_label(node)) {
1938                 /* emit the exception label of this instruction */
1939                 ia32_assign_exc_label(node);
1940         }
1941         if (op->ops.generic) {
1942                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
1943
1944                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
1945
1946                 (*func) (node);
1947         } else {
1948                 emit_Nothing(node);
1949                 ir_fprintf(stderr, "Error: No emit handler for node %+F (%+G, graph %+F)\n", node, node, current_ir_graph);
1950                 abort();
1951         }
1952 }
1953
1954 /**
1955  * Emits gas alignment directives
1956  */
1957 static void ia32_emit_alignment(unsigned align, unsigned skip)
1958 {
1959         be_emit_cstring("\t.p2align ");
1960         be_emit_irprintf("%u,,%u\n", align, skip);
1961         be_emit_write_line();
1962 }
1963
1964 /**
1965  * Emits gas alignment directives for Labels depended on cpu architecture.
1966  */
1967 static void ia32_emit_align_label(void)
1968 {
1969         unsigned align        = ia32_cg_config.label_alignment;
1970         unsigned maximum_skip = ia32_cg_config.label_alignment_max_skip;
1971         ia32_emit_alignment(align, maximum_skip);
1972 }
1973
1974 /**
1975  * Test whether a block should be aligned.
1976  * For cpus in the P4/Athlon class it is useful to align jump labels to
1977  * 16 bytes. However we should only do that if the alignment nops before the
1978  * label aren't executed more often than we have jumps to the label.
1979  */
1980 static int should_align_block(const ir_node *block)
1981 {
1982         static const double DELTA = .0001;
1983         ir_exec_freq *exec_freq   = cg->birg->exec_freq;
1984         ir_node      *prev        = get_prev_block_sched(block);
1985         double        block_freq;
1986         double        prev_freq = 0;  /**< execfreq of the fallthrough block */
1987         double        jmp_freq  = 0;  /**< execfreq of all non-fallthrough blocks */
1988         int           i, n_cfgpreds;
1989
1990         if (exec_freq == NULL)
1991                 return 0;
1992         if (ia32_cg_config.label_alignment_factor <= 0)
1993                 return 0;
1994
1995         block_freq = get_block_execfreq(exec_freq, block);
1996         if (block_freq < DELTA)
1997                 return 0;
1998
1999         n_cfgpreds = get_Block_n_cfgpreds(block);
2000         for(i = 0; i < n_cfgpreds; ++i) {
2001                 const ir_node *pred      = get_Block_cfgpred_block(block, i);
2002                 double         pred_freq = get_block_execfreq(exec_freq, pred);
2003
2004                 if (pred == prev) {
2005                         prev_freq += pred_freq;
2006                 } else {
2007                         jmp_freq  += pred_freq;
2008                 }
2009         }
2010
2011         if (prev_freq < DELTA && !(jmp_freq < DELTA))
2012                 return 1;
2013
2014         jmp_freq /= prev_freq;
2015
2016         return jmp_freq > ia32_cg_config.label_alignment_factor;
2017 }
2018
2019 /**
2020  * Emit the block header for a block.
2021  *
2022  * @param block       the block
2023  * @param prev_block  the previous block
2024  */
2025 static void ia32_emit_block_header(ir_node *block)
2026 {
2027         ir_graph     *irg = current_ir_graph;
2028         int           need_label = block_needs_label(block);
2029         int           i, arity;
2030         ir_exec_freq *exec_freq = cg->birg->exec_freq;
2031
2032         if (block == get_irg_end_block(irg) || block == get_irg_start_block(irg))
2033                 return;
2034
2035         if (ia32_cg_config.label_alignment > 0) {
2036                 /* align the current block if:
2037                  * a) if should be aligned due to its execution frequency
2038                  * b) there is no fall-through here
2039                  */
2040                 if (should_align_block(block)) {
2041                         ia32_emit_align_label();
2042                 } else {
2043                         /* if the predecessor block has no fall-through,
2044                            we can always align the label. */
2045                         int i;
2046                         int has_fallthrough = 0;
2047
2048                         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
2049                                 ir_node *cfg_pred = get_Block_cfgpred(block, i);
2050                                 if (can_be_fallthrough(cfg_pred)) {
2051                                         has_fallthrough = 1;
2052                                         break;
2053                                 }
2054                         }
2055
2056                         if (!has_fallthrough)
2057                                 ia32_emit_align_label();
2058                 }
2059         }
2060
2061         if (need_label || has_Block_label(block)) {
2062                 ia32_emit_block_name(block);
2063                 be_emit_char(':');
2064
2065                 be_emit_pad_comment();
2066                 be_emit_cstring("   /* ");
2067         } else {
2068                 be_emit_cstring("\t/* ");
2069                 ia32_emit_block_name(block);
2070                 be_emit_cstring(": ");
2071         }
2072
2073         be_emit_cstring("preds:");
2074
2075         /* emit list of pred blocks in comment */
2076         arity = get_irn_arity(block);
2077         for (i = 0; i < arity; ++i) {
2078                 ir_node *predblock = get_Block_cfgpred_block(block, i);
2079                 be_emit_irprintf(" %d", get_irn_node_nr(predblock));
2080         }
2081         if (exec_freq != NULL) {
2082                 be_emit_irprintf(" freq: %f",
2083                                  get_block_execfreq(exec_freq, block));
2084         }
2085         be_emit_cstring(" */\n");
2086         be_emit_write_line();
2087 }
2088
2089 /**
2090  * Walks over the nodes in a block connected by scheduling edges
2091  * and emits code for each node.
2092  */
2093 static void ia32_gen_block(ir_node *block)
2094 {
2095         ir_node *node;
2096
2097         ia32_emit_block_header(block);
2098
2099         /* emit the contents of the block */
2100         be_dbg_set_dbg_info(get_irn_dbg_info(block));
2101         sched_foreach(block, node) {
2102                 ia32_emit_node(node);
2103         }
2104 }
2105
2106 typedef struct exc_entry {
2107         ir_node *exc_instr;  /** The instruction that can issue an exception. */
2108         ir_node *block;      /** The block to call then. */
2109 } exc_entry;
2110
2111 /**
2112  * Block-walker:
2113  * Sets labels for control flow nodes (jump target).
2114  * Links control predecessors to there destination blocks.
2115  */
2116 static void ia32_gen_labels(ir_node *block, void *data)
2117 {
2118         exc_entry **exc_list = data;
2119         ir_node *pred;
2120         int     n;
2121
2122         for (n = get_Block_n_cfgpreds(block) - 1; n >= 0; --n) {
2123                 pred = get_Block_cfgpred(block, n);
2124                 set_irn_link(pred, block);
2125
2126                 pred = skip_Proj(pred);
2127                 if (is_ia32_irn(pred) && get_ia32_exc_label(pred)) {
2128                         exc_entry e;
2129
2130                         e.exc_instr = pred;
2131                         e.block     = block;
2132                         ARR_APP1(exc_entry, *exc_list, e);
2133                         set_irn_link(pred, block);
2134                 }
2135         }
2136 }
2137
2138 /**
2139  * Assign and emit an exception label if the current instruction can fail.
2140  */
2141 void ia32_assign_exc_label(ir_node *node)
2142 {
2143         if (get_ia32_exc_label(node)) {
2144                 /* assign a new ID to the instruction */
2145                 set_ia32_exc_label_id(node, ++exc_label_id);
2146                 /* print it */
2147                 ia32_emit_exc_label(node);
2148                 be_emit_char(':');
2149                 be_emit_pad_comment();
2150                 be_emit_cstring("/* exception to Block ");
2151                 ia32_emit_cfop_target(node);
2152                 be_emit_cstring(" */\n");
2153                 be_emit_write_line();
2154         }
2155 }
2156
2157 /**
2158  * Compare two exception_entries.
2159  */
2160 static int cmp_exc_entry(const void *a, const void *b)
2161 {
2162         const exc_entry *ea = a;
2163         const exc_entry *eb = b;
2164
2165         if (get_ia32_exc_label_id(ea->exc_instr) < get_ia32_exc_label_id(eb->exc_instr))
2166                 return -1;
2167         return +1;
2168 }
2169
2170 /**
2171  * Main driver. Emits the code for one routine.
2172  */
2173 void ia32_gen_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
2174 {
2175         ir_entity *entity     = get_irg_entity(irg);
2176         exc_entry *exc_list   = NEW_ARR_F(exc_entry, 0);
2177         int i, n;
2178
2179         cg       = ia32_cg;
2180         isa      = (const ia32_isa_t*) cg->arch_env;
2181         arch_env = cg->arch_env;
2182         do_pic   = cg->birg->main_env->options->pic;
2183
2184         ia32_register_emitters();
2185
2186         get_unique_label(pic_base_label, sizeof(pic_base_label), ".PIC_BASE");
2187
2188         be_dbg_method_begin(entity, be_abi_get_stack_layout(cg->birg->abi));
2189         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
2190
2191         /* we use links to point to target blocks */
2192         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2193         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &exc_list);
2194
2195         /* initialize next block links */
2196         n = ARR_LEN(cg->blk_sched);
2197         for (i = 0; i < n; ++i) {
2198                 ir_node *block = cg->blk_sched[i];
2199                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
2200
2201                 set_irn_link(block, prev);
2202         }
2203
2204         for (i = 0; i < n; ++i) {
2205                 ir_node *block = cg->blk_sched[i];
2206
2207                 ia32_gen_block(block);
2208         }
2209
2210         be_gas_emit_function_epilog(entity);
2211         be_dbg_method_end();
2212         be_emit_char('\n');
2213         be_emit_write_line();
2214
2215         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2216
2217         /* Sort the exception table using the exception label id's.
2218            Those are ascending with ascending addresses. */
2219         qsort(exc_list, ARR_LEN(exc_list), sizeof(exc_list[0]), cmp_exc_entry);
2220         {
2221                 int i;
2222
2223                 for (i = 0; i < ARR_LEN(exc_list); ++i) {
2224                         be_emit_cstring("\t.long ");
2225                         ia32_emit_exc_label(exc_list[i].exc_instr);
2226                         be_emit_char('\n');
2227                         be_emit_cstring("\t.long ");
2228                         ia32_emit_block_name(exc_list[i].block);
2229                         be_emit_char('\n');
2230                 }
2231         }
2232         DEL_ARR_F(exc_list);
2233 }
2234
2235 void ia32_init_emitter(void)
2236 {
2237         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.emitter");
2238 }