Remove handling for 32bit as smaller mode in emit_ia32_Conv_I2I(), because it is...
[libfirm] / ir / be / ia32 / ia32_emitter.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       This file implements the ia32 node emitter.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include <limits.h>
31
32 #include "xmalloc.h"
33 #include "tv.h"
34 #include "iredges.h"
35 #include "debug.h"
36 #include "irgwalk.h"
37 #include "irprintf.h"
38 #include "irop_t.h"
39 #include "irargs_t.h"
40 #include "irprog_t.h"
41 #include "iredges_t.h"
42 #include "execfreq.h"
43 #include "error.h"
44 #include "raw_bitset.h"
45 #include "dbginfo.h"
46
47 #include "../besched_t.h"
48 #include "../benode_t.h"
49 #include "../beabi.h"
50 #include "../be_dbgout.h"
51 #include "../beemitter.h"
52 #include "../begnuas.h"
53 #include "../beirg_t.h"
54 #include "../be_dbgout.h"
55
56 #include "ia32_emitter.h"
57 #include "gen_ia32_emitter.h"
58 #include "gen_ia32_regalloc_if.h"
59 #include "ia32_nodes_attr.h"
60 #include "ia32_new_nodes.h"
61 #include "ia32_map_regs.h"
62 #include "ia32_architecture.h"
63 #include "bearch_ia32_t.h"
64
65 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
66
67 #define BLOCK_PREFIX ".L"
68
69 #define SNPRINTF_BUF_LEN 128
70
71 static const arch_env_t *arch_env;
72 static const ia32_isa_t *isa;
73 static ia32_code_gen_t  *cg;
74 static int               do_pic;
75 static char              pic_base_label[128];
76 static ir_label_t        exc_label_id;
77
78 /** Return the next block in Block schedule */
79 static ir_node *get_prev_block_sched(const ir_node *block)
80 {
81         return get_irn_link(block);
82 }
83
84 static bool is_fallthrough(const ir_node *cfgpred)
85 {
86         ir_node *pred;
87
88         if(!is_Proj(cfgpred))
89                 return true;
90         pred = get_Proj_pred(cfgpred);
91         if(is_ia32_SwitchJmp(pred))
92                 return false;
93
94         return true;
95 }
96
97 static bool block_needs_label(const ir_node *block)
98 {
99         bool need_label = true;
100         int  n_cfgpreds = get_Block_n_cfgpreds(block);
101
102         if (n_cfgpreds == 0) {
103                 need_label = false;
104         } else if (n_cfgpreds == 1) {
105                 ir_node *cfgpred            = get_Block_cfgpred(block, 0);
106                 ir_node *cfgpred_block      = get_nodes_block(cfgpred);
107
108                 if (get_prev_block_sched(block) == cfgpred_block
109                                 && is_fallthrough(cfgpred)) {
110                         need_label = false;
111                 }
112         }
113
114         return need_label;
115 }
116
117 /**
118  * Returns the register at in position pos.
119  */
120 static const arch_register_t *get_in_reg(const ir_node *irn, int pos)
121 {
122         ir_node               *op;
123         const arch_register_t *reg = NULL;
124
125         assert(get_irn_arity(irn) > pos && "Invalid IN position");
126
127         /* The out register of the operator at position pos is the
128            in register we need. */
129         op = get_irn_n(irn, pos);
130
131         reg = arch_get_irn_register(arch_env, op);
132
133         assert(reg && "no in register found");
134
135         if(reg == &ia32_gp_regs[REG_GP_NOREG])
136                 panic("trying to emit noreg for %+F input %d", irn, pos);
137
138         /* in case of unknown register: just return a valid register */
139         if (reg == &ia32_gp_regs[REG_GP_UKNWN]) {
140                 const arch_register_req_t *req;
141
142                 /* ask for the requirements */
143                 req = arch_get_register_req(arch_env, irn, pos);
144
145                 if (arch_register_req_is(req, limited)) {
146                         /* in case of limited requirements: get the first allowed register */
147                         unsigned idx = rbitset_next(req->limited, 0, 1);
148                         reg = arch_register_for_index(req->cls, idx);
149                 } else {
150                         /* otherwise get first register in class */
151                         reg = arch_register_for_index(req->cls, 0);
152                 }
153         }
154
155         return reg;
156 }
157
158 /**
159  * Returns the register at out position pos.
160  */
161 static const arch_register_t *get_out_reg(const ir_node *irn, int pos)
162 {
163         ir_node               *proj;
164         const arch_register_t *reg = NULL;
165
166         /* 1st case: irn is not of mode_T, so it has only                 */
167         /*           one OUT register -> good                             */
168         /* 2nd case: irn is of mode_T -> collect all Projs and ask the    */
169         /*           Proj with the corresponding projnum for the register */
170
171         if (get_irn_mode(irn) != mode_T) {
172                 assert(pos == 0);
173                 reg = arch_get_irn_register(arch_env, irn);
174         } else if (is_ia32_irn(irn)) {
175                 reg = get_ia32_out_reg(irn, pos);
176         } else {
177                 const ir_edge_t *edge;
178
179                 foreach_out_edge(irn, edge) {
180                         proj = get_edge_src_irn(edge);
181                         assert(is_Proj(proj) && "non-Proj from mode_T node");
182                         if (get_Proj_proj(proj) == pos) {
183                                 reg = arch_get_irn_register(arch_env, proj);
184                                 break;
185                         }
186                 }
187         }
188
189         assert(reg && "no out register found");
190         return reg;
191 }
192
193 /**
194  * Add a number to a prefix. This number will not be used a second time.
195  */
196 static char *get_unique_label(char *buf, size_t buflen, const char *prefix)
197 {
198         static unsigned long id = 0;
199         snprintf(buf, buflen, "%s%lu", prefix, ++id);
200         return buf;
201 }
202
203 /*************************************************************
204  *             _       _    __   _          _
205  *            (_)     | |  / _| | |        | |
206  *  _ __  _ __ _ _ __ | |_| |_  | |__   ___| |_ __   ___ _ __
207  * | '_ \| '__| | '_ \| __|  _| | '_ \ / _ \ | '_ \ / _ \ '__|
208  * | |_) | |  | | | | | |_| |   | | | |  __/ | |_) |  __/ |
209  * | .__/|_|  |_|_| |_|\__|_|   |_| |_|\___|_| .__/ \___|_|
210  * | |                                       | |
211  * |_|                                       |_|
212  *************************************************************/
213
214 static void emit_8bit_register(const arch_register_t *reg)
215 {
216         const char *reg_name = arch_register_get_name(reg);
217
218         be_emit_char('%');
219         be_emit_char(reg_name[1]);
220         be_emit_char('l');
221 }
222
223 static void emit_16bit_register(const arch_register_t *reg)
224 {
225         const char *reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
226
227         be_emit_char('%');
228         be_emit_string(reg_name);
229 }
230
231 static void emit_register(const arch_register_t *reg, const ir_mode *mode)
232 {
233         const char *reg_name;
234
235         if(mode != NULL) {
236                 int size = get_mode_size_bits(mode);
237                 if(size == 8) {
238                         emit_8bit_register(reg);
239                         return;
240                 } else if(size == 16) {
241                         emit_16bit_register(reg);
242                         return;
243                 } else {
244                         assert(mode_is_float(mode) || size == 32);
245                 }
246         }
247
248         reg_name = arch_register_get_name(reg);
249
250         be_emit_char('%');
251         be_emit_string(reg_name);
252 }
253
254 void ia32_emit_source_register(const ir_node *node, int pos)
255 {
256         const arch_register_t *reg      = get_in_reg(node, pos);
257
258         emit_register(reg, NULL);
259 }
260
261 static void emit_ia32_Immediate(const ir_node *node);
262
263 void ia32_emit_8bit_source_register_or_immediate(const ir_node *node, int pos)
264 {
265         const arch_register_t *reg;
266         ir_node               *in = get_irn_n(node, pos);
267         if(is_ia32_Immediate(in)) {
268                 emit_ia32_Immediate(in);
269                 return;
270         }
271
272         reg = get_in_reg(node, pos);
273         emit_8bit_register(reg);
274 }
275
276 void ia32_emit_dest_register(const ir_node *node, int pos)
277 {
278         const arch_register_t *reg  = get_out_reg(node, pos);
279
280         emit_register(reg, NULL);
281 }
282
283 void ia32_emit_8bit_dest_register(const ir_node *node, int pos)
284 {
285         const arch_register_t *reg  = get_out_reg(node, pos);
286
287         emit_register(reg, mode_Bu);
288 }
289
290 void ia32_emit_x87_register(const ir_node *node, int pos)
291 {
292         const ia32_x87_attr_t *attr = get_ia32_x87_attr_const(node);
293
294         assert(pos < 3);
295         be_emit_char('%');
296         be_emit_string(attr->x87[pos]->name);
297 }
298
299 static void ia32_emit_mode_suffix_mode(const ir_mode *mode)
300 {
301         if(mode_is_float(mode)) {
302                 switch(get_mode_size_bits(mode)) {
303                 case 32: be_emit_char('s'); return;
304                 case 64: be_emit_char('l'); return;
305                 case 80:
306                 case 96: be_emit_char('t'); return;
307                 }
308         } else {
309                 assert(mode_is_int(mode) || mode_is_reference(mode));
310                 switch(get_mode_size_bits(mode)) {
311                 case 64: be_emit_cstring("ll"); return;
312                                  /* gas docu says q is the suffix but gcc, objdump and icc use
313                                         ll apparently */
314                 case 32: be_emit_char('l'); return;
315                 case 16: be_emit_char('w'); return;
316                 case 8:  be_emit_char('b'); return;
317                 }
318         }
319         panic("Can't output mode_suffix for %+F\n", mode);
320 }
321
322 void ia32_emit_mode_suffix(const ir_node *node)
323 {
324         ir_mode *mode = get_ia32_ls_mode(node);
325         if(mode == NULL)
326                 mode = mode_Iu;
327
328         ia32_emit_mode_suffix_mode(mode);
329 }
330
331 void ia32_emit_x87_mode_suffix(const ir_node *node)
332 {
333         /* we only need to emit the mode on address mode */
334         if(get_ia32_op_type(node) != ia32_Normal) {
335                 ir_mode *mode = get_ia32_ls_mode(node);
336                 assert(mode != NULL);
337                 ia32_emit_mode_suffix_mode(mode);
338         }
339 }
340
341 static char get_xmm_mode_suffix(ir_mode *mode)
342 {
343         assert(mode_is_float(mode));
344         switch(get_mode_size_bits(mode)) {
345         case 32:
346                 return 's';
347         case 64:
348                 return 'd';
349         default:
350                 assert(0);
351         }
352         return '%';
353 }
354
355 void ia32_emit_xmm_mode_suffix(const ir_node *node)
356 {
357         ir_mode *mode = get_ia32_ls_mode(node);
358         assert(mode != NULL);
359         be_emit_char('s');
360         be_emit_char(get_xmm_mode_suffix(mode));
361 }
362
363 void ia32_emit_xmm_mode_suffix_s(const ir_node *node)
364 {
365         ir_mode *mode = get_ia32_ls_mode(node);
366         assert(mode != NULL);
367         be_emit_char(get_xmm_mode_suffix(mode));
368 }
369
370 void ia32_emit_extend_suffix(const ir_mode *mode)
371 {
372         if(get_mode_size_bits(mode) == 32)
373                 return;
374         if(mode_is_signed(mode)) {
375                 be_emit_char('s');
376         } else {
377                 be_emit_char('z');
378         }
379 }
380
381 void ia32_emit_source_register_or_immediate(const ir_node *node, int pos)
382 {
383         ir_node *in = get_irn_n(node, pos);
384         if(is_ia32_Immediate(in)) {
385                 emit_ia32_Immediate(in);
386         } else {
387                 const ir_mode         *mode = get_ia32_ls_mode(node);
388                 const arch_register_t *reg  = get_in_reg(node, pos);
389                 emit_register(reg, mode);
390         }
391 }
392
393 /**
394  * Emits registers and/or address mode of a binary operation.
395  */
396 void ia32_emit_binop(const ir_node *node) {
397         const ir_node         *right_op  = get_irn_n(node, n_ia32_binary_right);
398         const ir_mode         *mode      = get_ia32_ls_mode(node);
399         const arch_register_t *reg_left;
400
401         switch(get_ia32_op_type(node)) {
402         case ia32_Normal:
403                 reg_left = get_in_reg(node, n_ia32_binary_left);
404                 if(is_ia32_Immediate(right_op)) {
405                         emit_ia32_Immediate(right_op);
406                         be_emit_cstring(", ");
407                         emit_register(reg_left, mode);
408                         break;
409                 } else {
410                         const arch_register_t *reg_right
411                                 = get_in_reg(node, n_ia32_binary_right);
412                         emit_register(reg_right, mode);
413                         be_emit_cstring(", ");
414                         emit_register(reg_left, mode);
415                 }
416                 break;
417         case ia32_AddrModeS:
418                 if(is_ia32_Immediate(right_op)) {
419                         emit_ia32_Immediate(right_op);
420                         be_emit_cstring(", ");
421                         ia32_emit_am(node);
422                 } else {
423                         reg_left = get_in_reg(node, n_ia32_binary_left);
424                         ia32_emit_am(node);
425                         be_emit_cstring(", ");
426                         emit_register(reg_left, mode);
427                 }
428                 break;
429         case ia32_AddrModeD:
430                 panic("DestMode can't be output by %%binop anymore");
431                 break;
432         default:
433                 assert(0 && "unsupported op type");
434         }
435 }
436
437 /**
438  * Emits registers and/or address mode of a binary operation.
439  */
440 void ia32_emit_x87_binop(const ir_node *node) {
441         switch(get_ia32_op_type(node)) {
442                 case ia32_Normal:
443                         {
444                                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
445                                 const arch_register_t *in1      = x87_attr->x87[0];
446                                 const arch_register_t *in2      = x87_attr->x87[1];
447                                 const arch_register_t *out      = x87_attr->x87[2];
448                                 const arch_register_t *in;
449
450                                 in  = out ? ((out == in2) ? in1 : in2) : in2;
451                                 out = out ? out : in1;
452
453                                 be_emit_char('%');
454                                 be_emit_string(arch_register_get_name(in));
455                                 be_emit_cstring(", %");
456                                 be_emit_string(arch_register_get_name(out));
457                         }
458                         break;
459                 case ia32_AddrModeS:
460                         ia32_emit_am(node);
461                         break;
462                 case ia32_AddrModeD:
463                 default:
464                         assert(0 && "unsupported op type");
465         }
466 }
467
468 /**
469  * Emits registers and/or address mode of a unary operation.
470  */
471 void ia32_emit_unop(const ir_node *node, int pos) {
472         const ir_node *op;
473
474         switch(get_ia32_op_type(node)) {
475         case ia32_Normal:
476                 op = get_irn_n(node, pos);
477                 if (is_ia32_Immediate(op)) {
478                         emit_ia32_Immediate(op);
479                 } else {
480                         ia32_emit_source_register(node, pos);
481                 }
482                 break;
483         case ia32_AddrModeS:
484         case ia32_AddrModeD:
485                 ia32_emit_am(node);
486                 break;
487         default:
488                 assert(0 && "unsupported op type");
489         }
490 }
491
492 static void ia32_emit_entity(ir_entity *entity, int no_pic_adjust)
493 {
494         ident *id;
495
496         set_entity_backend_marked(entity, 1);
497         id = get_entity_ld_ident(entity);
498         be_emit_ident(id);
499
500         if (get_entity_owner(entity) == get_tls_type()) {
501                 if (get_entity_visibility(entity) == visibility_external_allocated) {
502                         be_emit_cstring("@INDNTPOFF");
503                 } else {
504                         be_emit_cstring("@NTPOFF");
505                 }
506         }
507
508         if (!no_pic_adjust && do_pic) {
509                 /* TODO: only do this when necessary */
510                 be_emit_char('-');
511                 be_emit_string(pic_base_label);
512         }
513 }
514
515 /**
516  * Emits address mode.
517  */
518 void ia32_emit_am(const ir_node *node) {
519         ir_entity *ent       = get_ia32_am_sc(node);
520         int        offs      = get_ia32_am_offs_int(node);
521         ir_node   *base      = get_irn_n(node, 0);
522         int        has_base  = !is_ia32_NoReg_GP(base);
523         ir_node   *index     = get_irn_n(node, 1);
524         int        has_index = !is_ia32_NoReg_GP(index);
525
526         /* just to be sure... */
527         assert(!is_ia32_use_frame(node) || get_ia32_frame_ent(node) != NULL);
528
529         /* emit offset */
530         if (ent != NULL) {
531                 if (is_ia32_am_sc_sign(node))
532                         be_emit_char('-');
533                 ia32_emit_entity(ent, 0);
534         }
535
536         if(offs != 0) {
537                 if(ent != NULL) {
538                         be_emit_irprintf("%+d", offs);
539                 } else {
540                         be_emit_irprintf("%d", offs);
541                 }
542         }
543
544         if (has_base || has_index) {
545                 be_emit_char('(');
546
547                 /* emit base */
548                 if (has_base) {
549                         const arch_register_t *reg = get_in_reg(node, n_ia32_base);
550                         emit_register(reg, NULL);
551                 }
552
553                 /* emit index + scale */
554                 if (has_index) {
555                         const arch_register_t *reg = get_in_reg(node, n_ia32_index);
556                         int scale;
557                         be_emit_char(',');
558                         emit_register(reg, NULL);
559
560                         scale = get_ia32_am_scale(node);
561                         if (scale > 0) {
562                                 be_emit_irprintf(",%d", 1 << get_ia32_am_scale(node));
563                         }
564                 }
565                 be_emit_char(')');
566         }
567
568         /* special case if nothing is set */
569         if(ent == NULL && offs == 0 && !has_base && !has_index) {
570                 be_emit_char('0');
571         }
572 }
573
574 static void emit_ia32_IMul(const ir_node *node)
575 {
576         ir_node               *left    = get_irn_n(node, n_ia32_IMul_left);
577         const arch_register_t *out_reg = get_out_reg(node, pn_ia32_IMul_res);
578
579         be_emit_cstring("\timul");
580         ia32_emit_mode_suffix(node);
581         be_emit_char(' ');
582
583         ia32_emit_binop(node);
584
585         /* do we need the 3-address form? */
586         if(is_ia32_NoReg_GP(left) ||
587                         get_in_reg(node, n_ia32_IMul_left) != out_reg) {
588                 be_emit_cstring(", ");
589                 emit_register(out_reg, get_ia32_ls_mode(node));
590         }
591         be_emit_finish_line_gas(node);
592 }
593
594 /*************************************************
595  *                 _ _                         _
596  *                (_) |                       | |
597  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
598  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
599  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
600  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
601  *
602  *************************************************/
603
604 #undef IA32_DO_EMIT
605 #define IA32_DO_EMIT(irn) ia32_fprintf_format(F, irn, cmd_buf, cmnt_buf)
606
607 /*
608  * coding of conditions
609  */
610 struct cmp2conditon_t {
611         const char *name;
612         int         num;
613 };
614
615 /*
616  * positive conditions for signed compares
617  */
618 static const struct cmp2conditon_t cmp2condition_s[] = {
619         { NULL,              pn_Cmp_False },  /* always false */
620         { "e",               pn_Cmp_Eq },     /* == */
621         { "l",               pn_Cmp_Lt },     /* < */
622         { "le",              pn_Cmp_Le },     /* <= */
623         { "g",               pn_Cmp_Gt },     /* > */
624         { "ge",              pn_Cmp_Ge },     /* >= */
625         { "ne",              pn_Cmp_Lg },     /* != */
626         { NULL,              pn_Cmp_Leg},     /* always true */
627 };
628
629 /*
630  * positive conditions for unsigned compares
631  */
632 static const struct cmp2conditon_t cmp2condition_u[] = {
633         { NULL,              pn_Cmp_False },  /* always false */
634         { "e",               pn_Cmp_Eq },     /* == */
635         { "b",               pn_Cmp_Lt },     /* < */
636         { "be",              pn_Cmp_Le },     /* <= */
637         { "a",               pn_Cmp_Gt },     /* > */
638         { "ae",              pn_Cmp_Ge },     /* >= */
639         { "ne",              pn_Cmp_Lg },     /* != */
640         { NULL,              pn_Cmp_Leg },   /* always true  */
641 };
642
643 /**
644  * walks up a tree of copies/perms/spills/reloads to find the original value
645  * that is moved around
646  */
647 static ir_node *find_original_value(ir_node *node)
648 {
649         inc_irg_visited(current_ir_graph);
650         while(1) {
651                 mark_irn_visited(node);
652                 if(be_is_Copy(node)) {
653                         node = be_get_Copy_op(node);
654                 } else if(be_is_CopyKeep(node)) {
655                         node = be_get_CopyKeep_op(node);
656                 } else if(is_Proj(node)) {
657                         ir_node *pred = get_Proj_pred(node);
658                         if(be_is_Perm(pred)) {
659                                 node = get_irn_n(pred, get_Proj_proj(node));
660                         } else if(be_is_MemPerm(pred)) {
661                                 node = get_irn_n(pred, get_Proj_proj(node) + 1);
662                         } else if(is_ia32_Load(pred)) {
663                                 node = get_irn_n(pred, n_ia32_Load_mem);
664                         } else {
665                                 return node;
666                         }
667                 } else if(is_ia32_Store(node)) {
668                         node = get_irn_n(node, n_ia32_Store_val);
669                 } else if(is_Phi(node)) {
670                         int i, arity;
671                         arity = get_irn_arity(node);
672                         for(i = 0; i < arity; ++i) {
673                                 ir_node *in = get_irn_n(node, i);
674                                 if(irn_visited(in))
675                                         continue;
676                                 node = in;
677                                 break;
678                         }
679                         assert(i < arity);
680                 } else {
681                         return node;
682                 }
683         }
684 }
685
686 static int determine_final_pnc(const ir_node *node, int flags_pos,
687                                int pnc)
688 {
689         ir_node           *flags = get_irn_n(node, flags_pos);
690         const ia32_attr_t *flags_attr;
691         flags = skip_Proj(flags);
692
693         if(is_ia32_Sahf(flags)) {
694                 ir_node *cmp = get_irn_n(flags, n_ia32_Sahf_val);
695                 if(!(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
696                                 || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp))) {
697                         cmp = find_original_value(cmp);
698                         assert(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
699                                || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp));
700                 }
701
702                 flags_attr = get_ia32_attr_const(cmp);
703                 if(flags_attr->data.ins_permuted)
704                         pnc = get_mirrored_pnc(pnc);
705                 pnc |= ia32_pn_Cmp_float;
706         } else if(is_ia32_Ucomi(flags) || is_ia32_Fucomi(flags)
707                         || is_ia32_Fucompi(flags)) {
708                 flags_attr = get_ia32_attr_const(flags);
709
710                 if(flags_attr->data.ins_permuted)
711                         pnc = get_mirrored_pnc(pnc);
712                 pnc |= ia32_pn_Cmp_float;
713         } else {
714 #if 0
715                 assert(is_ia32_Cmp(flags) || is_ia32_Test(flags)
716                                 || is_ia32_Cmp8Bit(flags) || is_ia32_Test8Bit(flags));
717 #endif
718                 flags_attr = get_ia32_attr_const(flags);
719
720                 if(flags_attr->data.ins_permuted)
721                         pnc = get_mirrored_pnc(pnc);
722                 if(flags_attr->data.cmp_unsigned)
723                         pnc |= ia32_pn_Cmp_unsigned;
724         }
725
726         return pnc;
727 }
728
729 static void ia32_emit_cmp_suffix(int pnc)
730 {
731         const char        *str;
732
733         if((pnc & ia32_pn_Cmp_float) || (pnc & ia32_pn_Cmp_unsigned)) {
734                 pnc = pnc & 7;
735                 assert(cmp2condition_u[pnc].num == pnc);
736                 str = cmp2condition_u[pnc].name;
737         } else {
738                 pnc = pnc & 7;
739                 assert(cmp2condition_s[pnc].num == pnc);
740                 str = cmp2condition_s[pnc].name;
741         }
742
743         be_emit_string(str);
744 }
745
746 void ia32_emit_cmp_suffix_node(const ir_node *node,
747                                int flags_pos)
748 {
749         const ia32_attr_t *attr = get_ia32_attr_const(node);
750
751         pn_Cmp pnc = get_ia32_condcode(node);
752
753         pnc = determine_final_pnc(node, flags_pos, pnc);
754         if(attr->data.ins_permuted) {
755                 if(pnc & ia32_pn_Cmp_float) {
756                         pnc = get_negated_pnc(pnc, mode_F);
757                 } else {
758                         pnc = get_negated_pnc(pnc, mode_Iu);
759                 }
760         }
761
762         ia32_emit_cmp_suffix(pnc);
763 }
764
765 /**
766  * Returns the target block for a control flow node.
767  */
768 static ir_node *get_cfop_target_block(const ir_node *irn) {
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         const ir_edge_t *edge;
811         ir_node         *src;
812
813         assert(get_irn_mode(node) == mode_T && "expected mode_T node");
814
815         foreach_out_edge(node, edge) {
816                 src = get_edge_src_irn(edge);
817
818                 assert(is_Proj(src) && "Proj expected");
819                 if (get_irn_mode(src) == mode_M)
820                         continue;
821
822                 if (get_Proj_proj(src) == proj)
823                         return src;
824         }
825         return NULL;
826 }
827
828 static bool can_be_fallthrough(const ir_node *node)
829 {
830         ir_node *target_block = get_cfop_target_block(node);
831         ir_node *block        = get_nodes_block(node);
832         return get_prev_block_sched(target_block) == block;
833 }
834
835 /**
836  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
837  */
838 static void emit_ia32_Jcc(const ir_node *node)
839 {
840         int            need_parity_label = 0;
841         const ir_node *proj_true;
842         const ir_node *proj_false;
843         const ir_node *block;
844         const ir_node *next_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 (get_cfop_target_block(proj_false) == next_block) {
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 (get_cfop_target_block(proj_false) != next_block) {
930                 be_emit_cstring("\tjmp ");
931                 ia32_emit_cfop_target(proj_false);
932                 be_emit_finish_line_gas(proj_false);
933         } else {
934                 be_emit_cstring("\t/* fallthrough to ");
935                 ia32_emit_cfop_target(proj_false);
936                 be_emit_cstring(" */");
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         branch_t *b1 = (branch_t *)a;
1034         branch_t *b2 = (branch_t *)b;
1035
1036         if (b1->value <= b2->value)
1037                 return -1;
1038         else
1039                 return 1;
1040 }
1041
1042 /**
1043  * Emits code for a SwitchJmp (creates a jump table if
1044  * possible otherwise a cmp-jmp cascade). Port from
1045  * cggg ia32 backend
1046  */
1047 static void emit_ia32_SwitchJmp(const ir_node *node)
1048 {
1049         unsigned long       interval;
1050         int                 last_value, i;
1051         long                pnc;
1052         long                default_pn;
1053         jmp_tbl_t           tbl;
1054         ir_node            *proj;
1055         const ir_edge_t    *edge;
1056
1057         /* fill the table structure */
1058         tbl.label        = xmalloc(SNPRINTF_BUF_LEN);
1059         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, ".TBL_");
1060         tbl.defProj      = NULL;
1061         tbl.num_branches = get_irn_n_edges(node) - 1;
1062         tbl.branches     = xcalloc(tbl.num_branches, sizeof(tbl.branches[0]));
1063         tbl.min_value    = INT_MAX;
1064         tbl.max_value    = INT_MIN;
1065
1066         default_pn = get_ia32_condcode(node);
1067         i = 0;
1068         /* go over all proj's and collect them */
1069         foreach_out_edge(node, edge) {
1070                 proj = get_edge_src_irn(edge);
1071                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1072
1073                 pnc = get_Proj_proj(proj);
1074
1075                 /* check for default proj */
1076                 if (pnc == default_pn) {
1077                         assert(tbl.defProj == NULL && "found two default Projs at SwitchJmp");
1078                         tbl.defProj = proj;
1079                 } else {
1080                         tbl.min_value = pnc < tbl.min_value ? pnc : tbl.min_value;
1081                         tbl.max_value = pnc > tbl.max_value ? pnc : tbl.max_value;
1082
1083                         /* create branch entry */
1084                         tbl.branches[i].target = proj;
1085                         tbl.branches[i].value  = pnc;
1086                         ++i;
1087                 }
1088
1089         }
1090         assert(i == tbl.num_branches);
1091
1092         /* sort the branches by their number */
1093         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
1094
1095         /* two-complement's magic make this work without overflow */
1096         interval = tbl.max_value - tbl.min_value;
1097
1098         /* emit the table */
1099         be_emit_cstring("\tcmpl $");
1100         be_emit_irprintf("%u, ", interval);
1101         ia32_emit_source_register(node, 0);
1102         be_emit_finish_line_gas(node);
1103
1104         be_emit_cstring("\tja ");
1105         ia32_emit_cfop_target(tbl.defProj);
1106         be_emit_finish_line_gas(node);
1107
1108         if (tbl.num_branches > 1) {
1109                 /* create table */
1110                 be_emit_cstring("\tjmp *");
1111                 be_emit_string(tbl.label);
1112                 be_emit_cstring("(,");
1113                 ia32_emit_source_register(node, 0);
1114                 be_emit_cstring(",4)");
1115                 be_emit_finish_line_gas(node);
1116
1117                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1118                 be_emit_cstring("\t.align 4\n");
1119                 be_emit_write_line();
1120
1121                 be_emit_string(tbl.label);
1122                 be_emit_cstring(":\n");
1123                 be_emit_write_line();
1124
1125                 be_emit_cstring(".long ");
1126                 ia32_emit_cfop_target(tbl.branches[0].target);
1127                 be_emit_finish_line_gas(NULL);
1128
1129                 last_value = tbl.branches[0].value;
1130                 for (i = 1; i < tbl.num_branches; ++i) {
1131                         while (++last_value < tbl.branches[i].value) {
1132                                 be_emit_cstring(".long ");
1133                                 ia32_emit_cfop_target(tbl.defProj);
1134                                 be_emit_finish_line_gas(NULL);
1135                         }
1136                         be_emit_cstring(".long ");
1137                         ia32_emit_cfop_target(tbl.branches[i].target);
1138                         be_emit_finish_line_gas(NULL);
1139                 }
1140                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1141         } else {
1142                 /* one jump is enough */
1143                 be_emit_cstring("\tjmp ");
1144                 ia32_emit_cfop_target(tbl.branches[0].target);
1145                 be_emit_finish_line_gas(node);
1146         }
1147
1148         if (tbl.label)
1149                 free(tbl.label);
1150         if (tbl.branches)
1151                 free(tbl.branches);
1152 }
1153
1154 /**
1155  * Emits code for a unconditional jump.
1156  */
1157 static void emit_Jmp(const ir_node *node)
1158 {
1159         ir_node *block;
1160
1161         /* for now, the code works for scheduled and non-schedules blocks */
1162         block = get_nodes_block(node);
1163
1164         /* we have a block schedule */
1165         if (can_be_fallthrough(node)) {
1166                 be_emit_cstring("\t/* fallthrough to ");
1167                 ia32_emit_cfop_target(node);
1168                 be_emit_cstring(" */");
1169         } else {
1170                 be_emit_cstring("\tjmp ");
1171                 ia32_emit_cfop_target(node);
1172         }
1173         be_emit_finish_line_gas(node);
1174 }
1175
1176 static void emit_ia32_Immediate(const ir_node *node)
1177 {
1178         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
1179
1180         be_emit_char('$');
1181         if(attr->symconst != NULL) {
1182                 if(attr->sc_sign)
1183                         be_emit_char('-');
1184                 ia32_emit_entity(attr->symconst, 0);
1185         }
1186         if(attr->symconst == NULL || attr->offset != 0) {
1187                 if(attr->symconst != NULL) {
1188                         be_emit_irprintf("%+d", attr->offset);
1189                 } else {
1190                         be_emit_irprintf("0x%X", attr->offset);
1191                 }
1192         }
1193 }
1194
1195 /**
1196  * Emit an inline assembler operand.
1197  *
1198  * @param node  the ia32_ASM node
1199  * @param s     points to the operand (a %c)
1200  *
1201  * @return  pointer to the first char in s NOT in the current operand
1202  */
1203 static const char* emit_asm_operand(const ir_node *node, const char *s)
1204 {
1205         const ia32_attr_t     *ia32_attr = get_ia32_attr_const(node);
1206         const ia32_asm_attr_t *attr      = CONST_CAST_IA32_ATTR(ia32_asm_attr_t,
1207                                                             ia32_attr);
1208         const arch_register_t *reg;
1209         const ia32_asm_reg_t  *asm_regs = attr->register_map;
1210         const ia32_asm_reg_t  *asm_reg;
1211         const char            *reg_name;
1212         char                   c;
1213         char                   modifier = 0;
1214         int                    num      = -1;
1215         int                    p;
1216
1217         assert(*s == '%');
1218         c = *(++s);
1219
1220         /* parse modifiers */
1221         switch(c) {
1222         case 0:
1223                 ir_fprintf(stderr, "Warning: asm text (%+F) ends with %\n", node);
1224                 be_emit_char('%');
1225                 return s + 1;
1226         case '%':
1227                 be_emit_char('%');
1228                 return s + 1;
1229         case 'w':
1230         case 'b':
1231         case 'h':
1232                 modifier = c;
1233                 ++s;
1234                 break;
1235         case '0':
1236         case '1':
1237         case '2':
1238         case '3':
1239         case '4':
1240         case '5':
1241         case '6':
1242         case '7':
1243         case '8':
1244         case '9':
1245                 break;
1246         default:
1247                 ir_fprintf(stderr, "Warning: asm text (%+F) contains unknown modifier "
1248                            "'%c' for asm op\n", node, c);
1249                 ++s;
1250                 break;
1251         }
1252
1253         /* parse number */
1254         sscanf(s, "%d%n", &num, &p);
1255         if(num < 0) {
1256                 ir_fprintf(stderr, "Warning: Couldn't parse assembler operand (%+F)\n",
1257                            node);
1258                 return s;
1259         } else {
1260                 s += p;
1261         }
1262
1263         if(num < 0 || num >= ARR_LEN(asm_regs)) {
1264                 ir_fprintf(stderr, "Error: Custom assembler references invalid "
1265                            "input/output (%+F)\n", node);
1266                 return s;
1267         }
1268         asm_reg = & asm_regs[num];
1269         assert(asm_reg->valid);
1270
1271         /* get register */
1272         if(asm_reg->use_input == 0) {
1273                 reg = get_out_reg(node, asm_reg->inout_pos);
1274         } else {
1275                 ir_node *pred = get_irn_n(node, asm_reg->inout_pos);
1276
1277                 /* might be an immediate value */
1278                 if(is_ia32_Immediate(pred)) {
1279                         emit_ia32_Immediate(pred);
1280                         return s;
1281                 }
1282                 reg = get_in_reg(node, asm_reg->inout_pos);
1283         }
1284         if(reg == NULL) {
1285                 ir_fprintf(stderr, "Warning: no register assigned for %d asm op "
1286                            "(%+F)\n", num, node);
1287                 return s;
1288         }
1289
1290         if(asm_reg->memory) {
1291                 be_emit_char('(');
1292         }
1293
1294         /* emit it */
1295         if(modifier != 0) {
1296                 be_emit_char('%');
1297                 switch(modifier) {
1298                 case 'b':
1299                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit, reg);
1300                         break;
1301                 case 'h':
1302                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit_high, reg);
1303                         break;
1304                 case 'w':
1305                         reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
1306                         break;
1307                 default:
1308                         panic("Invalid asm op modifier");
1309                 }
1310                 be_emit_string(reg_name);
1311         } else {
1312                 emit_register(reg, asm_reg->mode);
1313         }
1314
1315         if(asm_reg->memory) {
1316                 be_emit_char(')');
1317         }
1318
1319         return s;
1320 }
1321
1322 /**
1323  * Emits code for an ASM pseudo op.
1324  */
1325 static void emit_ia32_Asm(const ir_node *node)
1326 {
1327         const void            *gen_attr = get_irn_generic_attr_const(node);
1328         const ia32_asm_attr_t *attr
1329                 = CONST_CAST_IA32_ATTR(ia32_asm_attr_t, gen_attr);
1330         ident                 *asm_text = attr->asm_text;
1331         const char            *s        = get_id_str(asm_text);
1332
1333         be_emit_cstring("# Begin ASM \t");
1334         be_emit_finish_line_gas(node);
1335
1336         if (s[0] != '\t')
1337                 be_emit_char('\t');
1338
1339         while(*s != 0) {
1340                 if(*s == '%') {
1341                         s = emit_asm_operand(node, s);
1342                         continue;
1343                 } else {
1344                         be_emit_char(*s);
1345                 }
1346                 ++s;
1347         }
1348
1349         be_emit_char('\n');
1350         be_emit_write_line();
1351
1352         be_emit_cstring("# End ASM\n");
1353         be_emit_write_line();
1354 }
1355
1356 /**********************************
1357  *   _____                  ____
1358  *  / ____|                |  _ \
1359  * | |     ___  _ __  _   _| |_) |
1360  * | |    / _ \| '_ \| | | |  _ <
1361  * | |___| (_) | |_) | |_| | |_) |
1362  *  \_____\___/| .__/ \__, |____/
1363  *             | |     __/ |
1364  *             |_|    |___/
1365  **********************************/
1366
1367 /**
1368  * Emit movsb/w instructions to make mov count divideable by 4
1369  */
1370 static void emit_CopyB_prolog(unsigned size) {
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                         assert(0 && "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)\n", 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) {
1852                 be_emit_irprintf(" $%d", pop);
1853         } else if (be_Return_get_emit_pop(node)) {
1854                 ir_node *block = get_nodes_block(node);
1855                 if (block_needs_label(block)) {
1856                         be_emit_cstring(" $0");
1857                 }
1858         }
1859         be_emit_finish_line_gas(node);
1860 }
1861
1862 static void emit_Nothing(const ir_node *node)
1863 {
1864         (void) node;
1865 }
1866
1867
1868 /***********************************************************************************
1869  *                  _          __                                             _
1870  *                 (_)        / _|                                           | |
1871  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1872  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1873  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1874  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1875  *
1876  ***********************************************************************************/
1877
1878 /**
1879  * Enters the emitter functions for handled nodes into the generic
1880  * pointer of an opcode.
1881  */
1882 static void ia32_register_emitters(void) {
1883
1884 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1885 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1886 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1887 #define IGN(a)                  op_##a->ops.generic = (op_func)emit_Nothing
1888 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1889 #define BE_IGN(a)               op_be_##a->ops.generic = (op_func)emit_Nothing
1890
1891         /* first clear the generic function pointer for all ops */
1892         clear_irp_opcodes_generic_func();
1893
1894         /* register all emitter functions defined in spec */
1895         ia32_register_spec_emitters();
1896
1897         /* other ia32 emitter functions */
1898         IA32_EMIT(Asm);
1899         IA32_EMIT(CMov);
1900         IA32_EMIT(IMul);
1901         IA32_EMIT(SwitchJmp);
1902         IA32_EMIT(CopyB);
1903         IA32_EMIT(CopyB_i);
1904         IA32_EMIT(Conv_I2FP);
1905         IA32_EMIT(Conv_FP2I);
1906         IA32_EMIT(Conv_FP2FP);
1907         IA32_EMIT(Conv_I2I);
1908         IA32_EMIT2(Conv_I2I8Bit, Conv_I2I);
1909         IA32_EMIT(Const);
1910         IA32_EMIT(LdTls);
1911         IA32_EMIT(Minus64Bit);
1912         IA32_EMIT(Jcc);
1913         IA32_EMIT(GetEIP);
1914
1915         /* benode emitter */
1916         BE_EMIT(Call);
1917         BE_EMIT(IncSP);
1918         BE_EMIT(Copy);
1919         BE_EMIT(CopyKeep);
1920         BE_EMIT(Perm);
1921         BE_EMIT(Return);
1922
1923         BE_IGN(RegParams);
1924         BE_IGN(Barrier);
1925         BE_IGN(Keep);
1926
1927         /* firm emitter */
1928         EMIT(Jmp);
1929         IGN(Proj);
1930         IGN(Phi);
1931         IGN(Start);
1932
1933 #undef BE_EMIT
1934 #undef EMIT
1935 #undef IGN
1936 #undef IA32_EMIT2
1937 #undef IA32_EMIT
1938 }
1939
1940 typedef void (*emit_func_ptr) (const ir_node *);
1941
1942 /**
1943  * Emits code for a node.
1944  */
1945 static void ia32_emit_node(ir_node *node)
1946 {
1947         ir_op *op = get_irn_op(node);
1948
1949         DBG((dbg, LEVEL_1, "emitting code for %+F\n", node));
1950
1951         if (is_ia32_irn(node) && get_ia32_exc_label(node)) {
1952                 /* emit the exception label of this instruction */
1953                 ia32_assign_exc_label(node);
1954         }
1955         if (op->ops.generic) {
1956                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
1957
1958                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
1959
1960                 (*func) (node);
1961         } else {
1962                 emit_Nothing(node);
1963                 ir_fprintf(stderr, "Error: No emit handler for node %+F (%+G, graph %+F)\n", node, node, current_ir_graph);
1964                 abort();
1965         }
1966 }
1967
1968 /**
1969  * Emits gas alignment directives
1970  */
1971 static void ia32_emit_alignment(unsigned align, unsigned skip)
1972 {
1973         be_emit_cstring("\t.p2align ");
1974         be_emit_irprintf("%u,,%u\n", align, skip);
1975         be_emit_write_line();
1976 }
1977
1978 /**
1979  * Emits gas alignment directives for Labels depended on cpu architecture.
1980  */
1981 static void ia32_emit_align_label(void)
1982 {
1983         unsigned align        = ia32_cg_config.label_alignment;
1984         unsigned maximum_skip = ia32_cg_config.label_alignment_max_skip;
1985         ia32_emit_alignment(align, maximum_skip);
1986 }
1987
1988 /**
1989  * Test whether a block should be aligned.
1990  * For cpus in the P4/Athlon class it is useful to align jump labels to
1991  * 16 bytes. However we should only do that if the alignment nops before the
1992  * label aren't executed more often than we have jumps to the label.
1993  */
1994 static int should_align_block(const ir_node *block)
1995 {
1996         static const double DELTA = .0001;
1997         ir_exec_freq *exec_freq   = cg->birg->exec_freq;
1998         ir_node      *prev        = get_prev_block_sched(block);
1999         double        block_freq;
2000         double        prev_freq = 0;  /**< execfreq of the fallthrough block */
2001         double        jmp_freq  = 0;  /**< execfreq of all non-fallthrough blocks */
2002         int           i, n_cfgpreds;
2003
2004         if(exec_freq == NULL)
2005                 return 0;
2006         if(ia32_cg_config.label_alignment_factor <= 0)
2007                 return 0;
2008
2009         block_freq = get_block_execfreq(exec_freq, block);
2010         if(block_freq < DELTA)
2011                 return 0;
2012
2013         n_cfgpreds = get_Block_n_cfgpreds(block);
2014         for(i = 0; i < n_cfgpreds; ++i) {
2015                 ir_node *pred      = get_Block_cfgpred_block(block, i);
2016                 double   pred_freq = get_block_execfreq(exec_freq, pred);
2017
2018                 if(pred == prev) {
2019                         prev_freq += pred_freq;
2020                 } else {
2021                         jmp_freq  += pred_freq;
2022                 }
2023         }
2024
2025         if(prev_freq < DELTA && !(jmp_freq < DELTA))
2026                 return 1;
2027
2028         jmp_freq /= prev_freq;
2029
2030         return jmp_freq > ia32_cg_config.label_alignment_factor;
2031 }
2032
2033 /**
2034  * Emit the block header for a block.
2035  *
2036  * @param block       the block
2037  * @param prev_block  the previous block
2038  */
2039 static void ia32_emit_block_header(ir_node *block)
2040 {
2041         ir_graph     *irg = current_ir_graph;
2042         int           n_cfgpreds;
2043         bool          need_label = block_needs_label(block);
2044         int           i, arity;
2045         ir_exec_freq *exec_freq = cg->birg->exec_freq;
2046
2047         if (block == get_irg_end_block(irg) || block == get_irg_start_block(irg))
2048                 return;
2049
2050         if (ia32_cg_config.label_alignment > 0) {
2051                 /* align the current block if:
2052                  * a) if should be aligned due to its execution frequency
2053                  * b) there is no fall-through here
2054                  */
2055                 if (should_align_block(block)) {
2056                         ia32_emit_align_label();
2057                 } else {
2058                         /* if the predecessor block has no fall-through,
2059                            we can always align the label. */
2060                         int      i;
2061                         bool     has_fallthrough = false;;
2062
2063                         for (i = n_cfgpreds - 1; i >= 0; --i) {
2064                                 ir_node *cfg_pred = get_Block_cfgpred(block, i);
2065                                 if (can_be_fallthrough(cfg_pred)) {
2066                                         has_fallthrough = true;
2067                                         break;
2068                                 }
2069                         }
2070
2071                         if (!has_fallthrough)
2072                                 ia32_emit_align_label();
2073                 }
2074         }
2075
2076         if (need_label || has_Block_label(block)) {
2077                 ia32_emit_block_name(block);
2078                 be_emit_char(':');
2079
2080                 be_emit_pad_comment();
2081                 be_emit_cstring("   /* ");
2082         } else {
2083                 be_emit_cstring("\t/* ");
2084                 ia32_emit_block_name(block);
2085                 be_emit_cstring(": ");
2086         }
2087
2088         be_emit_cstring("preds:");
2089
2090         /* emit list of pred blocks in comment */
2091         arity = get_irn_arity(block);
2092         for (i = 0; i < arity; ++i) {
2093                 ir_node *predblock = get_Block_cfgpred_block(block, i);
2094                 be_emit_irprintf(" %d", get_irn_node_nr(predblock));
2095         }
2096         if (exec_freq != NULL) {
2097                 be_emit_irprintf(" freq: %f",
2098                                  get_block_execfreq(exec_freq, block));
2099         }
2100         be_emit_cstring(" */\n");
2101         be_emit_write_line();
2102 }
2103
2104 /**
2105  * Walks over the nodes in a block connected by scheduling edges
2106  * and emits code for each node.
2107  */
2108 static void ia32_gen_block(ir_node *block)
2109 {
2110         ir_node *node;
2111
2112         ia32_emit_block_header(block);
2113
2114         /* emit the contents of the block */
2115         be_dbg_set_dbg_info(get_irn_dbg_info(block));
2116         sched_foreach(block, node) {
2117                 ia32_emit_node(node);
2118         }
2119 }
2120
2121 typedef struct exc_entry {
2122         ir_node *exc_instr;  /** The instruction that can issue an exception. */
2123         ir_node *block;      /** The block to call then. */
2124 } exc_entry;
2125
2126 /**
2127  * Block-walker:
2128  * Sets labels for control flow nodes (jump target).
2129  * Links control predecessors to there destination blocks.
2130  */
2131 static void ia32_gen_labels(ir_node *block, void *data)
2132 {
2133         exc_entry **exc_list = data;
2134         ir_node *pred;
2135         int     n;
2136
2137         for (n = get_Block_n_cfgpreds(block) - 1; n >= 0; --n) {
2138                 pred = get_Block_cfgpred(block, n);
2139                 set_irn_link(pred, block);
2140
2141                 pred = skip_Proj(pred);
2142                 if (is_ia32_irn(pred) && get_ia32_exc_label(pred)) {
2143                         exc_entry e;
2144
2145                         e.exc_instr = pred;
2146                         e.block     = block;
2147                         ARR_APP1(exc_entry, *exc_list, e);
2148                         set_irn_link(pred, block);
2149                 }
2150         }
2151 }
2152
2153 /**
2154  * Assign and emit an exception label if the current instruction can fail.
2155  */
2156 void ia32_assign_exc_label(ir_node *node)
2157 {
2158         if (get_ia32_exc_label(node)) {
2159                 /* assign a new ID to the instruction */
2160                 set_ia32_exc_label_id(node, ++exc_label_id);
2161                 /* print it */
2162                 ia32_emit_exc_label(node);
2163                 be_emit_char(':');
2164                 be_emit_pad_comment();
2165                 be_emit_cstring("/* exception to Block ");
2166                 ia32_emit_cfop_target(node);
2167                 be_emit_cstring(" */\n");
2168                 be_emit_write_line();
2169         }
2170 }
2171
2172 /**
2173  * Compare two exception_entries.
2174  */
2175 static int cmp_exc_entry(const void *a, const void *b) {
2176         const exc_entry *ea = a;
2177         const exc_entry *eb = b;
2178
2179         if (get_ia32_exc_label_id(ea->exc_instr) < get_ia32_exc_label_id(eb->exc_instr))
2180                 return -1;
2181         return +1;
2182 }
2183
2184 /**
2185  * Main driver. Emits the code for one routine.
2186  */
2187 void ia32_gen_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
2188 {
2189         ir_entity *entity     = get_irg_entity(irg);
2190         exc_entry *exc_list   = NEW_ARR_F(exc_entry, 0);
2191         int i, n;
2192
2193         cg       = ia32_cg;
2194         isa      = (const ia32_isa_t*) cg->arch_env;
2195         arch_env = cg->arch_env;
2196         do_pic   = cg->birg->main_env->options->pic;
2197
2198         ia32_register_emitters();
2199
2200         get_unique_label(pic_base_label, sizeof(pic_base_label), ".PIC_BASE");
2201
2202         be_dbg_method_begin(entity, be_abi_get_stack_layout(cg->birg->abi));
2203         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
2204
2205         /* we use links to point to target blocks */
2206         set_using_irn_link(irg);
2207         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &exc_list);
2208
2209         /* initialize next block links */
2210         n = ARR_LEN(cg->blk_sched);
2211         for (i = 0; i < n; ++i) {
2212                 ir_node *block = cg->blk_sched[i];
2213                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
2214
2215                 set_irn_link(block, prev);
2216         }
2217
2218         for (i = 0; i < n; ++i) {
2219                 ir_node *block = cg->blk_sched[i];
2220
2221                 ia32_gen_block(block);
2222         }
2223
2224         be_gas_emit_function_epilog(entity);
2225         be_dbg_method_end();
2226         be_emit_char('\n');
2227         be_emit_write_line();
2228
2229         clear_using_irn_link(irg);
2230
2231         /* Sort the exception table using the exception label id's.
2232            Those are ascending with ascending addresses. */
2233         qsort(exc_list, ARR_LEN(exc_list), sizeof(exc_list[0]), cmp_exc_entry);
2234         {
2235                 int i;
2236
2237                 for (i = 0; i < ARR_LEN(exc_list); ++i) {
2238                         be_emit_cstring("\t.long ");
2239                         ia32_emit_exc_label(exc_list[i].exc_instr);
2240                         be_emit_char('\n');
2241                         be_emit_cstring("\t.long ");
2242                         ia32_emit_block_name(exc_list[i].block);
2243                         be_emit_char('\n');
2244                 }
2245         }
2246         DEL_ARR_F(exc_list);
2247 }
2248
2249 void ia32_init_emitter(void)
2250 {
2251         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.emitter");
2252 }