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