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