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