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