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