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