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