Simplify inserting the fxchs in x87_shuffle().
[libfirm] / ir / be / ia32 / ia32_x87.c
1 /*
2  * Copyright (C) 1995-2010 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 x87 support and virtual to stack
23  *              register translation for the ia32 backend.
24  * @author      Michael Beck
25  */
26 #include "config.h"
27
28 #include <assert.h>
29
30 #include "irnode_t.h"
31 #include "irop_t.h"
32 #include "irprog.h"
33 #include "iredges_t.h"
34 #include "irgmod.h"
35 #include "ircons.h"
36 #include "irgwalk.h"
37 #include "obst.h"
38 #include "pmap.h"
39 #include "array_t.h"
40 #include "pdeq.h"
41 #include "irprintf.h"
42 #include "debug.h"
43 #include "error.h"
44
45 #include "belive_t.h"
46 #include "besched.h"
47 #include "benode.h"
48 #include "bearch_ia32_t.h"
49 #include "ia32_new_nodes.h"
50 #include "gen_ia32_new_nodes.h"
51 #include "gen_ia32_regalloc_if.h"
52 #include "ia32_x87.h"
53 #include "ia32_architecture.h"
54
55 /** the debug handle */
56 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
57
58 /* Forward declaration. */
59 typedef struct x87_simulator x87_simulator;
60
61 /**
62  * An exchange template.
63  * Note that our virtual functions have the same inputs
64  * and attributes as the real ones, so we can simple exchange
65  * their opcodes!
66  * Further, x87 supports inverse instructions, so we can handle them.
67  */
68 typedef struct exchange_tmpl {
69         ir_op *normal_op;       /**< the normal one */
70         ir_op *reverse_op;      /**< the reverse one if exists */
71         ir_op *normal_pop_op;   /**< the normal one with tos pop */
72         ir_op *reverse_pop_op;  /**< the reverse one with tos pop */
73 } exchange_tmpl;
74
75 /**
76  * An entry on the simulated x87 stack.
77  */
78 typedef struct st_entry {
79         int      reg_idx; /**< the virtual register index of this stack value */
80         ir_node *node;    /**< the node that produced this value */
81 } st_entry;
82
83 /**
84  * The x87 state.
85  */
86 typedef struct x87_state {
87         st_entry       st[N_ia32_st_REGS]; /**< the register stack */
88         int            depth;              /**< the current stack depth */
89         x87_simulator *sim;                /**< The simulator. */
90 } x87_state;
91
92 /** An empty state, used for blocks without fp instructions. */
93 static x87_state empty = { { {0, NULL}, }, 0, NULL };
94
95 /**
96  * Return values of the instruction simulator functions.
97  */
98 enum {
99         NO_NODE_ADDED = 0,  /**< No node that needs simulation was added. */
100         NODE_ADDED    = 1   /**< A node that must be simulated was added by the simulator
101                                  in the schedule AFTER the current node. */
102 };
103
104 /**
105  * The type of an instruction simulator function.
106  *
107  * @param state  the x87 state
108  * @param n      the node to be simulated
109  *
110  * @return NODE_ADDED    if a node was added AFTER n in schedule that MUST be
111  *                       simulated further
112  *         NO_NODE_ADDED otherwise
113  */
114 typedef int (*sim_func)(x87_state *state, ir_node *n);
115
116 /**
117  * A block state: Every block has a x87 state at the beginning and at the end.
118  */
119 typedef struct blk_state {
120         x87_state *begin;   /**< state at the begin or NULL if not assigned */
121         x87_state *end;     /**< state at the end or NULL if not assigned */
122 } blk_state;
123
124 /** liveness bitset for vfp registers. */
125 typedef unsigned char vfp_liveness;
126
127 /**
128  * The x87 simulator.
129  */
130 struct x87_simulator {
131         struct obstack obst;       /**< An obstack for fast allocating. */
132         pmap          *blk_states; /**< Map blocks to states. */
133         be_lv_t       *lv;         /**< intrablock liveness. */
134         vfp_liveness  *live;       /**< Liveness information. */
135         unsigned       n_idx;      /**< The cached get_irg_last_idx() result. */
136         waitq         *worklist;   /**< Worklist of blocks that must be processed. */
137 };
138
139 /**
140  * Returns the current stack depth.
141  *
142  * @param state  the x87 state
143  *
144  * @return the x87 stack depth
145  */
146 static int x87_get_depth(const x87_state *state)
147 {
148         return state->depth;
149 }
150
151 static st_entry *x87_get_entry(x87_state *const state, int const pos)
152 {
153         assert(0 <= pos && pos < state->depth);
154         return &state->st[N_ia32_st_REGS - state->depth + pos];
155 }
156
157 /**
158  * Return the virtual register index at st(pos).
159  *
160  * @param state  the x87 state
161  * @param pos    a stack position
162  *
163  * @return the vfp register index that produced the value at st(pos)
164  */
165 static int x87_get_st_reg(const x87_state *state, int pos)
166 {
167         return x87_get_entry((x87_state*)state, pos)->reg_idx;
168 }
169
170 #ifdef DEBUG_libfirm
171 /**
172  * Dump the stack for debugging.
173  *
174  * @param state  the x87 state
175  */
176 static void x87_dump_stack(const x87_state *state)
177 {
178         for (int i = state->depth; i-- != 0;) {
179                 st_entry const *const entry = x87_get_entry((x87_state*)state, i);
180                 DB((dbg, LEVEL_2, "vf%d(%+F) ", entry->reg_idx, entry->node));
181         }
182         DB((dbg, LEVEL_2, "<-- TOS\n"));
183 }
184 #endif /* DEBUG_libfirm */
185
186 /**
187  * Set a virtual register to st(pos).
188  *
189  * @param state    the x87 state
190  * @param reg_idx  the vfp register index that should be set
191  * @param node     the IR node that produces the value of the vfp register
192  * @param pos      the stack position where the new value should be entered
193  */
194 static void x87_set_st(x87_state *state, int reg_idx, ir_node *node, int pos)
195 {
196         st_entry *const entry = x87_get_entry(state, pos);
197         entry->reg_idx = reg_idx;
198         entry->node    = node;
199
200         DB((dbg, LEVEL_2, "After SET_REG: "));
201         DEBUG_ONLY(x87_dump_stack(state);)
202 }
203
204 /**
205  * Set the tos virtual register.
206  *
207  * @param state    the x87 state
208  * @param reg_idx  the vfp register index that should be set
209  * @param node     the IR node that produces the value of the vfp register
210  */
211 static void x87_set_tos(x87_state *state, int reg_idx, ir_node *node)
212 {
213         x87_set_st(state, reg_idx, node, 0);
214 }
215
216 /**
217  * Swap st(0) with st(pos).
218  *
219  * @param state    the x87 state
220  * @param pos      the stack position to change the tos with
221  */
222 static void x87_fxch(x87_state *state, int pos)
223 {
224         st_entry *const a = x87_get_entry(state, pos);
225         st_entry *const b = x87_get_entry(state, 0);
226         st_entry  const t = *a;
227         *a = *b;
228         *b = t;
229
230         DB((dbg, LEVEL_2, "After FXCH: "));
231         DEBUG_ONLY(x87_dump_stack(state);)
232 }
233
234 /**
235  * Convert a virtual register to the stack index.
236  *
237  * @param state    the x87 state
238  * @param reg_idx  the register vfp index
239  *
240  * @return the stack position where the register is stacked
241  *         or -1 if the virtual register was not found
242  */
243 static int x87_on_stack(const x87_state *state, int reg_idx)
244 {
245         for (int i = 0; i < state->depth; ++i) {
246                 if (x87_get_st_reg(state, i) == reg_idx)
247                         return i;
248         }
249         return -1;
250 }
251
252 /**
253  * Push a virtual Register onto the stack, double pushed allowed.
254  *
255  * @param state     the x87 state
256  * @param reg_idx   the register vfp index
257  * @param node      the node that produces the value of the vfp register
258  */
259 static void x87_push_dbl(x87_state *state, int reg_idx, ir_node *node)
260 {
261         assert(state->depth < N_ia32_st_REGS && "stack overrun");
262
263         ++state->depth;
264         st_entry *const entry = x87_get_entry(state, 0);
265         entry->reg_idx = reg_idx;
266         entry->node    = node;
267
268         DB((dbg, LEVEL_2, "After PUSH: ")); DEBUG_ONLY(x87_dump_stack(state);)
269 }
270
271 /**
272  * Push a virtual Register onto the stack, double pushes are NOT allowed.
273  *
274  * @param state     the x87 state
275  * @param reg_idx   the register vfp index
276  * @param node      the node that produces the value of the vfp register
277  */
278 static void x87_push(x87_state *state, int reg_idx, ir_node *node)
279 {
280         assert(x87_on_stack(state, reg_idx) == -1 && "double push");
281
282         x87_push_dbl(state, reg_idx, node);
283 }
284
285 /**
286  * Pop a virtual Register from the stack.
287  *
288  * @param state     the x87 state
289  */
290 static void x87_pop(x87_state *state)
291 {
292         assert(state->depth > 0 && "stack underrun");
293
294         --state->depth;
295
296         DB((dbg, LEVEL_2, "After POP: ")); DEBUG_ONLY(x87_dump_stack(state);)
297 }
298
299 /**
300  * Empty the fpu stack
301  *
302  * @param state     the x87 state
303  */
304 static void x87_emms(x87_state *state)
305 {
306         state->depth = 0;
307 }
308
309 /**
310  * Returns the block state of a block.
311  *
312  * @param sim    the x87 simulator handle
313  * @param block  the current block
314  *
315  * @return the block state
316  */
317 static blk_state *x87_get_bl_state(x87_simulator *sim, ir_node *block)
318 {
319         blk_state *res = pmap_get(blk_state, sim->blk_states, block);
320
321         if (res == NULL) {
322                 res = OALLOC(&sim->obst, blk_state);
323                 res->begin = NULL;
324                 res->end   = NULL;
325
326                 pmap_insert(sim->blk_states, block, res);
327         }
328
329         return res;
330 }
331
332 /**
333  * Clone a x87 state.
334  *
335  * @param sim    the x87 simulator handle
336  * @param src    the x87 state that will be cloned
337  *
338  * @return a cloned copy of the src state
339  */
340 static x87_state *x87_clone_state(x87_simulator *sim, const x87_state *src)
341 {
342         x87_state *const res = OALLOC(&sim->obst, x87_state);
343         *res = *src;
344         return res;
345 }
346
347 /**
348  * Patch a virtual instruction into a x87 one and return
349  * the node representing the result value.
350  *
351  * @param n   the IR node to patch
352  * @param op  the x87 opcode to patch in
353  */
354 static ir_node *x87_patch_insn(ir_node *n, ir_op *op)
355 {
356         ir_mode *mode = get_irn_mode(n);
357         ir_node *res = n;
358
359         set_irn_op(n, op);
360
361         if (mode == mode_T) {
362                 /* patch all Proj's */
363                 foreach_out_edge(n, edge) {
364                         ir_node *proj = get_edge_src_irn(edge);
365                         if (is_Proj(proj)) {
366                                 mode = get_irn_mode(proj);
367                                 if (mode_is_float(mode)) {
368                                         res = proj;
369                                         set_irn_mode(proj, ia32_reg_classes[CLASS_ia32_st].mode);
370                                 }
371                         }
372                 }
373         } else if (mode_is_float(mode))
374                 set_irn_mode(n, ia32_reg_classes[CLASS_ia32_st].mode);
375         return res;
376 }
377
378 /**
379  * Returns the first Proj of a mode_T node having a given mode.
380  *
381  * @param n  the mode_T node
382  * @param m  the desired mode of the Proj
383  * @return The first Proj of mode @p m found or NULL.
384  */
385 static ir_node *get_irn_Proj_for_mode(ir_node *n, ir_mode *m)
386 {
387         assert(get_irn_mode(n) == mode_T && "Need mode_T node");
388
389         foreach_out_edge(n, edge) {
390                 ir_node *proj = get_edge_src_irn(edge);
391                 if (get_irn_mode(proj) == m)
392                         return proj;
393         }
394
395         return NULL;
396 }
397
398 /**
399  * Wrap the arch_* function here so we can check for errors.
400  */
401 static inline const arch_register_t *x87_get_irn_register(const ir_node *irn)
402 {
403         const arch_register_t *res = arch_get_irn_register(irn);
404
405         assert(res->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]);
406         return res;
407 }
408
409 static inline const arch_register_t *x87_irn_get_register(const ir_node *irn,
410                                                           int pos)
411 {
412         const arch_register_t *res = arch_get_irn_register_out(irn, pos);
413
414         assert(res->reg_class == &ia32_reg_classes[CLASS_ia32_vfp]);
415         return res;
416 }
417
418 static inline const arch_register_t *get_st_reg(int index)
419 {
420         return &ia32_registers[REG_ST0 + index];
421 }
422
423 /* -------------- x87 perm --------------- */
424
425 /**
426  * Creates a fxch for shuffle.
427  *
428  * @param state     the x87 state
429  * @param pos       parameter for fxch
430  * @param block     the block were fxch is inserted
431  *
432  * Creates a new fxch node and reroute the user of the old node
433  * to the fxch.
434  *
435  * @return the fxch node
436  */
437 static ir_node *x87_fxch_shuffle(x87_state *state, int pos, ir_node *block)
438 {
439         ir_node         *fxch;
440         ia32_x87_attr_t *attr;
441
442         fxch = new_bd_ia32_fxch(NULL, block);
443         attr = get_ia32_x87_attr(fxch);
444         attr->x87[0] = get_st_reg(pos);
445         attr->x87[2] = get_st_reg(0);
446
447         keep_alive(fxch);
448
449         x87_fxch(state, pos);
450         return fxch;
451 }
452
453 /**
454  * Calculate the necessary permutations to reach dst_state.
455  *
456  * These permutations are done with fxch instructions and placed
457  * at the end of the block.
458  *
459  * Note that critical edges are removed here, so we need only
460  * a shuffle if the current block has only one successor.
461  *
462  * @param block      the current block
463  * @param state      the current x87 stack state, might be modified
464  * @param dst_state  destination state
465  *
466  * @return state
467  */
468 static x87_state *x87_shuffle(ir_node *block, x87_state *state, const x87_state *dst_state)
469 {
470         int      i, n_cycles, k, ri;
471         unsigned cycles[4], all_mask;
472         char     cycle_idx[4][8];
473
474         assert(state->depth == dst_state->depth);
475
476         /* Some mathematics here:
477          * If we have a cycle of length n that includes the tos,
478          * we need n-1 exchange operations.
479          * We can always add the tos and restore it, so we need
480          * n+1 exchange operations for a cycle not containing the tos.
481          * So, the maximum of needed operations is for a cycle of 7
482          * not including the tos == 8.
483          * This is the same number of ops we would need for using stores,
484          * so exchange is cheaper (we save the loads).
485          * On the other hand, we might need an additional exchange
486          * in the next block to bring one operand on top, so the
487          * number of ops in the first case is identical.
488          * Further, no more than 4 cycles can exists (4 x 2). */
489         all_mask = (1 << (state->depth)) - 1;
490
491         for (n_cycles = 0; all_mask; ++n_cycles) {
492                 int src_idx, dst_idx;
493
494                 /* find the first free slot */
495                 for (i = 0; i < state->depth; ++i) {
496                         if (all_mask & (1 << i)) {
497                                 all_mask &= ~(1 << i);
498
499                                 /* check if there are differences here */
500                                 if (x87_get_st_reg(state, i) != x87_get_st_reg(dst_state, i))
501                                         break;
502                         }
503                 }
504
505                 if (! all_mask) {
506                         /* no more cycles found */
507                         break;
508                 }
509
510                 k = 0;
511                 cycles[n_cycles] = (1 << i);
512                 cycle_idx[n_cycles][k++] = i;
513                 for (src_idx = i; ; src_idx = dst_idx) {
514                         dst_idx = x87_on_stack(dst_state, x87_get_st_reg(state, src_idx));
515
516                         if ((all_mask & (1 << dst_idx)) == 0)
517                                 break;
518
519                         cycle_idx[n_cycles][k++] = dst_idx;
520                         cycles[n_cycles] |=  (1 << dst_idx);
521                         all_mask       &= ~(1 << dst_idx);
522                 }
523                 cycle_idx[n_cycles][k] = -1;
524         }
525
526         if (n_cycles <= 0) {
527                 /* no permutation needed */
528                 return state;
529         }
530
531         /* Hmm: permutation needed */
532         DB((dbg, LEVEL_2, "\n%+F needs permutation: from\n", block));
533         DEBUG_ONLY(x87_dump_stack(state);)
534         DB((dbg, LEVEL_2, "                  to\n"));
535         DEBUG_ONLY(x87_dump_stack(dst_state);)
536
537
538 #ifdef DEBUG_libfirm
539         DB((dbg, LEVEL_2, "Need %d cycles\n", n_cycles));
540         for (ri = 0; ri < n_cycles; ++ri) {
541                 DB((dbg, LEVEL_2, " Ring %d:\n ", ri));
542                 for (k = 0; cycle_idx[ri][k] != -1; ++k)
543                         DB((dbg, LEVEL_2, " st%d ->", cycle_idx[ri][k]));
544                 DB((dbg, LEVEL_2, "\n"));
545         }
546 #endif
547
548         /*
549          * Find the place node must be insert.
550          * We have only one successor block, so the last instruction should
551          * be a jump.
552          */
553         ir_node *const before = sched_last(block);
554         assert(is_cfop(before));
555
556         /* now do the permutations */
557         for (ri = 0; ri < n_cycles; ++ri) {
558                 if ((cycles[ri] & 1) == 0) {
559                         /* this cycle does not include the tos */
560                         ir_node *const fxch = x87_fxch_shuffle(state, cycle_idx[ri][0], block);
561                         sched_add_before(before, fxch);
562                 }
563                 for (k = 1; cycle_idx[ri][k] != -1; ++k) {
564                         ir_node *const fxch = x87_fxch_shuffle(state, cycle_idx[ri][k], block);
565                         sched_add_before(before, fxch);
566                 }
567                 if ((cycles[ri] & 1) == 0) {
568                         /* this cycle does not include the tos */
569                         ir_node *const fxch = x87_fxch_shuffle(state, cycle_idx[ri][0], block);
570                         sched_add_before(before, fxch);
571                 }
572         }
573         return state;
574 }
575
576 /**
577  * Create a fxch node before another node.
578  *
579  * @param state   the x87 state
580  * @param n       the node after the fxch
581  * @param pos     exchange st(pos) with st(0)
582  *
583  * @return the fxch
584  */
585 static ir_node *x87_create_fxch(x87_state *state, ir_node *n, int pos)
586 {
587         ir_node         *fxch;
588         ia32_x87_attr_t *attr;
589         ir_node         *block = get_nodes_block(n);
590
591         x87_fxch(state, pos);
592
593         fxch = new_bd_ia32_fxch(NULL, block);
594         attr = get_ia32_x87_attr(fxch);
595         attr->x87[0] = get_st_reg(pos);
596         attr->x87[2] = get_st_reg(0);
597
598         keep_alive(fxch);
599
600         sched_add_before(n, fxch);
601         DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(fxch), attr->x87[0]->name, attr->x87[2]->name));
602         return fxch;
603 }
604
605 /**
606  * Create a fpush before node n.
607  *
608  * @param state     the x87 state
609  * @param n         the node after the fpush
610  * @param pos       push st(pos) on stack
611  * @param val       the value to push
612  */
613 static void x87_create_fpush(x87_state *state, ir_node *n, int pos, ir_node *const val)
614 {
615         arch_register_t const *const out = x87_get_irn_register(val);
616         x87_push_dbl(state, arch_register_get_index(out), val);
617
618         ir_node         *const fpush = new_bd_ia32_fpush(NULL, get_nodes_block(n));
619         ia32_x87_attr_t *const attr  = get_ia32_x87_attr(fpush);
620         attr->x87[0] = get_st_reg(pos);
621         attr->x87[2] = get_st_reg(0);
622
623         keep_alive(fpush);
624         sched_add_before(n, fpush);
625
626         DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(fpush), attr->x87[0]->name, attr->x87[2]->name));
627 }
628
629 /**
630  * Create a fpop before node n.
631  *
632  * @param state   the x87 state
633  * @param n       the node after the fpop
634  * @param num     pop 1 or 2 values
635  *
636  * @return the fpop node
637  */
638 static ir_node *x87_create_fpop(x87_state *state, ir_node *n, int num)
639 {
640         ir_node         *fpop = NULL;
641         ia32_x87_attr_t *attr;
642
643         assert(num > 0);
644         do {
645                 x87_pop(state);
646                 if (ia32_cg_config.use_ffreep)
647                         fpop = new_bd_ia32_ffreep(NULL, get_nodes_block(n));
648                 else
649                         fpop = new_bd_ia32_fpop(NULL, get_nodes_block(n));
650                 attr = get_ia32_x87_attr(fpop);
651                 attr->x87[0] = get_st_reg(0);
652                 attr->x87[1] = get_st_reg(0);
653                 attr->x87[2] = get_st_reg(0);
654
655                 keep_alive(fpop);
656                 sched_add_before(n, fpop);
657                 DB((dbg, LEVEL_1, "<<< %s %s\n", get_irn_opname(fpop), attr->x87[0]->name));
658         } while (--num > 0);
659         return fpop;
660 }
661
662 /* --------------------------------- liveness ------------------------------------------ */
663
664 /**
665  * The liveness transfer function.
666  * Updates a live set over a single step from a given node to its predecessor.
667  * Everything defined at the node is removed from the set, the uses of the node get inserted.
668  *
669  * @param irn      The node at which liveness should be computed.
670  * @param live     The bitset of registers live before @p irn. This set gets modified by updating it to
671  *                 the registers live after irn.
672  *
673  * @return The live bitset.
674  */
675 static vfp_liveness vfp_liveness_transfer(ir_node *irn, vfp_liveness live)
676 {
677         int i, n;
678         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_vfp];
679
680         if (get_irn_mode(irn) == mode_T) {
681                 foreach_out_edge(irn, edge) {
682                         ir_node *proj = get_edge_src_irn(edge);
683
684                         if (arch_irn_consider_in_reg_alloc(cls, proj)) {
685                                 const arch_register_t *reg = x87_get_irn_register(proj);
686                                 live &= ~(1 << arch_register_get_index(reg));
687                         }
688                 }
689         } else if (arch_irn_consider_in_reg_alloc(cls, irn)) {
690                 const arch_register_t *reg = x87_get_irn_register(irn);
691                 live &= ~(1 << arch_register_get_index(reg));
692         }
693
694         for (i = 0, n = get_irn_arity(irn); i < n; ++i) {
695                 ir_node *op = get_irn_n(irn, i);
696
697                 if (mode_is_float(get_irn_mode(op)) &&
698                                 arch_irn_consider_in_reg_alloc(cls, op)) {
699                         const arch_register_t *reg = x87_get_irn_register(op);
700                         live |= 1 << arch_register_get_index(reg);
701                 }
702         }
703         return live;
704 }
705
706 /**
707  * Put all live virtual registers at the end of a block into a bitset.
708  *
709  * @param sim      the simulator handle
710  * @param bl       the block
711  *
712  * @return The live bitset at the end of this block
713  */
714 static vfp_liveness vfp_liveness_end_of_block(x87_simulator *sim, const ir_node *block)
715 {
716         vfp_liveness live = 0;
717         const arch_register_class_t *cls = &ia32_reg_classes[CLASS_ia32_vfp];
718         const be_lv_t *lv = sim->lv;
719
720         be_lv_foreach(lv, block, be_lv_state_end, node) {
721                 const arch_register_t *reg;
722                 if (!arch_irn_consider_in_reg_alloc(cls, node))
723                         continue;
724
725                 reg = x87_get_irn_register(node);
726                 live |= 1 << arch_register_get_index(reg);
727         }
728
729         return live;
730 }
731
732 /** get the register mask from an arch_register */
733 #define REGMASK(reg)    (1 << (arch_register_get_index(reg)))
734
735 /**
736  * Return a bitset of argument registers which are live at the end of a node.
737  *
738  * @param sim    the simulator handle
739  * @param pos    the node
740  * @param kill   kill mask for the output registers
741  *
742  * @return The live bitset.
743  */
744 static unsigned vfp_live_args_after(x87_simulator *sim, const ir_node *pos, unsigned kill)
745 {
746         unsigned idx = get_irn_idx(pos);
747
748         assert(idx < sim->n_idx);
749         return sim->live[idx] & ~kill;
750 }
751
752 /**
753  * Calculate the liveness for a whole block and cache it.
754  *
755  * @param sim   the simulator handle
756  * @param block the block
757  */
758 static void update_liveness(x87_simulator *sim, ir_node *block)
759 {
760         vfp_liveness live = vfp_liveness_end_of_block(sim, block);
761         unsigned idx;
762
763         /* now iterate through the block backward and cache the results */
764         sched_foreach_reverse(block, irn) {
765                 /* stop at the first Phi: this produces the live-in */
766                 if (is_Phi(irn))
767                         break;
768
769                 idx = get_irn_idx(irn);
770                 sim->live[idx] = live;
771
772                 live = vfp_liveness_transfer(irn, live);
773         }
774         idx = get_irn_idx(block);
775         sim->live[idx] = live;
776 }
777
778 /**
779  * Returns true if a register is live in a set.
780  *
781  * @param reg_idx  the vfp register index
782  * @param live     a live bitset
783  */
784 #define is_vfp_live(reg_idx, live) ((live) & (1 << (reg_idx)))
785
786 #ifdef DEBUG_libfirm
787 /**
788  * Dump liveness info.
789  *
790  * @param live  the live bitset
791  */
792 static void vfp_dump_live(vfp_liveness live)
793 {
794         int i;
795
796         DB((dbg, LEVEL_2, "Live after: "));
797         for (i = 0; i < 8; ++i) {
798                 if (live & (1 << i)) {
799                         DB((dbg, LEVEL_2, "vf%d ", i));
800                 }
801         }
802         DB((dbg, LEVEL_2, "\n"));
803 }
804 #endif /* DEBUG_libfirm */
805
806 /* --------------------------------- simulators ---------------------------------------- */
807
808 /**
809  * Simulate a virtual binop.
810  *
811  * @param state  the x87 state
812  * @param n      the node that should be simulated (and patched)
813  * @param tmpl   the template containing the 4 possible x87 opcodes
814  *
815  * @return NO_NODE_ADDED
816  */
817 static int sim_binop(x87_state *state, ir_node *n, const exchange_tmpl *tmpl)
818 {
819         int op2_idx = 0, op1_idx;
820         int out_idx, do_pop = 0;
821         ia32_x87_attr_t *attr;
822         int permuted;
823         ir_node *patched_insn;
824         ir_op *dst;
825         x87_simulator         *sim     = state->sim;
826         ir_node               *op1     = get_irn_n(n, n_ia32_binary_left);
827         ir_node               *op2     = get_irn_n(n, n_ia32_binary_right);
828         const arch_register_t *op1_reg = x87_get_irn_register(op1);
829         const arch_register_t *op2_reg = x87_get_irn_register(op2);
830         const arch_register_t *out     = x87_irn_get_register(n, pn_ia32_res);
831         int reg_index_1                = arch_register_get_index(op1_reg);
832         int reg_index_2                = arch_register_get_index(op2_reg);
833         vfp_liveness           live    = vfp_live_args_after(sim, n, REGMASK(out));
834         int                    op1_live_after;
835         int                    op2_live_after;
836
837         DB((dbg, LEVEL_1, ">>> %+F %s, %s -> %s\n", n,
838                 arch_register_get_name(op1_reg), arch_register_get_name(op2_reg),
839                 arch_register_get_name(out)));
840         DEBUG_ONLY(vfp_dump_live(live);)
841         DB((dbg, LEVEL_1, "Stack before: "));
842         DEBUG_ONLY(x87_dump_stack(state);)
843
844         op1_idx = x87_on_stack(state, reg_index_1);
845         assert(op1_idx >= 0);
846         op1_live_after = is_vfp_live(reg_index_1, live);
847
848         attr     = get_ia32_x87_attr(n);
849         permuted = attr->attr.data.ins_permuted;
850
851         if (reg_index_2 != REG_VFP_VFP_NOREG) {
852                 assert(!permuted);
853
854                 /* second operand is a vfp register */
855                 op2_idx = x87_on_stack(state, reg_index_2);
856                 assert(op2_idx >= 0);
857                 op2_live_after = is_vfp_live(reg_index_2, live);
858
859                 if (op2_live_after) {
860                         /* Second operand is live. */
861
862                         if (op1_live_after) {
863                                 /* Both operands are live: push the first one.
864                                    This works even for op1 == op2. */
865                                 x87_create_fpush(state, n, op1_idx, op2);
866                                 /* now do fxxx (tos=tos X op) */
867                                 op1_idx = 0;
868                                 op2_idx += 1;
869                                 out_idx = 0;
870                                 dst = tmpl->normal_op;
871                         } else {
872                                 /* Second live, first operand is dead here, bring it to tos. */
873                                 if (op1_idx != 0) {
874                                         x87_create_fxch(state, n, op1_idx);
875                                         if (op2_idx == 0)
876                                                 op2_idx = op1_idx;
877                                         op1_idx = 0;
878                                 }
879                                 /* now do fxxx (tos=tos X op) */
880                                 out_idx = 0;
881                                 dst = tmpl->normal_op;
882                         }
883                 } else {
884                         /* Second operand is dead. */
885                         if (op1_live_after) {
886                                 /* First operand is live: bring second to tos. */
887                                 if (op2_idx != 0) {
888                                         x87_create_fxch(state, n, op2_idx);
889                                         if (op1_idx == 0)
890                                                 op1_idx = op2_idx;
891                                         op2_idx = 0;
892                                 }
893                                 /* now do fxxxr (tos = op X tos) */
894                                 out_idx = 0;
895                                 dst = tmpl->reverse_op;
896                         } else {
897                                 /* Both operands are dead here, pop them from the stack. */
898                                 if (op2_idx == 0) {
899                                         if (op1_idx == 0) {
900                                                 /* Both are identically and on tos, no pop needed. */
901                                                 /* here fxxx (tos = tos X tos) */
902                                                 dst = tmpl->normal_op;
903                                                 out_idx = 0;
904                                         } else {
905                                                 /* now do fxxxp (op = op X tos, pop) */
906                                                 dst = tmpl->normal_pop_op;
907                                                 do_pop = 1;
908                                                 out_idx = op1_idx;
909                                         }
910                                 } else if (op1_idx == 0) {
911                                         assert(op1_idx != op2_idx);
912                                         /* now do fxxxrp (op = tos X op, pop) */
913                                         dst = tmpl->reverse_pop_op;
914                                         do_pop = 1;
915                                         out_idx = op2_idx;
916                                 } else {
917                                         /* Bring the second on top. */
918                                         x87_create_fxch(state, n, op2_idx);
919                                         if (op1_idx == op2_idx) {
920                                                 /* Both are identically and on tos now, no pop needed. */
921                                                 op1_idx = 0;
922                                                 op2_idx = 0;
923                                                 /* use fxxx (tos = tos X tos) */
924                                                 dst = tmpl->normal_op;
925                                                 out_idx = 0;
926                                         } else {
927                                                 /* op2 is on tos now */
928                                                 op2_idx = 0;
929                                                 /* use fxxxp (op = op X tos, pop) */
930                                                 dst = tmpl->normal_pop_op;
931                                                 out_idx = op1_idx;
932                                                 do_pop = 1;
933                                         }
934                                 }
935                         }
936                 }
937         } else {
938                 /* second operand is an address mode */
939                 if (op1_live_after) {
940                         /* first operand is live: push it here */
941                         x87_create_fpush(state, n, op1_idx, op1);
942                         op1_idx = 0;
943                 } else {
944                         /* first operand is dead: bring it to tos */
945                         if (op1_idx != 0) {
946                                 x87_create_fxch(state, n, op1_idx);
947                                 op1_idx = 0;
948                         }
949                 }
950
951                 /* use fxxx (tos = tos X mem) */
952                 dst = permuted ? tmpl->reverse_op : tmpl->normal_op;
953                 out_idx = 0;
954         }
955
956         patched_insn = x87_patch_insn(n, dst);
957         x87_set_st(state, arch_register_get_index(out), patched_insn, out_idx);
958         if (do_pop) {
959                 x87_pop(state);
960         }
961
962         /* patch the operation */
963         attr->x87[0] = op1_reg = get_st_reg(op1_idx);
964         if (reg_index_2 != REG_VFP_VFP_NOREG) {
965                 attr->x87[1] = op2_reg = get_st_reg(op2_idx);
966         }
967         attr->x87[2] = out = get_st_reg(out_idx);
968
969         if (reg_index_2 != REG_VFP_VFP_NOREG) {
970                 DB((dbg, LEVEL_1, "<<< %s %s, %s -> %s\n", get_irn_opname(n),
971                         arch_register_get_name(op1_reg), arch_register_get_name(op2_reg),
972                         arch_register_get_name(out)));
973         } else {
974                 DB((dbg, LEVEL_1, "<<< %s %s, [AM] -> %s\n", get_irn_opname(n),
975                         arch_register_get_name(op1_reg),
976                         arch_register_get_name(out)));
977         }
978
979         return NO_NODE_ADDED;
980 }
981
982 /**
983  * Simulate a virtual Unop.
984  *
985  * @param state  the x87 state
986  * @param n      the node that should be simulated (and patched)
987  * @param op     the x87 opcode that will replace n's opcode
988  *
989  * @return NO_NODE_ADDED
990  */
991 static int sim_unop(x87_state *state, ir_node *n, ir_op *op)
992 {
993         arch_register_t const *const out  = x87_get_irn_register(n);
994         unsigned               const live = vfp_live_args_after(state->sim, n, REGMASK(out));
995         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, out->name));
996         DEBUG_ONLY(vfp_dump_live(live);)
997
998         ir_node               *const op1         = get_irn_n(n, 0);
999         arch_register_t const *const op1_reg     = x87_get_irn_register(op1);
1000         int                    const op1_reg_idx = arch_register_get_index(op1_reg);
1001         int                    const op1_idx     = x87_on_stack(state, op1_reg_idx);
1002         if (is_vfp_live(op1_reg_idx, live)) {
1003                 /* push the operand here */
1004                 x87_create_fpush(state, n, op1_idx, op1);
1005         } else {
1006                 /* operand is dead, bring it to tos */
1007                 if (op1_idx != 0) {
1008                         x87_create_fxch(state, n, op1_idx);
1009                 }
1010         }
1011
1012         x87_set_tos(state, arch_register_get_index(out), x87_patch_insn(n, op));
1013         ia32_x87_attr_t *const attr = get_ia32_x87_attr(n);
1014         attr->x87[2] = attr->x87[0] = get_st_reg(0);
1015         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), attr->x87[2]->name));
1016
1017         return NO_NODE_ADDED;
1018 }
1019
1020 /**
1021  * Simulate a virtual Load instruction.
1022  *
1023  * @param state  the x87 state
1024  * @param n      the node that should be simulated (and patched)
1025  * @param op     the x87 opcode that will replace n's opcode
1026  *
1027  * @return NO_NODE_ADDED
1028  */
1029 static int sim_load(x87_state *state, ir_node *n, ir_op *op, int res_pos)
1030 {
1031         const arch_register_t *out = x87_irn_get_register(n, res_pos);
1032         ia32_x87_attr_t *attr;
1033
1034         DB((dbg, LEVEL_1, ">>> %+F -> %s\n", n, arch_register_get_name(out)));
1035         x87_push(state, arch_register_get_index(out), x87_patch_insn(n, op));
1036         assert(out == x87_irn_get_register(n, res_pos));
1037         attr = get_ia32_x87_attr(n);
1038         attr->x87[2] = out = get_st_reg(0);
1039         DB((dbg, LEVEL_1, "<<< %s -> %s\n", get_irn_opname(n), arch_register_get_name(out)));
1040
1041         return NO_NODE_ADDED;
1042 }
1043
1044 /**
1045  * Rewire all users of @p old_val to @new_val iff they are scheduled after @p store.
1046  *
1047  * @param store   The store
1048  * @param old_val The former value
1049  * @param new_val The new value
1050  */
1051 static void collect_and_rewire_users(ir_node *store, ir_node *old_val, ir_node *new_val)
1052 {
1053         foreach_out_edge_safe(old_val, edge) {
1054                 ir_node *user = get_edge_src_irn(edge);
1055
1056                 if (! user || user == store)
1057                         continue;
1058
1059                 /* if the user is scheduled after the store: rewire */
1060                 if (sched_is_scheduled(user) && sched_comes_after(store, user)) {
1061                         int i;
1062                         /* find the input of the user pointing to the old value */
1063                         for (i = get_irn_arity(user) - 1; i >= 0; i--) {
1064                                 if (get_irn_n(user, i) == old_val)
1065                                         set_irn_n(user, i, new_val);
1066                         }
1067                 }
1068         }
1069 }
1070
1071 /**
1072  * Simulate a virtual Store.
1073  *
1074  * @param state  the x87 state
1075  * @param n      the node that should be simulated (and patched)
1076  * @param op     the x87 store opcode
1077  * @param op_p   the x87 store and pop opcode
1078  */
1079 static int sim_store(x87_state *state, ir_node *n, ir_op *op, ir_op *op_p)
1080 {
1081         ir_node               *const val = get_irn_n(n, n_ia32_vfst_val);
1082         arch_register_t const *const op2 = x87_get_irn_register(val);
1083         DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, arch_register_get_name(op2)));
1084
1085         int            insn            = NO_NODE_ADDED;
1086         int      const op2_reg_idx     = arch_register_get_index(op2);
1087         int      const op2_idx         = x87_on_stack(state, op2_reg_idx);
1088         unsigned const live            = vfp_live_args_after(state->sim, n, 0);
1089         int      const live_after_node = is_vfp_live(op2_reg_idx, live);
1090         assert(op2_idx >= 0);
1091         if (live_after_node) {
1092                 /* Problem: fst doesn't support 80bit modes (spills), only fstp does
1093                  *          fist doesn't support 64bit mode, only fistp
1094                  * Solution:
1095                  *   - stack not full: push value and fstp
1096                  *   - stack full: fstp value and load again
1097                  * Note that we cannot test on mode_E, because floats might be 80bit ... */
1098                 ir_mode *const mode = get_ia32_ls_mode(n);
1099                 if (get_mode_size_bits(mode) > (mode_is_int(mode) ? 32 : 64)) {
1100                         if (x87_get_depth(state) < N_ia32_st_REGS) {
1101                                 /* ok, we have a free register: push + fstp */
1102                                 x87_create_fpush(state, n, op2_idx, val);
1103                                 x87_pop(state);
1104                                 x87_patch_insn(n, op_p);
1105                         } else {
1106                                 /* stack full here: need fstp + load */
1107                                 x87_pop(state);
1108                                 x87_patch_insn(n, op_p);
1109
1110                                 ir_node  *const block = get_nodes_block(n);
1111                                 ir_graph *const irg   = get_irn_irg(n);
1112                                 ir_node  *const nomem = get_irg_no_mem(irg);
1113                                 ir_node  *const vfld  = new_bd_ia32_vfld(NULL, block, get_irn_n(n, 0), get_irn_n(n, 1), nomem, mode);
1114
1115                                 /* copy all attributes */
1116                                 set_ia32_frame_ent(vfld, get_ia32_frame_ent(n));
1117                                 if (is_ia32_use_frame(n))
1118                                         set_ia32_use_frame(vfld);
1119                                 set_ia32_op_type(vfld, ia32_AddrModeS);
1120                                 add_ia32_am_offs_int(vfld, get_ia32_am_offs_int(n));
1121                                 set_ia32_am_sc(vfld, get_ia32_am_sc(n));
1122                                 set_ia32_ls_mode(vfld, mode);
1123
1124                                 ir_node *const rproj = new_r_Proj(vfld, mode, pn_ia32_vfld_res);
1125                                 ir_node *const mproj = new_r_Proj(vfld, mode_M, pn_ia32_vfld_M);
1126                                 ir_node *const mem   = get_irn_Proj_for_mode(n, mode_M);
1127
1128                                 assert(mem && "Store memory not found");
1129
1130                                 arch_set_irn_register(rproj, op2);
1131
1132                                 /* reroute all former users of the store memory to the load memory */
1133                                 edges_reroute(mem, mproj);
1134                                 /* set the memory input of the load to the store memory */
1135                                 set_irn_n(vfld, n_ia32_vfld_mem, mem);
1136
1137                                 sched_add_after(n, vfld);
1138                                 sched_add_after(vfld, rproj);
1139
1140                                 /* rewire all users, scheduled after the store, to the loaded value */
1141                                 collect_and_rewire_users(n, val, rproj);
1142
1143                                 insn = NODE_ADDED;
1144                         }
1145                 } else {
1146                         /* we can only store the tos to memory */
1147                         if (op2_idx != 0)
1148                                 x87_create_fxch(state, n, op2_idx);
1149
1150                         /* mode size 64 or smaller -> use normal fst */
1151                         x87_patch_insn(n, op);
1152                 }
1153         } else {
1154                 /* we can only store the tos to memory */
1155                 if (op2_idx != 0)
1156                         x87_create_fxch(state, n, op2_idx);
1157
1158                 x87_pop(state);
1159                 x87_patch_insn(n, op_p);
1160         }
1161
1162         ia32_x87_attr_t *const attr = get_ia32_x87_attr(n);
1163         attr->x87[1] = get_st_reg(0);
1164         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), arch_register_get_name(attr->x87[1])));
1165
1166         return insn;
1167 }
1168
1169 #define _GEN_BINOP(op, rev) \
1170 static int sim_##op(x87_state *state, ir_node *n) { \
1171         exchange_tmpl tmpl = { op_ia32_##op, op_ia32_##rev, op_ia32_##op##p, op_ia32_##rev##p }; \
1172         return sim_binop(state, n, &tmpl); \
1173 }
1174
1175 #define GEN_BINOP(op)   _GEN_BINOP(op, op)
1176 #define GEN_BINOPR(op)  _GEN_BINOP(op, op##r)
1177
1178 #define GEN_LOAD(op)                                              \
1179 static int sim_##op(x87_state *state, ir_node *n) {               \
1180         return sim_load(state, n, op_ia32_##op, pn_ia32_v##op##_res); \
1181 }
1182
1183 #define GEN_UNOP(op) \
1184 static int sim_##op(x87_state *state, ir_node *n) { \
1185         return sim_unop(state, n, op_ia32_##op); \
1186 }
1187
1188 #define GEN_STORE(op) \
1189 static int sim_##op(x87_state *state, ir_node *n) { \
1190         return sim_store(state, n, op_ia32_##op, op_ia32_##op##p); \
1191 }
1192
1193 /* all stubs */
1194 GEN_BINOP(fadd)
1195 GEN_BINOPR(fsub)
1196 GEN_BINOP(fmul)
1197 GEN_BINOPR(fdiv)
1198 GEN_BINOP(fprem)
1199
1200 GEN_UNOP(fabs)
1201 GEN_UNOP(fchs)
1202
1203 GEN_LOAD(fld)
1204 GEN_LOAD(fild)
1205 GEN_LOAD(fldz)
1206 GEN_LOAD(fld1)
1207
1208 GEN_STORE(fst)
1209 GEN_STORE(fist)
1210
1211 /**
1212  * Simulate a virtual fisttp.
1213  *
1214  * @param state  the x87 state
1215  * @param n      the node that should be simulated (and patched)
1216  *
1217  * @return NO_NODE_ADDED
1218  */
1219 static int sim_fisttp(x87_state *state, ir_node *n)
1220 {
1221         ir_node               *val = get_irn_n(n, n_ia32_vfst_val);
1222         const arch_register_t *op2 = x87_get_irn_register(val);
1223         ia32_x87_attr_t *attr;
1224         int op2_reg_idx, op2_idx;
1225
1226         op2_reg_idx = arch_register_get_index(op2);
1227         op2_idx     = x87_on_stack(state, op2_reg_idx);
1228         DB((dbg, LEVEL_1, ">>> %+F %s ->\n", n, arch_register_get_name(op2)));
1229         assert(op2_idx >= 0);
1230
1231         /* Note: although the value is still live here, it is destroyed because
1232            of the pop. The register allocator is aware of that and introduced a copy
1233            if the value must be alive. */
1234
1235         /* we can only store the tos to memory */
1236         if (op2_idx != 0)
1237                 x87_create_fxch(state, n, op2_idx);
1238
1239         x87_pop(state);
1240         x87_patch_insn(n, op_ia32_fisttp);
1241
1242         attr = get_ia32_x87_attr(n);
1243         attr->x87[1] = op2 = get_st_reg(0);
1244         DB((dbg, LEVEL_1, "<<< %s %s ->\n", get_irn_opname(n), arch_register_get_name(op2)));
1245
1246         return NO_NODE_ADDED;
1247 }
1248
1249 /**
1250  * Simulate a virtual FtstFnstsw.
1251  *
1252  * @param state  the x87 state
1253  * @param n      the node that should be simulated (and patched)
1254  *
1255  * @return NO_NODE_ADDED
1256  */
1257 static int sim_FtstFnstsw(x87_state *state, ir_node *n)
1258 {
1259         x87_simulator         *sim         = state->sim;
1260         ia32_x87_attr_t       *attr        = get_ia32_x87_attr(n);
1261         ir_node               *op1_node    = get_irn_n(n, n_ia32_vFtstFnstsw_left);
1262         const arch_register_t *reg1        = x87_get_irn_register(op1_node);
1263         int                    reg_index_1 = arch_register_get_index(reg1);
1264         int                    op1_idx     = x87_on_stack(state, reg_index_1);
1265         unsigned               live        = vfp_live_args_after(sim, n, 0);
1266
1267         DB((dbg, LEVEL_1, ">>> %+F %s\n", n, arch_register_get_name(reg1)));
1268         DEBUG_ONLY(vfp_dump_live(live);)
1269         DB((dbg, LEVEL_1, "Stack before: "));
1270         DEBUG_ONLY(x87_dump_stack(state);)
1271         assert(op1_idx >= 0);
1272
1273         if (op1_idx != 0) {
1274                 /* bring the value to tos */
1275                 x87_create_fxch(state, n, op1_idx);
1276                 op1_idx = 0;
1277         }
1278
1279         /* patch the operation */
1280         x87_patch_insn(n, op_ia32_FtstFnstsw);
1281         reg1 = get_st_reg(op1_idx);
1282         attr->x87[0] = reg1;
1283         attr->x87[1] = NULL;
1284         attr->x87[2] = NULL;
1285
1286         if (!is_vfp_live(reg_index_1, live))
1287                 x87_create_fpop(state, sched_next(n), 1);
1288
1289         return NO_NODE_ADDED;
1290 }
1291
1292 /**
1293  * Simulate a Fucom
1294  *
1295  * @param state  the x87 state
1296  * @param n      the node that should be simulated (and patched)
1297  *
1298  * @return NO_NODE_ADDED
1299  */
1300 static int sim_Fucom(x87_state *state, ir_node *n)
1301 {
1302         int op1_idx;
1303         int op2_idx = -1;
1304         ia32_x87_attr_t *attr = get_ia32_x87_attr(n);
1305         ir_op *dst;
1306         x87_simulator         *sim        = state->sim;
1307         ir_node               *op1_node   = get_irn_n(n, n_ia32_vFucomFnstsw_left);
1308         ir_node               *op2_node   = get_irn_n(n, n_ia32_vFucomFnstsw_right);
1309         const arch_register_t *op1        = x87_get_irn_register(op1_node);
1310         const arch_register_t *op2        = x87_get_irn_register(op2_node);
1311         int reg_index_1 = arch_register_get_index(op1);
1312         int                    reg_index_2 = arch_register_get_index(op2);
1313         unsigned               live       = vfp_live_args_after(sim, n, 0);
1314         bool                   permuted   = attr->attr.data.ins_permuted;
1315         bool                   xchg       = false;
1316         int                    pops       = 0;
1317
1318         DB((dbg, LEVEL_1, ">>> %+F %s, %s\n", n,
1319                 arch_register_get_name(op1), arch_register_get_name(op2)));
1320         DEBUG_ONLY(vfp_dump_live(live);)
1321         DB((dbg, LEVEL_1, "Stack before: "));
1322         DEBUG_ONLY(x87_dump_stack(state);)
1323
1324         op1_idx = x87_on_stack(state, reg_index_1);
1325         assert(op1_idx >= 0);
1326
1327         /* BEWARE: check for comp a,a cases, they might happen */
1328         if (reg_index_2 != REG_VFP_VFP_NOREG) {
1329                 /* second operand is a vfp register */
1330                 op2_idx = x87_on_stack(state, reg_index_2);
1331                 assert(op2_idx >= 0);
1332
1333                 if (is_vfp_live(reg_index_2, live)) {
1334                         /* second operand is live */
1335
1336                         if (is_vfp_live(reg_index_1, live)) {
1337                                 /* both operands are live */
1338
1339                                 if (op1_idx == 0) {
1340                                         /* res = tos X op */
1341                                 } else if (op2_idx == 0) {
1342                                         /* res = op X tos */
1343                                         permuted = !permuted;
1344                                         xchg     = true;
1345                                 } else {
1346                                         /* bring the first one to tos */
1347                                         x87_create_fxch(state, n, op1_idx);
1348                                         if (op1_idx == op2_idx) {
1349                                                 op2_idx = 0;
1350                                         } else if (op2_idx == 0) {
1351                                                 op2_idx = op1_idx;
1352                                         }
1353                                         op1_idx = 0;
1354                                         /* res = tos X op */
1355                                 }
1356                         } else {
1357                                 /* second live, first operand is dead here, bring it to tos.
1358                                    This means further, op1_idx != op2_idx. */
1359                                 assert(op1_idx != op2_idx);
1360                                 if (op1_idx != 0) {
1361                                         x87_create_fxch(state, n, op1_idx);
1362                                         if (op2_idx == 0)
1363                                                 op2_idx = op1_idx;
1364                                         op1_idx = 0;
1365                                 }
1366                                 /* res = tos X op, pop */
1367                                 pops = 1;
1368                         }
1369                 } else {
1370                         /* second operand is dead */
1371                         if (is_vfp_live(reg_index_1, live)) {
1372                                 /* first operand is live: bring second to tos.
1373                                    This means further, op1_idx != op2_idx. */
1374                                 assert(op1_idx != op2_idx);
1375                                 if (op2_idx != 0) {
1376                                         x87_create_fxch(state, n, op2_idx);
1377                                         if (op1_idx == 0)
1378                                                 op1_idx = op2_idx;
1379                                         op2_idx = 0;
1380                                 }
1381                                 /* res = op X tos, pop */
1382                                 pops     = 1;
1383                                 permuted = !permuted;
1384                                 xchg     = true;
1385                         } else {
1386                                 /* both operands are dead here, check first for identity. */
1387                                 if (op1_idx == op2_idx) {
1388                                         /* identically, one pop needed */
1389                                         if (op1_idx != 0) {
1390                                                 x87_create_fxch(state, n, op1_idx);
1391                                                 op1_idx = 0;
1392                                                 op2_idx = 0;
1393                                         }
1394                                         /* res = tos X op, pop */
1395                                         pops    = 1;
1396                                 }
1397                                 /* different, move them to st and st(1) and pop both.
1398                                    The tricky part is to get one into st(1).*/
1399                                 else if (op2_idx == 1) {
1400                                         /* good, second operand is already in the right place, move the first */
1401                                         if (op1_idx != 0) {
1402                                                 /* bring the first on top */
1403                                                 x87_create_fxch(state, n, op1_idx);
1404                                                 assert(op2_idx != 0);
1405                                                 op1_idx = 0;
1406                                         }
1407                                         /* res = tos X op, pop, pop */
1408                                         pops = 2;
1409                                 } else if (op1_idx == 1) {
1410                                         /* good, first operand is already in the right place, move the second */
1411                                         if (op2_idx != 0) {
1412                                                 /* bring the first on top */
1413                                                 x87_create_fxch(state, n, op2_idx);
1414                                                 assert(op1_idx != 0);
1415                                                 op2_idx = 0;
1416                                         }
1417                                         /* res = op X tos, pop, pop */
1418                                         permuted = !permuted;
1419                                         xchg     = true;
1420                                         pops     = 2;
1421                                 } else {
1422                                         /* if one is already the TOS, we need two fxch */
1423                                         if (op1_idx == 0) {
1424                                                 /* first one is TOS, move to st(1) */
1425                                                 x87_create_fxch(state, n, 1);
1426                                                 assert(op2_idx != 1);
1427                                                 op1_idx = 1;
1428                                                 x87_create_fxch(state, n, op2_idx);
1429                                                 op2_idx = 0;
1430                                                 /* res = op X tos, pop, pop */
1431                                                 pops     = 2;
1432                                                 permuted = !permuted;
1433                                                 xchg     = true;
1434                                         } else if (op2_idx == 0) {
1435                                                 /* second one is TOS, move to st(1) */
1436                                                 x87_create_fxch(state, n, 1);
1437                                                 assert(op1_idx != 1);
1438                                                 op2_idx = 1;
1439                                                 x87_create_fxch(state, n, op1_idx);
1440                                                 op1_idx = 0;
1441                                                 /* res = tos X op, pop, pop */
1442                                                 pops    = 2;
1443                                         } else {
1444                                                 /* none of them is either TOS or st(1), 3 fxch needed */
1445                                                 x87_create_fxch(state, n, op2_idx);
1446                                                 assert(op1_idx != 0);
1447                                                 x87_create_fxch(state, n, 1);
1448                                                 op2_idx = 1;
1449                                                 x87_create_fxch(state, n, op1_idx);
1450                                                 op1_idx = 0;
1451                                                 /* res = tos X op, pop, pop */
1452                                                 pops    = 2;
1453                                         }
1454                                 }
1455                         }
1456                 }
1457         } else {
1458                 /* second operand is an address mode */
1459                 if (is_vfp_live(reg_index_1, live)) {
1460                         /* first operand is live: bring it to TOS */
1461                         if (op1_idx != 0) {
1462                                 x87_create_fxch(state, n, op1_idx);
1463                                 op1_idx = 0;
1464                         }
1465                 } else {
1466                         /* first operand is dead: bring it to tos */
1467                         if (op1_idx != 0) {
1468                                 x87_create_fxch(state, n, op1_idx);
1469                                 op1_idx = 0;
1470                         }
1471                         pops = 1;
1472                 }
1473         }
1474
1475         /* patch the operation */
1476         if (is_ia32_vFucomFnstsw(n)) {
1477                 int i;
1478
1479                 switch (pops) {
1480                 case 0: dst = op_ia32_FucomFnstsw;   break;
1481                 case 1: dst = op_ia32_FucompFnstsw;  break;
1482                 case 2: dst = op_ia32_FucomppFnstsw; break;
1483                 default: panic("invalid popcount");
1484                 }
1485
1486                 for (i = 0; i < pops; ++i) {
1487                         x87_pop(state);
1488                 }
1489         } else if (is_ia32_vFucomi(n)) {
1490                 switch (pops) {
1491                 case 0: dst = op_ia32_Fucomi;                  break;
1492                 case 1: dst = op_ia32_Fucompi; x87_pop(state); break;
1493                 case 2:
1494                         dst = op_ia32_Fucompi;
1495                         x87_pop(state);
1496                         x87_create_fpop(state, sched_next(n), 1);
1497                         break;
1498                 default: panic("invalid popcount");
1499                 }
1500         } else {
1501                 panic("invalid operation %+F", n);
1502         }
1503
1504         x87_patch_insn(n, dst);
1505         if (xchg) {
1506                 int tmp = op1_idx;
1507                 op1_idx = op2_idx;
1508                 op2_idx = tmp;
1509         }
1510
1511         op1 = get_st_reg(op1_idx);
1512         attr->x87[0] = op1;
1513         if (op2_idx >= 0) {
1514                 op2 = get_st_reg(op2_idx);
1515                 attr->x87[1] = op2;
1516         }
1517         attr->x87[2] = NULL;
1518         attr->attr.data.ins_permuted = permuted;
1519
1520         if (op2_idx >= 0) {
1521                 DB((dbg, LEVEL_1, "<<< %s %s, %s\n", get_irn_opname(n),
1522                         arch_register_get_name(op1), arch_register_get_name(op2)));
1523         } else {
1524                 DB((dbg, LEVEL_1, "<<< %s %s, [AM]\n", get_irn_opname(n),
1525                         arch_register_get_name(op1)));
1526         }
1527
1528         return NO_NODE_ADDED;
1529 }
1530
1531 /**
1532  * Simulate a Keep.
1533  *
1534  * @param state  the x87 state
1535  * @param n      the node that should be simulated (and patched)
1536  *
1537  * @return NO_NODE_ADDED
1538  */
1539 static int sim_Keep(x87_state *state, ir_node *node)
1540 {
1541         const ir_node         *op;
1542         const arch_register_t *op_reg;
1543         int                    reg_id;
1544         int                    op_stack_idx;
1545         unsigned               live;
1546         int                    i, arity;
1547
1548         DB((dbg, LEVEL_1, ">>> %+F\n", node));
1549
1550         arity = get_irn_arity(node);
1551         for (i = 0; i < arity; ++i) {
1552                 op      = get_irn_n(node, i);
1553                 op_reg  = arch_get_irn_register(op);
1554                 if (arch_register_get_class(op_reg) != &ia32_reg_classes[CLASS_ia32_vfp])
1555                         continue;
1556
1557                 reg_id = arch_register_get_index(op_reg);
1558                 live   = vfp_live_args_after(state->sim, node, 0);
1559
1560                 op_stack_idx = x87_on_stack(state, reg_id);
1561                 if (op_stack_idx >= 0 && !is_vfp_live(reg_id, live))
1562                         x87_create_fpop(state, sched_next(node), 1);
1563         }
1564
1565         DB((dbg, LEVEL_1, "Stack after: "));
1566         DEBUG_ONLY(x87_dump_stack(state);)
1567
1568         return NO_NODE_ADDED;
1569 }
1570
1571 /**
1572  * Keep the given node alive by adding a be_Keep.
1573  *
1574  * @param node  the node to kept alive
1575  */
1576 static void keep_float_node_alive(ir_node *node)
1577 {
1578         ir_node *block = get_nodes_block(node);
1579         ir_node *keep  = be_new_Keep(block, 1, &node);
1580
1581         assert(sched_is_scheduled(node));
1582         sched_add_after(node, keep);
1583 }
1584
1585 /**
1586  * Create a copy of a node. Recreate the node if it's a constant.
1587  *
1588  * @param state  the x87 state
1589  * @param n      the node to be copied
1590  *
1591  * @return the copy of n
1592  */
1593 static ir_node *create_Copy(x87_state *state, ir_node *n)
1594 {
1595         dbg_info *n_dbg = get_irn_dbg_info(n);
1596         ir_mode *mode = get_irn_mode(n);
1597         ir_node *block = get_nodes_block(n);
1598         ir_node *pred = get_irn_n(n, 0);
1599         ir_node *(*cnstr)(dbg_info *, ir_node *, ir_mode *) = NULL;
1600         ir_node *res;
1601         const arch_register_t *out;
1602         const arch_register_t *op1;
1603         ia32_x87_attr_t *attr;
1604
1605         /* Do not copy constants, recreate them. */
1606         switch (get_ia32_irn_opcode(pred)) {
1607         case iro_ia32_fldz:
1608                 cnstr = new_bd_ia32_fldz;
1609                 break;
1610         case iro_ia32_fld1:
1611                 cnstr = new_bd_ia32_fld1;
1612                 break;
1613         case iro_ia32_fldpi:
1614                 cnstr = new_bd_ia32_fldpi;
1615                 break;
1616         case iro_ia32_fldl2e:
1617                 cnstr = new_bd_ia32_fldl2e;
1618                 break;
1619         case iro_ia32_fldl2t:
1620                 cnstr = new_bd_ia32_fldl2t;
1621                 break;
1622         case iro_ia32_fldlg2:
1623                 cnstr = new_bd_ia32_fldlg2;
1624                 break;
1625         case iro_ia32_fldln2:
1626                 cnstr = new_bd_ia32_fldln2;
1627                 break;
1628         default:
1629                 break;
1630         }
1631
1632         out = x87_get_irn_register(n);
1633         op1 = x87_get_irn_register(pred);
1634
1635         if (cnstr != NULL) {
1636                 /* copy a constant */
1637                 res = (*cnstr)(n_dbg, block, mode);
1638
1639                 x87_push(state, arch_register_get_index(out), res);
1640
1641                 attr = get_ia32_x87_attr(res);
1642                 attr->x87[2] = get_st_reg(0);
1643         } else {
1644                 int op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1645
1646                 res = new_bd_ia32_fpushCopy(n_dbg, block, pred, mode);
1647
1648                 x87_push(state, arch_register_get_index(out), res);
1649
1650                 attr = get_ia32_x87_attr(res);
1651                 attr->x87[0] = get_st_reg(op1_idx);
1652                 attr->x87[2] = get_st_reg(0);
1653         }
1654         arch_set_irn_register(res, out);
1655
1656         return res;
1657 }
1658
1659 /**
1660  * Simulate a be_Copy.
1661  *
1662  * @param state  the x87 state
1663  * @param n      the node that should be simulated (and patched)
1664  *
1665  * @return NO_NODE_ADDED
1666  */
1667 static int sim_Copy(x87_state *state, ir_node *n)
1668 {
1669         arch_register_class_t const *const cls = arch_get_irn_reg_class(n);
1670         if (cls != &ia32_reg_classes[CLASS_ia32_vfp])
1671                 return NO_NODE_ADDED;
1672
1673         ir_node               *const pred = be_get_Copy_op(n);
1674         arch_register_t const *const op1  = x87_get_irn_register(pred);
1675         arch_register_t const *const out  = x87_get_irn_register(n);
1676         unsigned               const live = vfp_live_args_after(state->sim, n, REGMASK(out));
1677
1678         DB((dbg, LEVEL_1, ">>> %+F %s -> %s\n", n,
1679                 arch_register_get_name(op1), arch_register_get_name(out)));
1680         DEBUG_ONLY(vfp_dump_live(live);)
1681
1682         if (is_vfp_live(arch_register_get_index(op1), live)) {
1683                 /* Operand is still live, a real copy. We need here an fpush that can
1684                    hold a a register, so use the fpushCopy or recreate constants */
1685                 ir_node *const node = create_Copy(state, n);
1686
1687                 /* We have to make sure the old value doesn't go dead (which can happen
1688                  * when we recreate constants). As the simulator expected that value in
1689                  * the pred blocks. This is unfortunate as removing it would save us 1
1690                  * instruction, but we would have to rerun all the simulation to get
1691                  * this correct...
1692                  */
1693                 ir_node *const next = sched_next(n);
1694                 sched_remove(n);
1695                 exchange(n, node);
1696                 sched_add_before(next, node);
1697
1698                 if (get_irn_n_edges(pred) == 0) {
1699                         keep_float_node_alive(pred);
1700                 }
1701
1702                 DB((dbg, LEVEL_1, "<<< %+F %s -> ?\n", node, op1->name));
1703         } else {
1704                 int const op1_idx = x87_on_stack(state, arch_register_get_index(op1));
1705                 int const out_idx = x87_on_stack(state, arch_register_get_index(out));
1706                 if (out_idx >= 0 && out_idx != op1_idx) {
1707                         /* Matze: out already on stack? how can this happen? */
1708                         panic("invalid stack state");
1709
1710 #if 0
1711                         /* op1 must be killed and placed where out is */
1712                         if (out_idx == 0) {
1713                                 ia32_x87_attr_t *attr;
1714                                 /* best case, simple remove and rename */
1715                                 x87_patch_insn(n, op_ia32_Pop);
1716                                 attr = get_ia32_x87_attr(n);
1717                                 attr->x87[0] = op1 = get_st_reg(0);
1718
1719                                 x87_pop(state);
1720                                 x87_set_st(state, arch_register_get_index(out), n, op1_idx - 1);
1721                         } else {
1722                                 ia32_x87_attr_t *attr;
1723                                 /* move op1 to tos, store and pop it */
1724                                 if (op1_idx != 0) {
1725                                         x87_create_fxch(state, n, op1_idx);
1726                                         op1_idx = 0;
1727                                 }
1728                                 x87_patch_insn(n, op_ia32_Pop);
1729                                 attr = get_ia32_x87_attr(n);
1730                                 attr->x87[0] = op1 = get_st_reg(out_idx);
1731
1732                                 x87_pop(state);
1733                                 x87_set_st(state, arch_register_get_index(out), n, out_idx - 1);
1734                         }
1735                         DB((dbg, LEVEL_1, "<<< %+F %s\n", n, op1->name));
1736 #endif
1737                 } else {
1738                         /* just a virtual copy */
1739                         x87_set_st(state, arch_register_get_index(out), pred, op1_idx);
1740                         /* don't remove the node to keep the verifier quiet :),
1741                            the emitter won't emit any code for the node */
1742 #if 0
1743                         sched_remove(n);
1744                         DB((dbg, LEVEL_1, "<<< KILLED %s\n", get_irn_opname(n)));
1745                         exchange(n, pred);
1746 #endif
1747                 }
1748         }
1749         return NO_NODE_ADDED;
1750 }
1751
1752 /**
1753  * Returns the vf0 result Proj of a Call.
1754  *
1755  * @para call  the Call node
1756  */
1757 static ir_node *get_call_result_proj(ir_node *call)
1758 {
1759         /* search the result proj */
1760         foreach_out_edge(call, edge) {
1761                 ir_node *proj = get_edge_src_irn(edge);
1762                 long pn = get_Proj_proj(proj);
1763
1764                 if (pn == pn_ia32_Call_vf0)
1765                         return proj;
1766         }
1767
1768         panic("result Proj missing");
1769 }
1770
1771 static int sim_Asm(x87_state *const state, ir_node *const n)
1772 {
1773         (void)state;
1774
1775         for (size_t i = get_irn_arity(n); i-- != 0;) {
1776                 arch_register_req_t const *const req = arch_get_irn_register_req_in(n, i);
1777                 if (req->cls == &ia32_reg_classes[CLASS_ia32_vfp])
1778                         panic("cannot handle %+F with x87 constraints", n);
1779         }
1780
1781         for (size_t i = arch_get_irn_n_outs(n); i-- != 0;) {
1782                 arch_register_req_t const *const req = arch_get_irn_register_req_out(n, i);
1783                 if (req->cls == &ia32_reg_classes[CLASS_ia32_vfp])
1784                         panic("cannot handle %+F with x87 constraints", n);
1785         }
1786
1787         return NO_NODE_ADDED;
1788 }
1789
1790 /**
1791  * Simulate a ia32_Call.
1792  *
1793  * @param state      the x87 state
1794  * @param n          the node that should be simulated (and patched)
1795  *
1796  * @return NO_NODE_ADDED
1797  */
1798 static int sim_Call(x87_state *state, ir_node *n)
1799 {
1800         DB((dbg, LEVEL_1, ">>> %+F\n", n));
1801
1802         /* at the begin of a call the x87 state should be empty */
1803         assert(state->depth == 0 && "stack not empty before call");
1804
1805         ir_type *const call_tp = get_ia32_call_attr_const(n)->call_tp;
1806         if (get_method_n_ress(call_tp) != 0) {
1807                 /* If the called function returns a float, it is returned in st(0).
1808                  * This even happens if the return value is NOT used.
1809                  * Moreover, only one return result is supported. */
1810                 ir_type *const res_type = get_method_res_type(call_tp, 0);
1811                 ir_mode *const mode     = get_type_mode(res_type);
1812                 if (mode && mode_is_float(mode)) {
1813                         ir_node               *const resproj = get_call_result_proj(n);
1814                         arch_register_t const *const reg     = x87_get_irn_register(resproj);
1815                         x87_push(state, arch_register_get_index(reg), resproj);
1816                 }
1817         }
1818         DB((dbg, LEVEL_1, "Stack after: "));
1819         DEBUG_ONLY(x87_dump_stack(state);)
1820
1821         return NO_NODE_ADDED;
1822 }
1823
1824 /**
1825  * Simulate a be_Return.
1826  *
1827  * @param state  the x87 state
1828  * @param n      the node that should be simulated (and patched)
1829  *
1830  * @return NO_NODE_ADDED
1831  */
1832 static int sim_Return(x87_state *state, ir_node *n)
1833 {
1834 #ifdef DEBUG_libfirm
1835         /* only floating point return values must reside on stack */
1836         int       n_float_res = 0;
1837         int const n_res       = be_Return_get_n_rets(n);
1838         for (int i = 0; i < n_res; ++i) {
1839                 ir_node *const res = get_irn_n(n, n_be_Return_val + i);
1840                 if (mode_is_float(get_irn_mode(res)))
1841                         ++n_float_res;
1842         }
1843         assert(x87_get_depth(state) == n_float_res);
1844 #endif
1845
1846         /* pop them virtually */
1847         x87_emms(state);
1848         return NO_NODE_ADDED;
1849 }
1850
1851 /**
1852  * Simulate a be_Perm.
1853  *
1854  * @param state  the x87 state
1855  * @param irn    the node that should be simulated (and patched)
1856  *
1857  * @return NO_NODE_ADDED
1858  */
1859 static int sim_Perm(x87_state *state, ir_node *irn)
1860 {
1861         int      i, n;
1862         ir_node *pred = get_irn_n(irn, 0);
1863         int     *stack_pos;
1864
1865         /* handle only floating point Perms */
1866         if (! mode_is_float(get_irn_mode(pred)))
1867                 return NO_NODE_ADDED;
1868
1869         DB((dbg, LEVEL_1, ">>> %+F\n", irn));
1870
1871         /* Perm is a pure virtual instruction on x87.
1872            All inputs must be on the FPU stack and are pairwise
1873            different from each other.
1874            So, all we need to do is to permutate the stack state. */
1875         n = get_irn_arity(irn);
1876         NEW_ARR_A(int, stack_pos, n);
1877
1878         /* collect old stack positions */
1879         for (i = 0; i < n; ++i) {
1880                 const arch_register_t *inreg = x87_get_irn_register(get_irn_n(irn, i));
1881                 int idx = x87_on_stack(state, arch_register_get_index(inreg));
1882
1883                 assert(idx >= 0 && "Perm argument not on x87 stack");
1884
1885                 stack_pos[i] = idx;
1886         }
1887         /* now do the permutation */
1888         foreach_out_edge(irn, edge) {
1889                 ir_node               *proj = get_edge_src_irn(edge);
1890                 const arch_register_t *out  = x87_get_irn_register(proj);
1891                 long                  num   = get_Proj_proj(proj);
1892
1893                 assert(0 <= num && num < n && "More Proj's than Perm inputs");
1894                 x87_set_st(state, arch_register_get_index(out), proj, stack_pos[(unsigned)num]);
1895         }
1896         DB((dbg, LEVEL_1, "<<< %+F\n", irn));
1897
1898         return NO_NODE_ADDED;
1899 }
1900
1901 /**
1902  * Kill any dead registers at block start by popping them from the stack.
1903  *
1904  * @param sim    the simulator handle
1905  * @param block  the current block
1906  * @param state  the x87 state at the begin of the block
1907  */
1908 static void x87_kill_deads(x87_simulator *const sim, ir_node *const block, x87_state *const state)
1909 {
1910         ir_node *first_insn = sched_first(block);
1911         ir_node *keep = NULL;
1912         unsigned live = vfp_live_args_after(sim, block, 0);
1913         unsigned kill_mask;
1914         int i, depth, num_pop;
1915
1916         kill_mask = 0;
1917         depth = x87_get_depth(state);
1918         for (i = depth - 1; i >= 0; --i) {
1919                 int reg = x87_get_st_reg(state, i);
1920
1921                 if (! is_vfp_live(reg, live))
1922                         kill_mask |= (1 << i);
1923         }
1924
1925         if (kill_mask) {
1926                 DB((dbg, LEVEL_1, "Killing deads:\n"));
1927                 DEBUG_ONLY(vfp_dump_live(live);)
1928                 DEBUG_ONLY(x87_dump_stack(state);)
1929
1930                 if (kill_mask != 0 && live == 0) {
1931                         /* special case: kill all registers */
1932                         if (ia32_cg_config.use_femms || ia32_cg_config.use_emms) {
1933                                 if (ia32_cg_config.use_femms) {
1934                                         /* use FEMMS on AMD processors to clear all */
1935                                         keep = new_bd_ia32_femms(NULL, block);
1936                                 } else {
1937                                         /* use EMMS to clear all */
1938                                         keep = new_bd_ia32_emms(NULL, block);
1939                                 }
1940                                 sched_add_before(first_insn, keep);
1941                                 keep_alive(keep);
1942                                 x87_emms(state);
1943                                 return;
1944                         }
1945                 }
1946                 /* now kill registers */
1947                 while (kill_mask) {
1948                         /* we can only kill from TOS, so bring them up */
1949                         if (! (kill_mask & 1)) {
1950                                 /* search from behind, because we can to a double-pop */
1951                                 for (i = depth - 1; i >= 0; --i) {
1952                                         if (kill_mask & (1 << i)) {
1953                                                 kill_mask &= ~(1 << i);
1954                                                 kill_mask |= 1;
1955                                                 break;
1956                                         }
1957                                 }
1958
1959                                 if (keep)
1960                                         x87_set_st(state, -1, keep, i);
1961                                 x87_create_fxch(state, first_insn, i);
1962                         }
1963
1964                         if ((kill_mask & 3) == 3) {
1965                                 /* we can do a double-pop */
1966                                 num_pop = 2;
1967                         }
1968                         else {
1969                                 /* only a single pop */
1970                                 num_pop = 1;
1971                         }
1972
1973                         depth -= num_pop;
1974                         kill_mask >>= num_pop;
1975                         keep = x87_create_fpop(state, first_insn, num_pop);
1976                 }
1977                 keep_alive(keep);
1978         }
1979 }
1980
1981 /**
1982  * Run a simulation and fix all virtual instructions for a block.
1983  *
1984  * @param sim          the simulator handle
1985  * @param block        the current block
1986  */
1987 static void x87_simulate_block(x87_simulator *sim, ir_node *block)
1988 {
1989         ir_node *n, *next;
1990         blk_state *bl_state = x87_get_bl_state(sim, block);
1991         x87_state *state = bl_state->begin;
1992         ir_node *start_block;
1993
1994         assert(state != NULL);
1995         /* already processed? */
1996         if (bl_state->end != NULL)
1997                 return;
1998
1999         DB((dbg, LEVEL_1, "Simulate %+F\n", block));
2000         DB((dbg, LEVEL_2, "State at Block begin:\n "));
2001         DEBUG_ONLY(x87_dump_stack(state);)
2002
2003         /* create a new state, will be changed */
2004         state = x87_clone_state(sim, state);
2005         /* at block begin, kill all dead registers */
2006         x87_kill_deads(sim, block, state);
2007
2008         /* beware, n might change */
2009         for (n = sched_first(block); !sched_is_end(n); n = next) {
2010                 int node_inserted;
2011                 sim_func func;
2012                 ir_op *op = get_irn_op(n);
2013
2014                 /*
2015                  * get the next node to be simulated here.
2016                  * n might be completely removed from the schedule-
2017                  */
2018                 next = sched_next(n);
2019                 if (op->ops.generic != NULL) {
2020                         func = (sim_func)op->ops.generic;
2021
2022                         /* simulate it */
2023                         node_inserted = (*func)(state, n);
2024
2025                         /*
2026                          * sim_func might have added an additional node after n,
2027                          * so update next node
2028                          * beware: n must not be changed by sim_func
2029                          * (i.e. removed from schedule) in this case
2030                          */
2031                         if (node_inserted != NO_NODE_ADDED)
2032                                 next = sched_next(n);
2033                 }
2034         }
2035
2036         start_block = get_irg_start_block(get_irn_irg(block));
2037
2038         DB((dbg, LEVEL_2, "State at Block end:\n ")); DEBUG_ONLY(x87_dump_stack(state);)
2039
2040         /* check if the state must be shuffled */
2041         foreach_block_succ(block, edge) {
2042                 ir_node *succ = get_edge_src_irn(edge);
2043                 blk_state *succ_state;
2044
2045                 if (succ == start_block)
2046                         continue;
2047
2048                 succ_state = x87_get_bl_state(sim, succ);
2049
2050                 if (succ_state->begin == NULL) {
2051                         DB((dbg, LEVEL_2, "Set begin state for succ %+F:\n", succ));
2052                         DEBUG_ONLY(x87_dump_stack(state);)
2053                         succ_state->begin = state;
2054
2055                         waitq_put(sim->worklist, succ);
2056                 } else {
2057                         DB((dbg, LEVEL_2, "succ %+F already has a state, shuffling\n", succ));
2058                         /* There is already a begin state for the successor, bad.
2059                            Do the necessary permutations.
2060                            Note that critical edges are removed, so this is always possible:
2061                            If the successor has more than one possible input, then it must
2062                            be the only one.
2063                          */
2064                         x87_shuffle(block, state, succ_state->begin);
2065                 }
2066         }
2067         bl_state->end = state;
2068 }
2069
2070 /**
2071  * Register a simulator function.
2072  *
2073  * @param op    the opcode to simulate
2074  * @param func  the simulator function for the opcode
2075  */
2076 static void register_sim(ir_op *op, sim_func func)
2077 {
2078         assert(op->ops.generic == NULL);
2079         op->ops.generic = (op_func) func;
2080 }
2081
2082 /**
2083  * Create a new x87 simulator.
2084  *
2085  * @param sim       a simulator handle, will be initialized
2086  * @param irg       the current graph
2087  */
2088 static void x87_init_simulator(x87_simulator *sim, ir_graph *irg)
2089 {
2090         obstack_init(&sim->obst);
2091         sim->blk_states = pmap_create();
2092         sim->n_idx      = get_irg_last_idx(irg);
2093         sim->live       = OALLOCN(&sim->obst, vfp_liveness, sim->n_idx);
2094
2095         DB((dbg, LEVEL_1, "--------------------------------\n"
2096                 "x87 Simulator started for %+F\n", irg));
2097
2098         /* set the generic function pointer of instruction we must simulate */
2099         ir_clear_opcodes_generic_func();
2100
2101         register_sim(op_ia32_Asm,          sim_Asm);
2102         register_sim(op_ia32_Call,         sim_Call);
2103         register_sim(op_ia32_vfld,         sim_fld);
2104         register_sim(op_ia32_vfild,        sim_fild);
2105         register_sim(op_ia32_vfld1,        sim_fld1);
2106         register_sim(op_ia32_vfldz,        sim_fldz);
2107         register_sim(op_ia32_vfadd,        sim_fadd);
2108         register_sim(op_ia32_vfsub,        sim_fsub);
2109         register_sim(op_ia32_vfmul,        sim_fmul);
2110         register_sim(op_ia32_vfdiv,        sim_fdiv);
2111         register_sim(op_ia32_vfprem,       sim_fprem);
2112         register_sim(op_ia32_vfabs,        sim_fabs);
2113         register_sim(op_ia32_vfchs,        sim_fchs);
2114         register_sim(op_ia32_vfist,        sim_fist);
2115         register_sim(op_ia32_vfisttp,      sim_fisttp);
2116         register_sim(op_ia32_vfst,         sim_fst);
2117         register_sim(op_ia32_vFtstFnstsw,  sim_FtstFnstsw);
2118         register_sim(op_ia32_vFucomFnstsw, sim_Fucom);
2119         register_sim(op_ia32_vFucomi,      sim_Fucom);
2120         register_sim(op_be_Copy,           sim_Copy);
2121         register_sim(op_be_Return,         sim_Return);
2122         register_sim(op_be_Perm,           sim_Perm);
2123         register_sim(op_be_Keep,           sim_Keep);
2124 }
2125
2126 /**
2127  * Destroy a x87 simulator.
2128  *
2129  * @param sim  the simulator handle
2130  */
2131 static void x87_destroy_simulator(x87_simulator *sim)
2132 {
2133         pmap_destroy(sim->blk_states);
2134         obstack_free(&sim->obst, NULL);
2135         DB((dbg, LEVEL_1, "x87 Simulator stopped\n\n"));
2136 }
2137
2138 /**
2139  * Pre-block walker: calculate the liveness information for the block
2140  * and store it into the sim->live cache.
2141  */
2142 static void update_liveness_walker(ir_node *block, void *data)
2143 {
2144         x87_simulator *sim = (x87_simulator*)data;
2145         update_liveness(sim, block);
2146 }
2147
2148 /*
2149  * Run a simulation and fix all virtual instructions for a graph.
2150  * Replaces all virtual floating point instructions and registers
2151  * by real ones.
2152  */
2153 void ia32_x87_simulate_graph(ir_graph *irg)
2154 {
2155         /* TODO improve code quality (less executed fxch) by using execfreqs */
2156
2157         ir_node       *block, *start_block;
2158         blk_state     *bl_state;
2159         x87_simulator sim;
2160
2161         /* create the simulator */
2162         x87_init_simulator(&sim, irg);
2163
2164         start_block = get_irg_start_block(irg);
2165         bl_state    = x87_get_bl_state(&sim, start_block);
2166
2167         /* start with the empty state */
2168         empty.sim       = &sim;
2169         bl_state->begin = &empty;
2170
2171         sim.worklist = new_waitq();
2172         waitq_put(sim.worklist, start_block);
2173
2174         be_assure_live_sets(irg);
2175         sim.lv = be_get_irg_liveness(irg);
2176
2177         /* Calculate the liveness for all nodes. We must precalculate this info,
2178          * because the simulator adds new nodes (possible before Phi nodes) which
2179          * would let a lazy calculation fail.
2180          * On the other hand we reduce the computation amount due to
2181          * precaching from O(n^2) to O(n) at the expense of O(n) cache memory.
2182          */
2183         irg_block_walk_graph(irg, update_liveness_walker, NULL, &sim);
2184
2185         /* iterate */
2186         do {
2187                 block = (ir_node*)waitq_get(sim.worklist);
2188                 x87_simulate_block(&sim, block);
2189         } while (! waitq_empty(sim.worklist));
2190
2191         /* kill it */
2192         del_waitq(sim.worklist);
2193         x87_destroy_simulator(&sim);
2194 }
2195
2196 /* Initializes the x87 simulator. */
2197 void ia32_init_x87(void)
2198 {
2199         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.x87");
2200 }