OSDN Git Service

2009-07-30 Martin Jambor <mjambor@suse.cz>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-manip.c
1 /* High-level loop manipulation functions.
2    Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
3    
4 This file is part of GCC.
5    
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10    
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15    
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "tree.h"
25 #include "rtl.h"
26 #include "tm_p.h"
27 #include "hard-reg-set.h"
28 #include "basic-block.h"
29 #include "output.h"
30 #include "diagnostic.h"
31 #include "tree-flow.h"
32 #include "tree-dump.h"
33 #include "timevar.h"
34 #include "cfgloop.h"
35 #include "tree-pass.h"
36 #include "cfglayout.h"
37 #include "tree-scalar-evolution.h"
38 #include "params.h"
39 #include "tree-inline.h"
40 #include "langhooks.h"
41
42 /* Creates an induction variable with value BASE + STEP * iteration in LOOP.
43    It is expected that neither BASE nor STEP are shared with other expressions
44    (unless the sharing rules allow this).  Use VAR as a base var_decl for it
45    (if NULL, a new temporary will be created).  The increment will occur at
46    INCR_POS (after it if AFTER is true, before it otherwise).  INCR_POS and 
47    AFTER can be computed using standard_iv_increment_position.  The ssa versions
48    of the variable before and after increment will be stored in VAR_BEFORE and
49    VAR_AFTER (unless they are NULL).  */
50
51 void
52 create_iv (tree base, tree step, tree var, struct loop *loop,
53            gimple_stmt_iterator *incr_pos, bool after,
54            tree *var_before, tree *var_after)
55 {
56   gimple stmt;
57   tree initial, step1;
58   gimple_seq stmts;
59   tree vb, va;
60   enum tree_code incr_op = PLUS_EXPR;
61   edge pe = loop_preheader_edge (loop);
62
63   if (!var)
64     {
65       var = create_tmp_var (TREE_TYPE (base), "ivtmp");
66       add_referenced_var (var);
67     }
68
69   vb = make_ssa_name (var, NULL);
70   if (var_before)
71     *var_before = vb;
72   va = make_ssa_name (var, NULL);
73   if (var_after)
74     *var_after = va;
75
76   /* For easier readability of the created code, produce MINUS_EXPRs
77      when suitable.  */
78   if (TREE_CODE (step) == INTEGER_CST)
79     {
80       if (TYPE_UNSIGNED (TREE_TYPE (step)))
81         {
82           step1 = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
83           if (tree_int_cst_lt (step1, step))
84             {
85               incr_op = MINUS_EXPR;
86               step = step1;
87             }
88         }
89       else
90         {
91           bool ovf;
92
93           if (!tree_expr_nonnegative_warnv_p (step, &ovf)
94               && may_negate_without_overflow_p (step))
95             {
96               incr_op = MINUS_EXPR;
97               step = fold_build1 (NEGATE_EXPR, TREE_TYPE (step), step);
98             }
99         }
100     }
101   if (POINTER_TYPE_P (TREE_TYPE (base)))
102     {
103       if (TREE_CODE (base) == ADDR_EXPR)
104         mark_addressable (TREE_OPERAND (base, 0));
105       step = fold_convert (sizetype, step);
106       if (incr_op == MINUS_EXPR)
107         step = fold_build1 (NEGATE_EXPR, sizetype, step);
108       incr_op = POINTER_PLUS_EXPR;
109     }
110   /* Gimplify the step if necessary.  We put the computations in front of the
111      loop (i.e. the step should be loop invariant).  */
112   step = force_gimple_operand (step, &stmts, true, NULL_TREE);
113   if (stmts)
114     gsi_insert_seq_on_edge_immediate (pe, stmts);
115
116   stmt = gimple_build_assign_with_ops (incr_op, va, vb, step);
117   if (after)
118     gsi_insert_after (incr_pos, stmt, GSI_NEW_STMT);
119   else
120     gsi_insert_before (incr_pos, stmt, GSI_NEW_STMT);
121
122   initial = force_gimple_operand (base, &stmts, true, var);
123   if (stmts)
124     gsi_insert_seq_on_edge_immediate (pe, stmts);
125
126   stmt = create_phi_node (vb, loop->header);
127   SSA_NAME_DEF_STMT (vb) = stmt;
128   add_phi_arg (stmt, initial, loop_preheader_edge (loop));
129   add_phi_arg (stmt, va, loop_latch_edge (loop));
130 }
131
132 /* Add exit phis for the USE on EXIT.  */
133
134 static void
135 add_exit_phis_edge (basic_block exit, tree use)
136 {
137   gimple phi, def_stmt = SSA_NAME_DEF_STMT (use);
138   basic_block def_bb = gimple_bb (def_stmt);
139   struct loop *def_loop;
140   edge e;
141   edge_iterator ei;
142
143   /* Check that some of the edges entering the EXIT block exits a loop in
144      that USE is defined.  */
145   FOR_EACH_EDGE (e, ei, exit->preds)
146     {
147       def_loop = find_common_loop (def_bb->loop_father, e->src->loop_father);
148       if (!flow_bb_inside_loop_p (def_loop, e->dest))
149         break;
150     }
151
152   if (!e)
153     return;
154
155   phi = create_phi_node (use, exit);
156   create_new_def_for (gimple_phi_result (phi), phi,
157                       gimple_phi_result_ptr (phi));
158   FOR_EACH_EDGE (e, ei, exit->preds)
159     add_phi_arg (phi, use, e);
160 }
161
162 /* Add exit phis for VAR that is used in LIVEIN.
163    Exits of the loops are stored in EXITS.  */
164
165 static void
166 add_exit_phis_var (tree var, bitmap livein, bitmap exits)
167 {
168   bitmap def;
169   unsigned index;
170   basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (var));
171   bitmap_iterator bi;
172
173   if (is_gimple_reg (var))
174     bitmap_clear_bit (livein, def_bb->index);
175   else
176     bitmap_set_bit (livein, def_bb->index);
177
178   def = BITMAP_ALLOC (NULL);
179   bitmap_set_bit (def, def_bb->index);
180   compute_global_livein (livein, def);
181   BITMAP_FREE (def);
182
183   EXECUTE_IF_AND_IN_BITMAP (exits, livein, 0, index, bi)
184     {
185       add_exit_phis_edge (BASIC_BLOCK (index), var);
186     }
187 }
188
189 /* Add exit phis for the names marked in NAMES_TO_RENAME.
190    Exits of the loops are stored in EXITS.  Sets of blocks where the ssa
191    names are used are stored in USE_BLOCKS.  */
192
193 static void
194 add_exit_phis (bitmap names_to_rename, bitmap *use_blocks, bitmap loop_exits)
195 {
196   unsigned i;
197   bitmap_iterator bi;
198
199   EXECUTE_IF_SET_IN_BITMAP (names_to_rename, 0, i, bi)
200     {
201       add_exit_phis_var (ssa_name (i), use_blocks[i], loop_exits);
202     }
203 }
204
205 /* Returns a bitmap of all loop exit edge targets.  */
206
207 static bitmap
208 get_loops_exits (void)
209 {
210   bitmap exits = BITMAP_ALLOC (NULL);
211   basic_block bb;
212   edge e;
213   edge_iterator ei;
214
215   FOR_EACH_BB (bb)
216     {
217       FOR_EACH_EDGE (e, ei, bb->preds)
218         if (e->src != ENTRY_BLOCK_PTR
219             && !flow_bb_inside_loop_p (e->src->loop_father, bb))
220           {
221             bitmap_set_bit (exits, bb->index);
222             break;
223           }
224     }
225
226   return exits;
227 }
228
229 /* For USE in BB, if it is used outside of the loop it is defined in,
230    mark it for rewrite.  Record basic block BB where it is used
231    to USE_BLOCKS.  Record the ssa name index to NEED_PHIS bitmap.  */
232
233 static void
234 find_uses_to_rename_use (basic_block bb, tree use, bitmap *use_blocks,
235                          bitmap need_phis)
236 {
237   unsigned ver;
238   basic_block def_bb;
239   struct loop *def_loop;
240
241   if (TREE_CODE (use) != SSA_NAME)
242     return;
243
244   /* We don't need to keep virtual operands in loop-closed form.  */
245   if (!is_gimple_reg (use))
246     return;
247
248   ver = SSA_NAME_VERSION (use);
249   def_bb = gimple_bb (SSA_NAME_DEF_STMT (use));
250   if (!def_bb)
251     return;
252   def_loop = def_bb->loop_father;
253
254   /* If the definition is not inside a loop, it is not interesting.  */
255   if (!loop_outer (def_loop))
256     return;
257
258   /* If the use is not outside of the loop it is defined in, it is not
259      interesting.  */
260   if (flow_bb_inside_loop_p (def_loop, bb))
261     return;
262
263   if (!use_blocks[ver])
264     use_blocks[ver] = BITMAP_ALLOC (NULL);
265   bitmap_set_bit (use_blocks[ver], bb->index);
266
267   bitmap_set_bit (need_phis, ver);
268 }
269
270 /* For uses in STMT, mark names that are used outside of the loop they are
271    defined to rewrite.  Record the set of blocks in that the ssa
272    names are defined to USE_BLOCKS and the ssa names themselves to
273    NEED_PHIS.  */
274
275 static void
276 find_uses_to_rename_stmt (gimple stmt, bitmap *use_blocks, bitmap need_phis)
277 {
278   ssa_op_iter iter;
279   tree var;
280   basic_block bb = gimple_bb (stmt);
281
282   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
283     find_uses_to_rename_use (bb, var, use_blocks, need_phis);
284 }
285
286 /* Marks names that are used in BB and outside of the loop they are
287    defined in for rewrite.  Records the set of blocks in that the ssa
288    names are defined to USE_BLOCKS.  Record the SSA names that will
289    need exit PHIs in NEED_PHIS.  */
290
291 static void
292 find_uses_to_rename_bb (basic_block bb, bitmap *use_blocks, bitmap need_phis)
293 {
294   gimple_stmt_iterator bsi;
295   edge e;
296   edge_iterator ei;
297
298   FOR_EACH_EDGE (e, ei, bb->succs)
299     for (bsi = gsi_start_phis (e->dest); !gsi_end_p (bsi); gsi_next (&bsi))
300       find_uses_to_rename_use (bb, PHI_ARG_DEF_FROM_EDGE (gsi_stmt (bsi), e),
301                                use_blocks, need_phis);
302  
303   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
304     find_uses_to_rename_stmt (gsi_stmt (bsi), use_blocks, need_phis);
305 }
306      
307 /* Marks names that are used outside of the loop they are defined in
308    for rewrite.  Records the set of blocks in that the ssa
309    names are defined to USE_BLOCKS.  If CHANGED_BBS is not NULL,
310    scan only blocks in this set.  */
311
312 static void
313 find_uses_to_rename (bitmap changed_bbs, bitmap *use_blocks, bitmap need_phis)
314 {
315   basic_block bb;
316   unsigned index;
317   bitmap_iterator bi;
318
319   if (changed_bbs && !bitmap_empty_p (changed_bbs))
320     {
321       EXECUTE_IF_SET_IN_BITMAP (changed_bbs, 0, index, bi)
322         {
323           find_uses_to_rename_bb (BASIC_BLOCK (index), use_blocks, need_phis);
324         }
325     }
326   else
327     {
328       FOR_EACH_BB (bb)
329         {
330           find_uses_to_rename_bb (bb, use_blocks, need_phis);
331         }
332     }
333 }
334
335 /* Rewrites the program into a loop closed ssa form -- i.e. inserts extra
336    phi nodes to ensure that no variable is used outside the loop it is
337    defined in.
338
339    This strengthening of the basic ssa form has several advantages:
340
341    1) Updating it during unrolling/peeling/versioning is trivial, since
342       we do not need to care about the uses outside of the loop.
343    2) The behavior of all uses of an induction variable is the same.
344       Without this, you need to distinguish the case when the variable
345       is used outside of the loop it is defined in, for example
346
347       for (i = 0; i < 100; i++)
348         {
349           for (j = 0; j < 100; j++)
350             {
351               k = i + j;
352               use1 (k);
353             }
354           use2 (k);
355         }
356
357       Looking from the outer loop with the normal SSA form, the first use of k
358       is not well-behaved, while the second one is an induction variable with
359       base 99 and step 1.
360       
361       If CHANGED_BBS is not NULL, we look for uses outside loops only in
362       the basic blocks in this set.
363
364       UPDATE_FLAG is used in the call to update_ssa.  See
365       TODO_update_ssa* for documentation.  */
366
367 void
368 rewrite_into_loop_closed_ssa (bitmap changed_bbs, unsigned update_flag)
369 {
370   bitmap loop_exits;
371   bitmap *use_blocks;
372   unsigned i, old_num_ssa_names;
373   bitmap names_to_rename;
374
375   loops_state_set (LOOP_CLOSED_SSA);
376   if (number_of_loops () <= 1)
377     return;
378
379   loop_exits = get_loops_exits ();
380   names_to_rename = BITMAP_ALLOC (NULL);
381
382   /* If the pass has caused the SSA form to be out-of-date, update it
383      now.  */
384   update_ssa (update_flag);
385
386   old_num_ssa_names = num_ssa_names;
387   use_blocks = XCNEWVEC (bitmap, old_num_ssa_names);
388
389   /* Find the uses outside loops.  */
390   find_uses_to_rename (changed_bbs, use_blocks, names_to_rename);
391
392   /* Add the PHI nodes on exits of the loops for the names we need to
393      rewrite.  */
394   add_exit_phis (names_to_rename, use_blocks, loop_exits);
395
396   for (i = 0; i < old_num_ssa_names; i++)
397     BITMAP_FREE (use_blocks[i]);
398   free (use_blocks);
399   BITMAP_FREE (loop_exits);
400   BITMAP_FREE (names_to_rename);
401
402   /* Fix up all the names found to be used outside their original
403      loops.  */
404   update_ssa (TODO_update_ssa);
405 }
406
407 /* Check invariants of the loop closed ssa form for the USE in BB.  */
408
409 static void
410 check_loop_closed_ssa_use (basic_block bb, tree use)
411 {
412   gimple def;
413   basic_block def_bb;
414   
415   if (TREE_CODE (use) != SSA_NAME || !is_gimple_reg (use))
416     return;
417
418   def = SSA_NAME_DEF_STMT (use);
419   def_bb = gimple_bb (def);
420   gcc_assert (!def_bb
421               || flow_bb_inside_loop_p (def_bb->loop_father, bb));
422 }
423
424 /* Checks invariants of loop closed ssa form in statement STMT in BB.  */
425
426 static void
427 check_loop_closed_ssa_stmt (basic_block bb, gimple stmt)
428 {
429   ssa_op_iter iter;
430   tree var;
431
432   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_USES)
433     check_loop_closed_ssa_use (bb, var);
434 }
435
436 /* Checks that invariants of the loop closed ssa form are preserved.  */
437
438 void
439 verify_loop_closed_ssa (void)
440 {
441   basic_block bb;
442   gimple_stmt_iterator bsi;
443   gimple phi;
444   edge e;
445   edge_iterator ei;
446
447   if (number_of_loops () <= 1)
448     return;
449
450   verify_ssa (false);
451
452   FOR_EACH_BB (bb)
453     {
454       for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
455         {
456           phi = gsi_stmt (bsi);
457           FOR_EACH_EDGE (e, ei, bb->preds)
458             check_loop_closed_ssa_use (e->src,
459                                        PHI_ARG_DEF_FROM_EDGE (phi, e));
460         }
461
462       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
463         check_loop_closed_ssa_stmt (bb, gsi_stmt (bsi));
464     }
465 }
466
467 /* Split loop exit edge EXIT.  The things are a bit complicated by a need to
468    preserve the loop closed ssa form.  The newly created block is returned.  */
469
470 basic_block
471 split_loop_exit_edge (edge exit)
472 {
473   basic_block dest = exit->dest;
474   basic_block bb = split_edge (exit);
475   gimple phi, new_phi;
476   tree new_name, name;
477   use_operand_p op_p;
478   gimple_stmt_iterator psi;
479
480   for (psi = gsi_start_phis (dest); !gsi_end_p (psi); gsi_next (&psi))
481     {
482       phi = gsi_stmt (psi);
483       op_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, single_succ_edge (bb));
484
485       name = USE_FROM_PTR (op_p);
486
487       /* If the argument of the PHI node is a constant, we do not need
488          to keep it inside loop.  */
489       if (TREE_CODE (name) != SSA_NAME)
490         continue;
491
492       /* Otherwise create an auxiliary phi node that will copy the value
493          of the SSA name out of the loop.  */
494       new_name = duplicate_ssa_name (name, NULL);
495       new_phi = create_phi_node (new_name, bb);
496       SSA_NAME_DEF_STMT (new_name) = new_phi;
497       add_phi_arg (new_phi, name, exit);
498       SET_USE (op_p, new_name);
499     }
500
501   return bb;
502 }
503
504 /* Returns the basic block in that statements should be emitted for induction
505    variables incremented at the end of the LOOP.  */
506
507 basic_block
508 ip_end_pos (struct loop *loop)
509 {
510   return loop->latch;
511 }
512
513 /* Returns the basic block in that statements should be emitted for induction
514    variables incremented just before exit condition of a LOOP.  */
515
516 basic_block
517 ip_normal_pos (struct loop *loop)
518 {
519   gimple last;
520   basic_block bb;
521   edge exit;
522
523   if (!single_pred_p (loop->latch))
524     return NULL;
525
526   bb = single_pred (loop->latch);
527   last = last_stmt (bb);
528   if (!last
529       || gimple_code (last) != GIMPLE_COND)
530     return NULL;
531
532   exit = EDGE_SUCC (bb, 0);
533   if (exit->dest == loop->latch)
534     exit = EDGE_SUCC (bb, 1);
535
536   if (flow_bb_inside_loop_p (loop, exit->dest))
537     return NULL;
538
539   return bb;
540 }
541
542 /* Stores the standard position for induction variable increment in LOOP
543    (just before the exit condition if it is available and latch block is empty,
544    end of the latch block otherwise) to BSI.  INSERT_AFTER is set to true if
545    the increment should be inserted after *BSI.  */
546
547 void
548 standard_iv_increment_position (struct loop *loop, gimple_stmt_iterator *bsi,
549                                 bool *insert_after)
550 {
551   basic_block bb = ip_normal_pos (loop), latch = ip_end_pos (loop);
552   gimple last = last_stmt (latch);
553
554   if (!bb
555       || (last && gimple_code (last) != GIMPLE_LABEL))
556     {
557       *bsi = gsi_last_bb (latch);
558       *insert_after = true;
559     }
560   else
561     {
562       *bsi = gsi_last_bb (bb);
563       *insert_after = false;
564     }
565 }
566
567 /* Copies phi node arguments for duplicated blocks.  The index of the first
568    duplicated block is FIRST_NEW_BLOCK.  */
569
570 static void
571 copy_phi_node_args (unsigned first_new_block)
572 {
573   unsigned i;
574
575   for (i = first_new_block; i < (unsigned) last_basic_block; i++)
576     BASIC_BLOCK (i)->flags |= BB_DUPLICATED;
577
578   for (i = first_new_block; i < (unsigned) last_basic_block; i++)
579     add_phi_args_after_copy_bb (BASIC_BLOCK (i));
580
581   for (i = first_new_block; i < (unsigned) last_basic_block; i++)
582     BASIC_BLOCK (i)->flags &= ~BB_DUPLICATED;
583 }
584
585
586 /* The same as cfgloopmanip.c:duplicate_loop_to_header_edge, but also
587    updates the PHI nodes at start of the copied region.  In order to
588    achieve this, only loops whose exits all lead to the same location
589    are handled.
590
591    Notice that we do not completely update the SSA web after
592    duplication.  The caller is responsible for calling update_ssa
593    after the loop has been duplicated.  */
594
595 bool
596 gimple_duplicate_loop_to_header_edge (struct loop *loop, edge e,
597                                     unsigned int ndupl, sbitmap wont_exit,
598                                     edge orig, VEC (edge, heap) **to_remove,
599                                     int flags)
600 {
601   unsigned first_new_block;
602
603   if (!loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
604     return false;
605   if (!loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS))
606     return false;
607
608 #ifdef ENABLE_CHECKING
609   if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
610     verify_loop_closed_ssa ();
611 #endif
612
613   first_new_block = last_basic_block;
614   if (!duplicate_loop_to_header_edge (loop, e, ndupl, wont_exit,
615                                       orig, to_remove, flags))
616     return false;
617
618   /* Readd the removed phi args for e.  */
619   flush_pending_stmts (e);
620
621   /* Copy the phi node arguments.  */
622   copy_phi_node_args (first_new_block);
623
624   scev_reset ();
625
626   return true;
627 }
628
629 /* Returns true if we can unroll LOOP FACTOR times.  Number
630    of iterations of the loop is returned in NITER.  */
631
632 bool
633 can_unroll_loop_p (struct loop *loop, unsigned factor,
634                    struct tree_niter_desc *niter)
635 {
636   edge exit;
637
638   /* Check whether unrolling is possible.  We only want to unroll loops
639      for that we are able to determine number of iterations.  We also
640      want to split the extra iterations of the loop from its end,
641      therefore we require that the loop has precisely one
642      exit.  */
643
644   exit = single_dom_exit (loop);
645   if (!exit)
646     return false;
647
648   if (!number_of_iterations_exit (loop, exit, niter, false)
649       || niter->cmp == ERROR_MARK
650       /* Scalar evolutions analysis might have copy propagated
651          the abnormal ssa names into these expressions, hence
652          emitting the computations based on them during loop
653          unrolling might create overlapping life ranges for
654          them, and failures in out-of-ssa.  */
655       || contains_abnormal_ssa_name_p (niter->may_be_zero)
656       || contains_abnormal_ssa_name_p (niter->control.base)
657       || contains_abnormal_ssa_name_p (niter->control.step)
658       || contains_abnormal_ssa_name_p (niter->bound))
659     return false;
660
661   /* And of course, we must be able to duplicate the loop.  */
662   if (!can_duplicate_loop_p (loop))
663     return false;
664
665   /* The final loop should be small enough.  */
666   if (tree_num_loop_insns (loop, &eni_size_weights) * factor
667       > (unsigned) PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS))
668     return false;
669
670   return true;
671 }
672
673 /* Determines the conditions that control execution of LOOP unrolled FACTOR
674    times.  DESC is number of iterations of LOOP.  ENTER_COND is set to
675    condition that must be true if the main loop can be entered.
676    EXIT_BASE, EXIT_STEP, EXIT_CMP and EXIT_BOUND are set to values describing
677    how the exit from the unrolled loop should be controlled.  */
678
679 static void
680 determine_exit_conditions (struct loop *loop, struct tree_niter_desc *desc,
681                            unsigned factor, tree *enter_cond,
682                            tree *exit_base, tree *exit_step,
683                            enum tree_code *exit_cmp, tree *exit_bound)
684 {
685   gimple_seq stmts;
686   tree base = desc->control.base;
687   tree step = desc->control.step;
688   tree bound = desc->bound;
689   tree type = TREE_TYPE (step);
690   tree bigstep, delta;
691   tree min = lower_bound_in_type (type, type);
692   tree max = upper_bound_in_type (type, type);
693   enum tree_code cmp = desc->cmp;
694   tree cond = boolean_true_node, assum;
695
696   /* For pointers, do the arithmetics in the type of step (sizetype).  */
697   base = fold_convert (type, base);
698   bound = fold_convert (type, bound);
699
700   *enter_cond = boolean_false_node;
701   *exit_base = NULL_TREE;
702   *exit_step = NULL_TREE;
703   *exit_cmp = ERROR_MARK;
704   *exit_bound = NULL_TREE;
705   gcc_assert (cmp != ERROR_MARK);
706
707   /* We only need to be correct when we answer question
708      "Do at least FACTOR more iterations remain?" in the unrolled loop.
709      Thus, transforming BASE + STEP * i <> BOUND to
710      BASE + STEP * i < BOUND is ok.  */
711   if (cmp == NE_EXPR)
712     {
713       if (tree_int_cst_sign_bit (step))
714         cmp = GT_EXPR;
715       else
716         cmp = LT_EXPR;
717     }
718   else if (cmp == LT_EXPR)
719     {
720       gcc_assert (!tree_int_cst_sign_bit (step));
721     }
722   else if (cmp == GT_EXPR)
723     {
724       gcc_assert (tree_int_cst_sign_bit (step));
725     }
726   else
727     gcc_unreachable ();
728
729   /* The main body of the loop may be entered iff:
730
731      1) desc->may_be_zero is false.
732      2) it is possible to check that there are at least FACTOR iterations
733         of the loop, i.e., BOUND - step * FACTOR does not overflow.
734      3) # of iterations is at least FACTOR  */
735
736   if (!integer_zerop (desc->may_be_zero))
737     cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
738                         invert_truthvalue (desc->may_be_zero),
739                         cond);
740
741   bigstep = fold_build2 (MULT_EXPR, type, step,
742                          build_int_cst_type (type, factor));
743   delta = fold_build2 (MINUS_EXPR, type, bigstep, step);
744   if (cmp == LT_EXPR)
745     assum = fold_build2 (GE_EXPR, boolean_type_node,
746                          bound,
747                          fold_build2 (PLUS_EXPR, type, min, delta));
748   else
749     assum = fold_build2 (LE_EXPR, boolean_type_node,
750                          bound,
751                          fold_build2 (PLUS_EXPR, type, max, delta));
752   cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
753
754   bound = fold_build2 (MINUS_EXPR, type, bound, delta);
755   assum = fold_build2 (cmp, boolean_type_node, base, bound);
756   cond = fold_build2 (TRUTH_AND_EXPR, boolean_type_node, assum, cond);
757
758   cond = force_gimple_operand (unshare_expr (cond), &stmts, false, NULL_TREE);
759   if (stmts)
760     gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
761   /* cond now may be a gimple comparison, which would be OK, but also any
762      other gimple rhs (say a && b).  In this case we need to force it to
763      operand.  */
764   if (!is_gimple_condexpr (cond))
765     {
766       cond = force_gimple_operand (cond, &stmts, true, NULL_TREE);
767       if (stmts)
768         gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
769     }
770   *enter_cond = cond;
771
772   base = force_gimple_operand (unshare_expr (base), &stmts, true, NULL_TREE);
773   if (stmts)
774     gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
775   bound = force_gimple_operand (unshare_expr (bound), &stmts, true, NULL_TREE);
776   if (stmts)
777     gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
778
779   *exit_base = base;
780   *exit_step = bigstep;
781   *exit_cmp = cmp;
782   *exit_bound = bound;
783 }
784
785 /* Scales the frequencies of all basic blocks in LOOP that are strictly
786    dominated by BB by NUM/DEN.  */
787
788 static void
789 scale_dominated_blocks_in_loop (struct loop *loop, basic_block bb,
790                                 int num, int den)
791 {
792   basic_block son;
793
794   if (den == 0)
795     return;
796
797   for (son = first_dom_son (CDI_DOMINATORS, bb);
798        son;
799        son = next_dom_son (CDI_DOMINATORS, son))
800     {
801       if (!flow_bb_inside_loop_p (loop, son))
802         continue;
803       scale_bbs_frequencies_int (&son, 1, num, den);
804       scale_dominated_blocks_in_loop (loop, son, num, den);
805     }
806 }
807
808 /* Unroll LOOP FACTOR times.  DESC describes number of iterations of LOOP.
809    EXIT is the exit of the loop to that DESC corresponds.
810
811    If N is number of iterations of the loop and MAY_BE_ZERO is the condition
812    under that loop exits in the first iteration even if N != 0,
813    
814    while (1)
815      {
816        x = phi (init, next);
817
818        pre;
819        if (st)
820          break;
821        post;
822      }
823
824    becomes (with possibly the exit conditions formulated a bit differently,
825    avoiding the need to create a new iv):
826    
827    if (MAY_BE_ZERO || N < FACTOR)
828      goto rest;
829
830    do
831      {
832        x = phi (init, next);
833
834        pre;
835        post;
836        pre;
837        post;
838        ...
839        pre;
840        post;
841        N -= FACTOR;
842        
843      } while (N >= FACTOR);
844
845    rest:
846      init' = phi (init, x);
847
848    while (1)
849      {
850        x = phi (init', next);
851
852        pre;
853        if (st)
854          break;
855        post;
856      }
857  
858    Before the loop is unrolled, TRANSFORM is called for it (only for the
859    unrolled loop, but not for its versioned copy).  DATA is passed to
860    TRANSFORM.  */
861
862 /* Probability in % that the unrolled loop is entered.  Just a guess.  */
863 #define PROB_UNROLLED_LOOP_ENTERED 90
864
865 void
866 tree_transform_and_unroll_loop (struct loop *loop, unsigned factor,
867                                 edge exit, struct tree_niter_desc *desc,
868                                 transform_callback transform,
869                                 void *data)
870 {
871   gimple exit_if;
872   tree ctr_before, ctr_after;
873   tree enter_main_cond, exit_base, exit_step, exit_bound;
874   enum tree_code exit_cmp;
875   gimple phi_old_loop, phi_new_loop, phi_rest;
876   gimple_stmt_iterator psi_old_loop, psi_new_loop;
877   tree init, next, new_init, var;
878   struct loop *new_loop;
879   basic_block rest, exit_bb;
880   edge old_entry, new_entry, old_latch, precond_edge, new_exit;
881   edge new_nonexit, e;
882   gimple_stmt_iterator bsi;
883   use_operand_p op;
884   bool ok;
885   unsigned est_niter, prob_entry, scale_unrolled, scale_rest, freq_e, freq_h;
886   unsigned new_est_niter, i, prob;
887   unsigned irr = loop_preheader_edge (loop)->flags & EDGE_IRREDUCIBLE_LOOP;
888   sbitmap wont_exit;
889   VEC (edge, heap) *to_remove = NULL;
890
891   est_niter = expected_loop_iterations (loop);
892   determine_exit_conditions (loop, desc, factor,
893                              &enter_main_cond, &exit_base, &exit_step,
894                              &exit_cmp, &exit_bound);
895
896   /* Let us assume that the unrolled loop is quite likely to be entered.  */
897   if (integer_nonzerop (enter_main_cond))
898     prob_entry = REG_BR_PROB_BASE;
899   else
900     prob_entry = PROB_UNROLLED_LOOP_ENTERED * REG_BR_PROB_BASE / 100;
901
902   /* The values for scales should keep profile consistent, and somewhat close
903      to correct.
904
905      TODO: The current value of SCALE_REST makes it appear that the loop that
906      is created by splitting the remaining iterations of the unrolled loop is
907      executed the same number of times as the original loop, and with the same
908      frequencies, which is obviously wrong.  This does not appear to cause
909      problems, so we do not bother with fixing it for now.  To make the profile
910      correct, we would need to change the probability of the exit edge of the
911      loop, and recompute the distribution of frequencies in its body because
912      of this change (scale the frequencies of blocks before and after the exit
913      by appropriate factors).  */
914   scale_unrolled = prob_entry;
915   scale_rest = REG_BR_PROB_BASE;
916
917   new_loop = loop_version (loop, enter_main_cond, NULL,
918                            prob_entry, scale_unrolled, scale_rest, true);
919   gcc_assert (new_loop != NULL);
920   update_ssa (TODO_update_ssa);
921
922   /* Determine the probability of the exit edge of the unrolled loop.  */
923   new_est_niter = est_niter / factor;
924
925   /* Without profile feedback, loops for that we do not know a better estimate
926      are assumed to roll 10 times.  When we unroll such loop, it appears to
927      roll too little, and it may even seem to be cold.  To avoid this, we
928      ensure that the created loop appears to roll at least 5 times (but at
929      most as many times as before unrolling).  */
930   if (new_est_niter < 5)
931     {
932       if (est_niter < 5)
933         new_est_niter = est_niter;
934       else
935         new_est_niter = 5;
936     }
937
938   /* Prepare the cfg and update the phi nodes.  Move the loop exit to the
939      loop latch (and make its condition dummy, for the moment).  */
940   rest = loop_preheader_edge (new_loop)->src;
941   precond_edge = single_pred_edge (rest);
942   split_edge (loop_latch_edge (loop));
943   exit_bb = single_pred (loop->latch);
944
945   /* Since the exit edge will be removed, the frequency of all the blocks
946      in the loop that are dominated by it must be scaled by
947      1 / (1 - exit->probability).  */
948   scale_dominated_blocks_in_loop (loop, exit->src,
949                                   REG_BR_PROB_BASE,
950                                   REG_BR_PROB_BASE - exit->probability);
951
952   bsi = gsi_last_bb (exit_bb);
953   exit_if = gimple_build_cond (EQ_EXPR, integer_zero_node,
954                                integer_zero_node,
955                                NULL_TREE, NULL_TREE);
956
957   gsi_insert_after (&bsi, exit_if, GSI_NEW_STMT);
958   new_exit = make_edge (exit_bb, rest, EDGE_FALSE_VALUE | irr);
959   rescan_loop_exit (new_exit, true, false);
960
961   /* Set the probability of new exit to the same of the old one.  Fix
962      the frequency of the latch block, by scaling it back by
963      1 - exit->probability.  */
964   new_exit->count = exit->count;
965   new_exit->probability = exit->probability;
966   new_nonexit = single_pred_edge (loop->latch);
967   new_nonexit->probability = REG_BR_PROB_BASE - exit->probability;
968   new_nonexit->flags = EDGE_TRUE_VALUE;
969   new_nonexit->count -= exit->count;
970   if (new_nonexit->count < 0)
971     new_nonexit->count = 0;
972   scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
973                              REG_BR_PROB_BASE);
974
975   old_entry = loop_preheader_edge (loop);
976   new_entry = loop_preheader_edge (new_loop);
977   old_latch = loop_latch_edge (loop);
978   for (psi_old_loop = gsi_start_phis (loop->header),
979        psi_new_loop = gsi_start_phis (new_loop->header);
980        !gsi_end_p (psi_old_loop);
981        gsi_next (&psi_old_loop), gsi_next (&psi_new_loop))
982     {
983       phi_old_loop = gsi_stmt (psi_old_loop);
984       phi_new_loop = gsi_stmt (psi_new_loop);
985
986       init = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_entry);
987       op = PHI_ARG_DEF_PTR_FROM_EDGE (phi_new_loop, new_entry);
988       gcc_assert (operand_equal_for_phi_arg_p (init, USE_FROM_PTR (op)));
989       next = PHI_ARG_DEF_FROM_EDGE (phi_old_loop, old_latch);
990
991       /* Prefer using original variable as a base for the new ssa name.
992          This is necessary for virtual ops, and useful in order to avoid
993          losing debug info for real ops.  */
994       if (TREE_CODE (next) == SSA_NAME
995           && useless_type_conversion_p (TREE_TYPE (next),
996                                         TREE_TYPE (init)))
997         var = SSA_NAME_VAR (next);
998       else if (TREE_CODE (init) == SSA_NAME
999                && useless_type_conversion_p (TREE_TYPE (init),
1000                                              TREE_TYPE (next)))
1001         var = SSA_NAME_VAR (init);
1002       else if (useless_type_conversion_p (TREE_TYPE (next), TREE_TYPE (init)))
1003         {
1004           var = create_tmp_var (TREE_TYPE (next), "unrinittmp");
1005           add_referenced_var (var);
1006         }
1007       else
1008         {
1009           var = create_tmp_var (TREE_TYPE (init), "unrinittmp");
1010           add_referenced_var (var);
1011         }
1012
1013       new_init = make_ssa_name (var, NULL);
1014       phi_rest = create_phi_node (new_init, rest);
1015       SSA_NAME_DEF_STMT (new_init) = phi_rest;
1016
1017       add_phi_arg (phi_rest, init, precond_edge);
1018       add_phi_arg (phi_rest, next, new_exit);
1019       SET_USE (op, new_init);
1020     }
1021
1022   remove_path (exit);
1023
1024   /* Transform the loop.  */
1025   if (transform)
1026     (*transform) (loop, data);
1027
1028   /* Unroll the loop and remove the exits in all iterations except for the
1029      last one.  */
1030   wont_exit = sbitmap_alloc (factor);
1031   sbitmap_ones (wont_exit);
1032   RESET_BIT (wont_exit, factor - 1);
1033
1034   ok = gimple_duplicate_loop_to_header_edge
1035           (loop, loop_latch_edge (loop), factor - 1,
1036            wont_exit, new_exit, &to_remove, DLTHE_FLAG_UPDATE_FREQ);
1037   free (wont_exit);
1038   gcc_assert (ok);
1039
1040   for (i = 0; VEC_iterate (edge, to_remove, i, e); i++)
1041     {
1042       ok = remove_path (e);
1043       gcc_assert (ok);
1044     }
1045   VEC_free (edge, heap, to_remove);
1046   update_ssa (TODO_update_ssa);
1047
1048   /* Ensure that the frequencies in the loop match the new estimated
1049      number of iterations, and change the probability of the new
1050      exit edge.  */
1051   freq_h = loop->header->frequency;
1052   freq_e = EDGE_FREQUENCY (loop_preheader_edge (loop));
1053   if (freq_h != 0)
1054     scale_loop_frequencies (loop, freq_e * (new_est_niter + 1), freq_h);
1055
1056   exit_bb = single_pred (loop->latch);
1057   new_exit = find_edge (exit_bb, rest);
1058   new_exit->count = loop_preheader_edge (loop)->count;
1059   new_exit->probability = REG_BR_PROB_BASE / (new_est_niter + 1);
1060
1061   rest->count += new_exit->count;
1062   rest->frequency += EDGE_FREQUENCY (new_exit);
1063
1064   new_nonexit = single_pred_edge (loop->latch);
1065   prob = new_nonexit->probability;
1066   new_nonexit->probability = REG_BR_PROB_BASE - new_exit->probability;
1067   new_nonexit->count = exit_bb->count - new_exit->count;
1068   if (new_nonexit->count < 0)
1069     new_nonexit->count = 0;
1070   if (prob > 0)
1071     scale_bbs_frequencies_int (&loop->latch, 1, new_nonexit->probability,
1072                                prob);
1073
1074   /* Finally create the new counter for number of iterations and add the new
1075      exit instruction.  */
1076   bsi = gsi_last_bb (exit_bb);
1077   exit_if = gsi_stmt (bsi);
1078   create_iv (exit_base, exit_step, NULL_TREE, loop,
1079              &bsi, false, &ctr_before, &ctr_after);
1080   gimple_cond_set_code (exit_if, exit_cmp);
1081   gimple_cond_set_lhs (exit_if, ctr_after);
1082   gimple_cond_set_rhs (exit_if, exit_bound);
1083   update_stmt (exit_if);
1084
1085 #ifdef ENABLE_CHECKING
1086   verify_flow_info ();
1087   verify_dominators (CDI_DOMINATORS);
1088   verify_loop_structure ();
1089   verify_loop_closed_ssa ();
1090 #endif
1091 }
1092
1093 /* Wrapper over tree_transform_and_unroll_loop for case we do not
1094    want to transform the loop before unrolling.  The meaning
1095    of the arguments is the same as for tree_transform_and_unroll_loop.  */
1096
1097 void
1098 tree_unroll_loop (struct loop *loop, unsigned factor,
1099                   edge exit, struct tree_niter_desc *desc)
1100 {
1101   tree_transform_and_unroll_loop (loop, factor, exit, desc,
1102                                   NULL, NULL);
1103 }
1104
1105 /* Rewrite the phi node at position PSI in function of the main
1106    induction variable MAIN_IV and insert the generated code at GSI.  */
1107
1108 static void
1109 rewrite_phi_with_iv (loop_p loop,
1110                      gimple_stmt_iterator *psi,
1111                      gimple_stmt_iterator *gsi,
1112                      tree main_iv)
1113 {
1114   affine_iv iv;
1115   gimple stmt, phi = gsi_stmt (*psi);
1116   tree atype, mtype, val, res = PHI_RESULT (phi);
1117
1118   if (!is_gimple_reg (res) || res == main_iv)
1119     {
1120       gsi_next (psi);
1121       return;
1122     }
1123
1124   if (!simple_iv (loop, loop, res, &iv, true))
1125     {
1126       gsi_next (psi);
1127       return;
1128     }
1129
1130   remove_phi_node (psi, false);
1131
1132   atype = TREE_TYPE (res);
1133   mtype = POINTER_TYPE_P (atype) ? sizetype : atype;
1134   val = fold_build2 (MULT_EXPR, mtype, unshare_expr (iv.step),
1135                      fold_convert (mtype, main_iv));
1136   val = fold_build2 (POINTER_TYPE_P (atype)
1137                      ? POINTER_PLUS_EXPR : PLUS_EXPR,
1138                      atype, unshare_expr (iv.base), val);
1139   val = force_gimple_operand_gsi (gsi, val, false, NULL_TREE, true,
1140                                   GSI_SAME_STMT);
1141   stmt = gimple_build_assign (res, val);
1142   gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1143   SSA_NAME_DEF_STMT (res) = stmt;
1144 }
1145
1146 /* Rewrite all the phi nodes of LOOP in function of the main induction
1147    variable MAIN_IV.  */
1148
1149 static void
1150 rewrite_all_phi_nodes_with_iv (loop_p loop, tree main_iv)
1151 {
1152   unsigned i;
1153   basic_block *bbs = get_loop_body_in_dom_order (loop);
1154   gimple_stmt_iterator psi;
1155
1156   for (i = 0; i < loop->num_nodes; i++)
1157     {
1158       basic_block bb = bbs[i];
1159       gimple_stmt_iterator gsi = gsi_after_labels (bb);
1160
1161       if (bb->loop_father != loop)
1162         continue;
1163
1164       for (psi = gsi_start_phis (bb); !gsi_end_p (psi); )
1165         rewrite_phi_with_iv (loop, &psi, &gsi, main_iv);
1166     }
1167
1168   free (bbs);
1169 }
1170
1171 /* Bases all the induction variables in LOOP on a single induction
1172    variable (unsigned with base 0 and step 1), whose final value is
1173    compared with *NIT.  When the IV type precision has to be larger
1174    than *NIT type precision, *NIT is converted to the larger type, the
1175    conversion code is inserted before the loop, and *NIT is updated to
1176    the new definition.  The induction variable is incremented in the
1177    loop latch.  Return the induction variable that was created.  */
1178
1179 tree
1180 canonicalize_loop_ivs (struct loop *loop, tree *nit)
1181 {
1182   unsigned precision = TYPE_PRECISION (TREE_TYPE (*nit));
1183   unsigned original_precision = precision;
1184   tree type, var_before;
1185   gimple_stmt_iterator gsi, psi;
1186   gimple stmt;
1187   edge exit = single_dom_exit (loop);
1188   gimple_seq stmts;
1189
1190   for (psi = gsi_start_phis (loop->header);
1191        !gsi_end_p (psi); gsi_next (&psi))
1192     {
1193       gimple phi = gsi_stmt (psi);
1194       tree res = PHI_RESULT (phi);
1195
1196       if (is_gimple_reg (res) && TYPE_PRECISION (TREE_TYPE (res)) > precision)
1197         precision = TYPE_PRECISION (TREE_TYPE (res));
1198     }
1199
1200   type = lang_hooks.types.type_for_size (precision, 1);
1201
1202   if (original_precision != precision)
1203     {
1204       *nit = fold_convert (type, *nit);
1205       *nit = force_gimple_operand (*nit, &stmts, true, NULL_TREE);
1206       if (stmts)
1207         gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1208     }
1209
1210   gsi = gsi_last_bb (loop->latch);
1211   create_iv (build_int_cst_type (type, 0), build_int_cst (type, 1), NULL_TREE,
1212              loop, &gsi, true, &var_before, NULL);
1213
1214   rewrite_all_phi_nodes_with_iv (loop, var_before);
1215
1216   stmt = last_stmt (exit->src);
1217   /* Make the loop exit if the control condition is not satisfied.  */
1218   if (exit->flags & EDGE_TRUE_VALUE)
1219     {
1220       edge te, fe;
1221
1222       extract_true_false_edges_from_block (exit->src, &te, &fe);
1223       te->flags = EDGE_FALSE_VALUE;
1224       fe->flags = EDGE_TRUE_VALUE;
1225     }
1226   gimple_cond_set_code (stmt, LT_EXPR);
1227   gimple_cond_set_lhs (stmt, var_before);
1228   gimple_cond_set_rhs (stmt, *nit);
1229   update_stmt (stmt);
1230
1231   return var_before;
1232 }