Minor changes
[libfirm] / ir / be / belower.c
1 /**
2  * Author:      Christian Wuerdig
3  * Date:        2005/12/14
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  * CVS-Id:      $Id$
7  *
8  * Performs lowering of perm nodes and spill/reload optimization.
9  */
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13
14 #include <stdlib.h>
15
16 #include "ircons.h"
17 #include "debug.h"
18
19 #include "bearch.h"
20 #include "belower.h"
21 #include "benode_t.h"
22 #include "bechordal_t.h"
23 #include "besched_t.h"
24
25 #include "irgmod.h"
26 #include "iredges_t.h"
27 #include "irgwalk.h"
28
29 #undef is_Perm
30 #define is_Perm(arch_env, irn) (arch_irn_classify(arch_env, irn) == arch_irn_class_perm)
31
32 #undef is_Call
33 #define is_Call(arch_env, irn) (arch_irn_classify(arch_env, irn) == arch_irn_class_call)
34
35 /* lowering walker environment */
36 typedef struct _lower_env_t {
37         be_chordal_env_t  *chord_env;
38         int                do_copy;
39         firm_dbg_module_t *dbg_module;
40 } lower_env_t;
41
42 /* holds a perm register pair */
43 typedef struct _reg_pair_t {
44         const arch_register_t *in_reg;    /**< a perm IN register */
45         ir_node               *in_node;   /**< the in node to which the register belongs */
46
47         const arch_register_t *out_reg;   /**< a perm OUT register */
48         ir_node               *out_node;  /**< the out node to which the register belongs */
49
50         int                    checked;   /**< indicates whether the pair was check for cycle or not */
51 } reg_pair_t;
52
53 typedef enum _perm_type_t {
54         PERM_CYCLE,
55         PERM_CHAIN,
56         PERM_SWAP,
57         PERM_COPY
58 } perm_type_t;
59
60 /* structure to represent cycles or chains in a perm */
61 typedef struct _perm_cycle_t {
62         const arch_register_t **elems;       /**< the registers in the cycle */
63         int                     n_elems;     /**< number of elements in the cycle */
64         perm_type_t             type;        /**< type (CHAIN or CYCLE) */
65 } perm_cycle_t;
66
67 /* Compare the in registers of two register pairs */
68 static int compare_reg_pair(const void *a, const void *b) {
69         const reg_pair_t *pair_a = a;
70         const reg_pair_t *pair_b = b;
71
72         if (pair_a->in_reg->index > pair_b->in_reg->index)
73                 return 1;
74         else
75                 return -1;
76 }
77
78 /* returns the number register pairs marked as checked */
79 static int get_n_checked_pairs(reg_pair_t *pairs, int n) {
80         int i, n_checked = 0;
81
82         for (i = 0; i < n; i++) {
83                 if (pairs[i].checked)
84                         n_checked++;
85         }
86
87         return n_checked;
88 }
89
90 /**
91  * Gets the node corresponding to a register from an array of register pairs.
92  * NOTE: The given registers pairs and the register to look for must belong
93  *       to the same register class.
94  *
95  * @param pairs  The array of register pairs
96  * @param n      The number of pairs
97  * @param reg    The register to look for
98  * @param in_out 0 == look for IN register, 1 == look for OUT register
99  * @return The corresponding node or NULL if not found
100  */
101 static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_register_t *reg, int in_out) {
102         int i;
103
104         if (in_out) {
105                 for (i = 0; i < n; i++) {
106                         /* out register matches */
107                         if (pairs[i].out_reg->index == reg->index)
108                                 return pairs[i].out_node;
109                 }
110         }
111         else {
112                 for (i = 0; i < n; i++) {
113                         /* in register matches */
114                         if (pairs[i].in_reg->index == reg->index)
115                                 return pairs[i].in_node;
116                 }
117         }
118
119         return NULL;
120 }
121
122 /**
123  * Gets the index in the register pair array where the in/out register
124  * corresponds to reg_idx.
125  *
126  * @param pairs  The array of register pairs
127  * @param n      The number of pairs
128  * @param reg    The register index to look for
129  * @param in_out 0 == look for IN register, 1 == look for OUT register
130  * @return The corresponding index in pairs or -1 if not found
131  */
132 static int get_pairidx_for_regidx(reg_pair_t *pairs, int n, int reg_idx, 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_idx)
139                                 return i;
140                 }
141         }
142         else {
143                 for (i = 0; i < n; i++) {
144                         /* in register matches */
145                         if (pairs[i].in_reg->index == reg_idx)
146                                 return i;
147                 }
148         }
149
150         return -1;
151 }
152
153 /**
154  * Gets an array of register pairs and tries to identify a cycle or chain starting
155  * at position start.
156  *
157  * @param cycle Variable to hold the cycle
158  * @param pairs Array of register pairs
159  * @param start Index to start
160  * @return The cycle or chain
161  */
162 static perm_cycle_t *get_perm_cycle(perm_cycle_t *cycle, reg_pair_t *pairs, int n, int start) {
163         int head         = pairs[start].in_reg->index;
164         int cur_idx      = pairs[start].out_reg->index;
165         int cur_pair_idx = start;
166         int n_pairs_done = get_n_checked_pairs(pairs, n);
167         int idx, done = 0;
168         perm_type_t cycle_tp = PERM_CYCLE;
169
170         /* We could be right in the middle of a chain, so we need to find the start */
171         while (head != cur_idx && !done) {
172                 /* goto previous register in cycle or chain */
173                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, head, 1);
174
175                 if (cur_pair_idx < 0) {
176                         cycle_tp = PERM_CHAIN;
177                         done = 1;
178                 }
179                 else {
180                         head  = pairs[cur_pair_idx].in_reg->index;
181                         start = cur_pair_idx;
182                 }
183         }
184
185         /* assume worst case: all remaining pairs build a cycle or chain */
186         cycle->elems    = calloc((n - n_pairs_done) * 2, sizeof(cycle->elems[0]));
187         cycle->n_elems  = 2;  /* initial number of elements is 2 */
188         cycle->elems[0] = pairs[start].in_reg;
189         cycle->elems[1] = pairs[start].out_reg;
190         cycle->type     = cycle_tp;
191         n_pairs_done++;
192
193         idx = 2;
194         /* check for cycle or end of a chain */
195         while (cur_idx != head && n_pairs_done < n) {
196                 /* goto next register in cycle or chain */
197                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cur_idx, 0);
198
199                 if (cur_pair_idx < 0)
200                         break;
201
202                 cur_idx = pairs[cur_pair_idx].out_reg->index;
203
204                 /* it's not the first element: insert it */
205                 if (cur_idx != head) {
206                         cycle->elems[idx++] = pairs[cur_pair_idx].out_reg;
207                         cycle->n_elems++;
208
209                         n_pairs_done++;
210                 }
211                 else {
212                         /* we are there where we started -> CYCLE */
213                         cycle->type = PERM_CYCLE;
214                 }
215         }
216
217         /* mark all pairs having one in/out register with cycle in common as checked */
218         for (idx = 0; idx < cycle->n_elems; idx++) {
219                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 0);
220
221                 if (cur_pair_idx >= 0)
222                         pairs[cur_pair_idx].checked = 1;
223
224                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 1);
225
226                 if (cur_pair_idx >= 0)
227                         pairs[cur_pair_idx].checked = 1;
228         }
229
230         return cycle;
231 }
232
233 /**
234  * Lowers a perm node.  Resolves cycles and creates a bunch of
235  * copy and swap operations to permute registers.
236  * Note: The caller of this function has to make sure, that irn
237  *       is a Perm node.
238  *
239  * @param irn      The perm node
240  * @param block    The block the perm node belongs to
241  * @param walk_env The environment
242  */
243 static void lower_perm_node(ir_node *irn, void *walk_env) {
244         const arch_register_class_t *reg_class;
245         const arch_env_t            *arch_env;
246         firm_dbg_module_t           *mod;
247         lower_env_t     *env = walk_env;
248         reg_pair_t      *pairs;
249         const ir_edge_t *edge;
250         perm_cycle_t    *cycle;
251         int              n, i, pn, do_copy, j;
252         ir_node         *sched_point, *block, *in[2];
253         ir_node         *arg1, *arg2, *res1, *res2;
254         ir_node         *cpyxchg = NULL;
255
256         arch_env = env->chord_env->main_env->arch_env;
257         do_copy  = env->do_copy;
258         mod      = env->dbg_module;
259         block    = get_nodes_block(irn);
260
261         /*
262                 Get the schedule predecessor node to the perm
263                 NOTE: This works with auto-magic. If we insert the
264                         new copy/exchange nodes after this node, everything
265                         should be ok.
266         */
267         sched_point = sched_prev(irn);
268         DBG((mod, LEVEL_1, "sched point is %+F\n", sched_point));
269         assert(sched_point && "Perm is not scheduled or has no predecessor");
270
271         n = get_irn_arity(irn);
272         assert(n == get_irn_n_edges(irn) && "perm's in and out numbers different");
273
274         reg_class = arch_get_irn_register(arch_env, get_irn_n(irn, 0))->reg_class;
275         pairs     = calloc(n, sizeof(pairs[0]));
276
277         /* build the list of register pairs (in, out) */
278         i = 0;
279         foreach_out_edge(irn, edge) {
280                 pairs[i].out_node = get_edge_src_irn(edge);
281                 pn                = get_Proj_proj(pairs[i].out_node);
282                 pairs[i].in_node  = get_irn_n(irn, pn);
283
284                 pairs[i].in_reg  = arch_get_irn_register(arch_env, pairs[i].in_node);
285                 pairs[i].out_reg = arch_get_irn_register(arch_env, pairs[i].out_node);
286
287                 pairs[i].checked = 0;
288                 i++;
289         }
290
291         /* sort the register pairs by the indices of the in registers */
292         qsort(pairs, n, sizeof(pairs[0]), compare_reg_pair);
293
294         /* Mark all equal pairs as checked, and exchange the OUT proj with
295                 the IN node. */
296         for (i = 0; i < n; i++) {
297                 if (pairs[i].in_reg->index == pairs[i].out_reg->index) {
298                         DBG((mod, LEVEL_1, "%+F removing equal perm register pair (%+F, %+F, %s)\n",
299                                 irn, pairs[i].in_node, pairs[i].out_node, pairs[i].out_reg->name));
300
301                         /* We have to check for a special case:
302                                 The in-node could be a Proj from a Perm. In this case,
303                                 we need to correct the projnum */
304                         if (is_Perm(arch_env, pairs[i].in_node) && is_Proj(pairs[i].in_node)) {
305                                 set_Proj_proj(pairs[i].out_node, get_Proj_proj(pairs[i].in_node));
306                         }
307
308                         /* remove the proj from the schedule */
309                         sched_remove(pairs[i].out_node);
310
311                         /* reroute the edges from the proj to the argument */
312                         edges_reroute(pairs[i].out_node, pairs[i].in_node, env->chord_env->irg);
313
314                         pairs[i].checked = 1;
315                 }
316         }
317
318         /* Set do_copy to 0 if it's on but we have no free register */
319         if (do_copy) {
320                 do_copy = 0;
321         }
322
323         /* check for cycles and chains */
324         while (get_n_checked_pairs(pairs, n) < n) {
325                 i = 0;
326
327                 /* go to the first not-checked pair */
328                 while (pairs[i].checked) i++;
329                 cycle = calloc(1, sizeof(*cycle));
330                 cycle = get_perm_cycle(cycle, pairs, n, i);
331
332                 DB((mod, LEVEL_1, "%+F: following %s created:\n  ", irn, cycle->type == PERM_CHAIN ? "chain" : "cycle"));
333                 for (j = 0; j < cycle->n_elems; j++) {
334                         DB((mod, LEVEL_1, " %s", cycle->elems[j]->name));
335                 }
336                 DB((mod, LEVEL_1, "\n"));
337
338                 /* We don't need to do anything if we have a Perm with two
339                         elements which represents a cycle, because those nodes
340                         already represent exchange nodes */
341                 if (n == 2 && cycle->type == PERM_CYCLE) {
342                         free(cycle);
343                         continue;
344                 }
345
346 //TODO: - iff PERM_CYCLE && do_copy -> determine free temp reg and insert copy to/from it before/after
347 //        the copy cascade (this reduces the cycle into a chain)
348
349                 /* build copy/swap nodes */
350                 for (i = 0; i < cycle->n_elems - 1; i++) {
351                         arg1 = get_node_for_register(pairs, n, cycle->elems[i], 0);
352                         arg2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 0);
353
354                         res1 = get_node_for_register(pairs, n, cycle->elems[i], 1);
355                         res2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 1);
356
357                         /*
358                                 If we have a cycle and don't copy: we need to create exchange nodes
359                                 NOTE: An exchange node is a perm node with 2 INs and 2 OUTs
360                                 IN_1  = in node with register i
361                                 IN_2  = in node with register i + 1
362                                 OUT_1 = out node with register i + 1
363                                 OUT_2 = out node with register i
364                         */
365                         if (cycle->type == PERM_CYCLE && !do_copy) {
366                                 in[0] = arg1;
367                                 in[1] = arg2;
368
369                                 DBG((mod, LEVEL_1, "%+F creating exchange node (%+F, %s) and (%+F, %s) with\n",
370                                         irn, arg1, cycle->elems[i]->name, arg2, cycle->elems[i + 1]->name));
371                                 DBG((mod, LEVEL_1, "%+F                        (%+F, %s) and (%+F, %s)\n",
372                                         irn, res1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
373
374                                 cpyxchg = be_new_Perm(reg_class, env->chord_env->irg, block, 2, in);
375
376                                 sched_remove(res1);
377                                 sched_remove(res2);
378
379                                 set_Proj_pred(res2, cpyxchg);
380                                 set_Proj_proj(res2, 0);
381                                 set_Proj_pred(res1, cpyxchg);
382                                 set_Proj_proj(res1, 1);
383
384                                 sched_add_after(sched_point, res1);
385                                 sched_add_after(sched_point, res2);
386
387                                 arch_set_irn_register(arch_env, res2, cycle->elems[i + 1]);
388                                 arch_set_irn_register(arch_env, res1, cycle->elems[i]);
389                         }
390                         else {
391                                 DBG((mod, LEVEL_1, "%+F creating copy node (%+F, %s) -> (%+F, %s)\n",
392                                         irn, arg1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
393
394                                 cpyxchg = be_new_Copy(reg_class, env->chord_env->irg, block, arg1);
395                                 arch_set_irn_register(arch_env, cpyxchg, cycle->elems[i + 1]);
396
397                                 /* remove the proj from the schedule */
398                                 sched_remove(res2);
399
400                                 /* exchange copy node and proj */
401                                 exchange(res2, cpyxchg);
402                         }
403
404                         /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
405                         sched_add_after(sched_point, cpyxchg);
406
407                         DBG((mod, LEVEL_1, "replacing %+F with %+F, placed new node after %+F\n", irn, cpyxchg, sched_point));
408                 }
409
410                 free(cycle->elems);
411                 free(cycle);
412         }
413
414         /* remove the perm from schedule */
415         sched_remove(irn);
416 }
417
418
419
420 /**
421  * Adds Projs to keep nodes for each register class, which eats the
422  * caller saved registers.
423  * Note: The caller has to make sure, that call is a Call
424  *
425  * @param call     The Call node
426  * @param walk_env The walker environment
427  */
428 static void lower_call_node(ir_node *call, const void *walk_env) {
429         const arch_env_t            *arch_env = walk_env;
430         const arch_register_class_t *reg_class;
431         int                          i, j, set_size = 0, pn, keep_arity;
432         arch_isa_t                  *isa      = arch_env_get_isa(arch_env);
433         const ir_node               *proj_T   = NULL;
434         ir_node                     **in_keep, *block = get_nodes_block(call);
435         bitset_t                    *proj_set;
436         const ir_edge_t             *edge;
437         const arch_register_t       *reg;
438
439         /* Prepare the bitset where we store the projnums which are already in use*/
440         for (i = 0; i < arch_isa_get_n_reg_class(isa); i++) {
441                 reg_class  = arch_isa_get_reg_class(isa, i);
442                 set_size  += arch_register_class_n_regs(reg_class);
443         }
444
445         in_keep = malloc(set_size * sizeof(ir_node *));
446
447         proj_set = bitset_malloc(set_size);
448         bitset_clear_all(proj_set);
449
450         /* check if there is a ProjT node and which arguments are used */
451         foreach_out_edge(call, edge) {
452                 if (get_irn_mode(get_edge_src_irn(edge)) == mode_T)
453                         proj_T = get_edge_src_irn(edge);
454         }
455
456         /* set all used arguments */
457         if (proj_T) {
458                 foreach_out_edge(proj_T, edge) {
459                         ir_node *proj = get_edge_src_irn(edge);
460
461                         assert(is_Proj(proj));
462                         bitset_set(proj_set, get_Proj_proj(proj));
463                 }
464         }
465         else {
466                 proj_T = new_r_Proj(current_ir_graph, block, call, mode_T, pn_Call_T_result);
467                 last_proj = call;
468         }
469
470         /* Create for each caller save register a proj (keep node argument) */
471         /* if this proj is not already present */
472         for (i = 0; i < arch_isa_get_n_reg_class(isa); i++) {
473
474                 /* reset the keep input, as we need one keep for each register class */
475                 memset(in_keep, 0, set_size * sizeof(ir_node *));
476                 keep_arity = 0;
477                 reg_class  = arch_isa_get_reg_class(isa, i);
478
479                 for (j = 0; j < arch_register_class_n_regs(reg_class); j++) {
480                         reg = arch_register_for_index(reg_class, j);
481
482                         /* only check caller save registers */
483                         if (arch_register_type_is(reg, caller_saved)) {
484                                 pn = isa->impl->get_projnum_for_register(isa, reg);
485                                 if (!bitset_is_set(proj_set, pn)) {
486                                         ir_node *proj = new_r_Proj(current_ir_graph, block, (ir_node *)proj_T, mode_Is, pn);
487
488                                         in_keep[keep_arity++] = proj;
489                                 }
490                         }
491                 }
492
493                 /* ok, we found some caller save register which are not in use but must be saved */
494                 if (keep_arity) {
495                         be_new_Keep(reg_class, current_ir_graph, block, keep_arity, in_keep);
496                 }
497         }
498
499         bitset_free(proj_set);
500         return;
501 }
502
503
504
505 /**
506  * Calls the backend code generator functions to lower Spill and
507  * Reload nodes into Store and Load. The backend is fully responsible
508  * for creating the new nodes and setting their input correct.
509  * Note: The caller of this has to make sure that irn is a Spill
510  *       or Reload!
511  *
512  * @param irn      The Spill/Reload node
513  * @param walk_env The walker environment
514  */
515 static void lower_spill_reload(ir_node *irn, void *walk_env) {
516         lower_env_t           *env  = walk_env;
517         arch_code_generator_t *cg   = env->chord_env->main_env->cg;
518         const arch_env_t      *aenv = env->chord_env->main_env->arch_env;
519         ir_node               *res  = NULL;
520         ir_node               *sched_point;
521
522         if (be_is_Spill(irn) && cg->impl->lower_spill) {
523                 res = cg->impl->lower_spill(cg, irn);
524         }
525         else if (be_is_Reload(irn) && cg->impl->lower_reload) {
526                 res = cg->impl->lower_reload(cg, irn);
527                 if (res && res != irn) {
528                         /* copy the result register from the reload to the load */
529                         arch_set_irn_register(aenv, res, arch_get_irn_register(aenv, irn));
530                 }
531         }
532
533         if (res && res != irn) {
534                 sched_point = sched_prev(irn);
535                 sched_remove(irn);
536                 exchange(irn, res);
537                 sched_add_after(sched_point, res);
538         }
539         else {
540                 DBG((env->dbg_module, LEVEL_1, "node %+F not lowered\n", irn));
541         }
542
543         return;
544 }
545
546
547 /**
548  * Calls the corresponding lowering function for the node.
549  *
550  * @param irn      The node to be checked for lowering
551  * @param walk_env The walker environment
552  */
553 static void lower_nodes_before_sched_walker(ir_node *irn, const void *walk_env) {
554         const arch_env_t *arch_env = walk_env;
555
556         if (!is_Block(irn) && !is_Proj(irn)) {
557                 if (is_Call(arch_env, irn)) {
558                         lower_call_node(irn, walk_env);
559                 }
560         }
561
562         return;
563 }
564
565
566 /**
567  * Calls the corresponding lowering function for the node.
568  *
569  * @param irn      The node to be checked for lowering
570  * @param walk_env The walker environment
571  */
572 static void lower_nodes_after_ra_walker(ir_node *irn, void *walk_env) {
573         lower_env_t      *env      = walk_env;
574         const arch_env_t *arch_env = env->chord_env->main_env->arch_env;
575
576         if (!is_Block(irn) && !is_Proj(irn)) {
577                 if (is_Perm(arch_env, irn)) {
578                         lower_perm_node(irn, walk_env);
579                 }
580                 else if (be_is_Spill(irn) || be_is_Reload(irn)) {
581                         lower_spill_reload(irn, walk_env);
582                 }
583         }
584
585         return;
586 }
587
588
589
590 /**
591  * Walks over all blocks in an irg and performs lowering need
592  * to be done before scheduling (e.g. call lowering).
593  *
594  * @param chord_env The chordal environment containing the irg
595  * @param do_copy   1 == resolve cycles with a free reg if available
596  */
597 void lower_nodes_before_sched(ir_graph *irg, const void *env) {
598         irg_walk_blkwise_graph(irg, NULL, lower_nodes_before_sched_walker, env);
599 }
600
601
602
603 /**
604  * Walks over all blocks in an irg and performs lowering need to be
605  * done after register allocation (e.g. perm and spill/reload lowering).
606  *
607  * @param chord_env The chordal environment containing the irg
608  * @param do_copy   1 == resolve cycles with a free reg if available
609  */
610 void lower_nodes_after_ra(be_chordal_env_t *chord_env, int do_copy) {
611         lower_env_t env;
612
613         env.chord_env  = chord_env;
614         env.do_copy    = do_copy;
615         env.dbg_module = firm_dbg_register("ir.be.lower");
616
617         irg_walk_blkwise_graph(chord_env->irg, NULL, lower_nodes_after_ra_walker, &env);
618 }
619
620 #undef is_Perm
621 #undef is_Call