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