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