OSDN Git Service

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