Simplify emit_CopyB_prolog() and remove an unnecessary bit filter before calling it.
[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  * Emits registers and/or address mode of a binary operation.
396  */
397 void ia32_emit_binop(const ir_node *node)
398 {
399         const ir_node         *right_op  = get_irn_n(node, n_ia32_binary_right);
400         const ir_mode         *mode      = get_ia32_ls_mode(node);
401         const arch_register_t *reg_left;
402
403         switch(get_ia32_op_type(node)) {
404         case ia32_Normal:
405                 reg_left = get_in_reg(node, n_ia32_binary_left);
406                 if (is_ia32_Immediate(right_op)) {
407                         emit_ia32_Immediate(right_op);
408                         be_emit_cstring(", ");
409                         emit_register(reg_left, mode);
410                         break;
411                 } else {
412                         const arch_register_t *reg_right
413                                 = get_in_reg(node, n_ia32_binary_right);
414                         emit_register(reg_right, mode);
415                         be_emit_cstring(", ");
416                         emit_register(reg_left, mode);
417                 }
418                 break;
419         case ia32_AddrModeS:
420                 if (is_ia32_Immediate(right_op)) {
421                         emit_ia32_Immediate(right_op);
422                         be_emit_cstring(", ");
423                         ia32_emit_am(node);
424                 } else {
425                         reg_left = get_in_reg(node, n_ia32_binary_left);
426                         ia32_emit_am(node);
427                         be_emit_cstring(", ");
428                         emit_register(reg_left, mode);
429                 }
430                 break;
431         case ia32_AddrModeD:
432                 panic("DestMode can't be output by %%binop anymore");
433                 break;
434         default:
435                 assert(0 && "unsupported op type");
436         }
437 }
438
439 /**
440  * Emits registers and/or address mode of a binary operation.
441  */
442 void ia32_emit_x87_binop(const ir_node *node)
443 {
444         switch(get_ia32_op_type(node)) {
445                 case ia32_Normal:
446                         {
447                                 const ia32_x87_attr_t *x87_attr = get_ia32_x87_attr_const(node);
448                                 const arch_register_t *in1      = x87_attr->x87[0];
449                                 const arch_register_t *in       = x87_attr->x87[1];
450                                 const arch_register_t *out      = x87_attr->x87[2];
451
452                                 if (out == NULL) {
453                                         out = in1;
454                                 } else if (out == in) {
455                                         in = in1;
456                                 }
457
458                                 be_emit_char('%');
459                                 be_emit_string(arch_register_get_name(in));
460                                 be_emit_cstring(", %");
461                                 be_emit_string(arch_register_get_name(out));
462                         }
463                         break;
464                 case ia32_AddrModeS:
465                         ia32_emit_am(node);
466                         break;
467                 case ia32_AddrModeD:
468                 default:
469                         assert(0 && "unsupported op type");
470         }
471 }
472
473 /**
474  * Emits registers and/or address mode of a unary operation.
475  */
476 void ia32_emit_unop(const ir_node *node, int pos)
477 {
478         const ir_node *op;
479
480         switch(get_ia32_op_type(node)) {
481         case ia32_Normal:
482                 op = get_irn_n(node, pos);
483                 if (is_ia32_Immediate(op)) {
484                         emit_ia32_Immediate(op);
485                 } else {
486                         ia32_emit_source_register(node, pos);
487                 }
488                 break;
489         case ia32_AddrModeS:
490         case ia32_AddrModeD:
491                 ia32_emit_am(node);
492                 break;
493         default:
494                 assert(0 && "unsupported op type");
495         }
496 }
497
498 static void ia32_emit_entity(ir_entity *entity, int no_pic_adjust)
499 {
500         ident *id;
501
502         set_entity_backend_marked(entity, 1);
503         id = get_entity_ld_ident(entity);
504         be_emit_ident(id);
505
506         if (get_entity_owner(entity) == get_tls_type()) {
507                 if (get_entity_visibility(entity) == visibility_external_allocated) {
508                         be_emit_cstring("@INDNTPOFF");
509                 } else {
510                         be_emit_cstring("@NTPOFF");
511                 }
512         }
513
514         if (!no_pic_adjust && do_pic) {
515                 /* TODO: only do this when necessary */
516                 be_emit_char('-');
517                 be_emit_string(pic_base_label);
518         }
519 }
520
521 /**
522  * Emits address mode.
523  */
524 void ia32_emit_am(const ir_node *node)
525 {
526         ir_entity *ent       = get_ia32_am_sc(node);
527         int        offs      = get_ia32_am_offs_int(node);
528         ir_node   *base      = get_irn_n(node, n_ia32_base);
529         int        has_base  = !is_ia32_NoReg_GP(base);
530         ir_node   *index     = get_irn_n(node, n_ia32_index);
531         int        has_index = !is_ia32_NoReg_GP(index);
532
533         /* just to be sure... */
534         assert(!is_ia32_use_frame(node) || get_ia32_frame_ent(node) != NULL);
535
536         /* emit offset */
537         if (ent != NULL) {
538                 if (is_ia32_am_sc_sign(node))
539                         be_emit_char('-');
540                 ia32_emit_entity(ent, 0);
541         }
542
543         /* also handle special case if nothing is set */
544         if (offs != 0 || (ent == NULL && !has_base && !has_index)) {
545                 if (ent != NULL) {
546                         be_emit_irprintf("%+d", offs);
547                 } else {
548                         be_emit_irprintf("%d", offs);
549                 }
550         }
551
552         if (has_base || has_index) {
553                 be_emit_char('(');
554
555                 /* emit base */
556                 if (has_base) {
557                         const arch_register_t *reg = get_in_reg(node, n_ia32_base);
558                         emit_register(reg, NULL);
559                 }
560
561                 /* emit index + scale */
562                 if (has_index) {
563                         const arch_register_t *reg = get_in_reg(node, n_ia32_index);
564                         int scale;
565                         be_emit_char(',');
566                         emit_register(reg, NULL);
567
568                         scale = get_ia32_am_scale(node);
569                         if (scale > 0) {
570                                 be_emit_irprintf(",%d", 1 << scale);
571                         }
572                 }
573                 be_emit_char(')');
574         }
575 }
576
577 static void emit_ia32_IMul(const ir_node *node)
578 {
579         ir_node               *left    = get_irn_n(node, n_ia32_IMul_left);
580         const arch_register_t *out_reg = get_out_reg(node, pn_ia32_IMul_res);
581
582         be_emit_cstring("\timul");
583         ia32_emit_mode_suffix(node);
584         be_emit_char(' ');
585
586         ia32_emit_binop(node);
587
588         /* do we need the 3-address form? */
589         if (is_ia32_NoReg_GP(left) ||
590                         get_in_reg(node, n_ia32_IMul_left) != out_reg) {
591                 be_emit_cstring(", ");
592                 emit_register(out_reg, get_ia32_ls_mode(node));
593         }
594         be_emit_finish_line_gas(node);
595 }
596
597 /*************************************************
598  *                 _ _                         _
599  *                (_) |                       | |
600  *   ___ _ __ ___  _| |_    ___ ___  _ __   __| |
601  *  / _ \ '_ ` _ \| | __|  / __/ _ \| '_ \ / _` |
602  * |  __/ | | | | | | |_  | (_| (_) | | | | (_| |
603  *  \___|_| |_| |_|_|\__|  \___\___/|_| |_|\__,_|
604  *
605  *************************************************/
606
607 #undef IA32_DO_EMIT
608 #define IA32_DO_EMIT(irn) ia32_fprintf_format(F, irn, cmd_buf, cmnt_buf)
609
610 /*
611  * coding of conditions
612  */
613 struct cmp2conditon_t {
614         const char *name;
615         int         num;
616 };
617
618 /*
619  * positive conditions for signed compares
620  */
621 static const struct cmp2conditon_t cmp2condition_s[] = {
622         { NULL,              pn_Cmp_False },  /* always false */
623         { "e",               pn_Cmp_Eq },     /* == */
624         { "l",               pn_Cmp_Lt },     /* < */
625         { "le",              pn_Cmp_Le },     /* <= */
626         { "g",               pn_Cmp_Gt },     /* > */
627         { "ge",              pn_Cmp_Ge },     /* >= */
628         { "ne",              pn_Cmp_Lg },     /* != */
629         { NULL,              pn_Cmp_Leg},     /* always true */
630 };
631
632 /*
633  * positive conditions for unsigned compares
634  */
635 static const struct cmp2conditon_t cmp2condition_u[] = {
636         { NULL,              pn_Cmp_False },  /* always false */
637         { "e",               pn_Cmp_Eq },     /* == */
638         { "b",               pn_Cmp_Lt },     /* < */
639         { "be",              pn_Cmp_Le },     /* <= */
640         { "a",               pn_Cmp_Gt },     /* > */
641         { "ae",              pn_Cmp_Ge },     /* >= */
642         { "ne",              pn_Cmp_Lg },     /* != */
643         { NULL,              pn_Cmp_Leg },   /* always true  */
644 };
645
646 /**
647  * walks up a tree of copies/perms/spills/reloads to find the original value
648  * that is moved around
649  */
650 static ir_node *find_original_value(ir_node *node)
651 {
652         if (irn_visited(node))
653                 return NULL;
654
655         mark_irn_visited(node);
656         if (be_is_Copy(node)) {
657                 return find_original_value(be_get_Copy_op(node));
658         } else if (be_is_CopyKeep(node)) {
659                 return find_original_value(be_get_CopyKeep_op(node));
660         } else if (is_Proj(node)) {
661                 ir_node *pred = get_Proj_pred(node);
662                 if (be_is_Perm(pred)) {
663                         return find_original_value(get_irn_n(pred, get_Proj_proj(node)));
664                 } else if (be_is_MemPerm(pred)) {
665                         return find_original_value(get_irn_n(pred, get_Proj_proj(node) + 1));
666                 } else if (is_ia32_Load(pred)) {
667                         return find_original_value(get_irn_n(pred, n_ia32_Load_mem));
668                 } else {
669                         return node;
670                 }
671         } else if (is_ia32_Store(node)) {
672                 return find_original_value(get_irn_n(node, n_ia32_Store_val));
673         } else if (is_Phi(node)) {
674                 int i, arity;
675                 arity = get_irn_arity(node);
676                 for (i = 0; i < arity; ++i) {
677                         ir_node *in  = get_irn_n(node, i);
678                         ir_node *res = find_original_value(in);
679
680                         if (res != NULL)
681                                 return res;
682                 }
683                 return NULL;
684         } else {
685                 return node;
686         }
687 }
688
689 static int determine_final_pnc(const ir_node *node, int flags_pos,
690                                int pnc)
691 {
692         ir_node           *flags = get_irn_n(node, flags_pos);
693         const ia32_attr_t *flags_attr;
694         flags = skip_Proj(flags);
695
696         if (is_ia32_Sahf(flags)) {
697                 ir_node *cmp = get_irn_n(flags, n_ia32_Sahf_val);
698                 if (!(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
699                                 || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp))) {
700                         inc_irg_visited(current_ir_graph);
701                         cmp = find_original_value(cmp);
702                         assert(cmp != NULL);
703                         assert(is_ia32_FucomFnstsw(cmp) || is_ia32_FucompFnstsw(cmp)
704                                || is_ia32_FucomppFnstsw(cmp) || is_ia32_FtstFnstsw(cmp));
705                 }
706
707                 flags_attr = get_ia32_attr_const(cmp);
708                 if (flags_attr->data.ins_permuted)
709                         pnc = get_mirrored_pnc(pnc);
710                 pnc |= ia32_pn_Cmp_float;
711         } else if (is_ia32_Ucomi(flags) || is_ia32_Fucomi(flags)
712                         || is_ia32_Fucompi(flags)) {
713                 flags_attr = get_ia32_attr_const(flags);
714
715                 if (flags_attr->data.ins_permuted)
716                         pnc = get_mirrored_pnc(pnc);
717                 pnc |= ia32_pn_Cmp_float;
718         } else {
719                 flags_attr = get_ia32_attr_const(flags);
720
721                 if (flags_attr->data.ins_permuted)
722                         pnc = get_mirrored_pnc(pnc);
723                 if (flags_attr->data.cmp_unsigned)
724                         pnc |= ia32_pn_Cmp_unsigned;
725         }
726
727         return pnc;
728 }
729
730 static void ia32_emit_cmp_suffix(int pnc)
731 {
732         const char        *str;
733
734         if ((pnc & ia32_pn_Cmp_float) || (pnc & ia32_pn_Cmp_unsigned)) {
735                 pnc = pnc & 7;
736                 assert(cmp2condition_u[pnc].num == pnc);
737                 str = cmp2condition_u[pnc].name;
738         } else {
739                 pnc = pnc & 7;
740                 assert(cmp2condition_s[pnc].num == pnc);
741                 str = cmp2condition_s[pnc].name;
742         }
743
744         be_emit_string(str);
745 }
746
747 void ia32_emit_cmp_suffix_node(const ir_node *node,
748                                int flags_pos)
749 {
750         const ia32_attr_t *attr = get_ia32_attr_const(node);
751
752         pn_Cmp pnc = get_ia32_condcode(node);
753
754         pnc = determine_final_pnc(node, flags_pos, pnc);
755         if (attr->data.ins_permuted) {
756                 if (pnc & ia32_pn_Cmp_float) {
757                         pnc = get_negated_pnc(pnc, mode_F);
758                 } else {
759                         pnc = get_negated_pnc(pnc, mode_Iu);
760                 }
761         }
762
763         ia32_emit_cmp_suffix(pnc);
764 }
765
766 /**
767  * Returns the target block for a control flow node.
768  */
769 static ir_node *get_cfop_target_block(const ir_node *irn)
770 {
771         assert(get_irn_mode(irn) == mode_X);
772         return get_irn_link(irn);
773 }
774
775 /**
776  * Emits a block label for the given block.
777  */
778 static void ia32_emit_block_name(const ir_node *block)
779 {
780         if (has_Block_label(block)) {
781                 be_emit_string(be_gas_block_label_prefix());
782                 be_emit_irprintf("%lu", get_Block_label(block));
783         } else {
784                 be_emit_cstring(BLOCK_PREFIX);
785                 be_emit_irprintf("%ld", get_irn_node_nr(block));
786         }
787 }
788
789 /**
790  * Emits an exception label for a given node.
791  */
792 static void ia32_emit_exc_label(const ir_node *node)
793 {
794         be_emit_string(be_gas_insn_label_prefix());
795         be_emit_irprintf("%lu", get_ia32_exc_label_id(node));
796 }
797
798 /**
799  * Emits the target label for a control flow node.
800  */
801 static void ia32_emit_cfop_target(const ir_node *node)
802 {
803         ir_node *block = get_cfop_target_block(node);
804
805         ia32_emit_block_name(block);
806 }
807
808 /**
809  * Returns the Proj with projection number proj and NOT mode_M
810  */
811 static ir_node *get_proj(const ir_node *node, long proj)
812 {
813         const ir_edge_t *edge;
814         ir_node         *src;
815
816         assert(get_irn_mode(node) == mode_T && "expected mode_T node");
817
818         foreach_out_edge(node, edge) {
819                 src = get_edge_src_irn(edge);
820
821                 assert(is_Proj(src) && "Proj expected");
822                 if (get_irn_mode(src) == mode_M)
823                         continue;
824
825                 if (get_Proj_proj(src) == proj)
826                         return src;
827         }
828         return NULL;
829 }
830
831 static int can_be_fallthrough(const ir_node *node)
832 {
833         ir_node *target_block = get_cfop_target_block(node);
834         ir_node *block        = get_nodes_block(node);
835         return get_prev_block_sched(target_block) == block;
836 }
837
838 /**
839  * Emits the jump sequence for a conditional jump (cmp + jmp_true + jmp_false)
840  */
841 static void emit_ia32_Jcc(const ir_node *node)
842 {
843         int            need_parity_label = 0;
844         const ir_node *proj_true;
845         const ir_node *proj_false;
846         const ir_node *block;
847         pn_Cmp         pnc = get_ia32_condcode(node);
848
849         pnc = determine_final_pnc(node, 0, pnc);
850
851         /* get both Projs */
852         proj_true = get_proj(node, pn_ia32_Jcc_true);
853         assert(proj_true && "Jcc without true Proj");
854
855         proj_false = get_proj(node, pn_ia32_Jcc_false);
856         assert(proj_false && "Jcc without false Proj");
857
858         block      = get_nodes_block(node);
859
860         if (can_be_fallthrough(proj_true)) {
861                 /* exchange both proj's so the second one can be omitted */
862                 const ir_node *t = proj_true;
863
864                 proj_true  = proj_false;
865                 proj_false = t;
866                 if (pnc & ia32_pn_Cmp_float) {
867                         pnc = get_negated_pnc(pnc, mode_F);
868                 } else {
869                         pnc = get_negated_pnc(pnc, mode_Iu);
870                 }
871         }
872
873         if (pnc & ia32_pn_Cmp_float) {
874                 /* Some floating point comparisons require a test of the parity flag,
875                  * which indicates that the result is unordered */
876                 switch (pnc & 15) {
877                         case pn_Cmp_Uo: {
878                                 be_emit_cstring("\tjp ");
879                                 ia32_emit_cfop_target(proj_true);
880                                 be_emit_finish_line_gas(proj_true);
881                                 break;
882                         }
883
884                         case pn_Cmp_Leg:
885                                 be_emit_cstring("\tjnp ");
886                                 ia32_emit_cfop_target(proj_true);
887                                 be_emit_finish_line_gas(proj_true);
888                                 break;
889
890                         case pn_Cmp_Eq:
891                         case pn_Cmp_Lt:
892                         case pn_Cmp_Le:
893                                 /* we need a local label if the false proj is a fallthrough
894                                  * as the falseblock might have no label emitted then */
895                                 if (can_be_fallthrough(proj_false)) {
896                                         need_parity_label = 1;
897                                         be_emit_cstring("\tjp 1f");
898                                 } else {
899                                         be_emit_cstring("\tjp ");
900                                         ia32_emit_cfop_target(proj_false);
901                                 }
902                                 be_emit_finish_line_gas(proj_false);
903                                 goto emit_jcc;
904
905                         case pn_Cmp_Ug:
906                         case pn_Cmp_Uge:
907                         case pn_Cmp_Ne:
908                                 be_emit_cstring("\tjp ");
909                                 ia32_emit_cfop_target(proj_true);
910                                 be_emit_finish_line_gas(proj_true);
911                                 goto emit_jcc;
912
913                         default:
914                                 goto emit_jcc;
915                 }
916         } else {
917 emit_jcc:
918                 be_emit_cstring("\tj");
919                 ia32_emit_cmp_suffix(pnc);
920                 be_emit_char(' ');
921                 ia32_emit_cfop_target(proj_true);
922                 be_emit_finish_line_gas(proj_true);
923         }
924
925         if (need_parity_label) {
926                 be_emit_cstring("1:");
927                 be_emit_write_line();
928         }
929
930         /* the second Proj might be a fallthrough */
931         if (can_be_fallthrough(proj_false)) {
932                 be_emit_cstring("\t/* fallthrough to ");
933                 ia32_emit_cfop_target(proj_false);
934                 be_emit_cstring(" */");
935                 be_emit_finish_line_gas(proj_false);
936         } else {
937                 be_emit_cstring("\tjmp ");
938                 ia32_emit_cfop_target(proj_false);
939                 be_emit_finish_line_gas(proj_false);
940         }
941 }
942
943 static void emit_ia32_CMov(const ir_node *node)
944 {
945         const ia32_attr_t     *attr         = get_ia32_attr_const(node);
946         int                    ins_permuted = attr->data.ins_permuted;
947         const arch_register_t *out          = arch_get_irn_register(arch_env, node);
948         pn_Cmp                 pnc          = get_ia32_condcode(node);
949         const arch_register_t *in_true;
950         const arch_register_t *in_false;
951
952         pnc = determine_final_pnc(node, n_ia32_CMov_eflags, pnc);
953
954         in_true  = arch_get_irn_register(arch_env,
955                                          get_irn_n(node, n_ia32_CMov_val_true));
956         in_false = arch_get_irn_register(arch_env,
957                                          get_irn_n(node, n_ia32_CMov_val_false));
958
959         /* should be same constraint fullfilled? */
960         if (out == in_false) {
961                 /* yes -> nothing to do */
962         } else if (out == in_true) {
963                 const arch_register_t *tmp;
964
965                 assert(get_ia32_op_type(node) == ia32_Normal);
966
967                 ins_permuted = !ins_permuted;
968
969                 tmp      = in_true;
970                 in_true  = in_false;
971                 in_false = tmp;
972         } else {
973                 /* we need a mov */
974                 be_emit_cstring("\tmovl ");
975                 emit_register(in_false, NULL);
976                 be_emit_cstring(", ");
977                 emit_register(out, NULL);
978                 be_emit_finish_line_gas(node);
979         }
980
981         if (ins_permuted) {
982                 if (pnc & ia32_pn_Cmp_float) {
983                         pnc = get_negated_pnc(pnc, mode_F);
984                 } else {
985                         pnc = get_negated_pnc(pnc, mode_Iu);
986                 }
987         }
988
989         /* TODO: handling of Nans isn't correct yet */
990
991         be_emit_cstring("\tcmov");
992         ia32_emit_cmp_suffix(pnc);
993         be_emit_char(' ');
994         if (get_ia32_op_type(node) == ia32_AddrModeS) {
995                 ia32_emit_am(node);
996         } else {
997                 emit_register(in_true, get_ia32_ls_mode(node));
998         }
999         be_emit_cstring(", ");
1000         emit_register(out, get_ia32_ls_mode(node));
1001         be_emit_finish_line_gas(node);
1002 }
1003
1004 /*********************************************************
1005  *                 _ _       _
1006  *                (_) |     (_)
1007  *   ___ _ __ ___  _| |_     _ _   _ _ __ ___  _ __  ___
1008  *  / _ \ '_ ` _ \| | __|   | | | | | '_ ` _ \| '_ \/ __|
1009  * |  __/ | | | | | | |_    | | |_| | | | | | | |_) \__ \
1010  *  \___|_| |_| |_|_|\__|   | |\__,_|_| |_| |_| .__/|___/
1011  *                         _/ |               | |
1012  *                        |__/                |_|
1013  *********************************************************/
1014
1015 /* jump table entry (target and corresponding number) */
1016 typedef struct _branch_t {
1017         ir_node *target;
1018         int      value;
1019 } branch_t;
1020
1021 /* jump table for switch generation */
1022 typedef struct _jmp_tbl_t {
1023         ir_node  *defProj;         /**< default target */
1024         long      min_value;       /**< smallest switch case */
1025         long      max_value;       /**< largest switch case */
1026         long      num_branches;    /**< number of jumps */
1027         char     *label;           /**< label of the jump table */
1028         branch_t *branches;        /**< jump array */
1029 } jmp_tbl_t;
1030
1031 /**
1032  * Compare two variables of type branch_t. Used to sort all switch cases
1033  */
1034 static int ia32_cmp_branch_t(const void *a, const void *b)
1035 {
1036         branch_t *b1 = (branch_t *)a;
1037         branch_t *b2 = (branch_t *)b;
1038
1039         if (b1->value <= b2->value)
1040                 return -1;
1041         else
1042                 return 1;
1043 }
1044
1045 /**
1046  * Emits code for a SwitchJmp (creates a jump table if
1047  * possible otherwise a cmp-jmp cascade). Port from
1048  * cggg ia32 backend
1049  */
1050 static void emit_ia32_SwitchJmp(const ir_node *node)
1051 {
1052         unsigned long       interval;
1053         int                 last_value, i;
1054         long                pnc;
1055         long                default_pn;
1056         jmp_tbl_t           tbl;
1057         ir_node            *proj;
1058         const ir_edge_t    *edge;
1059
1060         /* fill the table structure */
1061         tbl.label        = XMALLOCN(char, SNPRINTF_BUF_LEN);
1062         tbl.label        = get_unique_label(tbl.label, SNPRINTF_BUF_LEN, ".TBL_");
1063         tbl.defProj      = NULL;
1064         tbl.num_branches = get_irn_n_edges(node) - 1;
1065         tbl.branches     = XMALLOCNZ(branch_t, tbl.num_branches);
1066         tbl.min_value    = INT_MAX;
1067         tbl.max_value    = INT_MIN;
1068
1069         default_pn = get_ia32_condcode(node);
1070         i = 0;
1071         /* go over all proj's and collect them */
1072         foreach_out_edge(node, edge) {
1073                 proj = get_edge_src_irn(edge);
1074                 assert(is_Proj(proj) && "Only proj allowed at SwitchJmp");
1075
1076                 pnc = get_Proj_proj(proj);
1077
1078                 /* check for default proj */
1079                 if (pnc == default_pn) {
1080                         assert(tbl.defProj == NULL && "found two default Projs at SwitchJmp");
1081                         tbl.defProj = proj;
1082                 } else {
1083                         tbl.min_value = pnc < tbl.min_value ? pnc : tbl.min_value;
1084                         tbl.max_value = pnc > tbl.max_value ? pnc : tbl.max_value;
1085
1086                         /* create branch entry */
1087                         tbl.branches[i].target = proj;
1088                         tbl.branches[i].value  = pnc;
1089                         ++i;
1090                 }
1091
1092         }
1093         assert(i == tbl.num_branches);
1094
1095         /* sort the branches by their number */
1096         qsort(tbl.branches, tbl.num_branches, sizeof(tbl.branches[0]), ia32_cmp_branch_t);
1097
1098         /* two-complement's magic make this work without overflow */
1099         interval = tbl.max_value - tbl.min_value;
1100
1101         /* emit the table */
1102         be_emit_cstring("\tcmpl $");
1103         be_emit_irprintf("%u, ", interval);
1104         ia32_emit_source_register(node, 0);
1105         be_emit_finish_line_gas(node);
1106
1107         be_emit_cstring("\tja ");
1108         ia32_emit_cfop_target(tbl.defProj);
1109         be_emit_finish_line_gas(node);
1110
1111         if (tbl.num_branches > 1) {
1112                 /* create table */
1113                 be_emit_cstring("\tjmp *");
1114                 be_emit_string(tbl.label);
1115                 be_emit_cstring("(,");
1116                 ia32_emit_source_register(node, 0);
1117                 be_emit_cstring(",4)");
1118                 be_emit_finish_line_gas(node);
1119
1120                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1121                 be_emit_cstring("\t.align 4\n");
1122                 be_emit_write_line();
1123
1124                 be_emit_string(tbl.label);
1125                 be_emit_cstring(":\n");
1126                 be_emit_write_line();
1127
1128                 be_emit_cstring(".long ");
1129                 ia32_emit_cfop_target(tbl.branches[0].target);
1130                 be_emit_finish_line_gas(NULL);
1131
1132                 last_value = tbl.branches[0].value;
1133                 for (i = 1; i < tbl.num_branches; ++i) {
1134                         while (++last_value < tbl.branches[i].value) {
1135                                 be_emit_cstring(".long ");
1136                                 ia32_emit_cfop_target(tbl.defProj);
1137                                 be_emit_finish_line_gas(NULL);
1138                         }
1139                         be_emit_cstring(".long ");
1140                         ia32_emit_cfop_target(tbl.branches[i].target);
1141                         be_emit_finish_line_gas(NULL);
1142                 }
1143                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1144         } else {
1145                 /* one jump is enough */
1146                 be_emit_cstring("\tjmp ");
1147                 ia32_emit_cfop_target(tbl.branches[0].target);
1148                 be_emit_finish_line_gas(node);
1149         }
1150
1151         if (tbl.label)
1152                 free(tbl.label);
1153         if (tbl.branches)
1154                 free(tbl.branches);
1155 }
1156
1157 /**
1158  * Emits code for a unconditional jump.
1159  */
1160 static void emit_Jmp(const ir_node *node)
1161 {
1162         ir_node *block;
1163
1164         /* for now, the code works for scheduled and non-schedules blocks */
1165         block = get_nodes_block(node);
1166
1167         /* we have a block schedule */
1168         if (can_be_fallthrough(node)) {
1169                 be_emit_cstring("\t/* fallthrough to ");
1170                 ia32_emit_cfop_target(node);
1171                 be_emit_cstring(" */");
1172         } else {
1173                 be_emit_cstring("\tjmp ");
1174                 ia32_emit_cfop_target(node);
1175         }
1176         be_emit_finish_line_gas(node);
1177 }
1178
1179 static void emit_ia32_Immediate(const ir_node *node)
1180 {
1181         const ia32_immediate_attr_t *attr = get_ia32_immediate_attr_const(node);
1182
1183         be_emit_char('$');
1184         if (attr->symconst != NULL) {
1185                 if (attr->sc_sign)
1186                         be_emit_char('-');
1187                 ia32_emit_entity(attr->symconst, 0);
1188         }
1189         if (attr->symconst == NULL || attr->offset != 0) {
1190                 if (attr->symconst != NULL) {
1191                         be_emit_irprintf("%+d", attr->offset);
1192                 } else {
1193                         be_emit_irprintf("0x%X", attr->offset);
1194                 }
1195         }
1196 }
1197
1198 /**
1199  * Emit an inline assembler operand.
1200  *
1201  * @param node  the ia32_ASM node
1202  * @param s     points to the operand (a %c)
1203  *
1204  * @return  pointer to the first char in s NOT in the current operand
1205  */
1206 static const char* emit_asm_operand(const ir_node *node, const char *s)
1207 {
1208         const ia32_attr_t     *ia32_attr = get_ia32_attr_const(node);
1209         const ia32_asm_attr_t *attr      = CONST_CAST_IA32_ATTR(ia32_asm_attr_t,
1210                                                             ia32_attr);
1211         const arch_register_t *reg;
1212         const ia32_asm_reg_t  *asm_regs = attr->register_map;
1213         const ia32_asm_reg_t  *asm_reg;
1214         const char            *reg_name;
1215         char                   c;
1216         char                   modifier = 0;
1217         int                    num      = -1;
1218         int                    p;
1219
1220         assert(*s == '%');
1221         c = *(++s);
1222
1223         /* parse modifiers */
1224         switch(c) {
1225         case 0:
1226                 ir_fprintf(stderr, "Warning: asm text (%+F) ends with %\n", node);
1227                 be_emit_char('%');
1228                 return s + 1;
1229         case '%':
1230                 be_emit_char('%');
1231                 return s + 1;
1232         case 'w':
1233         case 'b':
1234         case 'h':
1235                 modifier = c;
1236                 ++s;
1237                 break;
1238         case '0':
1239         case '1':
1240         case '2':
1241         case '3':
1242         case '4':
1243         case '5':
1244         case '6':
1245         case '7':
1246         case '8':
1247         case '9':
1248                 break;
1249         default:
1250                 ir_fprintf(stderr, "Warning: asm text (%+F) contains unknown modifier "
1251                            "'%c' for asm op\n", node, c);
1252                 ++s;
1253                 break;
1254         }
1255
1256         /* parse number */
1257         sscanf(s, "%d%n", &num, &p);
1258         if (num < 0) {
1259                 ir_fprintf(stderr, "Warning: Couldn't parse assembler operand (%+F)\n",
1260                            node);
1261                 return s;
1262         } else {
1263                 s += p;
1264         }
1265
1266         if (num < 0 || num >= ARR_LEN(asm_regs)) {
1267                 ir_fprintf(stderr, "Error: Custom assembler references invalid "
1268                            "input/output (%+F)\n", node);
1269                 return s;
1270         }
1271         asm_reg = & asm_regs[num];
1272         assert(asm_reg->valid);
1273
1274         /* get register */
1275         if (asm_reg->use_input == 0) {
1276                 reg = get_out_reg(node, asm_reg->inout_pos);
1277         } else {
1278                 ir_node *pred = get_irn_n(node, asm_reg->inout_pos);
1279
1280                 /* might be an immediate value */
1281                 if (is_ia32_Immediate(pred)) {
1282                         emit_ia32_Immediate(pred);
1283                         return s;
1284                 }
1285                 reg = get_in_reg(node, asm_reg->inout_pos);
1286         }
1287         if (reg == NULL) {
1288                 ir_fprintf(stderr, "Warning: no register assigned for %d asm op "
1289                            "(%+F)\n", num, node);
1290                 return s;
1291         }
1292
1293         if (asm_reg->memory) {
1294                 be_emit_char('(');
1295         }
1296
1297         /* emit it */
1298         if (modifier != 0) {
1299                 be_emit_char('%');
1300                 switch(modifier) {
1301                 case 'b':
1302                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit, reg);
1303                         break;
1304                 case 'h':
1305                         reg_name = ia32_get_mapped_reg_name(isa->regs_8bit_high, reg);
1306                         break;
1307                 case 'w':
1308                         reg_name = ia32_get_mapped_reg_name(isa->regs_16bit, reg);
1309                         break;
1310                 default:
1311                         panic("Invalid asm op modifier");
1312                 }
1313                 be_emit_string(reg_name);
1314         } else {
1315                 emit_register(reg, asm_reg->mode);
1316         }
1317
1318         if (asm_reg->memory) {
1319                 be_emit_char(')');
1320         }
1321
1322         return s;
1323 }
1324
1325 /**
1326  * Emits code for an ASM pseudo op.
1327  */
1328 static void emit_ia32_Asm(const ir_node *node)
1329 {
1330         const void            *gen_attr = get_irn_generic_attr_const(node);
1331         const ia32_asm_attr_t *attr
1332                 = CONST_CAST_IA32_ATTR(ia32_asm_attr_t, gen_attr);
1333         ident                 *asm_text = attr->asm_text;
1334         const char            *s        = get_id_str(asm_text);
1335
1336         be_emit_cstring("#APP\t");
1337         be_emit_finish_line_gas(node);
1338
1339         if (s[0] != '\t')
1340                 be_emit_char('\t');
1341
1342         while(*s != 0) {
1343                 if (*s == '%') {
1344                         s = emit_asm_operand(node, s);
1345                 } else {
1346                         be_emit_char(*s++);
1347                 }
1348         }
1349
1350         be_emit_char('\n');
1351         be_emit_write_line();
1352
1353         be_emit_cstring("#NO_APP\n");
1354         be_emit_write_line();
1355 }
1356
1357 /**********************************
1358  *   _____                  ____
1359  *  / ____|                |  _ \
1360  * | |     ___  _ __  _   _| |_) |
1361  * | |    / _ \| '_ \| | | |  _ <
1362  * | |___| (_) | |_) | |_| | |_) |
1363  *  \_____\___/| .__/ \__, |____/
1364  *             | |     __/ |
1365  *             |_|    |___/
1366  **********************************/
1367
1368 /**
1369  * Emit movsb/w instructions to make mov count divideable by 4
1370  */
1371 static void emit_CopyB_prolog(unsigned size)
1372 {
1373         be_emit_cstring("\tcld");
1374         be_emit_finish_line_gas(NULL);
1375
1376         if (size & 1) {
1377                 be_emit_cstring("\tmovsb");
1378                 be_emit_finish_line_gas(NULL);
1379         }
1380         if (size & 2) {
1381                 be_emit_cstring("\tmovsw");
1382                 be_emit_finish_line_gas(NULL);
1383         }
1384 }
1385
1386 /**
1387  * Emit rep movsd instruction for memcopy.
1388  */
1389 static void emit_ia32_CopyB(const ir_node *node)
1390 {
1391         unsigned size = get_ia32_copyb_size(node);
1392
1393         emit_CopyB_prolog(size);
1394
1395         be_emit_cstring("\trep movsd");
1396         be_emit_finish_line_gas(node);
1397 }
1398
1399 /**
1400  * Emits unrolled memcopy.
1401  */
1402 static void emit_ia32_CopyB_i(const ir_node *node)
1403 {
1404         unsigned size = get_ia32_copyb_size(node);
1405
1406         emit_CopyB_prolog(size);
1407
1408         size >>= 2;
1409         while (size--) {
1410                 be_emit_cstring("\tmovsd");
1411                 be_emit_finish_line_gas(NULL);
1412         }
1413 }
1414
1415
1416
1417 /***************************
1418  *   _____
1419  *  / ____|
1420  * | |     ___  _ ____   __
1421  * | |    / _ \| '_ \ \ / /
1422  * | |___| (_) | | | \ V /
1423  *  \_____\___/|_| |_|\_/
1424  *
1425  ***************************/
1426
1427 /**
1428  * Emit code for conversions (I, FP), (FP, I) and (FP, FP).
1429  */
1430 static void emit_ia32_Conv_with_FP(const ir_node *node)
1431 {
1432         ir_mode            *ls_mode = get_ia32_ls_mode(node);
1433         int                 ls_bits = get_mode_size_bits(ls_mode);
1434
1435         be_emit_cstring("\tcvt");
1436
1437         if (is_ia32_Conv_I2FP(node)) {
1438                 if (ls_bits == 32) {
1439                         be_emit_cstring("si2ss");
1440                 } else {
1441                         be_emit_cstring("si2sd");
1442                 }
1443         } else if (is_ia32_Conv_FP2I(node)) {
1444                 if (ls_bits == 32) {
1445                         be_emit_cstring("ss2si");
1446                 } else {
1447                         be_emit_cstring("sd2si");
1448                 }
1449         } else {
1450                 assert(is_ia32_Conv_FP2FP(node));
1451                 if (ls_bits == 32) {
1452                         be_emit_cstring("sd2ss");
1453                 } else {
1454                         be_emit_cstring("ss2sd");
1455                 }
1456         }
1457         be_emit_char(' ');
1458
1459         switch(get_ia32_op_type(node)) {
1460                 case ia32_Normal:
1461                         ia32_emit_source_register(node, n_ia32_unary_op);
1462                         break;
1463                 case ia32_AddrModeS:
1464                         ia32_emit_am(node);
1465                         break;
1466                 default:
1467                         assert(0 && "unsupported op type for Conv");
1468         }
1469         be_emit_cstring(", ");
1470         ia32_emit_dest_register(node, 0);
1471         be_emit_finish_line_gas(node);
1472 }
1473
1474 static void emit_ia32_Conv_I2FP(const ir_node *node)
1475 {
1476         emit_ia32_Conv_with_FP(node);
1477 }
1478
1479 static void emit_ia32_Conv_FP2I(const ir_node *node)
1480 {
1481         emit_ia32_Conv_with_FP(node);
1482 }
1483
1484 static void emit_ia32_Conv_FP2FP(const ir_node *node)
1485 {
1486         emit_ia32_Conv_with_FP(node);
1487 }
1488
1489 /**
1490  * Emits code for an Int conversion.
1491  */
1492 static void emit_ia32_Conv_I2I(const ir_node *node)
1493 {
1494         const char            *sign_suffix;
1495         ir_mode               *smaller_mode = get_ia32_ls_mode(node);
1496         int                    smaller_bits = get_mode_size_bits(smaller_mode);
1497         int                    signed_mode;
1498         const arch_register_t *in_reg, *out_reg;
1499
1500         assert(!mode_is_float(smaller_mode));
1501         assert(smaller_bits == 8 || smaller_bits == 16);
1502
1503         signed_mode = mode_is_signed(smaller_mode);
1504         sign_suffix = signed_mode ? "s" : "z";
1505
1506         out_reg = get_out_reg(node, 0);
1507
1508         switch(get_ia32_op_type(node)) {
1509                 case ia32_Normal:
1510                         in_reg  = get_in_reg(node, n_ia32_unary_op);
1511
1512                         if (in_reg  == &ia32_gp_regs[REG_EAX] &&
1513                                 out_reg == &ia32_gp_regs[REG_EAX] &&
1514                                 signed_mode &&
1515                                 smaller_bits == 16)
1516                         {
1517                                 /* argument and result are both in EAX and */
1518                                 /* signedness is ok: -> use the smaller cwtl opcode */
1519                                 be_emit_cstring("\tcwtl");
1520                         } else {
1521                                 be_emit_cstring("\tmov");
1522                                 be_emit_string(sign_suffix);
1523                                 ia32_emit_mode_suffix_mode(smaller_mode);
1524                                 be_emit_cstring("l ");
1525                                 emit_register(in_reg, smaller_mode);
1526                                 be_emit_cstring(", ");
1527                                 emit_register(out_reg, NULL);
1528                         }
1529                         break;
1530                 case ia32_AddrModeS: {
1531                         be_emit_cstring("\tmov");
1532                         be_emit_string(sign_suffix);
1533                         ia32_emit_mode_suffix_mode(smaller_mode);
1534                         be_emit_cstring("l ");
1535                         ia32_emit_am(node);
1536                         be_emit_cstring(", ");
1537                         emit_register(out_reg, NULL);
1538                         break;
1539                 }
1540                 default:
1541                         panic("unsupported op type for Conv");
1542         }
1543         be_emit_finish_line_gas(node);
1544 }
1545
1546
1547 /*******************************************
1548  *  _                          _
1549  * | |                        | |
1550  * | |__   ___ _ __   ___   __| | ___  ___
1551  * | '_ \ / _ \ '_ \ / _ \ / _` |/ _ \/ __|
1552  * | |_) |  __/ | | | (_) | (_| |  __/\__ \
1553  * |_.__/ \___|_| |_|\___/ \__,_|\___||___/
1554  *
1555  *******************************************/
1556
1557 /**
1558  * Emits a backend call
1559  */
1560 static void emit_be_Call(const ir_node *node)
1561 {
1562         ir_entity *ent = be_Call_get_entity(node);
1563
1564         be_emit_cstring("\tcall ");
1565         if (ent) {
1566                 ia32_emit_entity(ent, 1);
1567         } else {
1568                 const arch_register_t *reg = get_in_reg(node, be_pos_Call_ptr);
1569                 be_emit_char('*');
1570                 emit_register(reg, NULL);
1571         }
1572         be_emit_finish_line_gas(node);
1573 }
1574
1575 /**
1576  * Emits code to increase stack pointer.
1577  */
1578 static void emit_be_IncSP(const ir_node *node)
1579 {
1580         int                    offs = be_get_IncSP_offset(node);
1581         const arch_register_t *reg  = arch_get_irn_register(arch_env, node);
1582
1583         if (offs == 0)
1584                 return;
1585
1586         if (offs > 0) {
1587                 be_emit_cstring("\tsubl $");
1588                 be_emit_irprintf("%u, ", offs);
1589                 emit_register(reg, NULL);
1590         } else {
1591                 be_emit_cstring("\taddl $");
1592                 be_emit_irprintf("%u, ", -offs);
1593                 emit_register(reg, NULL);
1594         }
1595         be_emit_finish_line_gas(node);
1596 }
1597
1598 /**
1599  * Emits code for Copy/CopyKeep.
1600  */
1601 static void Copy_emitter(const ir_node *node, const ir_node *op)
1602 {
1603         const arch_register_t *in  = arch_get_irn_register(arch_env, op);
1604         const arch_register_t *out = arch_get_irn_register(arch_env, node);
1605         ir_mode               *mode;
1606
1607         if (in == out) {
1608                 return;
1609         }
1610         if (is_unknown_reg(in))
1611                 return;
1612         /* copies of vf nodes aren't real... */
1613         if (arch_register_get_class(in) == &ia32_reg_classes[CLASS_ia32_vfp])
1614                 return;
1615
1616         mode = get_irn_mode(node);
1617         if (mode == mode_E) {
1618                 be_emit_cstring("\tmovsd ");
1619                 emit_register(in, NULL);
1620                 be_emit_cstring(", ");
1621                 emit_register(out, NULL);
1622         } else {
1623                 be_emit_cstring("\tmovl ");
1624                 emit_register(in, NULL);
1625                 be_emit_cstring(", ");
1626                 emit_register(out, NULL);
1627         }
1628         be_emit_finish_line_gas(node);
1629 }
1630
1631 static void emit_be_Copy(const ir_node *node)
1632 {
1633         Copy_emitter(node, be_get_Copy_op(node));
1634 }
1635
1636 static void emit_be_CopyKeep(const ir_node *node)
1637 {
1638         Copy_emitter(node, be_get_CopyKeep_op(node));
1639 }
1640
1641 /**
1642  * Emits code for exchange.
1643  */
1644 static void emit_be_Perm(const ir_node *node)
1645 {
1646         const arch_register_t *in0, *in1;
1647         const arch_register_class_t *cls0, *cls1;
1648
1649         in0 = arch_get_irn_register(arch_env, get_irn_n(node, 0));
1650         in1 = arch_get_irn_register(arch_env, get_irn_n(node, 1));
1651
1652         cls0 = arch_register_get_class(in0);
1653         cls1 = arch_register_get_class(in1);
1654
1655         assert(cls0 == cls1 && "Register class mismatch at Perm");
1656
1657         if (cls0 == &ia32_reg_classes[CLASS_ia32_gp]) {
1658                 be_emit_cstring("\txchg ");
1659                 emit_register(in1, NULL);
1660                 be_emit_cstring(", ");
1661                 emit_register(in0, NULL);
1662                 be_emit_finish_line_gas(node);
1663         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_xmm]) {
1664                 be_emit_cstring("\txorpd ");
1665                 emit_register(in1, NULL);
1666                 be_emit_cstring(", ");
1667                 emit_register(in0, NULL);
1668                 be_emit_finish_line_gas(NULL);
1669
1670                 be_emit_cstring("\txorpd ");
1671                 emit_register(in0, NULL);
1672                 be_emit_cstring(", ");
1673                 emit_register(in1, NULL);
1674                 be_emit_finish_line_gas(NULL);
1675
1676                 be_emit_cstring("\txorpd ");
1677                 emit_register(in1, NULL);
1678                 be_emit_cstring(", ");
1679                 emit_register(in0, NULL);
1680                 be_emit_finish_line_gas(node);
1681         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_vfp]) {
1682                 /* is a NOP */
1683         } else if (cls0 == &ia32_reg_classes[CLASS_ia32_st]) {
1684                 /* is a NOP */
1685         } else {
1686                 panic("unexpected register class in be_Perm (%+F)", node);
1687         }
1688 }
1689
1690 /**
1691  * Emits code for Constant loading.
1692  */
1693 static void emit_ia32_Const(const ir_node *node)
1694 {
1695         be_emit_cstring("\tmovl ");
1696         emit_ia32_Immediate(node);
1697         be_emit_cstring(", ");
1698         ia32_emit_dest_register(node, 0);
1699
1700         be_emit_finish_line_gas(node);
1701 }
1702
1703 /**
1704  * Emits code to load the TLS base
1705  */
1706 static void emit_ia32_LdTls(const ir_node *node)
1707 {
1708         be_emit_cstring("\tmovl %gs:0, ");
1709         ia32_emit_dest_register(node, 0);
1710         be_emit_finish_line_gas(node);
1711 }
1712
1713 /* helper function for emit_ia32_Minus64Bit */
1714 static void emit_mov(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1715 {
1716         be_emit_cstring("\tmovl ");
1717         emit_register(src, NULL);
1718         be_emit_cstring(", ");
1719         emit_register(dst, NULL);
1720         be_emit_finish_line_gas(node);
1721 }
1722
1723 /* helper function for emit_ia32_Minus64Bit */
1724 static void emit_neg(const ir_node* node, const arch_register_t *reg)
1725 {
1726         be_emit_cstring("\tnegl ");
1727         emit_register(reg, NULL);
1728         be_emit_finish_line_gas(node);
1729 }
1730
1731 /* helper function for emit_ia32_Minus64Bit */
1732 static void emit_sbb0(const ir_node* node, const arch_register_t *reg)
1733 {
1734         be_emit_cstring("\tsbbl $0, ");
1735         emit_register(reg, NULL);
1736         be_emit_finish_line_gas(node);
1737 }
1738
1739 /* helper function for emit_ia32_Minus64Bit */
1740 static void emit_sbb(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1741 {
1742         be_emit_cstring("\tsbbl ");
1743         emit_register(src, NULL);
1744         be_emit_cstring(", ");
1745         emit_register(dst, NULL);
1746         be_emit_finish_line_gas(node);
1747 }
1748
1749 /* helper function for emit_ia32_Minus64Bit */
1750 static void emit_xchg(const ir_node* node, const arch_register_t *src, const arch_register_t *dst)
1751 {
1752         be_emit_cstring("\txchgl ");
1753         emit_register(src, NULL);
1754         be_emit_cstring(", ");
1755         emit_register(dst, NULL);
1756         be_emit_finish_line_gas(node);
1757 }
1758
1759 /* helper function for emit_ia32_Minus64Bit */
1760 static void emit_zero(const ir_node* node, const arch_register_t *reg)
1761 {
1762         be_emit_cstring("\txorl ");
1763         emit_register(reg, NULL);
1764         be_emit_cstring(", ");
1765         emit_register(reg, NULL);
1766         be_emit_finish_line_gas(node);
1767 }
1768
1769 static void emit_ia32_Minus64Bit(const ir_node *node)
1770 {
1771         const arch_register_t *in_lo  = get_in_reg(node, 0);
1772         const arch_register_t *in_hi  = get_in_reg(node, 1);
1773         const arch_register_t *out_lo = get_out_reg(node, 0);
1774         const arch_register_t *out_hi = get_out_reg(node, 1);
1775
1776         if (out_lo == in_lo) {
1777                 if (out_hi != in_hi) {
1778                         /* a -> a, b -> d */
1779                         goto zero_neg;
1780                 } else {
1781                         /* a -> a, b -> b */
1782                         goto normal_neg;
1783                 }
1784         } else if (out_lo == in_hi) {
1785                 if (out_hi == in_lo) {
1786                         /* a -> b, b -> a */
1787                         emit_xchg(node, in_lo, in_hi);
1788                         goto normal_neg;
1789                 } else {
1790                         /* a -> b, b -> d */
1791                         emit_mov(node, in_hi, out_hi);
1792                         emit_mov(node, in_lo, out_lo);
1793                         goto normal_neg;
1794                 }
1795         } else {
1796                 if (out_hi == in_lo) {
1797                         /* a -> c, b -> a */
1798                         emit_mov(node, in_lo, out_lo);
1799                         goto zero_neg;
1800                 } else if (out_hi == in_hi) {
1801                         /* a -> c, b -> b */
1802                         emit_mov(node, in_lo, out_lo);
1803                         goto normal_neg;
1804                 } else {
1805                         /* a -> c, b -> d */
1806                         emit_mov(node, in_lo, out_lo);
1807                         goto zero_neg;
1808                 }
1809         }
1810
1811 normal_neg:
1812         emit_neg( node, out_hi);
1813         emit_neg( node, out_lo);
1814         emit_sbb0(node, out_hi);
1815         return;
1816
1817 zero_neg:
1818         emit_zero(node, out_hi);
1819         emit_neg( node, out_lo);
1820         emit_sbb( node, in_hi, out_hi);
1821 }
1822
1823 static void emit_ia32_GetEIP(const ir_node *node)
1824 {
1825         be_emit_cstring("\tcall ");
1826         be_emit_string(pic_base_label);
1827         be_emit_finish_line_gas(node);
1828
1829         be_emit_string(pic_base_label);
1830         be_emit_cstring(":\n");
1831         be_emit_write_line();
1832
1833         be_emit_cstring("\tpopl ");
1834         ia32_emit_dest_register(node, 0);
1835         be_emit_char('\n');
1836         be_emit_write_line();
1837 }
1838
1839 static void emit_be_Return(const ir_node *node)
1840 {
1841         unsigned pop;
1842         be_emit_cstring("\tret");
1843
1844         pop = be_Return_get_pop(node);
1845         if (pop > 0 || be_Return_get_emit_pop(node)) {
1846                 be_emit_irprintf(" $%d", pop);
1847         }
1848         be_emit_finish_line_gas(node);
1849 }
1850
1851 static void emit_Nothing(const ir_node *node)
1852 {
1853         (void) node;
1854 }
1855
1856
1857 /***********************************************************************************
1858  *                  _          __                                             _
1859  *                 (_)        / _|                                           | |
1860  *  _ __ ___   __ _ _ _ __   | |_ _ __ __ _ _ __ ___   _____      _____  _ __| | __
1861  * | '_ ` _ \ / _` | | '_ \  |  _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ /
1862  * | | | | | | (_| | | | | | | | | | | (_| | | | | | |  __/\ V  V / (_) | |  |   <
1863  * |_| |_| |_|\__,_|_|_| |_| |_| |_|  \__,_|_| |_| |_|\___| \_/\_/ \___/|_|  |_|\_\
1864  *
1865  ***********************************************************************************/
1866
1867 /**
1868  * Enters the emitter functions for handled nodes into the generic
1869  * pointer of an opcode.
1870  */
1871 static void ia32_register_emitters(void)
1872 {
1873 #define IA32_EMIT2(a,b) op_ia32_##a->ops.generic = (op_func)emit_ia32_##b
1874 #define IA32_EMIT(a)    IA32_EMIT2(a,a)
1875 #define EMIT(a)         op_##a->ops.generic = (op_func)emit_##a
1876 #define IGN(a)                  op_##a->ops.generic = (op_func)emit_Nothing
1877 #define BE_EMIT(a)      op_be_##a->ops.generic = (op_func)emit_be_##a
1878 #define BE_IGN(a)               op_be_##a->ops.generic = (op_func)emit_Nothing
1879
1880         /* first clear the generic function pointer for all ops */
1881         clear_irp_opcodes_generic_func();
1882
1883         /* register all emitter functions defined in spec */
1884         ia32_register_spec_emitters();
1885
1886         /* other ia32 emitter functions */
1887         IA32_EMIT(Asm);
1888         IA32_EMIT(CMov);
1889         IA32_EMIT(IMul);
1890         IA32_EMIT(SwitchJmp);
1891         IA32_EMIT(CopyB);
1892         IA32_EMIT(CopyB_i);
1893         IA32_EMIT(Conv_I2FP);
1894         IA32_EMIT(Conv_FP2I);
1895         IA32_EMIT(Conv_FP2FP);
1896         IA32_EMIT(Conv_I2I);
1897         IA32_EMIT2(Conv_I2I8Bit, Conv_I2I);
1898         IA32_EMIT(Const);
1899         IA32_EMIT(LdTls);
1900         IA32_EMIT(Minus64Bit);
1901         IA32_EMIT(Jcc);
1902         IA32_EMIT(GetEIP);
1903
1904         /* benode emitter */
1905         BE_EMIT(Call);
1906         BE_EMIT(IncSP);
1907         BE_EMIT(Copy);
1908         BE_EMIT(CopyKeep);
1909         BE_EMIT(Perm);
1910         BE_EMIT(Return);
1911
1912         BE_IGN(RegParams);
1913         BE_IGN(Barrier);
1914         BE_IGN(Keep);
1915
1916         /* firm emitter */
1917         EMIT(Jmp);
1918         IGN(Proj);
1919         IGN(Phi);
1920         IGN(Start);
1921
1922 #undef BE_EMIT
1923 #undef EMIT
1924 #undef IGN
1925 #undef IA32_EMIT2
1926 #undef IA32_EMIT
1927 }
1928
1929 typedef void (*emit_func_ptr) (const ir_node *);
1930
1931 /**
1932  * Emits code for a node.
1933  */
1934 static void ia32_emit_node(ir_node *node)
1935 {
1936         ir_op *op = get_irn_op(node);
1937
1938         DBG((dbg, LEVEL_1, "emitting code for %+F\n", node));
1939
1940         if (is_ia32_irn(node)) {
1941                 if (get_ia32_exc_label(node)) {
1942                         /* emit the exception label of this instruction */
1943                         ia32_assign_exc_label(node);
1944                 }
1945                 if (mark_spill_reload) {
1946                         if (is_ia32_is_spill(node)) {
1947                                 be_emit_cstring("\txchg %ebx, %ebx        /* spill mark */\n");
1948                                 be_emit_write_line();
1949                         }
1950                         if (is_ia32_is_reload(node)) {
1951                                 be_emit_cstring("\txchg %edx, %edx        /* reload mark */\n");
1952                                 be_emit_write_line();
1953                         }
1954                         if (is_ia32_is_remat(node)) {
1955                                 be_emit_cstring("\txchg %ecx, %ecx        /* remat mark */\n");
1956                                 be_emit_write_line();
1957                         }
1958                 }
1959         }
1960         if (op->ops.generic) {
1961                 emit_func_ptr func = (emit_func_ptr) op->ops.generic;
1962
1963                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
1964
1965                 (*func) (node);
1966         } else {
1967                 emit_Nothing(node);
1968                 ir_fprintf(stderr, "Error: No emit handler for node %+F (%+G, graph %+F)\n", node, node, current_ir_graph);
1969                 abort();
1970         }
1971 }
1972
1973 /**
1974  * Emits gas alignment directives
1975  */
1976 static void ia32_emit_alignment(unsigned align, unsigned skip)
1977 {
1978         be_emit_cstring("\t.p2align ");
1979         be_emit_irprintf("%u,,%u\n", align, skip);
1980         be_emit_write_line();
1981 }
1982
1983 /**
1984  * Emits gas alignment directives for Labels depended on cpu architecture.
1985  */
1986 static void ia32_emit_align_label(void)
1987 {
1988         unsigned align        = ia32_cg_config.label_alignment;
1989         unsigned maximum_skip = ia32_cg_config.label_alignment_max_skip;
1990         ia32_emit_alignment(align, maximum_skip);
1991 }
1992
1993 /**
1994  * Test whether a block should be aligned.
1995  * For cpus in the P4/Athlon class it is useful to align jump labels to
1996  * 16 bytes. However we should only do that if the alignment nops before the
1997  * label aren't executed more often than we have jumps to the label.
1998  */
1999 static int should_align_block(const ir_node *block)
2000 {
2001         static const double DELTA = .0001;
2002         ir_exec_freq *exec_freq   = cg->birg->exec_freq;
2003         ir_node      *prev        = get_prev_block_sched(block);
2004         double        block_freq;
2005         double        prev_freq = 0;  /**< execfreq of the fallthrough block */
2006         double        jmp_freq  = 0;  /**< execfreq of all non-fallthrough blocks */
2007         int           i, n_cfgpreds;
2008
2009         if (exec_freq == NULL)
2010                 return 0;
2011         if (ia32_cg_config.label_alignment_factor <= 0)
2012                 return 0;
2013
2014         block_freq = get_block_execfreq(exec_freq, block);
2015         if (block_freq < DELTA)
2016                 return 0;
2017
2018         n_cfgpreds = get_Block_n_cfgpreds(block);
2019         for(i = 0; i < n_cfgpreds; ++i) {
2020                 const ir_node *pred      = get_Block_cfgpred_block(block, i);
2021                 double         pred_freq = get_block_execfreq(exec_freq, pred);
2022
2023                 if (pred == prev) {
2024                         prev_freq += pred_freq;
2025                 } else {
2026                         jmp_freq  += pred_freq;
2027                 }
2028         }
2029
2030         if (prev_freq < DELTA && !(jmp_freq < DELTA))
2031                 return 1;
2032
2033         jmp_freq /= prev_freq;
2034
2035         return jmp_freq > ia32_cg_config.label_alignment_factor;
2036 }
2037
2038 /**
2039  * Emit the block header for a block.
2040  *
2041  * @param block       the block
2042  * @param prev_block  the previous block
2043  */
2044 static void ia32_emit_block_header(ir_node *block)
2045 {
2046         ir_graph     *irg = current_ir_graph;
2047         int           need_label = block_needs_label(block);
2048         int           i, arity;
2049         ir_exec_freq *exec_freq = cg->birg->exec_freq;
2050
2051         if (block == get_irg_end_block(irg) || block == get_irg_start_block(irg))
2052                 return;
2053
2054         if (ia32_cg_config.label_alignment > 0) {
2055                 /* align the current block if:
2056                  * a) if should be aligned due to its execution frequency
2057                  * b) there is no fall-through here
2058                  */
2059                 if (should_align_block(block)) {
2060                         ia32_emit_align_label();
2061                 } else {
2062                         /* if the predecessor block has no fall-through,
2063                            we can always align the label. */
2064                         int i;
2065                         int has_fallthrough = 0;
2066
2067                         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
2068                                 ir_node *cfg_pred = get_Block_cfgpred(block, i);
2069                                 if (can_be_fallthrough(cfg_pred)) {
2070                                         has_fallthrough = 1;
2071                                         break;
2072                                 }
2073                         }
2074
2075                         if (!has_fallthrough)
2076                                 ia32_emit_align_label();
2077                 }
2078         }
2079
2080         if (need_label || has_Block_label(block)) {
2081                 ia32_emit_block_name(block);
2082                 be_emit_char(':');
2083
2084                 be_emit_pad_comment();
2085                 be_emit_cstring("   /* ");
2086         } else {
2087                 be_emit_cstring("\t/* ");
2088                 ia32_emit_block_name(block);
2089                 be_emit_cstring(": ");
2090         }
2091
2092         be_emit_cstring("preds:");
2093
2094         /* emit list of pred blocks in comment */
2095         arity = get_irn_arity(block);
2096         for (i = 0; i < arity; ++i) {
2097                 ir_node *predblock = get_Block_cfgpred_block(block, i);
2098                 be_emit_irprintf(" %d", get_irn_node_nr(predblock));
2099         }
2100         if (exec_freq != NULL) {
2101                 be_emit_irprintf(" freq: %f",
2102                                  get_block_execfreq(exec_freq, block));
2103         }
2104         be_emit_cstring(" */\n");
2105         be_emit_write_line();
2106 }
2107
2108 /**
2109  * Walks over the nodes in a block connected by scheduling edges
2110  * and emits code for each node.
2111  */
2112 static void ia32_gen_block(ir_node *block)
2113 {
2114         ir_node *node;
2115
2116         ia32_emit_block_header(block);
2117
2118         /* emit the contents of the block */
2119         be_dbg_set_dbg_info(get_irn_dbg_info(block));
2120         sched_foreach(block, node) {
2121                 ia32_emit_node(node);
2122         }
2123 }
2124
2125 typedef struct exc_entry {
2126         ir_node *exc_instr;  /** The instruction that can issue an exception. */
2127         ir_node *block;      /** The block to call then. */
2128 } exc_entry;
2129
2130 /**
2131  * Block-walker:
2132  * Sets labels for control flow nodes (jump target).
2133  * Links control predecessors to there destination blocks.
2134  */
2135 static void ia32_gen_labels(ir_node *block, void *data)
2136 {
2137         exc_entry **exc_list = data;
2138         ir_node *pred;
2139         int     n;
2140
2141         for (n = get_Block_n_cfgpreds(block) - 1; n >= 0; --n) {
2142                 pred = get_Block_cfgpred(block, n);
2143                 set_irn_link(pred, block);
2144
2145                 pred = skip_Proj(pred);
2146                 if (is_ia32_irn(pred) && get_ia32_exc_label(pred)) {
2147                         exc_entry e;
2148
2149                         e.exc_instr = pred;
2150                         e.block     = block;
2151                         ARR_APP1(exc_entry, *exc_list, e);
2152                         set_irn_link(pred, block);
2153                 }
2154         }
2155 }
2156
2157 /**
2158  * Assign and emit an exception label if the current instruction can fail.
2159  */
2160 void ia32_assign_exc_label(ir_node *node)
2161 {
2162         if (get_ia32_exc_label(node)) {
2163                 /* assign a new ID to the instruction */
2164                 set_ia32_exc_label_id(node, ++exc_label_id);
2165                 /* print it */
2166                 ia32_emit_exc_label(node);
2167                 be_emit_char(':');
2168                 be_emit_pad_comment();
2169                 be_emit_cstring("/* exception to Block ");
2170                 ia32_emit_cfop_target(node);
2171                 be_emit_cstring(" */\n");
2172                 be_emit_write_line();
2173         }
2174 }
2175
2176 /**
2177  * Compare two exception_entries.
2178  */
2179 static int cmp_exc_entry(const void *a, const void *b)
2180 {
2181         const exc_entry *ea = a;
2182         const exc_entry *eb = b;
2183
2184         if (get_ia32_exc_label_id(ea->exc_instr) < get_ia32_exc_label_id(eb->exc_instr))
2185                 return -1;
2186         return +1;
2187 }
2188
2189 /**
2190  * Main driver. Emits the code for one routine.
2191  */
2192 void ia32_gen_routine(ia32_code_gen_t *ia32_cg, ir_graph *irg)
2193 {
2194         ir_entity *entity     = get_irg_entity(irg);
2195         exc_entry *exc_list   = NEW_ARR_F(exc_entry, 0);
2196         int i, n;
2197
2198         cg       = ia32_cg;
2199         isa      = (const ia32_isa_t*) cg->arch_env;
2200         arch_env = cg->arch_env;
2201         do_pic   = cg->birg->main_env->options->pic;
2202
2203         ia32_register_emitters();
2204
2205         get_unique_label(pic_base_label, sizeof(pic_base_label), ".PIC_BASE");
2206
2207         be_dbg_method_begin(entity, be_abi_get_stack_layout(cg->birg->abi));
2208         be_gas_emit_function_prolog(entity, ia32_cg_config.function_alignment);
2209
2210         /* we use links to point to target blocks */
2211         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK);
2212         irg_block_walk_graph(irg, ia32_gen_labels, NULL, &exc_list);
2213
2214         /* initialize next block links */
2215         n = ARR_LEN(cg->blk_sched);
2216         for (i = 0; i < n; ++i) {
2217                 ir_node *block = cg->blk_sched[i];
2218                 ir_node *prev  = i > 0 ? cg->blk_sched[i-1] : NULL;
2219
2220                 set_irn_link(block, prev);
2221         }
2222
2223         for (i = 0; i < n; ++i) {
2224                 ir_node *block = cg->blk_sched[i];
2225
2226                 ia32_gen_block(block);
2227         }
2228
2229         be_gas_emit_function_epilog(entity);
2230         be_dbg_method_end();
2231         be_emit_char('\n');
2232         be_emit_write_line();
2233
2234         ir_free_resources(irg, IR_RESOURCE_IRN_LINK);
2235
2236         /* Sort the exception table using the exception label id's.
2237            Those are ascending with ascending addresses. */
2238         qsort(exc_list, ARR_LEN(exc_list), sizeof(exc_list[0]), cmp_exc_entry);
2239         {
2240                 int i;
2241
2242                 for (i = 0; i < ARR_LEN(exc_list); ++i) {
2243                         be_emit_cstring("\t.long ");
2244                         ia32_emit_exc_label(exc_list[i].exc_instr);
2245                         be_emit_char('\n');
2246                         be_emit_cstring("\t.long ");
2247                         ia32_emit_block_name(exc_list[i].block);
2248                         be_emit_char('\n');
2249                 }
2250         }
2251         DEL_ARR_F(exc_list);
2252 }
2253
2254 static const lc_opt_table_entry_t ia32_emitter_options[] = {
2255         LC_OPT_ENT_BOOL("mark_spill_reload",   "mark spills and reloads with ud opcodes", &mark_spill_reload),
2256         LC_OPT_LAST
2257 };
2258
2259 void ia32_init_emitter(void)
2260 {
2261         lc_opt_entry_t *be_grp;
2262         lc_opt_entry_t *ia32_grp;
2263
2264         be_grp   = lc_opt_get_grp(firm_opt_get_root(), "be");
2265         ia32_grp = lc_opt_get_grp(be_grp, "ia32");
2266
2267         lc_opt_add_table(ia32_grp, ia32_emitter_options);
2268
2269         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.emitter");
2270 }