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