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