fixed constraint assurance
[libfirm] / ir / be / belower.c
index 001e8c9..aafa6a3 100644 (file)
 #include "config.h"
 #endif
 
+#include <stdlib.h>
+
+#include "ircons.h"
+#include "debug.h"
+#include "irhooks.h"
+
 #include "bearch.h"
 #include "belower.h"
 #include "benode_t.h"
 #include "bechordal_t.h"
-#include "besched.h"
+#include "besched_t.h"
+#include "bestat.h"
+#include "benodesets.h"
 
 #include "irgmod.h"
-#include "iredges.h"
+#include "iredges_t.h"
 #include "irgwalk.h"
 
+#ifdef HAVE_MALLOC_H
+ #include <malloc.h>
+#endif
+#ifdef HAVE_ALLOCA_H
+ #include <alloca.h>
+#endif
+
+#undef KEEP_ALIVE_COPYKEEP_HACK
+
 #undef is_Perm
-#define is_Perm(arch_env, irn) (arch_irn_classify(arch_env, irn) == arch_irn_class_perm)
+#define is_Perm(arch_env, irn) (arch_irn_class_is(arch_env, irn, perm))
+
+/* associates op with it's copy and CopyKeep */
+typedef struct {
+       ir_node *op;         /* an irn which must be different */
+       pset    *copies;     /* all non-spillable copies of this irn */
+       const arch_register_class_t *cls;
+} op_copy_assoc_t;
+
+/* environment for constraints */
+typedef struct {
+       be_irg_t       *birg;
+       pset           *op_set;
+       struct obstack obst;
+       DEBUG_ONLY(firm_dbg_module_t *dbg;)
+} constraint_env_t;
 
 /* lowering walker environment */
 typedef struct _lower_env_t {
-       be_chordal_env_t *chord_env;
-       int               do_copy;
+       be_chordal_env_t  *chord_env;
+       unsigned           do_copy:1;
+       DEBUG_ONLY(firm_dbg_module_t *dbg_module;)
 } lower_env_t;
 
 /* holds a perm register pair */
@@ -48,12 +81,30 @@ typedef enum _perm_type_t {
        PERM_COPY
 } perm_type_t;
 
+/* structure to represent cycles or chains in a perm */
 typedef struct _perm_cycle_t {
        const arch_register_t **elems;       /**< the registers in the cycle */
        int                     n_elems;     /**< number of elements in the cycle */
        perm_type_t             type;        /**< type (CHAIN or CYCLE) */
 } perm_cycle_t;
 
+static void kill_node(ir_node *irn, int kill_block) {
+       int      i, arity = get_irn_arity(irn);
+       ir_graph *irg     = get_irn_irg(irn);
+
+       for (i = -1; i < arity; ++i) {
+               set_irn_n(irn, i, new_r_Bad(irg));
+       }
+}
+
+/* Compare the two operands */
+static int cmp_op_copy_assoc(const void *a, const void *b) {
+       const op_copy_assoc_t *op1 = a;
+       const op_copy_assoc_t *op2 = b;
+
+       return op1->op != op2->op;
+}
+
 /* Compare the in registers of two register pairs */
 static int compare_reg_pair(const void *a, const void *b) {
        const reg_pair_t *pair_a = a;
@@ -65,6 +116,7 @@ static int compare_reg_pair(const void *a, const void *b) {
                return -1;
 }
 
+/* returns the number register pairs marked as checked */
 static int get_n_checked_pairs(reg_pair_t *pairs, int n) {
        int i, n_checked = 0;
 
@@ -90,13 +142,15 @@ static int get_n_checked_pairs(reg_pair_t *pairs, int n) {
 static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_register_t *reg, int in_out) {
        int i;
 
-       for (i = 0; i < n; i++) {
-               if (in_out) {
+       if (in_out) {
+               for (i = 0; i < n; i++) {
                        /* out register matches */
                        if (pairs[i].out_reg->index == reg->index)
                                return pairs[i].out_node;
                }
-               else {
+       }
+       else {
+               for (i = 0; i < n; i++) {
                        /* in register matches */
                        if (pairs[i].in_reg->index == reg->index)
                                return pairs[i].in_node;
@@ -106,6 +160,37 @@ static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_regis
        return NULL;
 }
 
+/**
+ * Gets the index in the register pair array where the in/out register
+ * corresponds to reg_idx.
+ *
+ * @param pairs  The array of register pairs
+ * @param n      The number of pairs
+ * @param reg    The register index to look for
+ * @param in_out 0 == look for IN register, 1 == look for OUT register
+ * @return The corresponding index in pairs or -1 if not found
+ */
+static int get_pairidx_for_regidx(reg_pair_t *pairs, int n, int reg_idx, int in_out) {
+       int i;
+
+       if (in_out) {
+               for (i = 0; i < n; i++) {
+                       /* out register matches */
+                       if (pairs[i].out_reg->index == reg_idx)
+                               return i;
+               }
+       }
+       else {
+               for (i = 0; i < n; i++) {
+                       /* in register matches */
+                       if (pairs[i].in_reg->index == reg_idx)
+                               return i;
+               }
+       }
+
+       return -1;
+}
+
 /**
  * Gets an array of register pairs and tries to identify a cycle or chain starting
  * at position start.
@@ -118,32 +203,49 @@ static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_regis
 static perm_cycle_t *get_perm_cycle(perm_cycle_t *cycle, reg_pair_t *pairs, int n, int start) {
        int head         = pairs[start].in_reg->index;
        int cur_idx      = pairs[start].out_reg->index;
-       int n_pairs_done = get_n_checked_pairs(pairs, n) + 1;
+       int cur_pair_idx = start;
+       int n_pairs_done = get_n_checked_pairs(pairs, n);
        int idx;
+       perm_type_t cycle_tp = PERM_CYCLE;
+
+       /* We could be right in the middle of a chain, so we need to find the start */
+       while (head != cur_idx) {
+               /* goto previous register in cycle or chain */
+               cur_pair_idx = get_pairidx_for_regidx(pairs, n, head, 1);
+
+               if (cur_pair_idx < 0) {
+                       cycle_tp = PERM_CHAIN;
+                       break;
+               }
+               else {
+                       head  = pairs[cur_pair_idx].in_reg->index;
+                       start = cur_pair_idx;
+               }
+       }
 
        /* assume worst case: all remaining pairs build a cycle or chain */
-       cycle->elems    = calloc(n - n_pairs_done, sizeof(cycle->elems[0]));
+       cycle->elems    = xcalloc((n - n_pairs_done) * 2, sizeof(cycle->elems[0]));
        cycle->n_elems  = 2;  /* initial number of elements is 2 */
        cycle->elems[0] = pairs[start].in_reg;
        cycle->elems[1] = pairs[start].out_reg;
-       cycle->type     = PERM_CHAIN; /* default is CHAIN, only changed when we found a cycle */
-
-       /* mark the first pair as checked */
-       pairs[start].checked = 1;
+       cycle->type     = cycle_tp;
+       cur_idx         = pairs[start].out_reg->index;
 
        idx = 2;
        /* check for cycle or end of a chain */
-       while (cur_idx != head && n_pairs_done < n) {
+       while (cur_idx != head) {
                /* goto next register in cycle or chain */
-               cur_idx = pairs[cur_idx].out_reg->index;
+               cur_pair_idx = get_pairidx_for_regidx(pairs, n, cur_idx, 0);
+
+               if (cur_pair_idx < 0)
+                       break;
+
+               cur_idx = pairs[cur_pair_idx].out_reg->index;
 
                /* it's not the first element: insert it */
                if (cur_idx != head) {
-                       cycle->elems[idx++] = pairs[cur_idx].out_reg;
+                       cycle->elems[idx++] = pairs[cur_pair_idx].out_reg;
                        cycle->n_elems++;
-
-                       pairs[cur_idx].checked = 1;
-                       n_pairs_done++;
                }
                else {
                        /* we are there where we started -> CYCLE */
@@ -151,37 +253,51 @@ static perm_cycle_t *get_perm_cycle(perm_cycle_t *cycle, reg_pair_t *pairs, int
                }
        }
 
+       /* mark all pairs having one in/out register with cycle in common as checked */
+       for (idx = 0; idx < cycle->n_elems; idx++) {
+               cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 0);
+
+               if (cur_pair_idx >= 0)
+                       pairs[cur_pair_idx].checked = 1;
+
+               cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 1);
+
+               if (cur_pair_idx >= 0)
+                       pairs[cur_pair_idx].checked = 1;
+       }
+
        return cycle;
 }
 
 /**
  * Lowers a perm node.  Resolves cycles and creates a bunch of
  * copy and swap operations to permute registers.
+ * Note: The caller of this function has to make sure, that irn
+ *       is a Perm node.
  *
  * @param irn      The perm node
+ * @param block    The block the perm node belongs to
  * @param walk_env The environment
  */
-static void lower_perms_walker(ir_node *irn, void *walk_env) {
-       const be_node_factory_t     *fact;
+static void lower_perm_node(ir_node *irn, void *walk_env) {
        const arch_register_class_t *reg_class;
        const arch_env_t            *arch_env;
-       lower_env_t     *env = walk_env;
+       lower_env_t     *env         = walk_env;
+       int             real_size    = 0;
+       int             keep_perm    = 0;
+       int             n, i, pn, do_copy, j, n_ops;
        reg_pair_t      *pairs;
        const ir_edge_t *edge;
        perm_cycle_t    *cycle;
-       int              n, i, pn, do_copy;
-       ir_node         *block, *arg, *res, *sched_point, *in[2];
+       ir_node         *sched_point, *block, *in[2];
+       ir_node         *arg1, *arg2, *res1, *res2;
        ir_node         *cpyxchg = NULL;
+       DEBUG_ONLY(firm_dbg_module_t *mod;)
 
-       fact     = env->chord_env->main_env->node_factory;
-       arch_env = env->chord_env->main_env->arch_env;
+       arch_env = env->chord_env->birg->main_env->arch_env;
        do_copy  = env->do_copy;
-
-       /* check if perm */
-       if (! is_Perm(arch_env, irn))
-               return;
-
-       block = get_nodes_block(irn);
+       DEBUG_ONLY(mod = env->dbg_module;)
+       block    = get_nodes_block(irn);
 
        /*
                Get the schedule predecessor node to the perm
@@ -190,13 +306,14 @@ static void lower_perms_walker(ir_node *irn, void *walk_env) {
                        should be ok.
        */
        sched_point = sched_prev(irn);
+       DBG((mod, LEVEL_1, "sched point is %+F\n", sched_point));
        assert(sched_point && "Perm is not scheduled or has no predecessor");
 
        n = get_irn_arity(irn);
        assert(n == get_irn_n_edges(irn) && "perm's in and out numbers different");
 
        reg_class = arch_get_irn_register(arch_env, get_irn_n(irn, 0))->reg_class;
-       pairs     = calloc(n, sizeof(pairs[0]));
+       pairs     = alloca(n * sizeof(pairs[0]));
 
        /* build the list of register pairs (in, out) */
        i = 0;
@@ -217,21 +334,27 @@ static void lower_perms_walker(ir_node *irn, void *walk_env) {
 
        /* Mark all equal pairs as checked, and exchange the OUT proj with
                the IN node. */
-       i = 0;
-       while (pairs[i].in_reg->index == pairs[i].out_reg->index) {
-               /* remove the proj from the schedule */
-               sched_remove(pairs[i].out_node);
-
-               /* remove the argument from schedule */
-               sched_remove(pairs[i].in_node);
+       for (i = 0; i < n; i++) {
+               if (pairs[i].in_reg->index == pairs[i].out_reg->index) {
+                       DBG((mod, LEVEL_1, "%+F removing equal perm register pair (%+F, %+F, %s)\n",
+                               irn, pairs[i].in_node, pairs[i].out_node, pairs[i].out_reg->name));
+
+                       /* We have to check for a special case:
+                               The in-node could be a Proj from a Perm. In this case,
+                               we need to correct the projnum */
+                       if (is_Perm(arch_env, pairs[i].in_node) && is_Proj(pairs[i].in_node)) {
+                               set_Proj_proj(pairs[i].out_node, get_Proj_proj(pairs[i].in_node));
+                       }
 
-               /* exchange the proj with the argument */
-               exchange(pairs[i].out_node, pairs[i].in_node);
+                       /* remove the proj from the schedule */
+                       sched_remove(pairs[i].out_node);
 
-               /* add the argument after the magic scheduling point */
-               sched_add_after(sched_point, pairs[i].in_node);
+                       /* reroute the edges from the proj to the argument */
+                       edges_reroute(pairs[i].out_node, pairs[i].in_node, env->chord_env->irg);
+                       set_irn_n(pairs[i].out_node, 0, new_Bad());
 
-               pairs[i++].checked = 1;
+                       pairs[i].checked = 1;
+               }
        }
 
        /* Set do_copy to 0 if it's on but we have no free register */
@@ -239,23 +362,46 @@ static void lower_perms_walker(ir_node *irn, void *walk_env) {
                do_copy = 0;
        }
 
+       real_size = n - get_n_checked_pairs(pairs, n);
+
+       be_do_stat_perm(reg_class->name, reg_class->n_regs, irn, block, n, real_size);
+
        /* check for cycles and chains */
        while (get_n_checked_pairs(pairs, n) < n) {
-               i = 0;
+               i = n_ops = 0;
 
                /* go to the first not-checked pair */
                while (pairs[i].checked) i++;
-               cycle = calloc(1, sizeof(*cycle));
+               cycle = xcalloc(1, sizeof(*cycle));
                cycle = get_perm_cycle(cycle, pairs, n, i);
 
-//todo: - iff PERM_CYCLE && do_copy -> determine free temp reg and insert copy to/from it before/after
+               DB((mod, LEVEL_1, "%+F: following %s created:\n  ", irn, cycle->type == PERM_CHAIN ? "chain" : "cycle"));
+               for (j = 0; j < cycle->n_elems; j++) {
+                       DB((mod, LEVEL_1, " %s", cycle->elems[j]->name));
+               }
+               DB((mod, LEVEL_1, "\n"));
+
+               /*
+                       We don't need to do anything if we have a Perm with two
+                       elements which represents a cycle, because those nodes
+                       already represent exchange nodes
+               */
+               if (n == 2 && cycle->type == PERM_CYCLE) {
+                       free(cycle);
+                       keep_perm = 1;
+                       continue;
+               }
+
+//TODO: - iff PERM_CYCLE && do_copy -> determine free temp reg and insert copy to/from it before/after
 //        the copy cascade (this reduces the cycle into a chain)
 
                /* build copy/swap nodes from back to front */
-               for (i = cycle->n_elems - 2; i >= 0; i++) {
-                       arg = get_node_for_register(pairs, n, cycle->elems[i], 0);
-                       res = get_node_for_register(pairs, n, cycle->elems[i + 1], 1);
+               for (i = cycle->n_elems - 2; i >= 0; i--) {
+                       arg1 = get_node_for_register(pairs, n, cycle->elems[i], 0);
+                       arg2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 0);
 
+                       res1 = get_node_for_register(pairs, n, cycle->elems[i], 1);
+                       res2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 1);
                        /*
                                If we have a cycle and don't copy: we need to create exchange nodes
                                NOTE: An exchange node is a perm node with 2 INs and 2 OUTs
@@ -265,49 +411,498 @@ static void lower_perms_walker(ir_node *irn, void *walk_env) {
                                OUT_2 = out node with register i
                        */
                        if (cycle->type == PERM_CYCLE && !do_copy) {
-                               in[0] = arg;
-                               in[1] = get_node_for_register(pairs, n, cycle->elems[i + 1], 0);
-
-                               cpyxchg = new_Perm(fact, reg_class, env->chord_env->irg, block, 2, in);
-                               set_Proj_pred(res, cpyxchg);
-                               set_Proj_proj(res, 0);
-                               set_Proj_pred(get_node_for_register(pairs, n, cycle->elems[i], 1), cpyxchg);
-                               set_Proj_proj(get_node_for_register(pairs, n, cycle->elems[i], 1), 1);
+                               in[0] = arg1;
+                               in[1] = arg2;
+
+                               /* At this point we have to handle the following problem:     */
+                               /*                                                            */
+                               /* If we have a cycle with more than two elements, then       */
+                               /* this could correspond to the following Perm node:          */
+                               /*                                                            */
+                               /*   +----+   +----+   +----+                                 */
+                               /*   | r1 |   | r2 |   | r3 |                                 */
+                               /*   +-+--+   +-+--+   +--+-+                                 */
+                               /*     |        |         |                                   */
+                               /*     |        |         |                                   */
+                               /*   +-+--------+---------+-+                                 */
+                               /*   |         Perm         |                                 */
+                               /*   +-+--------+---------+-+                                 */
+                               /*     |        |         |                                   */
+                               /*     |        |         |                                   */
+                               /*   +-+--+   +-+--+   +--+-+                                 */
+                               /*   |Proj|   |Proj|   |Proj|                                 */
+                               /*   | r2 |   | r3 |   | r1 |                                 */
+                               /*   +----+   +----+   +----+                                 */
+                               /*                                                            */
+                               /* This node is about to be split up into two 2x Perm's       */
+                               /* for which we need 4 Proj's and the one additional Proj     */
+                               /* of the first Perm has to be one IN of the second. So in    */
+                               /* general we need to create one additional Proj for each     */
+                               /* "middle" Perm and set this to one in node of the successor */
+                               /* Perm.                                                      */
+
+                               DBG((mod, LEVEL_1, "%+F creating exchange node (%+F, %s) and (%+F, %s) with\n",
+                                       irn, arg1, cycle->elems[i]->name, arg2, cycle->elems[i + 1]->name));
+                               DBG((mod, LEVEL_1, "%+F                        (%+F, %s) and (%+F, %s)\n",
+                                       irn, res1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
+
+                               cpyxchg = be_new_Perm(reg_class, env->chord_env->irg, block, 2, in);
+                               n_ops++;
+
+                               if (i > 0) {
+                                       /* cycle is not done yet */
+                                       int pidx = get_pairidx_for_regidx(pairs, n, cycle->elems[i]->index, 0);
+
+                                       /* create intermediate proj */
+                                       res1 = new_r_Proj(get_irn_irg(irn), block, cpyxchg, get_irn_mode(res1), 0);
+
+                                       /* set as in for next Perm */
+                                       pairs[pidx].in_node = res1;
+                               }
+                               else {
+                                       sched_remove(res1);
+                               }
+
+                               sched_remove(res2);
+
+                               set_Proj_pred(res2, cpyxchg);
+                               set_Proj_proj(res2, 0);
+                               set_Proj_pred(res1, cpyxchg);
+                               set_Proj_proj(res1, 1);
+
+                               sched_add_after(sched_point, res1);
+                               sched_add_after(sched_point, res2);
+
+                               arch_set_irn_register(arch_env, res2, cycle->elems[i + 1]);
+                               arch_set_irn_register(arch_env, res1, cycle->elems[i]);
+
+                               /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
+                               sched_add_after(sched_point, cpyxchg);
+
+                               DBG((mod, LEVEL_1, "replacing %+F with %+F, placed new node after %+F\n", irn, cpyxchg, sched_point));
+
+                               /* set the new scheduling point */
+                               sched_point = res1;
                        }
                        else {
-                               cpyxchg = new_Copy(fact, reg_class, env->chord_env->irg, block, arg);
+                               DBG((mod, LEVEL_1, "%+F creating copy node (%+F, %s) -> (%+F, %s)\n",
+                                       irn, arg1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
+
+                               cpyxchg = be_new_Copy(reg_class, env->chord_env->irg, block, arg1);
                                arch_set_irn_register(arch_env, cpyxchg, cycle->elems[i + 1]);
+                               n_ops++;
 
                                /* remove the proj from the schedule */
-                               sched_remove(res);
+                               sched_remove(res2);
 
                                /* exchange copy node and proj */
-                               exchange(res, cpyxchg);
-                       }
+                               exchange(res2, cpyxchg);
 
-                       /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
-                       sched_add_after(sched_point, cpyxchg);
+                               /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
+                               sched_add_after(sched_point, cpyxchg);
+
+                               /* set the new scheduling point */
+                               sched_point = cpyxchg;
+                       }
                }
 
-               free(cycle->elems);
+               be_do_stat_permcycle(reg_class->name, irn, block, cycle->type == PERM_CHAIN, cycle->n_elems, n_ops);
+
+               free((void *) cycle->elems);
                free(cycle);
        }
 
        /* remove the perm from schedule */
-       sched_remove(irn);
+       if (! keep_perm) {
+               kill_node(irn, 0);
+               sched_remove(irn);
+       }
+}
+
+
+
+static int get_n_out_edges(const ir_node *irn) {
+       const ir_edge_t *edge;
+       int cnt = 0;
+
+       foreach_out_edge(irn, edge) {
+               cnt++;
+       }
+
+       return cnt;
+}
+
+static ir_node *belower_skip_proj(ir_node *irn) {
+       while(is_Proj(irn))
+               irn = get_Proj_pred(irn);
+       return irn;
+}
+
+static ir_node *find_copy(constraint_env_t *env, ir_node *irn, ir_node *op) {
+       const arch_env_t *arch_env = env->birg->main_env->arch_env;
+       ir_node          *block    = get_nodes_block(irn);
+       ir_node          *cur_node;
+
+       for (cur_node = sched_prev(irn);
+               ! is_Block(cur_node) && be_is_Copy(cur_node) && get_nodes_block(cur_node) == block;
+               cur_node = sched_prev(cur_node))
+       {
+               if (be_get_Copy_op(cur_node) == op && arch_irn_is(arch_env, cur_node, dont_spill))
+                       return cur_node;
+       }
+
+       return NULL;
 }
 
+static void gen_assure_different_pattern(ir_node *irn, ir_node *other_different, constraint_env_t *env) {
+       be_irg_t                    *birg     = env->birg;
+       pset                        *op_set   = env->op_set;
+       const arch_env_t            *arch_env = birg->main_env->arch_env;
+       ir_node                     *block    = get_nodes_block(irn);
+       const arch_register_class_t *cls      = arch_get_irn_reg_class(arch_env, other_different, -1);
+       ir_node                     *in[2], *keep, *cpy;
+       op_copy_assoc_t             key, *entry;
+       DEBUG_ONLY(firm_dbg_module_t *mod     = env->dbg;)
+
+       if (arch_irn_is(arch_env, other_different, ignore) || ! mode_is_datab(get_irn_mode(other_different))) {
+               DBG((mod, LEVEL_1, "ignore constraint for %+F because other_irn is ignore or not a datab node\n", irn));
+               return;
+       }
+
+       /* Make a not spillable copy of the different node   */
+       /* this is needed because the different irn could be */
+       /* in block far far away                             */
+       /* The copy is optimized later if not needed         */
+
+       /* check if already exists such a copy in the schedule immediatly before */
+       cpy = find_copy(env, belower_skip_proj(irn), other_different);
+       if (! cpy) {
+               cpy = be_new_Copy(cls, birg->irg, block, other_different);
+               be_node_set_flags(cpy, BE_OUT_POS(0), arch_irn_flags_dont_spill);
+               DBG((mod, LEVEL_1, "created non-spillable %+F for value %+F\n", cpy, other_different));
+       }
+       else {
+               DBG((mod, LEVEL_1, "using already existing %+F for value %+F\n", cpy, other_different));
+       }
+
+       in[0] = irn;
+       in[1] = cpy;
+
+       /* Add the Keep resp. CopyKeep and reroute the users */
+       /* of the other_different irn in case of CopyKeep.   */
+       if (get_n_out_edges(other_different) == 0) {
+               keep = be_new_Keep(cls, birg->irg, block, 2, in);
+       }
+       else {
+               keep = be_new_CopyKeep_single(cls, birg->irg, block, cpy, irn, get_irn_mode(other_different));
+               be_node_set_reg_class(keep, 1, cls);
+       }
+
+       DBG((mod, LEVEL_1, "created %+F(%+F, %+F)\n\n", keep, irn, cpy));
+
+       /* insert copy and keep into schedule */
+       assert(sched_is_scheduled(irn) && "need schedule to assure constraints");
+       if (! sched_is_scheduled(cpy))
+               sched_add_before(belower_skip_proj(irn), cpy);
+       sched_add_after(irn, keep);
+
+       /* insert the other different and it's copies into the set */
+       key.op         = other_different;
+       key.copies     = NULL;
+       entry          = pset_find(op_set, &key, nodeset_hash(other_different));
+
+       if (! entry) {
+               entry         = obstack_alloc(&env->obst, sizeof(*entry));
+               entry->copies = pset_new_ptr_default();
+               entry->op     = other_different;
+               entry->cls    = cls;
+       }
+
+       /* insert copy */
+       pset_insert_ptr(entry->copies, cpy);
+
+       /* insert keep in case of CopyKeep */
+       if (be_is_CopyKeep(keep))
+               pset_insert_ptr(entry->copies, keep);
+
+       pset_insert(op_set, entry, nodeset_hash(other_different));
+}
+
+/**
+ * Checks if node has a should_be_different constraint in output
+ * and adds a Keep then to assure the constraint.
+ */
+static void assure_different_constraints(ir_node *irn, constraint_env_t *env) {
+       const arch_register_req_t *req;
+       arch_register_req_t       req_temp;
+
+       req = arch_get_register_req(env->birg->main_env->arch_env, &req_temp, irn, -1);
+
+       if (req) {
+               if (arch_register_req_is(req, should_be_different)) {
+                       gen_assure_different_pattern(irn, req->other_different, env);
+               }
+               else if (arch_register_req_is(req, should_be_different_from_all)) {
+                       int i, n = get_irn_arity(belower_skip_proj(irn));
+                       for (i = 0; i < n; i++) {
+                               gen_assure_different_pattern(irn, get_irn_n(belower_skip_proj(irn), i), env);
+                       }
+               }
+       }
+}
+
+
+
 /**
- * Walks over all nodes in an irg and performs perm lowering.
+ * Calls the functions to assure register constraints.
+ *
+ * @param irn      The node to be checked for lowering
+ * @param walk_env The walker environment
+ */
+static void assure_constraints_walker(ir_node *irn, void *walk_env) {
+       if (is_Block(irn))
+               return;
+
+       if (mode_is_datab(get_irn_mode(irn)))
+               assure_different_constraints(irn, walk_env);
+
+       return;
+}
+
+/**
+ * Melt all copykeeps pointing to the same node
+ * (or Projs of the same node), copying the same operand.
+ */
+static void melt_copykeeps(constraint_env_t *cenv) {
+       op_copy_assoc_t *entry;
+
+       /* for all */
+       foreach_pset(cenv->op_set, entry) {
+               int     idx, num_ck;
+               ir_node *cp;
+               struct obstack obst;
+               ir_node **ck_arr, **melt_arr;
+
+               obstack_init(&obst);
+
+               /* collect all copykeeps */
+               num_ck = idx = 0;
+               foreach_pset(entry->copies, cp) {
+                       if (be_is_CopyKeep(cp)) {
+                               obstack_grow(&obst, &cp, sizeof(cp));
+                               ++num_ck;
+                       }
+#ifdef KEEP_ALIVE_COPYKEEP_HACK
+                       else {
+                               set_irn_mode(cp, mode_ANY);
+                               keep_alive(cp);
+                       }
+#endif /* KEEP_ALIVE_COPYKEEP_HACK */
+               }
+
+               /* compare each copykeep with all other copykeeps */
+               ck_arr = (ir_node **)obstack_finish(&obst);
+               for (idx = 0; idx < num_ck; ++idx) {
+                       ir_node *ref, *ref_mode_T;
+
+                       if (ck_arr[idx]) {
+                               int j, n_melt;
+                               ir_node **new_ck_in;
+                               ir_node *new_ck;
+                               ir_node *sched_pt = NULL;
+
+                               n_melt     = 1;
+                               ref        = ck_arr[idx];
+                               ref_mode_T = skip_Proj(get_irn_n(ref, 1));
+                               obstack_grow(&obst, &ref, sizeof(ref));
+
+                               DBG((cenv->dbg, LEVEL_1, "Trying to melt %+F:\n", ref));
+
+                               /* check for copykeeps pointing to the same mode_T node as the reference copykeep */
+                               for (j = 0; j < num_ck; ++j) {
+                                       ir_node *cur_ck = ck_arr[j];
+
+                                       if (j != idx && cur_ck && skip_Proj(get_irn_n(cur_ck, 1)) == ref_mode_T) {
+                                               obstack_grow(&obst, &cur_ck, sizeof(cur_ck));
+                                               pset_remove_ptr(entry->copies, cur_ck);
+                                               DBG((cenv->dbg, LEVEL_1, "\t%+F\n", cur_ck));
+                                               ck_arr[j] = NULL;
+                                               ++n_melt;
+                                               sched_remove(cur_ck);
+                                       }
+                               }
+                               ck_arr[idx] = NULL;
+
+                               /* check, if we found some candidates for melting */
+                               if (n_melt == 1) {
+                                       DBG((cenv->dbg, LEVEL_1, "\tno candidate found\n"));
+                                       continue;
+                               }
+
+                               pset_remove_ptr(entry->copies, ref);
+                               sched_remove(ref);
+
+                               melt_arr = (ir_node **)obstack_finish(&obst);
+                               /* melt all found copykeeps */
+                               NEW_ARR_A(ir_node *, new_ck_in, n_melt);
+                               for (j = 0; j < n_melt; ++j) {
+                                       new_ck_in[j] = get_irn_n(melt_arr[j], 1);
+
+                                       /* now, we can kill the melted keep, except the */
+                                       /* ref one, we still need some information      */
+                                       if (melt_arr[j] != ref)
+                                               kill_node(melt_arr[j], 0);
+                               }
+
+#ifdef KEEP_ALIVE_COPYKEEP_HACK
+                               new_ck = be_new_CopyKeep(entry->cls, cenv->birg->irg, get_nodes_block(ref), be_get_CopyKeep_op(ref), n_melt, new_ck_in, mode_ANY);
+                               keep_alive(new_ck);
+#else
+                               new_ck = be_new_CopyKeep(entry->cls, cenv->birg->irg, get_nodes_block(ref), be_get_CopyKeep_op(ref), n_melt, new_ck_in, get_irn_mode(ref));
+#endif /* KEEP_ALIVE_COPYKEEP_HACK */
+
+                               /* set register class for all keeped inputs */
+                               for (j = 1; j <= n_melt; ++j)
+                                       be_node_set_reg_class(new_ck, j, entry->cls);
+
+                               pset_insert_ptr(entry->copies, new_ck);
+
+                               /* find scheduling point */
+                               if (get_irn_mode(ref_mode_T) == mode_T) {
+                                       /* walk along the Projs */
+                                       for (sched_pt = sched_next(ref_mode_T); is_Proj(sched_pt) || be_is_Keep(sched_pt) || be_is_CopyKeep(sched_pt); sched_pt = sched_next(sched_pt))
+                                               /* just walk along the schedule until a non-Proj/Keep/CopyKeep node is found*/ ;
+                               }
+                               else {
+                                       sched_pt = ref_mode_T;
+                               }
+
+                               sched_add_before(sched_pt, new_ck);
+                               DBG((cenv->dbg, LEVEL_1, "created %+F, scheduled before %+F\n", new_ck, sched_pt));
+
+                               /* finally: kill the reference copykeep */
+                               kill_node(ref, 0);
+                       }
+               }
+
+               obstack_free(&obst, NULL);
+       }
+}
+
+/**
+ * Walks over all nodes to assure register constraints.
+ *
+ * @param birg  The birg structure containing the irg
+ */
+void assure_constraints(be_irg_t *birg) {
+       constraint_env_t cenv;
+       op_copy_assoc_t  *entry;
+       dom_front_info_t *dom;
+       ir_node          **nodes;
+       FIRM_DBG_REGISTER(firm_dbg_module_t *mod, "firm.be.lower.constr");
+
+       DEBUG_ONLY(cenv.dbg = mod;)
+       cenv.birg   = birg;
+       cenv.op_set = new_pset(cmp_op_copy_assoc, 16);
+       obstack_init(&cenv.obst);
+
+       irg_walk_blkwise_graph(birg->irg, NULL, assure_constraints_walker, &cenv);
+
+       /* melt copykeeps, pointing to projs of */
+       /* the same mode_T node and keeping the */
+       /* same operand                         */
+       melt_copykeeps(&cenv);
+
+       /* introduce copies needs dominance information */
+       dom = be_compute_dominance_frontiers(birg->irg);
+
+       /* for all */
+       foreach_pset(cenv.op_set, entry) {
+               int     n;
+               ir_node *cp;
+
+               n     = pset_count(entry->copies);
+               nodes = alloca((n + 1) * sizeof(nodes[0]));
+
+               /* put the node in an array */
+               n          = 0;
+               nodes[n++] = entry->op;
+               DBG((mod, LEVEL_1, "introduce copies for %+F ", entry->op));
+
+               /* collect all copies */
+               foreach_pset(entry->copies, cp) {
+                       nodes[n++] = cp;
+                       DB((mod, LEVEL_1, ", %+F ", cp));
+               }
+
+               DB((mod, LEVEL_1, "\n"));
+
+               /* introduce the copies for the operand and it's copies */
+               be_ssa_constr(dom, NULL, n, nodes);
+
+
+               /* Could be that not all CopyKeeps are really needed, */
+               /* so we transform unnecessary ones into Keeps.       */
+               foreach_pset(entry->copies, cp) {
+                       if (be_is_CopyKeep(cp) && get_irn_n_edges(cp) < 1) {
+                               ir_node *keep;
+                               int     n = get_irn_arity(cp);
+
+                               keep = be_new_Keep(arch_get_irn_reg_class(birg->main_env->arch_env, cp, -1),
+                                       birg->irg, get_nodes_block(cp), n, (ir_node **)&get_irn_in(cp)[1]);
+                               sched_add_before(cp, keep);
+
+                               /* Set all ins (including the block) of the CopyKeep BAD to keep the verifier happy. */
+                               kill_node(cp, 1);
+                               sched_remove(cp);
+                       }
+               }
+
+               del_pset(entry->copies);
+       }
+
+       be_free_dominance_frontiers(dom);
+
+       del_pset(cenv.op_set);
+       obstack_free(&cenv.obst, NULL);
+}
+
+
+
+/**
+ * Calls the corresponding lowering function for the node.
+ *
+ * @param irn      The node to be checked for lowering
+ * @param walk_env The walker environment
+ */
+static void lower_nodes_after_ra_walker(ir_node *irn, void *walk_env) {
+       lower_env_t      *env      = walk_env;
+       const arch_env_t *arch_env = env->chord_env->birg->main_env->arch_env;
+
+       if (! is_Block(irn) && ! is_Proj(irn)) {
+               if (is_Perm(arch_env, irn)) {
+                       lower_perm_node(irn, walk_env);
+               }
+       }
+
+       return;
+}
+
+/**
+ * Walks over all blocks in an irg and performs lowering need to be
+ * done after register allocation (e.g. perm lowering).
  *
  * @param chord_env The chordal environment containing the irg
  * @param do_copy   1 == resolve cycles with a free reg if available
  */
-void lower_perms(be_chordal_env_t *chord_env, int do_copy) {
+void lower_nodes_after_ra(be_chordal_env_t *chord_env, int do_copy) {
        lower_env_t env;
 
-       env.chord_env = chord_env;
-       env.do_copy   = do_copy;
+       env.chord_env  = chord_env;
+       env.do_copy    = do_copy;
+       FIRM_DBG_REGISTER(env.dbg_module, "firm.be.lower");
 
-       irg_walk_blkwise_graph(chord_env->irg,  NULL, lower_perms_walker, &env);
+       irg_walk_blkwise_graph(chord_env->irg, NULL, lower_nodes_after_ra_walker, &env);
 }
+
+#undef is_Perm