OSDN Git Service

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