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