aarch64 - Set the mode for the unspec in speculation_tracker insn.
[platform/upstream/linaro-gcc.git] / gcc / shrink-wrap.c
1 /* Shrink-wrapping related optimizations.
2    Copyright (C) 1987-2016 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 under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 /* This file handles shrink-wrapping related optimizations.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "target.h"
27 #include "rtl.h"
28 #include "tree.h"
29 #include "cfghooks.h"
30 #include "df.h"
31 #include "tm_p.h"
32 #include "regs.h"
33 #include "emit-rtl.h"
34 #include "output.h"
35 #include "tree-pass.h"
36 #include "cfgrtl.h"
37 #include "params.h"
38 #include "bb-reorder.h"
39 #include "shrink-wrap.h"
40 #include "regcprop.h"
41 #include "rtl-iter.h"
42 #include "valtrack.h"
43
44
45 /* Return true if INSN requires the stack frame to be set up.
46    PROLOGUE_USED contains the hard registers used in the function
47    prologue.  SET_UP_BY_PROLOGUE is the set of registers we expect the
48    prologue to set up for the function.  */
49 bool
50 requires_stack_frame_p (rtx_insn *insn, HARD_REG_SET prologue_used,
51                         HARD_REG_SET set_up_by_prologue)
52 {
53   df_ref def, use;
54   HARD_REG_SET hardregs;
55   unsigned regno;
56
57   if (CALL_P (insn))
58     return !SIBLING_CALL_P (insn);
59
60   /* We need a frame to get the unique CFA expected by the unwinder.  */
61   if (cfun->can_throw_non_call_exceptions && can_throw_internal (insn))
62     return true;
63
64   CLEAR_HARD_REG_SET (hardregs);
65   FOR_EACH_INSN_DEF (def, insn)
66     {
67       rtx dreg = DF_REF_REG (def);
68
69       if (!REG_P (dreg))
70         continue;
71
72       add_to_hard_reg_set (&hardregs, GET_MODE (dreg), REGNO (dreg));
73     }
74   if (hard_reg_set_intersect_p (hardregs, prologue_used))
75     return true;
76   AND_COMPL_HARD_REG_SET (hardregs, call_used_reg_set);
77   for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
78     if (TEST_HARD_REG_BIT (hardregs, regno)
79         && df_regs_ever_live_p (regno))
80       return true;
81
82   FOR_EACH_INSN_USE (use, insn)
83     {
84       rtx reg = DF_REF_REG (use);
85
86       if (!REG_P (reg))
87         continue;
88
89       add_to_hard_reg_set (&hardregs, GET_MODE (reg),
90                            REGNO (reg));
91     }
92   if (hard_reg_set_intersect_p (hardregs, set_up_by_prologue))
93     return true;
94
95   return false;
96 }
97
98 /* See whether there has a single live edge from BB, which dest uses
99    [REGNO, END_REGNO).  Return the live edge if its dest bb has
100    one or two predecessors.  Otherwise return NULL.  */
101
102 static edge
103 live_edge_for_reg (basic_block bb, int regno, int end_regno)
104 {
105   edge e, live_edge;
106   edge_iterator ei;
107   bitmap live;
108   int i;
109
110   live_edge = NULL;
111   FOR_EACH_EDGE (e, ei, bb->succs)
112     {
113       live = df_get_live_in (e->dest);
114       for (i = regno; i < end_regno; i++)
115         if (REGNO_REG_SET_P (live, i))
116           {
117             if (live_edge && live_edge != e)
118               return NULL;
119             live_edge = e;
120           }
121     }
122
123   /* We can sometimes encounter dead code.  Don't try to move it
124      into the exit block.  */
125   if (!live_edge || live_edge->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
126     return NULL;
127
128   /* Reject targets of abnormal edges.  This is needed for correctness
129      on ports like Alpha and MIPS, whose pic_offset_table_rtx can die on
130      exception edges even though it is generally treated as call-saved
131      for the majority of the compilation.  Moving across abnormal edges
132      isn't going to be interesting for shrink-wrap usage anyway.  */
133   if (live_edge->flags & EDGE_ABNORMAL)
134     return NULL;
135
136   /* When live_edge->dest->preds == 2, we can create a new block on
137      the edge to make it meet the requirement.  */
138   if (EDGE_COUNT (live_edge->dest->preds) > 2)
139     return NULL;
140
141   return live_edge;
142 }
143
144 /* Try to move INSN from BB to a successor.  Return true on success.
145    USES and DEFS are the set of registers that are used and defined
146    after INSN in BB.  SPLIT_P indicates whether a live edge from BB
147    is splitted or not.  */
148
149 static bool
150 move_insn_for_shrink_wrap (basic_block bb, rtx_insn *insn,
151                            const HARD_REG_SET uses,
152                            const HARD_REG_SET defs,
153                            bool *split_p,
154                            struct dead_debug_local *debug)
155 {
156   rtx set, src, dest;
157   bitmap live_out, live_in, bb_uses, bb_defs;
158   unsigned int i, dregno, end_dregno;
159   unsigned int sregno = FIRST_PSEUDO_REGISTER;
160   unsigned int end_sregno = FIRST_PSEUDO_REGISTER;
161   basic_block next_block;
162   edge live_edge;
163   rtx_insn *dinsn;
164   df_ref def;
165
166   /* Look for a simple register assignment.  We don't use single_set here
167      because we can't deal with any CLOBBERs, USEs, or REG_UNUSED secondary
168      destinations.  */
169   if (!INSN_P (insn))
170     return false;
171   set = PATTERN (insn);
172   if (GET_CODE (set) != SET)
173     return false;
174   src = SET_SRC (set);
175   dest = SET_DEST (set);
176
177   /* For the destination, we want only a register.  Also disallow STACK
178      or FRAME related adjustments.  They are likely part of the prologue,
179      so keep them in the entry block.  */
180   if (!REG_P (dest)
181       || dest == stack_pointer_rtx
182       || dest == frame_pointer_rtx
183       || dest == hard_frame_pointer_rtx)
184     return false;
185
186   /* For the source, we want one of:
187       (1) A (non-overlapping) register
188       (2) A constant,
189       (3) An expression involving no more than one register.
190
191      That last point comes from the code following, which was originally
192      written to handle only register move operations, and still only handles
193      a single source register when checking for overlaps.  Happily, the
194      same checks can be applied to expressions like (plus reg const).  */
195
196   if (CONSTANT_P (src))
197     ;
198   else if (!REG_P (src))
199     {
200       rtx src_inner = NULL_RTX;
201
202       if (can_throw_internal (insn))
203         return false;
204
205       subrtx_var_iterator::array_type array;
206       FOR_EACH_SUBRTX_VAR (iter, array, src, ALL)
207         {
208           rtx x = *iter;
209           switch (GET_RTX_CLASS (GET_CODE (x)))
210             {
211             case RTX_CONST_OBJ:
212             case RTX_COMPARE:
213             case RTX_COMM_COMPARE:
214             case RTX_BIN_ARITH:
215             case RTX_COMM_ARITH:
216             case RTX_UNARY:
217             case RTX_TERNARY:
218               /* Constant or expression.  Continue.  */
219               break;
220
221             case RTX_OBJ:
222             case RTX_EXTRA:
223               switch (GET_CODE (x))
224                 {
225                 case UNSPEC:
226                 case SUBREG:
227                 case STRICT_LOW_PART:
228                 case PC:
229                 case LO_SUM:
230                   /* Ok.  Continue.  */
231                   break;
232
233                 case REG:
234                   /* Fail if we see a second inner register.  */
235                   if (src_inner != NULL)
236                     return false;
237                   src_inner = x;
238                   break;
239
240                 default:
241                   return false;
242                 }
243               break;
244
245             default:
246               return false;
247             }
248         }
249
250       if (src_inner != NULL)
251         src = src_inner;
252     }
253
254   /* Make sure that the source register isn't defined later in BB.  */
255   if (REG_P (src))
256     {
257       sregno = REGNO (src);
258       end_sregno = END_REGNO (src);
259       if (overlaps_hard_reg_set_p (defs, GET_MODE (src), sregno))
260         return false;
261     }
262
263   /* Make sure that the destination register isn't referenced later in BB.  */
264   dregno = REGNO (dest);
265   end_dregno = END_REGNO (dest);
266   if (overlaps_hard_reg_set_p (uses, GET_MODE (dest), dregno)
267       || overlaps_hard_reg_set_p (defs, GET_MODE (dest), dregno))
268     return false;
269
270   /* See whether there is a successor block to which we could move INSN.  */
271   live_edge = live_edge_for_reg (bb, dregno, end_dregno);
272   if (!live_edge)
273     return false;
274
275   next_block = live_edge->dest;
276   /* Create a new basic block on the edge.  */
277   if (EDGE_COUNT (next_block->preds) == 2)
278     {
279       /* split_edge for a block with only one successor is meaningless.  */
280       if (EDGE_COUNT (bb->succs) == 1)
281         return false;
282
283       /* If DF_LIVE doesn't exist, i.e. at -O1, just give up.  */
284       if (!df_live)
285         return false;
286
287       basic_block old_dest = live_edge->dest;
288       next_block = split_edge (live_edge);
289
290       /* We create a new basic block.  Call df_grow_bb_info to make sure
291          all data structures are allocated.  */
292       df_grow_bb_info (df_live);
293
294       bitmap_and (df_get_live_in (next_block), df_get_live_out (bb),
295                   df_get_live_in (old_dest));
296       df_set_bb_dirty (next_block);
297
298       /* We should not split more than once for a function.  */
299       if (*split_p)
300         return false;
301
302       *split_p = true;
303     }
304
305   /* At this point we are committed to moving INSN, but let's try to
306      move it as far as we can.  */
307   do
308     {
309       if (MAY_HAVE_DEBUG_INSNS)
310         {
311           FOR_BB_INSNS_REVERSE (bb, dinsn)
312             if (DEBUG_INSN_P (dinsn))
313               {
314                 df_ref use;
315                 FOR_EACH_INSN_USE (use, dinsn)
316                   if (refers_to_regno_p (dregno, end_dregno,
317                                          DF_REF_REG (use), (rtx *) NULL))
318                     dead_debug_add (debug, use, DF_REF_REGNO (use));
319               }
320             else if (dinsn == insn)
321               break;
322         }
323       live_out = df_get_live_out (bb);
324       live_in = df_get_live_in (next_block);
325       bb = next_block;
326
327       /* Check whether BB uses DEST or clobbers DEST.  We need to add
328          INSN to BB if so.  Either way, DEST is no longer live on entry,
329          except for any part that overlaps SRC (next loop).  */
330       bb_uses = &DF_LR_BB_INFO (bb)->use;
331       bb_defs = &DF_LR_BB_INFO (bb)->def;
332       if (df_live)
333         {
334           for (i = dregno; i < end_dregno; i++)
335             {
336               if (*split_p
337                   || REGNO_REG_SET_P (bb_uses, i)
338                   || REGNO_REG_SET_P (bb_defs, i)
339                   || REGNO_REG_SET_P (&DF_LIVE_BB_INFO (bb)->gen, i))
340                 next_block = NULL;
341               CLEAR_REGNO_REG_SET (live_out, i);
342               CLEAR_REGNO_REG_SET (live_in, i);
343             }
344
345           /* Check whether BB clobbers SRC.  We need to add INSN to BB if so.
346              Either way, SRC is now live on entry.  */
347           for (i = sregno; i < end_sregno; i++)
348             {
349               if (*split_p
350                   || REGNO_REG_SET_P (bb_defs, i)
351                   || REGNO_REG_SET_P (&DF_LIVE_BB_INFO (bb)->gen, i))
352                 next_block = NULL;
353               SET_REGNO_REG_SET (live_out, i);
354               SET_REGNO_REG_SET (live_in, i);
355             }
356         }
357       else
358         {
359           /* DF_LR_BB_INFO (bb)->def does not comprise the DF_REF_PARTIAL and
360              DF_REF_CONDITIONAL defs.  So if DF_LIVE doesn't exist, i.e.
361              at -O1, just give up searching NEXT_BLOCK.  */
362           next_block = NULL;
363           for (i = dregno; i < end_dregno; i++)
364             {
365               CLEAR_REGNO_REG_SET (live_out, i);
366               CLEAR_REGNO_REG_SET (live_in, i);
367             }
368
369           for (i = sregno; i < end_sregno; i++)
370             {
371               SET_REGNO_REG_SET (live_out, i);
372               SET_REGNO_REG_SET (live_in, i);
373             }
374         }
375
376       /* If we don't need to add the move to BB, look for a single
377          successor block.  */
378       if (next_block)
379         {
380           live_edge = live_edge_for_reg (next_block, dregno, end_dregno);
381           if (!live_edge || EDGE_COUNT (live_edge->dest->preds) > 1)
382             break;
383           next_block = live_edge->dest;
384         }
385     }
386   while (next_block);
387
388   /* For the new created basic block, there is no dataflow info at all.
389      So skip the following dataflow update and check.  */
390   if (!(*split_p))
391     {
392       /* BB now defines DEST.  It only uses the parts of DEST that overlap SRC
393          (next loop).  */
394       for (i = dregno; i < end_dregno; i++)
395         {
396           CLEAR_REGNO_REG_SET (bb_uses, i);
397           SET_REGNO_REG_SET (bb_defs, i);
398         }
399
400       /* BB now uses SRC.  */
401       for (i = sregno; i < end_sregno; i++)
402         SET_REGNO_REG_SET (bb_uses, i);
403     }
404
405   /* Insert debug temps for dead REGs used in subsequent debug insns.  */
406   if (debug->used && !bitmap_empty_p (debug->used))
407     FOR_EACH_INSN_DEF (def, insn)
408       dead_debug_insert_temp (debug, DF_REF_REGNO (def), insn,
409                               DEBUG_TEMP_BEFORE_WITH_VALUE);
410
411   emit_insn_after (PATTERN (insn), bb_note (bb));
412   delete_insn (insn);
413   return true;
414 }
415
416 /* Look for register copies in the first block of the function, and move
417    them down into successor blocks if the register is used only on one
418    path.  This exposes more opportunities for shrink-wrapping.  These
419    kinds of sets often occur when incoming argument registers are moved
420    to call-saved registers because their values are live across one or
421    more calls during the function.  */
422
423 static void
424 prepare_shrink_wrap (basic_block entry_block)
425 {
426   rtx_insn *insn, *curr;
427   rtx x;
428   HARD_REG_SET uses, defs;
429   df_ref def, use;
430   bool split_p = false;
431   unsigned int i;
432   struct dead_debug_local debug;
433
434   if (JUMP_P (BB_END (entry_block)))
435     {
436       /* To have more shrink-wrapping opportunities, prepare_shrink_wrap tries
437          to sink the copies from parameter to callee saved register out of
438          entry block.  copyprop_hardreg_forward_bb_without_debug_insn is called
439          to release some dependences.  */
440       copyprop_hardreg_forward_bb_without_debug_insn (entry_block);
441     }
442
443   dead_debug_local_init (&debug, NULL, NULL);
444   CLEAR_HARD_REG_SET (uses);
445   CLEAR_HARD_REG_SET (defs);
446
447   FOR_BB_INSNS_REVERSE_SAFE (entry_block, insn, curr)
448     if (NONDEBUG_INSN_P (insn)
449         && !move_insn_for_shrink_wrap (entry_block, insn, uses, defs,
450                                        &split_p, &debug))
451       {
452         /* Add all defined registers to DEFs.  */
453         FOR_EACH_INSN_DEF (def, insn)
454           {
455             x = DF_REF_REG (def);
456             if (REG_P (x) && HARD_REGISTER_P (x))
457               for (i = REGNO (x); i < END_REGNO (x); i++)
458                 SET_HARD_REG_BIT (defs, i);
459           }
460
461         /* Add all used registers to USESs.  */
462         FOR_EACH_INSN_USE (use, insn)
463           {
464             x = DF_REF_REG (use);
465             if (REG_P (x) && HARD_REGISTER_P (x))
466               for (i = REGNO (x); i < END_REGNO (x); i++)
467                 SET_HARD_REG_BIT (uses, i);
468           }
469       }
470
471   dead_debug_local_finish (&debug, NULL);
472 }
473
474 /* Return whether basic block PRO can get the prologue.  It can not if it
475    has incoming complex edges that need a prologue inserted (we make a new
476    block for the prologue, so those edges would need to be redirected, which
477    does not work).  It also can not if there exist registers live on entry
478    to PRO that are clobbered by the prologue.  */
479
480 static bool
481 can_get_prologue (basic_block pro, HARD_REG_SET prologue_clobbered)
482 {
483   edge e;
484   edge_iterator ei;
485   FOR_EACH_EDGE (e, ei, pro->preds)
486     if (e->flags & (EDGE_COMPLEX | EDGE_CROSSING)
487         && !dominated_by_p (CDI_DOMINATORS, e->src, pro))
488       return false;
489
490   HARD_REG_SET live;
491   REG_SET_TO_HARD_REG_SET (live, df_get_live_in (pro));
492   if (hard_reg_set_intersect_p (live, prologue_clobbered))
493     return false;
494
495   return true;
496 }
497
498 /* Return whether we can duplicate basic block BB for shrink wrapping.  We
499    cannot if the block cannot be duplicated at all, or if any of its incoming
500    edges are complex and come from a block that does not require a prologue
501    (we cannot redirect such edges), or if the block is too big to copy.
502    PRO is the basic block before which we would put the prologue, MAX_SIZE is
503    the maximum size block we allow to be copied.  */
504
505 static bool
506 can_dup_for_shrink_wrapping (basic_block bb, basic_block pro, unsigned max_size)
507 {
508   if (!can_duplicate_block_p (bb))
509     return false;
510
511   edge e;
512   edge_iterator ei;
513   FOR_EACH_EDGE (e, ei, bb->preds)
514     if (e->flags & (EDGE_COMPLEX | EDGE_CROSSING)
515         && !dominated_by_p (CDI_DOMINATORS, e->src, pro))
516       return false;
517
518   unsigned size = 0;
519
520   rtx_insn *insn;
521   FOR_BB_INSNS (bb, insn)
522     if (NONDEBUG_INSN_P (insn))
523       {
524         size += get_attr_min_length (insn);
525         if (size > max_size)
526           return false;
527       }
528
529   return true;
530 }
531
532 /* If the source of edge E has more than one successor, the verifier for
533    branch probabilities gets confused by the fake edges we make where
534    simple_return statements will be inserted later (because those are not
535    marked as fallthrough edges).  Fix this by creating an extra block just
536    for that fallthrough.  */
537
538 static edge
539 fix_fake_fallthrough_edge (edge e)
540 {
541   if (EDGE_COUNT (e->src->succs) <= 1)
542     return e;
543
544   basic_block old_bb = e->src;
545   rtx_insn *end = BB_END (old_bb);
546   rtx_note *note = emit_note_after (NOTE_INSN_DELETED, end);
547   basic_block new_bb = create_basic_block (note, note, old_bb);
548   BB_COPY_PARTITION (new_bb, old_bb);
549   BB_END (old_bb) = end;
550
551   redirect_edge_succ (e, new_bb);
552   e->flags |= EDGE_FALLTHRU;
553   e->flags &= ~EDGE_FAKE;
554
555   return make_edge (new_bb, EXIT_BLOCK_PTR_FOR_FN (cfun), EDGE_FAKE);
556 }
557
558 /* Try to perform a kind of shrink-wrapping, making sure the
559    prologue/epilogue is emitted only around those parts of the
560    function that require it.
561
562    There will be exactly one prologue, and it will be executed either
563    zero or one time, on any path.  Depending on where the prologue is
564    placed, some of the basic blocks can be reached via both paths with
565    and without a prologue.  Such blocks will be duplicated here, and the
566    edges changed to match.
567
568    Paths that go to the exit without going through the prologue will use
569    a simple_return instead of the epilogue.  We maximize the number of
570    those, making sure to only duplicate blocks that can be duplicated.
571    If the prologue can then still be placed in multiple locations, we
572    place it as early as possible.
573
574    An example, where we duplicate blocks with control flow (legend:
575    _B_egin, _R_eturn and _S_imple_return; edges without arrowhead should
576    be taken to point down or to the right, to simplify the diagram; here,
577    block 3 needs a prologue, the rest does not):
578
579
580        B                 B
581        |                 |
582        2                 2
583        |\                |\
584        | 3    becomes    | 3
585        |/                |  \
586        4                 7   4
587        |\                |\  |\
588        | 5               | 8 | 5
589        |/                |/  |/
590        6                 9   6
591        |                 |   |
592        R                 S   R
593
594
595    (bb 4 is duplicated to 7, and so on; the prologue is inserted on the
596    edge 2->3).
597
598    Another example, where part of a loop is duplicated (again, bb 3 is
599    the only block that needs a prologue):
600
601
602        B   3<--              B       ->3<--
603        |   |   |             |      |  |   |
604        |   v   |   becomes   |      |  v   |
605        2---4---              2---5--   4---
606            |                     |     |
607            R                     S     R
608
609
610    (bb 4 is duplicated to 5; the prologue is inserted on the edge 5->3).
611
612    ENTRY_EDGE is the edge where the prologue will be placed, possibly
613    changed by this function.  BB_WITH is a bitmap that, if we do shrink-
614    wrap, will on return contain the interesting blocks that run with
615    prologue.  PROLOGUE_SEQ is the prologue we will insert.  */
616
617 void
618 try_shrink_wrapping (edge *entry_edge, bitmap_head *bb_with,
619                      rtx_insn *prologue_seq)
620 {
621   /* If we cannot shrink-wrap, are told not to shrink-wrap, or it makes
622      no sense to shrink-wrap: then do not shrink-wrap!  */
623
624   if (!SHRINK_WRAPPING_ENABLED)
625     return;
626
627   if (crtl->profile && !targetm.profile_before_prologue ())
628     return;
629
630   if (crtl->calls_eh_return)
631     return;
632
633   bool empty_prologue = true;
634   for (rtx_insn *insn = prologue_seq; insn; insn = NEXT_INSN (insn))
635     if (!(NOTE_P (insn) && NOTE_KIND (insn) == NOTE_INSN_PROLOGUE_END))
636       {
637         empty_prologue = false;
638         break;
639       }
640   if (empty_prologue)
641     return;
642
643   /* Move some code down to expose more shrink-wrapping opportunities.  */
644
645   basic_block entry = (*entry_edge)->dest;
646   prepare_shrink_wrap (entry);
647
648   if (dump_file)
649     fprintf (dump_file, "Attempting shrink-wrapping optimization.\n");
650
651   /* Compute the registers set and used in the prologue.  */
652
653   HARD_REG_SET prologue_clobbered, prologue_used;
654   CLEAR_HARD_REG_SET (prologue_clobbered);
655   CLEAR_HARD_REG_SET (prologue_used);
656   for (rtx_insn *insn = prologue_seq; insn; insn = NEXT_INSN (insn))
657     if (NONDEBUG_INSN_P (insn))
658       {
659         HARD_REG_SET this_used;
660         CLEAR_HARD_REG_SET (this_used);
661         note_uses (&PATTERN (insn), record_hard_reg_uses, &this_used);
662         AND_COMPL_HARD_REG_SET (this_used, prologue_clobbered);
663         IOR_HARD_REG_SET (prologue_used, this_used);
664         note_stores (PATTERN (insn), record_hard_reg_sets, &prologue_clobbered);
665       }
666   CLEAR_HARD_REG_BIT (prologue_clobbered, STACK_POINTER_REGNUM);
667   if (frame_pointer_needed)
668     CLEAR_HARD_REG_BIT (prologue_clobbered, HARD_FRAME_POINTER_REGNUM);
669
670   /* Find out what registers are set up by the prologue; any use of these
671      cannot happen before the prologue.  */
672
673   struct hard_reg_set_container set_up_by_prologue;
674   CLEAR_HARD_REG_SET (set_up_by_prologue.set);
675   add_to_hard_reg_set (&set_up_by_prologue.set, Pmode, STACK_POINTER_REGNUM);
676   add_to_hard_reg_set (&set_up_by_prologue.set, Pmode, ARG_POINTER_REGNUM);
677   if (frame_pointer_needed)
678     add_to_hard_reg_set (&set_up_by_prologue.set, Pmode,
679                          HARD_FRAME_POINTER_REGNUM);
680   if (pic_offset_table_rtx 
681       && (unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM)
682     add_to_hard_reg_set (&set_up_by_prologue.set, Pmode,
683                          PIC_OFFSET_TABLE_REGNUM);
684   if (crtl->drap_reg)
685     add_to_hard_reg_set (&set_up_by_prologue.set,
686                          GET_MODE (crtl->drap_reg),
687                          REGNO (crtl->drap_reg));
688   if (targetm.set_up_by_prologue)
689     targetm.set_up_by_prologue (&set_up_by_prologue);
690
691   /* We will insert the prologue before the basic block PRO.  PRO should
692      dominate all basic blocks that need the prologue to be executed
693      before them.  First, make PRO the "tightest wrap" possible.  */
694
695   calculate_dominance_info (CDI_DOMINATORS);
696
697   basic_block pro = 0;
698
699   basic_block bb;
700   edge e;
701   edge_iterator ei;
702   FOR_EACH_BB_FN (bb, cfun)
703     {
704       rtx_insn *insn;
705       FOR_BB_INSNS (bb, insn)
706         if (NONDEBUG_INSN_P (insn)
707             && requires_stack_frame_p (insn, prologue_used,
708                                        set_up_by_prologue.set))
709           {
710             if (dump_file)
711               fprintf (dump_file, "Block %d needs the prologue.\n", bb->index);
712             pro = nearest_common_dominator (CDI_DOMINATORS, pro, bb);
713             break;
714           }
715     }
716
717   /* If nothing needs a prologue, just put it at the start.  This really
718      shouldn't happen, but we cannot fix it here.  */
719
720   if (pro == 0)
721     {
722       if (dump_file)
723         fprintf(dump_file, "Nothing needs a prologue, but it isn't empty; "
724                            "putting it at the start.\n");
725       pro = entry;
726     }
727
728   if (dump_file)
729     fprintf (dump_file, "After wrapping required blocks, PRO is now %d\n",
730              pro->index);
731
732   /* Now see if we can put the prologue at the start of PRO.  Putting it
733      there might require duplicating a block that cannot be duplicated,
734      or in some cases we cannot insert the prologue there at all.  If PRO
735      wont't do, try again with the immediate dominator of PRO, and so on.
736
737      The blocks that need duplicating are those reachable from PRO but
738      not dominated by it.  We keep in BB_WITH a bitmap of the blocks
739      reachable from PRO that we already found, and in VEC a stack of
740      those we still need to consider (to find successors).  */
741
742   bitmap_set_bit (bb_with, pro->index);
743
744   vec<basic_block> vec;
745   vec.create (n_basic_blocks_for_fn (cfun));
746   vec.quick_push (pro);
747
748   unsigned max_grow_size = get_uncond_jump_length ();
749   max_grow_size *= PARAM_VALUE (PARAM_MAX_GROW_COPY_BB_INSNS);
750
751   while (!vec.is_empty () && pro != entry)
752     {
753       while (pro != entry && !can_get_prologue (pro, prologue_clobbered))
754         {
755           pro = get_immediate_dominator (CDI_DOMINATORS, pro);
756
757           if (bitmap_set_bit (bb_with, pro->index))
758             vec.quick_push (pro);
759         }
760
761       basic_block bb = vec.pop ();
762       if (!can_dup_for_shrink_wrapping (bb, pro, max_grow_size))
763         while (!dominated_by_p (CDI_DOMINATORS, bb, pro))
764           {
765             gcc_assert (pro != entry);
766
767             pro = get_immediate_dominator (CDI_DOMINATORS, pro);
768
769             if (bitmap_set_bit (bb_with, pro->index))
770               vec.quick_push (pro);
771           }
772
773       FOR_EACH_EDGE (e, ei, bb->succs)
774         if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun)
775             && bitmap_set_bit (bb_with, e->dest->index))
776           vec.quick_push (e->dest);
777     }
778
779   if (dump_file)
780     fprintf (dump_file, "Avoiding non-duplicatable blocks, PRO is now %d\n",
781              pro->index);
782
783   /* If we can move PRO back without having to duplicate more blocks, do so.
784      We do this because putting the prologue earlier is better for scheduling.
785
786      We can move back to a block PRE if every path from PRE will eventually
787      need a prologue, that is, PRO is a post-dominator of PRE.  PRE needs
788      to dominate every block reachable from itself.  We keep in BB_TMP a
789      bitmap of the blocks reachable from PRE that we already found, and in
790      VEC a stack of those we still need to consider.
791
792      Any block reachable from PRE is also reachable from all predecessors
793      of PRE, so if we find we need to move PRE back further we can leave
794      everything not considered so far on the stack.  Any block dominated
795      by PRE is also dominated by all other dominators of PRE, so anything
796      found good for some PRE does not need to be reconsidered later.
797
798      We don't need to update BB_WITH because none of the new blocks found
799      can jump to a block that does not need the prologue.  */
800
801   if (pro != entry)
802     {
803       calculate_dominance_info (CDI_POST_DOMINATORS);
804
805       bitmap bb_tmp = BITMAP_ALLOC (NULL);
806       bitmap_copy (bb_tmp, bb_with);
807       basic_block last_ok = pro;
808       vec.truncate (0);
809
810       while (pro != entry)
811         {
812           basic_block pre = get_immediate_dominator (CDI_DOMINATORS, pro);
813           if (!dominated_by_p (CDI_POST_DOMINATORS, pre, pro))
814             break;
815
816           if (bitmap_set_bit (bb_tmp, pre->index))
817             vec.quick_push (pre);
818
819           bool ok = true;
820           while (!vec.is_empty ())
821             {
822               if (!dominated_by_p (CDI_DOMINATORS, vec.last (), pre))
823                 {
824                   ok = false;
825                   break;
826                 }
827
828               basic_block bb = vec.pop ();
829               FOR_EACH_EDGE (e, ei, bb->succs)
830                 if (bitmap_set_bit (bb_tmp, e->dest->index))
831                   vec.quick_push (e->dest);
832             }
833
834           if (ok && can_get_prologue (pre, prologue_clobbered))
835             last_ok = pre;
836
837           pro = pre;
838         }
839
840       pro = last_ok;
841
842       BITMAP_FREE (bb_tmp);
843       free_dominance_info (CDI_POST_DOMINATORS);
844     }
845
846   vec.release ();
847
848   if (dump_file)
849     fprintf (dump_file, "Bumping back to anticipatable blocks, PRO is now %d\n",
850              pro->index);
851
852   if (pro == entry)
853     {
854       free_dominance_info (CDI_DOMINATORS);
855       return;
856     }
857
858   /* Compute what fraction of the frequency and count of the blocks that run
859      both with and without prologue are for running with prologue.  This gives
860      the correct answer for reducible flow graphs; for irreducible flow graphs
861      our profile is messed up beyond repair anyway.  */
862
863   gcov_type num = 0;
864   gcov_type den = 0;
865
866   FOR_EACH_EDGE (e, ei, pro->preds)
867     if (!dominated_by_p (CDI_DOMINATORS, e->src, pro))
868       {
869         num += EDGE_FREQUENCY (e);
870         den += e->src->frequency;
871       }
872
873   if (den == 0)
874     den = 1;
875
876   /* All is okay, so do it.  */
877
878   crtl->shrink_wrapped = true;
879   if (dump_file)
880     fprintf (dump_file, "Performing shrink-wrapping.\n");
881
882   /* Copy the blocks that can run both with and without prologue.  The
883      originals run with prologue, the copies without.  Store a pointer to
884      the copy in the ->aux field of the original.  */
885
886   FOR_EACH_BB_FN (bb, cfun)
887     if (bitmap_bit_p (bb_with, bb->index)
888         && !dominated_by_p (CDI_DOMINATORS, bb, pro))
889       {
890         basic_block dup = duplicate_block (bb, 0, 0);
891
892         bb->aux = dup;
893
894         if (JUMP_P (BB_END (dup)) && !any_condjump_p (BB_END (dup)))
895           emit_barrier_after_bb (dup);
896
897         if (EDGE_COUNT (dup->succs) == 0)
898           emit_barrier_after_bb (dup);
899
900         if (dump_file)
901           fprintf (dump_file, "Duplicated %d to %d\n", bb->index, dup->index);
902
903         bb->frequency = RDIV (num * bb->frequency, den);
904         dup->frequency -= bb->frequency;
905         bb->count = RDIV (num * bb->count, den);
906         dup->count -= bb->count;
907       }
908
909   /* Now change the edges to point to the copies, where appropriate.  */
910
911   FOR_EACH_BB_FN (bb, cfun)
912     if (!dominated_by_p (CDI_DOMINATORS, bb, pro))
913       {
914         basic_block src = bb;
915         if (bitmap_bit_p (bb_with, bb->index))
916           src = (basic_block) bb->aux;
917
918         FOR_EACH_EDGE (e, ei, src->succs)
919           {
920             if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
921               continue;
922
923             if (bitmap_bit_p (bb_with, e->dest->index)
924                 && !dominated_by_p (CDI_DOMINATORS, e->dest, pro))
925               {
926                 if (dump_file)
927                   fprintf (dump_file, "Redirecting edge %d->%d to %d\n",
928                            e->src->index, e->dest->index,
929                            ((basic_block) e->dest->aux)->index);
930                 redirect_edge_and_branch_force (e, (basic_block) e->dest->aux);
931               }
932             else if (e->flags & EDGE_FALLTHRU
933                      && bitmap_bit_p (bb_with, bb->index))
934               force_nonfallthru (e);
935           }
936       }
937
938   /* Also redirect the function entry edge if necessary.  */
939
940   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR_FOR_FN (cfun)->succs)
941     if (bitmap_bit_p (bb_with, e->dest->index)
942         && !dominated_by_p (CDI_DOMINATORS, e->dest, pro))
943       {
944         basic_block split_bb = split_edge (e);
945         e = single_succ_edge (split_bb);
946         redirect_edge_and_branch_force (e, (basic_block) e->dest->aux);
947       }
948
949   /* Change all the exits that should get a simple_return to FAKE.
950      They will be converted later.  */
951
952   FOR_EACH_BB_FN (bb, cfun)
953     if (!bitmap_bit_p (bb_with, bb->index))
954       FOR_EACH_EDGE (e, ei, bb->succs)
955         if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
956           {
957             e = fix_fake_fallthrough_edge (e);
958
959             e->flags &= ~EDGE_FALLTHRU;
960             if (!(e->flags & EDGE_SIBCALL))
961               e->flags |= EDGE_FAKE;
962
963             emit_barrier_after_bb (e->src);
964           }
965
966   /* Finally, we want a single edge to put the prologue on.  Make a new
967      block before the PRO block; the edge beteen them is the edge we want.
968      Then redirect those edges into PRO that come from blocks without the
969      prologue, to point to the new block instead.  The new prologue block
970      is put at the end of the insn chain.  */
971
972   basic_block new_bb = create_empty_bb (EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb);
973   BB_COPY_PARTITION (new_bb, pro);
974   if (dump_file)
975     fprintf (dump_file, "Made prologue block %d\n", new_bb->index);
976
977   for (ei = ei_start (pro->preds); (e = ei_safe_edge (ei)); )
978     {
979       if (bitmap_bit_p (bb_with, e->src->index)
980           || dominated_by_p (CDI_DOMINATORS, e->src, pro))
981         {
982           ei_next (&ei);
983           continue;
984         }
985
986       new_bb->count += RDIV (e->src->count * e->probability, REG_BR_PROB_BASE);
987       new_bb->frequency += EDGE_FREQUENCY (e);
988
989       redirect_edge_and_branch_force (e, new_bb);
990       if (dump_file)
991         fprintf (dump_file, "Redirected edge from %d\n", e->src->index);
992     }
993
994   *entry_edge = make_single_succ_edge (new_bb, pro, EDGE_FALLTHRU);
995   force_nonfallthru (*entry_edge);
996
997   free_dominance_info (CDI_DOMINATORS);
998 }
999
1000 /* If we're allowed to generate a simple return instruction, then by
1001    definition we don't need a full epilogue.  If the last basic
1002    block before the exit block does not contain active instructions,
1003    examine its predecessors and try to emit (conditional) return
1004    instructions.  */
1005
1006 edge
1007 get_unconverted_simple_return (edge exit_fallthru_edge, bitmap_head bb_flags,
1008                                vec<edge> *unconverted_simple_returns,
1009                                rtx_insn **returnjump)
1010 {
1011   if (optimize)
1012     {
1013       unsigned i, last;
1014
1015       /* convert_jumps_to_returns may add to preds of the exit block
1016          (but won't remove).  Stop at end of current preds.  */
1017       last = EDGE_COUNT (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds);
1018       for (i = 0; i < last; i++)
1019         {
1020           edge e = EDGE_I (EXIT_BLOCK_PTR_FOR_FN (cfun)->preds, i);
1021           if (LABEL_P (BB_HEAD (e->src))
1022               && !bitmap_bit_p (&bb_flags, e->src->index)
1023               && !active_insn_between (BB_HEAD (e->src), BB_END (e->src)))
1024             *unconverted_simple_returns
1025                   = convert_jumps_to_returns (e->src, true,
1026                                               *unconverted_simple_returns);
1027         }
1028     }
1029
1030   if (exit_fallthru_edge != NULL
1031       && EDGE_COUNT (exit_fallthru_edge->src->preds) != 0
1032       && !bitmap_bit_p (&bb_flags, exit_fallthru_edge->src->index))
1033     {
1034       basic_block last_bb;
1035
1036       last_bb = emit_return_for_exit (exit_fallthru_edge, true);
1037       *returnjump = BB_END (last_bb);
1038       exit_fallthru_edge = NULL;
1039     }
1040   return exit_fallthru_edge;
1041 }
1042
1043 /* If there were branches to an empty LAST_BB which we tried to
1044    convert to conditional simple_returns, but couldn't for some
1045    reason, create a block to hold a simple_return insn and redirect
1046    those remaining edges.  */
1047
1048 void
1049 convert_to_simple_return (edge entry_edge, edge orig_entry_edge,
1050                           bitmap_head bb_flags, rtx_insn *returnjump,
1051                           vec<edge> unconverted_simple_returns)
1052 {
1053   edge e;
1054   edge_iterator ei;
1055
1056   if (!unconverted_simple_returns.is_empty ())
1057     {
1058       basic_block simple_return_block_hot = NULL;
1059       basic_block simple_return_block_cold = NULL;
1060       edge pending_edge_hot = NULL;
1061       edge pending_edge_cold = NULL;
1062       basic_block exit_pred;
1063       int i;
1064
1065       gcc_assert (entry_edge != orig_entry_edge);
1066
1067       /* See if we can reuse the last insn that was emitted for the
1068          epilogue.  */
1069       if (returnjump != NULL_RTX
1070           && JUMP_LABEL (returnjump) == simple_return_rtx)
1071         {
1072           e = split_block (BLOCK_FOR_INSN (returnjump), PREV_INSN (returnjump));
1073           if (BB_PARTITION (e->src) == BB_HOT_PARTITION)
1074             simple_return_block_hot = e->dest;
1075           else
1076             simple_return_block_cold = e->dest;
1077         }
1078
1079       /* Also check returns we might need to add to tail blocks.  */
1080       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1081         if (EDGE_COUNT (e->src->preds) != 0
1082             && (e->flags & EDGE_FAKE) != 0
1083             && !bitmap_bit_p (&bb_flags, e->src->index))
1084           {
1085             if (BB_PARTITION (e->src) == BB_HOT_PARTITION)
1086               pending_edge_hot = e;
1087             else
1088               pending_edge_cold = e;
1089           }
1090
1091       /* Save a pointer to the exit's predecessor BB for use in
1092          inserting new BBs at the end of the function.  Do this
1093          after the call to split_block above which may split
1094          the original exit pred.  */
1095       exit_pred = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
1096
1097       FOR_EACH_VEC_ELT (unconverted_simple_returns, i, e)
1098         {
1099           basic_block *pdest_bb;
1100           edge pending;
1101
1102           if (BB_PARTITION (e->src) == BB_HOT_PARTITION)
1103             {
1104               pdest_bb = &simple_return_block_hot;
1105               pending = pending_edge_hot;
1106             }
1107           else
1108             {
1109               pdest_bb = &simple_return_block_cold;
1110               pending = pending_edge_cold;
1111             }
1112
1113           if (*pdest_bb == NULL && pending != NULL)
1114             {
1115               emit_return_into_block (true, pending->src);
1116               pending->flags &= ~(EDGE_FALLTHRU | EDGE_FAKE);
1117               *pdest_bb = pending->src;
1118             }
1119           else if (*pdest_bb == NULL)
1120             {
1121               basic_block bb;
1122
1123               bb = create_basic_block (NULL, NULL, exit_pred);
1124               BB_COPY_PARTITION (bb, e->src);
1125               rtx_insn *ret = targetm.gen_simple_return ();
1126               rtx_jump_insn *start = emit_jump_insn_after (ret, BB_END (bb));
1127               JUMP_LABEL (start) = simple_return_rtx;
1128               emit_barrier_after (start);
1129
1130               *pdest_bb = bb;
1131               make_edge (bb, EXIT_BLOCK_PTR_FOR_FN (cfun), 0);
1132             }
1133           redirect_edge_and_branch_force (e, *pdest_bb);
1134         }
1135       unconverted_simple_returns.release ();
1136     }
1137
1138   if (entry_edge != orig_entry_edge)
1139     {
1140       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
1141         if (EDGE_COUNT (e->src->preds) != 0
1142             && (e->flags & EDGE_FAKE) != 0
1143             && !bitmap_bit_p (&bb_flags, e->src->index))
1144           {
1145             e = fix_fake_fallthrough_edge (e);
1146
1147             emit_return_into_block (true, e->src);
1148             e->flags &= ~(EDGE_FALLTHRU | EDGE_FAKE);
1149           }
1150     }
1151 }