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