OSDN Git Service

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