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