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