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