- use ir_nodemap_t instead of pset: This probably
[libfirm] / ir / be / belower.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Performs lowering of perm nodes. Inserts copies to assure register constraints.
23  * @author      Christian Wuerdig
24  * @date        14.12.2005
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include <stdlib.h>
30
31 #include "ircons.h"
32 #include "debug.h"
33 #include "irhooks.h"
34 #include "xmalloc.h"
35 #include "irnodeset.h"
36 #include "irnodemap.h"
37 #include "irgmod.h"
38 #include "iredges_t.h"
39 #include "irgwalk.h"
40 #include "array_t.h"
41
42 #include "bearch_t.h"
43 #include "belower.h"
44 #include "benode_t.h"
45 #include "besched_t.h"
46 #include "bestat.h"
47 #include "bessaconstr.h"
48 #include "beintlive_t.h"
49
50 #undef KEEP_ALIVE_COPYKEEP_HACK
51
52 /** Associates an ir_node with it's copy and CopyKeep. */
53 typedef struct {
54         ir_nodeset_t copies; /**< all non-spillable copies of this irn */
55         const arch_register_class_t *cls;
56 } op_copy_assoc_t;
57
58 /** Environment for constraints. */
59 typedef struct {
60         be_irg_t       *birg;
61         ir_nodemap_t   op_set;
62         struct obstack obst;
63         DEBUG_ONLY(firm_dbg_module_t *dbg;)
64 } constraint_env_t;
65
66 /** Lowering walker environment. */
67 typedef struct _lower_env_t {
68         be_irg_t         *birg;
69         unsigned          do_copy : 1;
70         DEBUG_ONLY(firm_dbg_module_t *dbg_module;)
71 } lower_env_t;
72
73 /** Holds a Perm register pair. */
74 typedef struct _reg_pair_t {
75         const arch_register_t *in_reg;    /**< a perm IN register */
76         ir_node               *in_node;   /**< the in node to which the register belongs */
77
78         const arch_register_t *out_reg;   /**< a perm OUT register */
79         ir_node               *out_node;  /**< the out node to which the register belongs */
80
81         int                    checked;   /**< indicates whether the pair was check for cycle or not */
82 } reg_pair_t;
83
84 typedef enum _perm_type_t {
85         PERM_CYCLE,
86         PERM_CHAIN,
87         PERM_SWAP,
88         PERM_COPY
89 } perm_type_t;
90
91 /** Structure to represent cycles or chains in a Perm. */
92 typedef struct _perm_cycle_t {
93         const arch_register_t **elems;       /**< the registers in the cycle */
94         int                     n_elems;     /**< number of elements in the cycle */
95         perm_type_t             type;        /**< type (CHAIN or CYCLE) */
96 } perm_cycle_t;
97
98 /** Compare the in registers of two register pairs. */
99 static int compare_reg_pair(const void *a, const void *b) {
100         const reg_pair_t *pair_a = a;
101         const reg_pair_t *pair_b = b;
102
103         if (pair_a->in_reg->index > pair_b->in_reg->index)
104                 return 1;
105         else
106                 return -1;
107 }
108
109 /** returns the number register pairs marked as checked. */
110 static int get_n_checked_pairs(reg_pair_t *pairs, int n) {
111         int i, n_checked = 0;
112
113         for (i = 0; i < n; i++) {
114                 if (pairs[i].checked)
115                         n_checked++;
116         }
117
118         return n_checked;
119 }
120
121 /**
122  * Gets the node corresponding to a register from an array of register pairs.
123  * NOTE: The given registers pairs and the register to look for must belong
124  *       to the same register class.
125  *
126  * @param pairs  The array of register pairs
127  * @param n      The number of pairs
128  * @param reg    The register to look for
129  * @param in_out 0 == look for IN register, 1 == look for OUT register
130  * @return The corresponding node or NULL if not found
131  */
132 static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_register_t *reg, int in_out) {
133         int i;
134
135         if (in_out) {
136                 for (i = 0; i < n; i++) {
137                         /* out register matches */
138                         if (pairs[i].out_reg->index == reg->index)
139                                 return pairs[i].out_node;
140                 }
141         }
142         else {
143                 for (i = 0; i < n; i++) {
144                         /* in register matches */
145                         if (pairs[i].in_reg->index == reg->index)
146                                 return pairs[i].in_node;
147                 }
148         }
149
150         return NULL;
151 }
152
153 /**
154  * Gets the index in the register pair array where the in/out register
155  * corresponds to reg_idx.
156  *
157  * @param pairs  The array of register pairs
158  * @param n      The number of pairs
159  * @param reg    The register index to look for
160  * @param in_out 0 == look for IN register, 1 == look for OUT register
161  * @return The corresponding index in pairs or -1 if not found
162  */
163 static int get_pairidx_for_regidx(reg_pair_t *pairs, int n, int reg_idx, int in_out) {
164         int i;
165
166         if (in_out) {
167                 for (i = 0; i < n; i++) {
168                         /* out register matches */
169                         if ((int) pairs[i].out_reg->index == reg_idx)
170                                 return i;
171                 }
172         }
173         else {
174                 for (i = 0; i < n; i++) {
175                         /* in register matches */
176                         if ((int) pairs[i].in_reg->index == reg_idx)
177                                 return i;
178                 }
179         }
180
181         return -1;
182 }
183
184 /**
185  * Gets an array of register pairs and tries to identify a cycle or chain starting
186  * at position start.
187  *
188  * @param cycle Variable to hold the cycle
189  * @param pairs Array of register pairs
190  * @param start Index to start
191  * @return The cycle or chain
192  */
193 static perm_cycle_t *get_perm_cycle(perm_cycle_t *cycle, reg_pair_t *pairs, int n, int start) {
194         int head         = pairs[start].in_reg->index;
195         int cur_idx      = pairs[start].out_reg->index;
196         int cur_pair_idx = start;
197         int n_pairs_done = get_n_checked_pairs(pairs, n);
198         int idx;
199         perm_type_t cycle_tp = PERM_CYCLE;
200
201         /* We could be right in the middle of a chain, so we need to find the start */
202         while (head != cur_idx) {
203                 /* goto previous register in cycle or chain */
204                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, head, 1);
205
206                 if (cur_pair_idx < 0) {
207                         cycle_tp = PERM_CHAIN;
208                         break;
209                 }
210                 else {
211                         head  = pairs[cur_pair_idx].in_reg->index;
212                         start = cur_pair_idx;
213                 }
214         }
215
216         /* assume worst case: all remaining pairs build a cycle or chain */
217         cycle->elems    = XMALLOCNZ(const arch_register_t*, (n - n_pairs_done) * 2);
218         cycle->n_elems  = 2;  /* initial number of elements is 2 */
219         cycle->elems[0] = pairs[start].in_reg;
220         cycle->elems[1] = pairs[start].out_reg;
221         cycle->type     = cycle_tp;
222         cur_idx         = pairs[start].out_reg->index;
223
224         idx = 2;
225         /* check for cycle or end of a chain */
226         while (cur_idx != head) {
227                 /* goto next register in cycle or chain */
228                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cur_idx, 0);
229
230                 if (cur_pair_idx < 0)
231                         break;
232
233                 cur_idx = pairs[cur_pair_idx].out_reg->index;
234
235                 /* it's not the first element: insert it */
236                 if (cur_idx != head) {
237                         cycle->elems[idx++] = pairs[cur_pair_idx].out_reg;
238                         cycle->n_elems++;
239                 }
240                 else {
241                         /* we are there where we started -> CYCLE */
242                         cycle->type = PERM_CYCLE;
243                 }
244         }
245
246         /* mark all pairs having one in/out register with cycle in common as checked */
247         for (idx = 0; idx < cycle->n_elems; idx++) {
248                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 0);
249
250                 if (cur_pair_idx >= 0)
251                         pairs[cur_pair_idx].checked = 1;
252
253                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 1);
254
255                 if (cur_pair_idx >= 0)
256                         pairs[cur_pair_idx].checked = 1;
257         }
258
259         return cycle;
260 }
261
262 /**
263  * Lowers a perm node.  Resolves cycles and creates a bunch of
264  * copy and swap operations to permute registers.
265  * Note: The caller of this function has to make sure, that irn
266  *       is a Perm node.
267  *
268  * @param irn      The perm node
269  * @param block    The block the perm node belongs to
270  * @param walk_env The environment
271  */
272 static void lower_perm_node(ir_node *irn, void *walk_env) {
273         ir_graph        *irg = get_irn_irg(irn);
274         const arch_register_class_t *reg_class;
275         lower_env_t     *env         = walk_env;
276         int             real_size    = 0;
277         int             keep_perm    = 0;
278         int             n, i, pn, do_copy, j, n_ops;
279         reg_pair_t      *pairs;
280         const ir_edge_t *edge;
281         ir_node         *sched_point, *block, *in[2];
282         ir_node         *arg1, *arg2, *res1, *res2;
283         ir_node         *cpyxchg = NULL;
284         DEBUG_ONLY(firm_dbg_module_t *mod;)
285
286         do_copy  = env->do_copy;
287         DEBUG_ONLY(mod = env->dbg_module;)
288         block    = get_nodes_block(irn);
289
290         /*
291                 Get the schedule predecessor node to the perm
292                 NOTE: This works with auto-magic. If we insert the
293                         new copy/exchange nodes after this node, everything
294                         should be ok.
295         */
296         sched_point = sched_prev(irn);
297         DBG((mod, LEVEL_1, "perm: %+F\n", irn));
298         DBG((mod, LEVEL_1, "sched point is %+F\n", sched_point));
299         assert(sched_point && "Perm is not scheduled or has no predecessor");
300
301         n = get_irn_arity(irn);
302         assert(n == get_irn_n_edges(irn) && "perm's in and out numbers different");
303
304         reg_class = arch_get_irn_register(get_irn_n(irn, 0))->reg_class;
305         pairs     = alloca(n * sizeof(pairs[0]));
306
307         /* build the list of register pairs (in, out) */
308         i = 0;
309         foreach_out_edge(irn, edge) {
310                 pairs[i].out_node = get_edge_src_irn(edge);
311                 pn                = get_Proj_proj(pairs[i].out_node);
312                 pairs[i].in_node  = get_irn_n(irn, pn);
313
314                 pairs[i].in_reg  = arch_get_irn_register(pairs[i].in_node);
315                 pairs[i].out_reg = arch_get_irn_register(pairs[i].out_node);
316
317                 pairs[i].checked = 0;
318                 i++;
319         }
320
321         /* sort the register pairs by the indices of the in registers */
322         qsort(pairs, n, sizeof(pairs[0]), compare_reg_pair);
323
324         /* Mark all equal pairs as checked, and exchange the OUT proj with
325                 the IN node. */
326         for (i = 0; i < n; i++) {
327                 if (pairs[i].in_reg->index == pairs[i].out_reg->index) {
328                         DBG((mod, LEVEL_1, "%+F removing equal perm register pair (%+F, %+F, %s)\n",
329                                 irn, pairs[i].in_node, pairs[i].out_node, pairs[i].out_reg->name));
330
331                         /* We have to check for a special case:
332                                 The in-node could be a Proj from a Perm. In this case,
333                                 we need to correct the projnum */
334                         if (be_is_Perm(pairs[i].in_node) && is_Proj(pairs[i].in_node)) {
335                                 set_Proj_proj(pairs[i].out_node, get_Proj_proj(pairs[i].in_node));
336                         }
337
338                         /* reroute the edges from the proj to the argument */
339                         exchange(pairs[i].out_node, pairs[i].in_node);
340                         //edges_reroute(pairs[i].out_node, pairs[i].in_node, env->birg->irg);
341                         //set_irn_n(pairs[i].out_node, 0, new_Bad());
342
343                         pairs[i].checked = 1;
344                 }
345         }
346
347         /* Set do_copy to 0 if it's on but we have no free register */
348         if (do_copy) {
349                 do_copy = 0;
350         }
351
352         real_size = n - get_n_checked_pairs(pairs, n);
353
354         /* check for cycles and chains */
355         while (get_n_checked_pairs(pairs, n) < n) {
356                 perm_cycle_t *cycle;
357
358                 i = n_ops = 0;
359
360                 /* go to the first not-checked pair */
361                 while (pairs[i].checked) i++;
362                 cycle = XMALLOCZ(perm_cycle_t);
363                 cycle = get_perm_cycle(cycle, pairs, n, i);
364
365                 DB((mod, LEVEL_1, "%+F: following %s created:\n  ", irn, cycle->type == PERM_CHAIN ? "chain" : "cycle"));
366                 for (j = 0; j < cycle->n_elems; j++) {
367                         DB((mod, LEVEL_1, " %s", cycle->elems[j]->name));
368                 }
369                 DB((mod, LEVEL_1, "\n"));
370
371                 /*
372                         We don't need to do anything if we have a Perm with two
373                         elements which represents a cycle, because those nodes
374                         already represent exchange nodes
375                 */
376                 if (n == 2 && cycle->type == PERM_CYCLE) {
377                         free(cycle);
378                         keep_perm = 1;
379                         continue;
380                 }
381
382 //TODO: - iff PERM_CYCLE && do_copy -> determine free temp reg and insert copy to/from it before/after
383 //        the copy cascade (this reduces the cycle into a chain)
384
385                 /* build copy/swap nodes from back to front */
386                 for (i = cycle->n_elems - 2; i >= 0; i--) {
387                         arg1 = get_node_for_register(pairs, n, cycle->elems[i], 0);
388                         arg2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 0);
389
390                         res1 = get_node_for_register(pairs, n, cycle->elems[i], 1);
391                         res2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 1);
392                         /*
393                                 If we have a cycle and don't copy: we need to create exchange nodes
394                                 NOTE: An exchange node is a perm node with 2 INs and 2 OUTs
395                                 IN_1  = in node with register i
396                                 IN_2  = in node with register i + 1
397                                 OUT_1 = out node with register i + 1
398                                 OUT_2 = out node with register i
399                         */
400                         if (cycle->type == PERM_CYCLE && !do_copy) {
401                                 in[0] = arg1;
402                                 in[1] = arg2;
403
404                                 /* At this point we have to handle the following problem:     */
405                                 /*                                                            */
406                                 /* If we have a cycle with more than two elements, then       */
407                                 /* this could correspond to the following Perm node:          */
408                                 /*                                                            */
409                                 /*   +----+   +----+   +----+                                 */
410                                 /*   | r1 |   | r2 |   | r3 |                                 */
411                                 /*   +-+--+   +-+--+   +--+-+                                 */
412                                 /*     |        |         |                                   */
413                                 /*     |        |         |                                   */
414                                 /*   +-+--------+---------+-+                                 */
415                                 /*   |         Perm         |                                 */
416                                 /*   +-+--------+---------+-+                                 */
417                                 /*     |        |         |                                   */
418                                 /*     |        |         |                                   */
419                                 /*   +-+--+   +-+--+   +--+-+                                 */
420                                 /*   |Proj|   |Proj|   |Proj|                                 */
421                                 /*   | r2 |   | r3 |   | r1 |                                 */
422                                 /*   +----+   +----+   +----+                                 */
423                                 /*                                                            */
424                                 /* This node is about to be split up into two 2x Perm's       */
425                                 /* for which we need 4 Proj's and the one additional Proj     */
426                                 /* of the first Perm has to be one IN of the second. So in    */
427                                 /* general we need to create one additional Proj for each     */
428                                 /* "middle" Perm and set this to one in node of the successor */
429                                 /* Perm.                                                      */
430
431                                 DBG((mod, LEVEL_1, "%+F creating exchange node (%+F, %s) and (%+F, %s) with\n",
432                                         irn, arg1, cycle->elems[i]->name, arg2, cycle->elems[i + 1]->name));
433                                 DBG((mod, LEVEL_1, "%+F                        (%+F, %s) and (%+F, %s)\n",
434                                         irn, res1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
435
436                                 cpyxchg = be_new_Perm(reg_class, irg, block, 2, in);
437                                 n_ops++;
438
439                                 if (i > 0) {
440                                         /* cycle is not done yet */
441                                         int pidx = get_pairidx_for_regidx(pairs, n, cycle->elems[i]->index, 0);
442
443                                         /* create intermediate proj */
444                                         res1 = new_r_Proj(irg, block, cpyxchg, get_irn_mode(res1), 0);
445
446                                         /* set as in for next Perm */
447                                         pairs[pidx].in_node = res1;
448                                 }
449
450                                 set_Proj_pred(res2, cpyxchg);
451                                 set_Proj_proj(res2, 0);
452                                 set_Proj_pred(res1, cpyxchg);
453                                 set_Proj_proj(res1, 1);
454
455                                 arch_set_irn_register(res2, cycle->elems[i + 1]);
456                                 arch_set_irn_register(res1, cycle->elems[i]);
457
458                                 /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
459                                 sched_add_after(sched_point, cpyxchg);
460
461                                 DBG((mod, LEVEL_1, "replacing %+F with %+F, placed new node after %+F\n", irn, cpyxchg, sched_point));
462
463                                 /* set the new scheduling point */
464                                 sched_point = res1;
465                         }
466                         else {
467                                 DBG((mod, LEVEL_1, "%+F creating copy node (%+F, %s) -> (%+F, %s)\n",
468                                         irn, arg1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
469
470                                 cpyxchg = be_new_Copy(reg_class, irg, block, arg1);
471                                 arch_set_irn_register(cpyxchg, cycle->elems[i + 1]);
472                                 n_ops++;
473
474                                 /* exchange copy node and proj */
475                                 exchange(res2, cpyxchg);
476
477                                 /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
478                                 sched_add_after(sched_point, cpyxchg);
479
480                                 /* set the new scheduling point */
481                                 sched_point = cpyxchg;
482                         }
483                 }
484
485                 free((void *) cycle->elems);
486                 free(cycle);
487         }
488
489         /* remove the perm from schedule */
490         if (! keep_perm) {
491                 sched_remove(irn);
492                 kill_node(irn);
493         }
494 }
495
496
497
498 static int has_irn_users(const ir_node *irn) {
499         return get_irn_out_edge_first_kind(irn, EDGE_KIND_NORMAL) != 0;
500 }
501
502 /**
503  * Skip all Proj nodes.
504  */
505 static INLINE ir_node *belower_skip_proj(ir_node *irn) {
506         while(is_Proj(irn))
507                 irn = get_Proj_pred(irn);
508         return irn;
509 }
510
511 static ir_node *find_copy(ir_node *irn, ir_node *op)
512 {
513         ir_node *block    = get_nodes_block(irn);
514         ir_node *cur_node;
515
516         for (cur_node = sched_prev(irn);
517                 ! is_Block(cur_node) && be_is_Copy(cur_node) && get_nodes_block(cur_node) == block;
518                 cur_node = sched_prev(cur_node))
519         {
520                 if (be_get_Copy_op(cur_node) == op && arch_irn_is(cur_node, dont_spill))
521                         return cur_node;
522         }
523
524         return NULL;
525 }
526
527 static void gen_assure_different_pattern(ir_node *irn, ir_node *other_different, constraint_env_t *env) {
528         be_irg_t                    *birg     = env->birg;
529         ir_graph                    *irg      = be_get_birg_irg(birg);
530         ir_nodemap_t                *op_set   = &env->op_set;
531         ir_node                     *block    = get_nodes_block(irn);
532         const arch_register_class_t *cls      = arch_get_irn_reg_class(other_different, -1);
533         ir_node                     *in[2], *keep, *cpy;
534         op_copy_assoc_t             *entry;
535         DEBUG_ONLY(firm_dbg_module_t *mod     = env->dbg;)
536
537         if (arch_irn_is(other_different, ignore) ||
538                         !mode_is_datab(get_irn_mode(other_different))) {
539                 DBG((mod, LEVEL_1, "ignore constraint for %+F because other_irn is ignore or not a datab node\n", irn));
540                 return;
541         }
542
543         /* Make a not spillable copy of the different node   */
544         /* this is needed because the different irn could be */
545         /* in block far far away                             */
546         /* The copy is optimized later if not needed         */
547
548         /* check if already exists such a copy in the schedule immediately before */
549         cpy = find_copy(belower_skip_proj(irn), other_different);
550         if (! cpy) {
551                 cpy = be_new_Copy(cls, irg, block, other_different);
552                 be_node_set_flags(cpy, BE_OUT_POS(0), arch_irn_flags_dont_spill);
553                 DBG((mod, LEVEL_1, "created non-spillable %+F for value %+F\n", cpy, other_different));
554         }
555         else {
556                 DBG((mod, LEVEL_1, "using already existing %+F for value %+F\n", cpy, other_different));
557         }
558
559         in[0] = irn;
560         in[1] = cpy;
561
562         /* Add the Keep resp. CopyKeep and reroute the users */
563         /* of the other_different irn in case of CopyKeep.   */
564         if (has_irn_users(other_different)) {
565                 keep = be_new_CopyKeep_single(cls, irg, block, cpy, irn, get_irn_mode(other_different));
566                 be_node_set_reg_class(keep, 1, cls);
567         }
568         else {
569                 keep = be_new_Keep(cls, irg, block, 2, in);
570         }
571
572         DBG((mod, LEVEL_1, "created %+F(%+F, %+F)\n\n", keep, irn, cpy));
573
574         /* insert copy and keep into schedule */
575         assert(sched_is_scheduled(irn) && "need schedule to assure constraints");
576         if (! sched_is_scheduled(cpy))
577                 sched_add_before(belower_skip_proj(irn), cpy);
578         sched_add_after(irn, keep);
579
580         /* insert the other different and it's copies into the map */
581         entry = ir_nodemap_get(op_set, other_different);
582         if (! entry) {
583                 entry      = obstack_alloc(&env->obst, sizeof(*entry));
584                 entry->cls = cls;
585                 ir_nodeset_init(&entry->copies);
586
587                 ir_nodemap_insert(op_set, other_different, entry);
588         }
589
590         /* insert copy */
591         ir_nodeset_insert(&entry->copies, cpy);
592
593         /* insert keep in case of CopyKeep */
594         if (be_is_CopyKeep(keep)) {
595                 ir_nodeset_insert(&entry->copies, keep);
596         }
597 }
598
599 /**
600  * Checks if node has a must_be_different constraint in output and adds a Keep
601  * then to assure the constraint.
602  */
603 static void assure_different_constraints(ir_node *irn, constraint_env_t *env) {
604         ir_node                   *skipped_irn = belower_skip_proj(irn);
605         const arch_register_req_t *req         = arch_get_register_req(irn, -1);
606
607         if (arch_register_req_is(req, must_be_different)) {
608                 const unsigned other = req->other_different;
609                 int i;
610
611                 if (arch_register_req_is(req, should_be_same)) {
612                         const unsigned same = req->other_same;
613
614                         if (is_po2(other) && is_po2(same)) {
615                                 int idx_other = ntz(other);
616                                 int idx_same  = ntz(same);
617
618                                 /*
619                                  * We can safely ignore a should_be_same x must_be_different y
620                                  * IFF both inputs are equal!
621                                  */
622                                 if (get_irn_n(skipped_irn, idx_other) == get_irn_n(skipped_irn, idx_same)) {
623                                         return;
624                                 }
625                         }
626                 }
627                 for (i = 0; 1U << i <= other; ++i) {
628                         if (other & (1U << i)) {
629                                 ir_node *different_from = get_irn_n(skipped_irn, i);
630                                 gen_assure_different_pattern(irn, different_from, env);
631                         }
632                 }
633         }
634 }
635
636 /**
637  * Calls the functions to assure register constraints.
638  *
639  * @param irn      The node to be checked for lowering
640  * @param walk_env The walker environment
641  */
642 static void assure_constraints_walker(ir_node *irn, void *walk_env) {
643         if (is_Block(irn))
644                 return;
645
646         if (sched_is_scheduled(irn) && mode_is_datab(get_irn_mode(irn)))
647                 assure_different_constraints(irn, walk_env);
648 }
649
650 /**
651  * Melt all copykeeps pointing to the same node
652  * (or Projs of the same node), copying the same operand.
653  */
654 static void melt_copykeeps(constraint_env_t *cenv) {
655         be_irg_t *birg = cenv->birg;
656         ir_graph *irg  = be_get_birg_irg(birg);
657         ir_nodemap_iterator_t map_iter;
658         ir_nodemap_entry_t    map_entry;
659
660         /* for all */
661         foreach_ir_nodemap(&cenv->op_set, map_entry, map_iter) {
662                 op_copy_assoc_t *entry = map_entry.data;
663                 int     idx, num_ck;
664                 ir_node *cp;
665                 struct obstack obst;
666                 ir_nodeset_iterator_t iter;
667                 ir_node **ck_arr, **melt_arr;
668
669                 obstack_init(&obst);
670
671                 /* collect all copykeeps */
672                 num_ck = idx = 0;
673                 foreach_ir_nodeset(&entry->copies, cp, iter) {
674                         if (be_is_CopyKeep(cp)) {
675                                 obstack_grow(&obst, &cp, sizeof(cp));
676                                 ++num_ck;
677                         }
678 #ifdef KEEP_ALIVE_COPYKEEP_HACK
679                         else {
680                                 set_irn_mode(cp, mode_ANY);
681                                 keep_alive(cp);
682                         }
683 #endif /* KEEP_ALIVE_COPYKEEP_HACK */
684                 }
685
686                 /* compare each copykeep with all other copykeeps */
687                 ck_arr = (ir_node **)obstack_finish(&obst);
688                 for (idx = 0; idx < num_ck; ++idx) {
689                         ir_node *ref, *ref_mode_T;
690
691                         if (ck_arr[idx]) {
692                                 int j, n_melt;
693                                 ir_node **new_ck_in;
694                                 ir_node *new_ck;
695                                 ir_node *sched_pt = NULL;
696
697                                 n_melt     = 1;
698                                 ref        = ck_arr[idx];
699                                 ref_mode_T = skip_Proj(get_irn_n(ref, 1));
700                                 obstack_grow(&obst, &ref, sizeof(ref));
701
702                                 DBG((cenv->dbg, LEVEL_1, "Trying to melt %+F:\n", ref));
703
704                                 /* check for copykeeps pointing to the same mode_T node as the reference copykeep */
705                                 for (j = 0; j < num_ck; ++j) {
706                                         ir_node *cur_ck = ck_arr[j];
707
708                                         if (j != idx && cur_ck && skip_Proj(get_irn_n(cur_ck, 1)) == ref_mode_T) {
709                                                 obstack_grow(&obst, &cur_ck, sizeof(cur_ck));
710                                                 ir_nodeset_remove(&entry->copies, cur_ck);
711                                                 DBG((cenv->dbg, LEVEL_1, "\t%+F\n", cur_ck));
712                                                 ck_arr[j] = NULL;
713                                                 ++n_melt;
714                                                 sched_remove(cur_ck);
715                                         }
716                                 }
717                                 ck_arr[idx] = NULL;
718
719                                 /* check, if we found some candidates for melting */
720                                 if (n_melt == 1) {
721                                         DBG((cenv->dbg, LEVEL_1, "\tno candidate found\n"));
722                                         continue;
723                                 }
724
725                                 ir_nodeset_remove(&entry->copies, ref);
726                                 sched_remove(ref);
727
728                                 melt_arr = (ir_node **)obstack_finish(&obst);
729                                 /* melt all found copykeeps */
730                                 NEW_ARR_A(ir_node *, new_ck_in, n_melt);
731                                 for (j = 0; j < n_melt; ++j) {
732                                         new_ck_in[j] = get_irn_n(melt_arr[j], 1);
733
734                                         /* now, we can kill the melted keep, except the */
735                                         /* ref one, we still need some information      */
736                                         if (melt_arr[j] != ref)
737                                                 kill_node(melt_arr[j]);
738                                 }
739
740 #ifdef KEEP_ALIVE_COPYKEEP_HACK
741                                 new_ck = be_new_CopyKeep(entry->cls, irg, get_nodes_block(ref), be_get_CopyKeep_op(ref), n_melt, new_ck_in, mode_ANY);
742                                 keep_alive(new_ck);
743 #else
744                                 new_ck = be_new_CopyKeep(entry->cls, irg, get_nodes_block(ref), be_get_CopyKeep_op(ref), n_melt, new_ck_in, get_irn_mode(ref));
745 #endif /* KEEP_ALIVE_COPYKEEP_HACK */
746
747                                 /* set register class for all kept inputs */
748                                 for (j = 1; j <= n_melt; ++j)
749                                         be_node_set_reg_class(new_ck, j, entry->cls);
750
751                                 ir_nodeset_insert(&entry->copies, new_ck);
752
753                                 /* find scheduling point */
754                                 sched_pt = ref_mode_T;
755                                 do {
756                                         /* just walk along the schedule until a non-Keep/CopyKeep node is found */
757                                         sched_pt = sched_next(sched_pt);
758                                 } while (be_is_Keep(sched_pt) || be_is_CopyKeep(sched_pt));
759
760                                 sched_add_before(sched_pt, new_ck);
761                                 DBG((cenv->dbg, LEVEL_1, "created %+F, scheduled before %+F\n", new_ck, sched_pt));
762
763                                 /* finally: kill the reference copykeep */
764                                 kill_node(ref);
765                         }
766                 }
767
768                 obstack_free(&obst, NULL);
769         }
770 }
771
772 /**
773  * Walks over all nodes to assure register constraints.
774  *
775  * @param birg  The birg structure containing the irg
776  */
777 void assure_constraints(be_irg_t *birg) {
778         ir_graph              *irg = be_get_birg_irg(birg);
779         constraint_env_t      cenv;
780         ir_node               **nodes;
781         ir_nodemap_iterator_t map_iter;
782         ir_nodemap_entry_t    map_entry;
783         FIRM_DBG_REGISTER(firm_dbg_module_t *mod, "firm.be.lower.constr");
784
785         DEBUG_ONLY(cenv.dbg = mod;)
786         cenv.birg   = birg;
787         ir_nodemap_init(&cenv.op_set);
788         obstack_init(&cenv.obst);
789
790         irg_walk_blkwise_graph(irg, NULL, assure_constraints_walker, &cenv);
791
792         /* melt copykeeps, pointing to projs of */
793         /* the same mode_T node and keeping the */
794         /* same operand                         */
795         melt_copykeeps(&cenv);
796
797         /* for all */
798         foreach_ir_nodemap(&cenv.op_set, map_entry, map_iter) {
799                 op_copy_assoc_t *entry = map_entry.data;
800                 int     n;
801                 ir_node *cp;
802                 ir_nodeset_iterator_t iter;
803                 be_ssa_construction_env_t senv;
804
805                 n     = ir_nodeset_size(&entry->copies);
806                 nodes = alloca(n * sizeof(nodes[0]));
807
808                 /* put the node in an array */
809                 DBG((mod, LEVEL_1, "introduce copies for %+F ", map_entry.node));
810
811                 /* collect all copies */
812                 n = 0;
813                 foreach_ir_nodeset(&entry->copies, cp, iter) {
814                         nodes[n++] = cp;
815                         DB((mod, LEVEL_1, ", %+F ", cp));
816                 }
817
818                 DB((mod, LEVEL_1, "\n"));
819
820                 /* introduce the copies for the operand and it's copies */
821                 be_ssa_construction_init(&senv, birg);
822                 be_ssa_construction_add_copy(&senv, map_entry.node);
823                 be_ssa_construction_add_copies(&senv, nodes, n);
824                 be_ssa_construction_fix_users(&senv, map_entry.node);
825                 be_ssa_construction_destroy(&senv);
826
827                 /* Could be that not all CopyKeeps are really needed, */
828                 /* so we transform unnecessary ones into Keeps.       */
829                 foreach_ir_nodeset(&entry->copies, cp, iter) {
830                         if (be_is_CopyKeep(cp) && get_irn_n_edges(cp) < 1) {
831                                 ir_node *keep;
832                                 int     n = get_irn_arity(cp);
833
834                                 keep = be_new_Keep(arch_get_irn_reg_class(cp, -1),
835                                         irg, get_nodes_block(cp), n, get_irn_in(cp) + 1);
836                                 sched_add_before(cp, keep);
837
838                                 /* Set all ins (including the block) of the CopyKeep BAD to keep the verifier happy. */
839                                 sched_remove(cp);
840                                 kill_node(cp);
841                         }
842                 }
843
844                 ir_nodeset_destroy(&entry->copies);
845         }
846
847         ir_nodemap_destroy(&cenv.op_set);
848         obstack_free(&cenv.obst, NULL);
849         be_liveness_invalidate(be_get_birg_liveness(birg));
850 }
851
852
853 /**
854  * Push nodes that do not need to be permed through the Perm.
855  * This is commonly a reload cascade at block ends.
856  * @note This routine needs interference.
857  * @note Probably, we can implement it a little more efficient.
858  *       Especially searching the frontier lazily might be better.
859  * @param perm The perm.
860  * @param data The walker data (lower_env_t).
861  * @return     1, if there is something left to perm over.
862  *             0, if removed the complete perm.
863  */
864 static int push_through_perm(ir_node *perm, void *data)
865 {
866         lower_env_t *env = data;
867
868         ir_graph *irg     = get_irn_irg(perm);
869         ir_node *bl       = get_nodes_block(perm);
870         ir_node *node;
871         int  arity        = get_irn_arity(perm);
872         int *map;
873         int *proj_map;
874         bitset_t *moved   = bitset_alloca(arity);
875         int n_moved;
876         int new_size;
877         ir_node *frontier = bl;
878         FIRM_DBG_REGISTER(firm_dbg_module_t *mod, "firm.be.lower.permmove");
879
880         int i, n;
881         const ir_edge_t *edge;
882         ir_node *one_proj = NULL, *irn;
883         const arch_register_class_t *cls = NULL;
884
885         DBG((mod, LEVEL_1, "perm move %+F irg %+F\n", perm, irg));
886
887         /* get some Proj and find out the register class of that Proj. */
888         edge     = get_irn_out_edge_first_kind(perm, EDGE_KIND_NORMAL);
889         one_proj = get_edge_src_irn(edge);
890         assert(is_Proj(one_proj));
891         cls      = arch_get_irn_reg_class(one_proj, -1);
892
893         /* Find the point in the schedule after which the
894          * potentially movable nodes must be defined.
895          * A Perm will only be pushed up to first instruction
896          * which lets an operand of itself die.
897          * If we would allow to move the Perm above this instruction,
898          * the former dead operand would be live now at the point of
899          * the Perm, increasing the register pressure by one.
900          */
901         sched_foreach_reverse_from (sched_prev(perm), irn) {
902                 for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
903                         ir_node *op = get_irn_n(irn, i);
904                         if (arch_irn_consider_in_reg_alloc(cls, op) &&
905                             !values_interfere(env->birg, op, one_proj)) {
906                                 frontier = irn;
907                                 goto found_front;
908                         }
909                 }
910         }
911 found_front:
912
913         DBG((mod, LEVEL_2, "\tfrontier: %+F\n", frontier));
914
915         node = sched_prev(perm);
916         n_moved = 0;
917         while(!sched_is_begin(node)) {
918                 const arch_register_req_t *req;
919                 int                        input = -1;
920                 ir_node                   *proj;
921
922                 /* search if node is a INPUT of Perm */
923                 foreach_out_edge(perm, edge) {
924                         ir_node *out = get_edge_src_irn(edge);
925                         int      pn  = get_Proj_proj(out);
926                         ir_node *in  = get_irn_n(perm, pn);
927                         if (node == in) {
928                                 proj  = out;
929                                 input = pn;
930                                 break;
931                         }
932                 }
933                 /* it wasn't an input to the perm, we can't do anything more */
934                 if(input < 0)
935                         break;
936                 if(!sched_comes_after(frontier, node))
937                         break;
938                 if (arch_irn_is(node, modify_flags))
939                         break;
940                 if(is_Proj(node)) {
941                         req = arch_get_register_req(get_Proj_pred(node),
942                                                     -1 - get_Proj_proj(node));
943                 } else {
944                         req = arch_get_register_req(node, -1);
945                 }
946                 if(req->type != arch_register_req_type_normal)
947                         break;
948                 for(i = get_irn_arity(node) - 1; i >= 0; --i) {
949                         ir_node *opop = get_irn_n(node, i);
950                         if (arch_irn_consider_in_reg_alloc(cls, opop)) {
951                                 break;
952                         }
953                 }
954                 if(i >= 0)
955                         break;
956
957                 DBG((mod, LEVEL_2, "\tmoving %+F after %+F, killing %+F\n", node, perm, proj));
958
959                 /* move the movable node in front of the Perm */
960                 sched_remove(node);
961                 sched_add_after(perm, node);
962
963                 /* give it the proj's register */
964                 arch_set_irn_register(node, arch_get_irn_register(proj));
965
966                 /* reroute all users of the proj to the moved node. */
967                 edges_reroute(proj, node, irg);
968
969                 /* and kill it */
970                 set_Proj_pred(proj, new_Bad());
971                 kill_node(proj);
972
973                 bitset_set(moved, input);
974                 n_moved++;
975
976                 node = sched_prev(node);
977         }
978
979         /* well, we could not push anything through the perm */
980         if(n_moved == 0)
981                 return 1;
982
983         new_size = arity - n_moved;
984         if(new_size == 0) {
985                 return 0;
986         }
987
988         map      = alloca(new_size * sizeof(map[0]));
989         proj_map = alloca(arity * sizeof(proj_map[0]));
990         memset(proj_map, -1, sizeof(proj_map[0]));
991         n   = 0;
992         for(i = 0; i < arity; ++i) {
993                 if(bitset_is_set(moved, i))
994                         continue;
995                 map[n]      = i;
996                 proj_map[i] = n;
997                 n++;
998         }
999         assert(n == new_size);
1000         foreach_out_edge(perm, edge) {
1001                 ir_node *proj = get_edge_src_irn(edge);
1002                 int      pn   = get_Proj_proj(proj);
1003                 pn = proj_map[pn];
1004                 assert(pn >= 0);
1005                 set_Proj_proj(proj, pn);
1006         }
1007
1008         be_Perm_reduce(perm, new_size, map);
1009         return 1;
1010 }
1011
1012 /**
1013  * Calls the corresponding lowering function for the node.
1014  *
1015  * @param irn      The node to be checked for lowering
1016  * @param walk_env The walker environment
1017  */
1018 static void lower_nodes_after_ra_walker(ir_node *irn, void *walk_env) {
1019         int perm_stayed;
1020
1021         if (is_Block(irn) || is_Proj(irn))
1022                 return;
1023         if (!be_is_Perm(irn))
1024                 return;
1025
1026         perm_stayed = push_through_perm(irn, walk_env);
1027         if (!perm_stayed)
1028                 return;
1029
1030         lower_perm_node(irn, walk_env);
1031 }
1032
1033 /**
1034  * Walks over all blocks in an irg and performs lowering need to be
1035  * done after register allocation (e.g. perm lowering).
1036  *
1037  * @param birg      The birg object
1038  * @param do_copy   1 == resolve cycles with a free reg if available
1039  */
1040 void lower_nodes_after_ra(be_irg_t *birg, int do_copy) {
1041         lower_env_t env;
1042         ir_graph    *irg = be_get_birg_irg(birg);
1043
1044         env.birg    = birg;
1045         env.do_copy = do_copy;
1046         FIRM_DBG_REGISTER(env.dbg_module, "firm.be.lower");
1047
1048         /* we will need interference */
1049         be_liveness_assure_chk(be_get_birg_liveness(birg));
1050
1051         irg_walk_blkwise_graph(irg, NULL, lower_nodes_after_ra_walker, &env);
1052 }