7c8353618243331b14c9e63a1e98a3c1149bc797
[libfirm] / ir / opt / return.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   Normalize returns.
23  * @author  Michael Beck
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include <stdbool.h>
29
30 #include "iroptimize.h"
31 #include "irgraph_t.h"
32 #include "ircons_t.h"
33 #include "irnode_t.h"
34 #include "irgmod.h"
35 #include "irpass.h"
36 #include "util.h"
37 #include "raw_bitset.h"
38
39 /*
40  * Normalize the Returns of a graph by creating a new End block
41  * with One Return(Phi).
42  * This is the preferred input for the if-conversion.
43  *
44  * In pseudocode, it means:
45  *
46  * if (a)
47  *   return b;
48  * else
49  *   return c;
50  *
51  * is transformed into
52  *
53  * if (a)
54  *   res = b;
55  * else
56  *   res = c;
57  * return res;
58  */
59 void normalize_one_return(ir_graph *irg)
60 {
61         ir_node   *endbl         = get_irg_end_block(irg);
62         ir_entity *entity        = get_irg_entity(irg);
63         ir_type   *type          = get_entity_type(entity);
64         int        n_ret_vals    = get_method_n_ress(type) + 1;
65         int        n_rets        = 0;
66         bool       filter_dbgi   = false;
67         dbg_info  *combined_dbgi = NULL;
68         unsigned  *returns;
69         int i, j, k, n, last_idx;
70         ir_node **in, **retvals, **endbl_in;
71         ir_node *block;
72
73         /* look, if we have more than one return */
74         n = get_Block_n_cfgpreds(endbl);
75         if (n <= 0) {
76                 /* The end block has no predecessors, we have an endless
77                    loop. In that case, no returns exists. */
78                 return;
79         }
80
81         rbitset_alloca(returns, n);
82
83         for (i = 0; i < n; ++i) {
84                 ir_node *node = get_Block_cfgpred(endbl, i);
85
86                 if (is_Return(node)) {
87                         dbg_info *dbgi = get_irn_dbg_info(node);
88
89                         if (dbgi != NULL && dbgi != combined_dbgi) {
90                                 if (filter_dbgi) {
91                                         combined_dbgi = NULL;
92                                 } else {
93                                         combined_dbgi = dbgi;
94                                         filter_dbgi   = true;
95                                 }
96                         }
97
98                         ++n_rets;
99                         rbitset_set(returns, i);
100                 }
101         }
102
103         if (n_rets <= 1)
104                 return;
105
106         in       = ALLOCAN(ir_node*, MAX(n_rets, n_ret_vals));
107         retvals  = ALLOCAN(ir_node*, n_rets * n_ret_vals);
108         endbl_in = ALLOCAN(ir_node*, n);
109
110         last_idx = 0;
111         for (j = i = 0; i < n; ++i) {
112                 ir_node *ret = get_Block_cfgpred(endbl, i);
113
114                 if (rbitset_is_set(returns, i)) {
115                         ir_node *block = get_nodes_block(ret);
116
117                         /* create a new Jmp for every Ret and place the in in */
118                         in[j] = new_r_Jmp(block);
119
120                         /* save the return values and shuffle them */
121                         for (k = 0; k < n_ret_vals; ++k)
122                                 retvals[j + k*n_rets] = get_irn_n(ret, k);
123
124                         ++j;
125                 } else {
126                         endbl_in[last_idx++] = ret;
127                 }
128         }
129
130         /* ok, create a new block with all created in's */
131         block = new_r_Block(irg, n_rets, in);
132
133         /* now create the Phi nodes */
134         for (j = i = 0; i < n_ret_vals; ++i, j += n_rets) {
135                 ir_mode *mode = get_irn_mode(retvals[j]);
136                 in[i] = new_r_Phi(block, n_rets, &retvals[j], mode);
137         }
138
139         endbl_in[last_idx++] = new_rd_Return(combined_dbgi, block, in[0], n_ret_vals-1, &in[1]);
140
141         set_irn_in(endbl, last_idx, endbl_in);
142
143         /* invalidate analysis information:
144          * a new Block was added, so dominator, outs and loop are inconsistent,
145          * trouts and callee-state should be still valid
146          */
147         clear_irg_state(irg, IR_GRAPH_STATE_CONSISTENT_DOMINANCE
148                            | IR_GRAPH_STATE_VALID_EXTENDED_BLOCKS);
149 }
150
151 /* Create a graph pass. */
152 ir_graph_pass_t *normalize_one_return_pass(const char *name)
153 {
154         return def_graph_pass(name ? name : "one_ret", normalize_one_return);
155 }
156
157 /**
158  * Check, whether a Return can be moved on block upwards.
159  *
160  * In a block with a Return, all live nodes must be linked
161  * with the Return, otherwise they are dead (because the Return leaves
162  * the graph, so no more users of the other nodes can exists.
163  *
164  * We can move a Return, if its predecessors are Phi nodes or
165  * comes from another block. In the later case, it is always possible
166  * to move the Return one block up, because the predecessor block must
167  * dominate the Return block (SSA) and then it dominates the predecessor
168  * block of the Return block as well.
169  *
170  * All predecessors of the Return block must be Jmp's of course, or we
171  * cannot move it up, so we add blocks if needed.
172  */
173 static bool can_move_ret(ir_node *ret)
174 {
175         ir_node *retbl = get_nodes_block(ret);
176         int i, n = get_irn_arity(ret);
177
178         for (i = 0; i < n; ++i) {
179                 ir_node *pred = get_irn_n(ret, i);
180
181                 if (! is_Phi(pred) && retbl == get_nodes_block(pred)) {
182                         /* first condition failed, found a non-Phi predecessor
183                          * then is in the Return block */
184                         return false;
185                 }
186         }
187
188         /* check, that predecessors are Jmps */
189         n = get_Block_n_cfgpreds(retbl);
190         /* we cannot move above a labeled block, as this might kill the block */
191         if (n <= 1 || has_Block_entity(retbl))
192                 return false;
193         for (i = 0; i < n; ++i) {
194                 ir_node *pred = get_Block_cfgpred(retbl, i);
195
196                 pred = skip_Tuple(pred);
197                 if (! is_Jmp(pred) && !is_Bad(pred)) {
198                         /* simply place a new block here */
199                         ir_graph *irg  = get_irn_irg(retbl);
200                         ir_node *block = new_r_Block(irg, 1, &pred);
201                         ir_node *jmp   = new_r_Jmp(block);
202                         set_Block_cfgpred(retbl, i, jmp);
203                 }
204         }
205         return true;
206 }
207
208 /*
209  * Normalize the Returns of a graph by moving
210  * the Returns upwards as much as possible.
211  * This might be preferred for code generation.
212  *
213  * In pseudocode, it means:
214  *
215  * if (a)
216  *   res = b;
217  * else
218  *   res = c;
219  * return res;
220  *
221  * is transformed into
222  *
223  * if (a)
224  *   return b;
225  * else
226  *   return c;
227  */
228 void normalize_n_returns(ir_graph *irg)
229 {
230         int i, j, n;
231         ir_node  *list     = NULL;
232         ir_node  *final    = NULL;
233         unsigned  n_rets   = 0;
234         unsigned  n_finals = 0;
235         ir_node  *endbl    = get_irg_end_block(irg);
236         int       n_ret_vals;
237         ir_node **in;
238         ir_node  *end;
239
240         /*
241          * First, link all returns:
242          * These must be predecessors of the endblock.
243          * Place Returns that can be moved on list, all others
244          * on final.
245          */
246         n = get_Block_n_cfgpreds(endbl);
247         for (i = 0; i < n; ++i) {
248                 ir_node *ret = get_Block_cfgpred(endbl, i);
249
250                 if (is_Bad(ret)) {
251                         continue;
252                 } else if (is_Return(ret) && can_move_ret(ret)) {
253                         /*
254                          * Ok, all conditions met, we can move this Return, put it
255                          * on our work list.
256                          */
257                         set_irn_link(ret, list);
258                         list = ret;
259                         ++n_rets;
260                 } else {
261                         /* Put all nodes that are not changed on the final list. */
262                         set_irn_link(ret, final);
263                         final = ret;
264                         ++n_finals;
265                 }
266         }
267
268         if (n_rets == 0)
269                 return;
270
271         /*
272          * Now move the Returns upwards. We move always one block up (and create n
273          * new Returns), than we check if a newly created Return can be moved even
274          * further. If yes, we simply add it to our work list, else to the final
275          * list.
276          */
277         end        = get_irg_end(irg);
278         n_ret_vals = get_irn_arity(list);
279         in         = ALLOCAN(ir_node*, n_ret_vals);
280         while (list != NULL) {
281                 ir_node  *ret   = list;
282                 ir_node  *block = get_nodes_block(ret);
283                 dbg_info *dbgi  = get_irn_dbg_info(ret);
284                 ir_node  *phiM;
285
286                 list = (ir_node*)get_irn_link(ret);
287                 --n_rets;
288
289                 n = get_Block_n_cfgpreds(block);
290                 for (i = 0; i < n; ++i) {
291                         ir_node *jmp = get_Block_cfgpred(block, i);
292                         ir_node *new_bl, *new_ret;
293
294                         if (is_Bad(jmp))
295                                 continue;
296                         assert(is_Jmp(jmp));
297
298                         new_bl = get_nodes_block(jmp);
299
300                         /* create the in-array for the new Return */
301                         for (j = 0; j < n_ret_vals; ++j) {
302                                 ir_node *pred = get_irn_n(ret, j);
303
304                                 in[j] = (is_Phi(pred) && get_nodes_block(pred) == block) ? get_Phi_pred(pred, i) : pred;
305                         }
306
307                         new_ret = new_rd_Return(dbgi, new_bl, in[0], n_ret_vals-1, &in[1]);
308
309                         if (! is_Bad(new_ret)) {
310                                 /*
311                                  * The newly created node might be bad, if we
312                                  * create it in a block with only Bad predecessors.
313                                  * In that case ignore this block.
314                                  *
315                                  * We could even kill the jmp then ...
316                                  */
317                                 if (can_move_ret(new_ret)) {
318                                         set_irn_link(new_ret, list);
319                                         list = new_ret;
320                                         ++n_rets;
321                                 } else {
322                                         set_irn_link(new_ret, final);
323                                         final = new_ret;
324                                         ++n_finals;
325                                 }
326                         }
327
328                         /* remove the Jmp, we have placed a Return here */
329                         exchange(jmp, new_r_Bad(irg, mode_X));
330                 }
331
332                 /*
333                  * if the memory of the old Return is a PhiM, remove it
334                  * from the keep-alives, or it will keep the block which
335                  * will crash the dominator algorithm.
336                  */
337                 phiM = get_Return_mem(ret);
338                 if (is_Phi(phiM)) {
339                         n = get_End_n_keepalives(end);
340                         for (i = 0; i < n; ++i) {
341                                 if (get_End_keepalive(end, i) == phiM) {
342                                         set_End_keepalive(end, i, new_r_Bad(irg, mode_M));
343                                         break;
344                                 }
345                         }
346                 }
347         }
348
349         /*
350          * Last step: Create a new endblock, with all nodes on the final list as
351          * predecessors.
352          */
353         in = ALLOCAN(ir_node*, n_finals);
354
355         for (i = 0; final != NULL; ++i, final = (ir_node*)get_irn_link(final)) {
356                 in[i] = final;
357         }
358
359         exchange(endbl, new_r_Block(irg, n_finals, in));
360
361         /* Invalidate analysis information:
362          * Blocks become dead and new Returns were deleted, so dominator, outs and
363          * loop are inconsistent, trouts and callee-state should be still valid */
364         clear_irg_state(irg, IR_GRAPH_STATE_CONSISTENT_DOMINANCE
365                            | IR_GRAPH_STATE_CONSISTENT_POSTDOMINANCE
366                            | IR_GRAPH_STATE_ONE_RETURN
367                            | IR_GRAPH_STATE_CONSISTENT_OUTS
368                            | IR_GRAPH_STATE_NO_UNREACHABLE_CODE
369                            | IR_GRAPH_STATE_NO_BADS
370                            | IR_GRAPH_STATE_VALID_EXTENDED_BLOCKS);
371 }
372
373 /* Create a graph pass. */
374 ir_graph_pass_t *normalize_n_returns_pass(const char *name)
375 {
376         return def_graph_pass(name ? name : "n_rets", normalize_n_returns);
377 }