Backport from GCC mainline.
[platform/upstream/linaro-gcc.git] / gcc / tree-ssa-live.c
1 /* Liveness for SSA trees.
2    Copyright (C) 2003-2016 Free Software Foundation, Inc.
3    Contributed by Andrew MacLeod <amacleod@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License 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 "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "timevar.h"
29 #include "ssa.h"
30 #include "cgraph.h"
31 #include "gimple-pretty-print.h"
32 #include "diagnostic-core.h"
33 #include "gimple-iterator.h"
34 #include "tree-dfa.h"
35 #include "dumpfile.h"
36 #include "tree-ssa-live.h"
37 #include "debug.h"
38 #include "tree-ssa.h"
39 #include "ipa-utils.h"
40 #include "cfgloop.h"
41
42 static void verify_live_on_entry (tree_live_info_p);
43
44
45 /* VARMAP maintains a mapping from SSA version number to real variables.
46
47    All SSA_NAMES are divided into partitions.  Initially each ssa_name is the
48    only member of it's own partition.  Coalescing will attempt to group any
49    ssa_names which occur in a copy or in a PHI node into the same partition.
50
51    At the end of out-of-ssa, each partition becomes a "real" variable and is
52    rewritten as a compiler variable.
53
54    The var_map data structure is used to manage these partitions.  It allows
55    partitions to be combined, and determines which partition belongs to what
56    ssa_name or variable, and vice versa.  */
57
58
59 /* Remove the base table in MAP.  */
60
61 static void
62 var_map_base_fini (var_map map)
63 {
64   /* Free the basevar info if it is present.  */
65   if (map->partition_to_base_index != NULL)
66     {
67       free (map->partition_to_base_index);
68       map->partition_to_base_index = NULL;
69       map->num_basevars = 0;
70     }
71 }
72 /* Create a variable partition map of SIZE, initialize and return it.  */
73
74 var_map
75 init_var_map (int size)
76 {
77   var_map map;
78
79   map = (var_map) xmalloc (sizeof (struct _var_map));
80   map->var_partition = partition_new (size);
81
82   map->partition_to_view = NULL;
83   map->view_to_partition = NULL;
84   map->num_partitions = size;
85   map->partition_size = size;
86   map->num_basevars = 0;
87   map->partition_to_base_index = NULL;
88   return map;
89 }
90
91
92 /* Free memory associated with MAP.  */
93
94 void
95 delete_var_map (var_map map)
96 {
97   var_map_base_fini (map);
98   partition_delete (map->var_partition);
99   free (map->partition_to_view);
100   free (map->view_to_partition);
101   free (map);
102 }
103
104
105 /* This function will combine the partitions in MAP for VAR1 and VAR2.  It
106    Returns the partition which represents the new partition.  If the two
107    partitions cannot be combined, NO_PARTITION is returned.  */
108
109 int
110 var_union (var_map map, tree var1, tree var2)
111 {
112   int p1, p2, p3;
113
114   gcc_assert (TREE_CODE (var1) == SSA_NAME);
115   gcc_assert (TREE_CODE (var2) == SSA_NAME);
116
117   /* This is independent of partition_to_view. If partition_to_view is
118      on, then whichever one of these partitions is absorbed will never have a
119      dereference into the partition_to_view array any more.  */
120
121   p1 = partition_find (map->var_partition, SSA_NAME_VERSION (var1));
122   p2 = partition_find (map->var_partition, SSA_NAME_VERSION (var2));
123
124   gcc_assert (p1 != NO_PARTITION);
125   gcc_assert (p2 != NO_PARTITION);
126
127   if (p1 == p2)
128     p3 = p1;
129   else
130     p3 = partition_union (map->var_partition, p1, p2);
131
132   if (map->partition_to_view)
133     p3 = map->partition_to_view[p3];
134
135   return p3;
136 }
137
138
139 /* Compress the partition numbers in MAP such that they fall in the range
140    0..(num_partitions-1) instead of wherever they turned out during
141    the partitioning exercise.  This removes any references to unused
142    partitions, thereby allowing bitmaps and other vectors to be much
143    denser.
144
145    This is implemented such that compaction doesn't affect partitioning.
146    Ie., once partitions are created and possibly merged, running one
147    or more different kind of compaction will not affect the partitions
148    themselves.  Their index might change, but all the same variables will
149    still be members of the same partition group.  This allows work on reduced
150    sets, and no loss of information when a larger set is later desired.
151
152    In particular, coalescing can work on partitions which have 2 or more
153    definitions, and then 'recompact' later to include all the single
154    definitions for assignment to program variables.  */
155
156
157 /* Set MAP back to the initial state of having no partition view.  Return a
158    bitmap which has a bit set for each partition number which is in use in the
159    varmap.  */
160
161 static bitmap
162 partition_view_init (var_map map)
163 {
164   bitmap used;
165   int tmp;
166   unsigned int x;
167
168   used = BITMAP_ALLOC (NULL);
169
170   /* Already in a view? Abandon the old one.  */
171   if (map->partition_to_view)
172     {
173       free (map->partition_to_view);
174       map->partition_to_view = NULL;
175     }
176   if (map->view_to_partition)
177     {
178       free (map->view_to_partition);
179       map->view_to_partition = NULL;
180     }
181
182   /* Find out which partitions are actually referenced.  */
183   for (x = 0; x < map->partition_size; x++)
184     {
185       tmp = partition_find (map->var_partition, x);
186       if (ssa_name (tmp) != NULL_TREE && !virtual_operand_p (ssa_name (tmp))
187           && (!has_zero_uses (ssa_name (tmp))
188               || !SSA_NAME_IS_DEFAULT_DEF (ssa_name (tmp))
189               || (SSA_NAME_VAR (ssa_name (tmp))
190                   && !VAR_P (SSA_NAME_VAR (ssa_name (tmp))))))
191         bitmap_set_bit (used, tmp);
192     }
193
194   map->num_partitions = map->partition_size;
195   return used;
196 }
197
198
199 /* This routine will finalize the view data for MAP based on the partitions
200    set in SELECTED.  This is either the same bitmap returned from
201    partition_view_init, or a trimmed down version if some of those partitions
202    were not desired in this view.  SELECTED is freed before returning.  */
203
204 static void
205 partition_view_fini (var_map map, bitmap selected)
206 {
207   bitmap_iterator bi;
208   unsigned count, i, x, limit;
209
210   gcc_assert (selected);
211
212   count = bitmap_count_bits (selected);
213   limit = map->partition_size;
214
215   /* If its a one-to-one ratio, we don't need any view compaction.  */
216   if (count < limit)
217     {
218       map->partition_to_view = (int *)xmalloc (limit * sizeof (int));
219       memset (map->partition_to_view, 0xff, (limit * sizeof (int)));
220       map->view_to_partition = (int *)xmalloc (count * sizeof (int));
221
222       i = 0;
223       /* Give each selected partition an index.  */
224       EXECUTE_IF_SET_IN_BITMAP (selected, 0, x, bi)
225         {
226           map->partition_to_view[x] = i;
227           map->view_to_partition[i] = x;
228           i++;
229         }
230       gcc_assert (i == count);
231       map->num_partitions = i;
232     }
233
234   BITMAP_FREE (selected);
235 }
236
237
238 /* Create a partition view which includes all the used partitions in MAP.  */
239
240 void
241 partition_view_normal (var_map map)
242 {
243   bitmap used;
244
245   used = partition_view_init (map);
246   partition_view_fini (map, used);
247
248   var_map_base_fini (map);
249 }
250
251
252 /* Create a partition view in MAP which includes just partitions which occur in
253    the bitmap ONLY. If WANT_BASES is true, create the base variable map
254    as well.  */
255
256 void
257 partition_view_bitmap (var_map map, bitmap only)
258 {
259   bitmap used;
260   bitmap new_partitions = BITMAP_ALLOC (NULL);
261   unsigned x, p;
262   bitmap_iterator bi;
263
264   used = partition_view_init (map);
265   EXECUTE_IF_SET_IN_BITMAP (only, 0, x, bi)
266     {
267       p = partition_find (map->var_partition, x);
268       gcc_assert (bitmap_bit_p (used, p));
269       bitmap_set_bit (new_partitions, p);
270     }
271   partition_view_fini (map, new_partitions);
272
273   var_map_base_fini (map);
274 }
275
276
277 static bitmap usedvars;
278
279 /* Mark VAR as used, so that it'll be preserved during rtl expansion.
280    Returns true if VAR wasn't marked before.  */
281
282 static inline bool
283 set_is_used (tree var)
284 {
285   return bitmap_set_bit (usedvars, DECL_UID (var));
286 }
287
288 /* Return true if VAR is marked as used.  */
289
290 static inline bool
291 is_used_p (tree var)
292 {
293   return bitmap_bit_p (usedvars, DECL_UID (var));
294 }
295
296 static inline void mark_all_vars_used (tree *);
297
298 /* Helper function for mark_all_vars_used, called via walk_tree.  */
299
300 static tree
301 mark_all_vars_used_1 (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
302 {
303   tree t = *tp;
304   enum tree_code_class c = TREE_CODE_CLASS (TREE_CODE (t));
305   tree b;
306
307   if (TREE_CODE (t) == SSA_NAME)
308     {
309       *walk_subtrees = 0;
310       t = SSA_NAME_VAR (t);
311       if (!t)
312         return NULL;
313     }
314
315   if (IS_EXPR_CODE_CLASS (c)
316       && (b = TREE_BLOCK (t)) != NULL)
317     TREE_USED (b) = true;
318
319   /* Ignore TMR_OFFSET and TMR_STEP for TARGET_MEM_REFS, as those
320      fields do not contain vars.  */
321   if (TREE_CODE (t) == TARGET_MEM_REF)
322     {
323       mark_all_vars_used (&TMR_BASE (t));
324       mark_all_vars_used (&TMR_INDEX (t));
325       mark_all_vars_used (&TMR_INDEX2 (t));
326       *walk_subtrees = 0;
327       return NULL;
328     }
329
330   /* Only need to mark VAR_DECLS; parameters and return results are not
331      eliminated as unused.  */
332   if (TREE_CODE (t) == VAR_DECL)
333     {
334       /* When a global var becomes used for the first time also walk its
335          initializer (non global ones don't have any).  */
336       if (set_is_used (t) && is_global_var (t)
337           && DECL_CONTEXT (t) == current_function_decl)
338         mark_all_vars_used (&DECL_INITIAL (t));
339     }
340   /* remove_unused_scope_block_p requires information about labels
341      which are not DECL_IGNORED_P to tell if they might be used in the IL.  */
342   else if (TREE_CODE (t) == LABEL_DECL)
343     /* Although the TREE_USED values that the frontend uses would be
344        acceptable (albeit slightly over-conservative) for our purposes,
345        init_vars_expansion clears TREE_USED for LABEL_DECLs too, so we
346        must re-compute it here.  */
347     TREE_USED (t) = 1;
348
349   if (IS_TYPE_OR_DECL_P (t))
350     *walk_subtrees = 0;
351
352   return NULL;
353 }
354
355 /* Mark the scope block SCOPE and its subblocks unused when they can be
356    possibly eliminated if dead.  */
357
358 static void
359 mark_scope_block_unused (tree scope)
360 {
361   tree t;
362   TREE_USED (scope) = false;
363   if (!(*debug_hooks->ignore_block) (scope))
364     TREE_USED (scope) = true;
365   for (t = BLOCK_SUBBLOCKS (scope); t ; t = BLOCK_CHAIN (t))
366     mark_scope_block_unused (t);
367 }
368
369 /* Look if the block is dead (by possibly eliminating its dead subblocks)
370    and return true if so.
371    Block is declared dead if:
372      1) No statements are associated with it.
373      2) Declares no live variables
374      3) All subblocks are dead
375         or there is precisely one subblocks and the block
376         has same abstract origin as outer block and declares
377         no variables, so it is pure wrapper.
378    When we are not outputting full debug info, we also eliminate dead variables
379    out of scope blocks to let them to be recycled by GGC and to save copying work
380    done by the inliner.  */
381
382 static bool
383 remove_unused_scope_block_p (tree scope, bool in_ctor_dtor_block)
384 {
385   tree *t, *next;
386   bool unused = !TREE_USED (scope);
387   int nsubblocks = 0;
388
389   /* For ipa-polymorphic-call.c purposes, preserve blocks:
390      1) with BLOCK_ABSTRACT_ORIGIN of a ctor/dtor or their clones  */
391   if (inlined_polymorphic_ctor_dtor_block_p (scope, true))
392     {
393       in_ctor_dtor_block = true;
394       unused = false;
395     }
396   /* 2) inside such blocks, the outermost block with block_ultimate_origin
397      being a FUNCTION_DECL.  */
398   else if (in_ctor_dtor_block)
399     {
400       tree fn = block_ultimate_origin (scope);
401       if (fn && TREE_CODE (fn) == FUNCTION_DECL)
402         {
403           in_ctor_dtor_block = false;
404           unused = false;
405         }
406     }
407
408   for (t = &BLOCK_VARS (scope); *t; t = next)
409     {
410       next = &DECL_CHAIN (*t);
411
412       /* Debug info of nested function refers to the block of the
413          function.  We might stil call it even if all statements
414          of function it was nested into was elliminated.
415
416          TODO: We can actually look into cgraph to see if function
417          will be output to file.  */
418       if (TREE_CODE (*t) == FUNCTION_DECL)
419         unused = false;
420
421       /* If a decl has a value expr, we need to instantiate it
422          regardless of debug info generation, to avoid codegen
423          differences in memory overlap tests.  update_equiv_regs() may
424          indirectly call validate_equiv_mem() to test whether a
425          SET_DEST overlaps with others, and if the value expr changes
426          by virtual register instantiation, we may get end up with
427          different results.  */
428       else if (TREE_CODE (*t) == VAR_DECL && DECL_HAS_VALUE_EXPR_P (*t))
429         unused = false;
430
431       /* Remove everything we don't generate debug info for.  */
432       else if (DECL_IGNORED_P (*t))
433         {
434           *t = DECL_CHAIN (*t);
435           next = t;
436         }
437
438       /* When we are outputting debug info, we usually want to output
439          info about optimized-out variables in the scope blocks.
440          Exception are the scope blocks not containing any instructions
441          at all so user can't get into the scopes at first place.  */
442       else if (is_used_p (*t))
443         unused = false;
444       else if (TREE_CODE (*t) == LABEL_DECL && TREE_USED (*t))
445         /* For labels that are still used in the IL, the decision to
446            preserve them must not depend DEBUG_INFO_LEVEL, otherwise we
447            risk having different ordering in debug vs.  non-debug builds
448            during inlining or versioning.
449            A label appearing here (we have already checked DECL_IGNORED_P)
450            should not be used in the IL unless it has been explicitly used
451            before, so we use TREE_USED as an approximation.  */
452         /* In principle, we should do the same here as for the debug case
453            below, however, when debugging, there might be additional nested
454            levels that keep an upper level with a label live, so we have to
455            force this block to be considered used, too.  */
456         unused = false;
457
458       /* When we are not doing full debug info, we however can keep around
459          only the used variables for cfgexpand's memory packing saving quite
460          a lot of memory.
461
462          For sake of -g3, we keep around those vars but we don't count this as
463          use of block, so innermost block with no used vars and no instructions
464          can be considered dead.  We only want to keep around blocks user can
465          breakpoint into and ask about value of optimized out variables.
466
467          Similarly we need to keep around types at least until all
468          variables of all nested blocks are gone.  We track no
469          information on whether given type is used or not, so we have
470          to keep them even when not emitting debug information,
471          otherwise we may end up remapping variables and their (local)
472          types in different orders depending on whether debug
473          information is being generated.  */
474
475       else if (TREE_CODE (*t) == TYPE_DECL
476                || debug_info_level == DINFO_LEVEL_NORMAL
477                || debug_info_level == DINFO_LEVEL_VERBOSE)
478         ;
479       else
480         {
481           *t = DECL_CHAIN (*t);
482           next = t;
483         }
484     }
485
486   for (t = &BLOCK_SUBBLOCKS (scope); *t ;)
487     if (remove_unused_scope_block_p (*t, in_ctor_dtor_block))
488       {
489         if (BLOCK_SUBBLOCKS (*t))
490           {
491             tree next = BLOCK_CHAIN (*t);
492             tree supercontext = BLOCK_SUPERCONTEXT (*t);
493
494             *t = BLOCK_SUBBLOCKS (*t);
495             while (BLOCK_CHAIN (*t))
496               {
497                 BLOCK_SUPERCONTEXT (*t) = supercontext;
498                 t = &BLOCK_CHAIN (*t);
499               }
500             BLOCK_CHAIN (*t) = next;
501             BLOCK_SUPERCONTEXT (*t) = supercontext;
502             t = &BLOCK_CHAIN (*t);
503             nsubblocks ++;
504           }
505         else
506           *t = BLOCK_CHAIN (*t);
507       }
508     else
509       {
510         t = &BLOCK_CHAIN (*t);
511         nsubblocks ++;
512       }
513
514
515    if (!unused)
516      ;
517    /* Outer scope is always used.  */
518    else if (!BLOCK_SUPERCONTEXT (scope)
519             || TREE_CODE (BLOCK_SUPERCONTEXT (scope)) == FUNCTION_DECL)
520      unused = false;
521    /* Innermost blocks with no live variables nor statements can be always
522       eliminated.  */
523    else if (!nsubblocks)
524      ;
525    /* When not generating debug info we can eliminate info on unused
526       variables.  */
527    else if (!flag_auto_profile && debug_info_level == DINFO_LEVEL_NONE)
528      {
529        /* Even for -g0 don't prune outer scopes from artificial
530           functions, otherwise diagnostics using tree_nonartificial_location
531           will not be emitted properly.  */
532        if (inlined_function_outer_scope_p (scope))
533          {
534            tree ao = scope;
535
536            while (ao
537                   && TREE_CODE (ao) == BLOCK
538                   && BLOCK_ABSTRACT_ORIGIN (ao) != ao)
539              ao = BLOCK_ABSTRACT_ORIGIN (ao);
540            if (ao
541                && TREE_CODE (ao) == FUNCTION_DECL
542                && DECL_DECLARED_INLINE_P (ao)
543                && lookup_attribute ("artificial", DECL_ATTRIBUTES (ao)))
544              unused = false;
545          }
546      }
547    else if (BLOCK_VARS (scope) || BLOCK_NUM_NONLOCALIZED_VARS (scope))
548      unused = false;
549    /* See if this block is important for representation of inlined function.
550       Inlined functions are always represented by block with
551       block_ultimate_origin being set to FUNCTION_DECL and DECL_SOURCE_LOCATION
552       set...  */
553    else if (inlined_function_outer_scope_p (scope))
554      unused = false;
555    else
556    /* Verfify that only blocks with source location set
557       are entry points to the inlined functions.  */
558      gcc_assert (LOCATION_LOCUS (BLOCK_SOURCE_LOCATION (scope))
559                  == UNKNOWN_LOCATION);
560
561    TREE_USED (scope) = !unused;
562    return unused;
563 }
564
565 /* Mark all VAR_DECLS under *EXPR_P as used, so that they won't be
566    eliminated during the tree->rtl conversion process.  */
567
568 static inline void
569 mark_all_vars_used (tree *expr_p)
570 {
571   walk_tree (expr_p, mark_all_vars_used_1, NULL, NULL);
572 }
573
574 /* Helper function for clear_unused_block_pointer, called via walk_tree.  */
575
576 static tree
577 clear_unused_block_pointer_1 (tree *tp, int *, void *)
578 {
579   if (EXPR_P (*tp) && TREE_BLOCK (*tp)
580       && !TREE_USED (TREE_BLOCK (*tp)))
581     TREE_SET_BLOCK (*tp, NULL);
582   return NULL_TREE;
583 }
584
585 /* Set all block pointer in debug or clobber stmt to NULL if the block
586    is unused, so that they will not be streamed out.  */
587
588 static void
589 clear_unused_block_pointer (void)
590 {
591   basic_block bb;
592   gimple_stmt_iterator gsi;
593
594   FOR_EACH_BB_FN (bb, cfun)
595     for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
596       {
597         unsigned i;
598         tree b;
599         gimple *stmt = gsi_stmt (gsi);
600
601         if (!is_gimple_debug (stmt) && !gimple_clobber_p (stmt))
602           continue;
603         b = gimple_block (stmt);
604         if (b && !TREE_USED (b))
605           gimple_set_block (stmt, NULL);
606         for (i = 0; i < gimple_num_ops (stmt); i++)
607           walk_tree (gimple_op_ptr (stmt, i), clear_unused_block_pointer_1,
608                      NULL, NULL);
609       }
610 }
611
612 /* Dump scope blocks starting at SCOPE to FILE.  INDENT is the
613    indentation level and FLAGS is as in print_generic_expr.  */
614
615 static void
616 dump_scope_block (FILE *file, int indent, tree scope, int flags)
617 {
618   tree var, t;
619   unsigned int i;
620
621   fprintf (file, "\n%*s{ Scope block #%i%s%s",indent, "" , BLOCK_NUMBER (scope),
622            TREE_USED (scope) ? "" : " (unused)",
623            BLOCK_ABSTRACT (scope) ? " (abstract)": "");
624   if (LOCATION_LOCUS (BLOCK_SOURCE_LOCATION (scope)) != UNKNOWN_LOCATION)
625     {
626       expanded_location s = expand_location (BLOCK_SOURCE_LOCATION (scope));
627       fprintf (file, " %s:%i", s.file, s.line);
628     }
629   if (BLOCK_ABSTRACT_ORIGIN (scope))
630     {
631       tree origin = block_ultimate_origin (scope);
632       if (origin)
633         {
634           fprintf (file, " Originating from :");
635           if (DECL_P (origin))
636             print_generic_decl (file, origin, flags);
637           else
638             fprintf (file, "#%i", BLOCK_NUMBER (origin));
639         }
640     }
641   fprintf (file, " \n");
642   for (var = BLOCK_VARS (scope); var; var = DECL_CHAIN (var))
643     {
644       fprintf (file, "%*s", indent, "");
645       print_generic_decl (file, var, flags);
646       fprintf (file, "\n");
647     }
648   for (i = 0; i < BLOCK_NUM_NONLOCALIZED_VARS (scope); i++)
649     {
650       fprintf (file, "%*s",indent, "");
651       print_generic_decl (file, BLOCK_NONLOCALIZED_VAR (scope, i),
652                           flags);
653       fprintf (file, " (nonlocalized)\n");
654     }
655   for (t = BLOCK_SUBBLOCKS (scope); t ; t = BLOCK_CHAIN (t))
656     dump_scope_block (file, indent + 2, t, flags);
657   fprintf (file, "\n%*s}\n",indent, "");
658 }
659
660 /* Dump the tree of lexical scopes starting at SCOPE to stderr.  FLAGS
661    is as in print_generic_expr.  */
662
663 DEBUG_FUNCTION void
664 debug_scope_block (tree scope, int flags)
665 {
666   dump_scope_block (stderr, 0, scope, flags);
667 }
668
669
670 /* Dump the tree of lexical scopes of current_function_decl to FILE.
671    FLAGS is as in print_generic_expr.  */
672
673 void
674 dump_scope_blocks (FILE *file, int flags)
675 {
676   dump_scope_block (file, 0, DECL_INITIAL (current_function_decl), flags);
677 }
678
679
680 /* Dump the tree of lexical scopes of current_function_decl to stderr.
681    FLAGS is as in print_generic_expr.  */
682
683 DEBUG_FUNCTION void
684 debug_scope_blocks (int flags)
685 {
686   dump_scope_blocks (stderr, flags);
687 }
688
689 /* Remove local variables that are not referenced in the IL.  */
690
691 void
692 remove_unused_locals (void)
693 {
694   basic_block bb;
695   tree var;
696   unsigned srcidx, dstidx, num;
697   bool have_local_clobbers = false;
698
699   /* Removing declarations from lexical blocks when not optimizing is
700      not only a waste of time, it actually causes differences in stack
701      layout.  */
702   if (!optimize)
703     return;
704
705   timevar_push (TV_REMOVE_UNUSED);
706
707   mark_scope_block_unused (DECL_INITIAL (current_function_decl));
708
709   usedvars = BITMAP_ALLOC (NULL);
710
711   /* Walk the CFG marking all referenced symbols.  */
712   FOR_EACH_BB_FN (bb, cfun)
713     {
714       gimple_stmt_iterator gsi;
715       size_t i;
716       edge_iterator ei;
717       edge e;
718
719       /* Walk the statements.  */
720       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
721         {
722           gimple *stmt = gsi_stmt (gsi);
723           tree b = gimple_block (stmt);
724
725           if (is_gimple_debug (stmt))
726             continue;
727
728           if (gimple_clobber_p (stmt))
729             {
730               have_local_clobbers = true;
731               continue;
732             }
733
734           if (b)
735             TREE_USED (b) = true;
736
737           for (i = 0; i < gimple_num_ops (stmt); i++)
738             mark_all_vars_used (gimple_op_ptr (gsi_stmt (gsi), i));
739         }
740
741       for (gphi_iterator gpi = gsi_start_phis (bb);
742            !gsi_end_p (gpi);
743            gsi_next (&gpi))
744         {
745           use_operand_p arg_p;
746           ssa_op_iter i;
747           tree def;
748           gphi *phi = gpi.phi ();
749
750           if (virtual_operand_p (gimple_phi_result (phi)))
751             continue;
752
753           def = gimple_phi_result (phi);
754           mark_all_vars_used (&def);
755
756           FOR_EACH_PHI_ARG (arg_p, phi, i, SSA_OP_ALL_USES)
757             {
758               tree arg = USE_FROM_PTR (arg_p);
759               int index = PHI_ARG_INDEX_FROM_USE (arg_p);
760               tree block =
761                 LOCATION_BLOCK (gimple_phi_arg_location (phi, index));
762               if (block != NULL)
763                 TREE_USED (block) = true;
764               mark_all_vars_used (&arg);
765             }
766         }
767
768       FOR_EACH_EDGE (e, ei, bb->succs)
769         if (LOCATION_BLOCK (e->goto_locus) != NULL)
770           TREE_USED (LOCATION_BLOCK (e->goto_locus)) = true;
771     }
772
773   /* We do a two-pass approach about the out-of-scope clobbers.  We want
774      to remove them if they are the only references to a local variable,
775      but we want to retain them when there's any other.  So the first pass
776      ignores them, and the second pass (if there were any) tries to remove
777      them.  */
778   if (have_local_clobbers)
779     FOR_EACH_BB_FN (bb, cfun)
780       {
781         gimple_stmt_iterator gsi;
782
783         for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
784           {
785             gimple *stmt = gsi_stmt (gsi);
786             tree b = gimple_block (stmt);
787
788             if (gimple_clobber_p (stmt))
789               {
790                 tree lhs = gimple_assign_lhs (stmt);
791                 tree base = get_base_address (lhs);
792                 /* Remove clobbers referencing unused vars, or clobbers
793                    with MEM_REF lhs referencing uninitialized pointers.  */
794                 if ((TREE_CODE (base) == VAR_DECL && !is_used_p (base))
795                     || (TREE_CODE (lhs) == MEM_REF
796                         && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME
797                         && SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (lhs, 0))
798                         && (TREE_CODE (SSA_NAME_VAR (TREE_OPERAND (lhs, 0)))
799                             != PARM_DECL)))
800                   {
801                     unlink_stmt_vdef (stmt);
802                     gsi_remove (&gsi, true);
803                     release_defs (stmt);
804                     continue;
805                   }
806                 if (b)
807                   TREE_USED (b) = true;
808               }
809             gsi_next (&gsi);
810           }
811       }
812
813   if (cfun->has_simduid_loops)
814     {
815       struct loop *loop;
816       FOR_EACH_LOOP (loop, 0)
817         if (loop->simduid && !is_used_p (loop->simduid))
818           loop->simduid = NULL_TREE;
819     }
820
821   cfun->has_local_explicit_reg_vars = false;
822
823   /* Remove unmarked local and global vars from local_decls.  */
824   num = vec_safe_length (cfun->local_decls);
825   for (srcidx = 0, dstidx = 0; srcidx < num; srcidx++)
826     {
827       var = (*cfun->local_decls)[srcidx];
828       if (TREE_CODE (var) == VAR_DECL)
829         {
830           if (!is_used_p (var))
831             {
832               tree def;
833               if (cfun->nonlocal_goto_save_area
834                   && TREE_OPERAND (cfun->nonlocal_goto_save_area, 0) == var)
835                 cfun->nonlocal_goto_save_area = NULL;
836               /* Release any default def associated with var.  */
837               if ((def = ssa_default_def (cfun, var)) != NULL_TREE)
838                 {
839                   set_ssa_default_def (cfun, var, NULL_TREE);
840                   release_ssa_name (def);
841                 }
842               continue;
843             }
844         }
845       if (TREE_CODE (var) == VAR_DECL
846           && DECL_HARD_REGISTER (var)
847           && !is_global_var (var))
848         cfun->has_local_explicit_reg_vars = true;
849
850       if (srcidx != dstidx)
851         (*cfun->local_decls)[dstidx] = var;
852       dstidx++;
853     }
854   if (dstidx != num)
855     {
856       statistics_counter_event (cfun, "unused VAR_DECLs removed", num - dstidx);
857       cfun->local_decls->truncate (dstidx);
858     }
859
860   remove_unused_scope_block_p (DECL_INITIAL (current_function_decl),
861                                polymorphic_ctor_dtor_p (current_function_decl,
862                                                         true) != NULL_TREE);
863   clear_unused_block_pointer ();
864
865   BITMAP_FREE (usedvars);
866
867   if (dump_file && (dump_flags & TDF_DETAILS))
868     {
869       fprintf (dump_file, "Scope blocks after cleanups:\n");
870       dump_scope_blocks (dump_file, dump_flags);
871     }
872
873   timevar_pop (TV_REMOVE_UNUSED);
874 }
875
876 /* Allocate and return a new live range information object base on MAP.  */
877
878 static tree_live_info_p
879 new_tree_live_info (var_map map)
880 {
881   tree_live_info_p live;
882   basic_block bb;
883
884   live = XNEW (struct tree_live_info_d);
885   live->map = map;
886   live->num_blocks = last_basic_block_for_fn (cfun);
887
888   bitmap_obstack_initialize (&live->livein_obstack);
889   bitmap_obstack_initialize (&live->liveout_obstack);
890   live->livein = XNEWVEC (bitmap_head, last_basic_block_for_fn (cfun));
891   FOR_EACH_BB_FN (bb, cfun)
892     bitmap_initialize (&live->livein[bb->index], &live->livein_obstack);
893
894   live->liveout = XNEWVEC (bitmap_head, last_basic_block_for_fn (cfun));
895   FOR_EACH_BB_FN (bb, cfun)
896     bitmap_initialize (&live->liveout[bb->index], &live->liveout_obstack);
897
898   live->work_stack = XNEWVEC (int, last_basic_block_for_fn (cfun));
899   live->stack_top = live->work_stack;
900
901   live->global = BITMAP_ALLOC (NULL);
902   return live;
903 }
904
905
906 /* Free storage for live range info object LIVE.  */
907
908 void
909 delete_tree_live_info (tree_live_info_p live)
910 {
911   if (live->livein)
912     {
913       bitmap_obstack_release (&live->livein_obstack);
914       free (live->livein);
915     }
916   if (live->liveout)
917     {
918       bitmap_obstack_release (&live->liveout_obstack);
919       free (live->liveout);
920     }
921   BITMAP_FREE (live->global);
922   free (live->work_stack);
923   free (live);
924 }
925
926
927 /* Visit basic block BB and propagate any required live on entry bits from
928    LIVE into the predecessors.  VISITED is the bitmap of visited blocks.
929    TMP is a temporary work bitmap which is passed in to avoid reallocating
930    it each time.  */
931
932 static void
933 loe_visit_block (tree_live_info_p live, basic_block bb, sbitmap visited)
934 {
935   edge e;
936   bool change;
937   edge_iterator ei;
938   basic_block pred_bb;
939   bitmap loe;
940
941   gcc_checking_assert (!bitmap_bit_p (visited, bb->index));
942   bitmap_set_bit (visited, bb->index);
943
944   loe = live_on_entry (live, bb);
945
946   FOR_EACH_EDGE (e, ei, bb->preds)
947     {
948       pred_bb = e->src;
949       if (pred_bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
950         continue;
951       /* Variables live-on-entry from BB that aren't defined in the
952          predecessor block.  This should be the live on entry vars to pred.
953          Note that liveout is the DEFs in a block while live on entry is
954          being calculated.
955          Add these bits to live-on-entry for the pred. if there are any
956          changes, and pred_bb has been visited already, add it to the
957          revisit stack.  */
958       change = bitmap_ior_and_compl_into (live_on_entry (live, pred_bb),
959                                           loe, &live->liveout[pred_bb->index]);
960       if (change
961           && bitmap_bit_p (visited, pred_bb->index))
962         {
963           bitmap_clear_bit (visited, pred_bb->index);
964           *(live->stack_top)++ = pred_bb->index;
965         }
966     }
967 }
968
969
970 /* Using LIVE, fill in all the live-on-entry blocks between the defs and uses
971    of all the variables.  */
972
973 static void
974 live_worklist (tree_live_info_p live)
975 {
976   unsigned b;
977   basic_block bb;
978   sbitmap visited = sbitmap_alloc (last_basic_block_for_fn (cfun) + 1);
979
980   bitmap_clear (visited);
981
982   /* Visit all the blocks in reverse order and propagate live on entry values
983      into the predecessors blocks.  */
984   FOR_EACH_BB_REVERSE_FN (bb, cfun)
985     loe_visit_block (live, bb, visited);
986
987   /* Process any blocks which require further iteration.  */
988   while (live->stack_top != live->work_stack)
989     {
990       b = *--(live->stack_top);
991       loe_visit_block (live, BASIC_BLOCK_FOR_FN (cfun, b), visited);
992     }
993
994   sbitmap_free (visited);
995 }
996
997
998 /* Calculate the initial live on entry vector for SSA_NAME using immediate_use
999    links.  Set the live on entry fields in LIVE.  Def's are marked temporarily
1000    in the liveout vector.  */
1001
1002 static void
1003 set_var_live_on_entry (tree ssa_name, tree_live_info_p live)
1004 {
1005   int p;
1006   gimple *stmt;
1007   use_operand_p use;
1008   basic_block def_bb = NULL;
1009   imm_use_iterator imm_iter;
1010   bool global = false;
1011
1012   p = var_to_partition (live->map, ssa_name);
1013   if (p == NO_PARTITION)
1014     return;
1015
1016   stmt = SSA_NAME_DEF_STMT (ssa_name);
1017   if (stmt)
1018     {
1019       def_bb = gimple_bb (stmt);
1020       /* Mark defs in liveout bitmap temporarily.  */
1021       if (def_bb)
1022         bitmap_set_bit (&live->liveout[def_bb->index], p);
1023     }
1024   else
1025     def_bb = ENTRY_BLOCK_PTR_FOR_FN (cfun);
1026
1027   /* An undefined local variable does not need to be very alive.  */
1028   if (ssa_undefined_value_p (ssa_name, false))
1029     return;
1030
1031   /* Visit each use of SSA_NAME and if it isn't in the same block as the def,
1032      add it to the list of live on entry blocks.  */
1033   FOR_EACH_IMM_USE_FAST (use, imm_iter, ssa_name)
1034     {
1035       gimple *use_stmt = USE_STMT (use);
1036       basic_block add_block = NULL;
1037
1038       if (gimple_code (use_stmt) == GIMPLE_PHI)
1039         {
1040           /* Uses in PHI's are considered to be live at exit of the SRC block
1041              as this is where a copy would be inserted.  Check to see if it is
1042              defined in that block, or whether its live on entry.  */
1043           int index = PHI_ARG_INDEX_FROM_USE (use);
1044           edge e = gimple_phi_arg_edge (as_a <gphi *> (use_stmt), index);
1045           if (e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
1046             {
1047               if (e->src != def_bb)
1048                 add_block = e->src;
1049             }
1050         }
1051       else if (is_gimple_debug (use_stmt))
1052         continue;
1053       else
1054         {
1055           /* If its not defined in this block, its live on entry.  */
1056           basic_block use_bb = gimple_bb (use_stmt);
1057           if (use_bb != def_bb)
1058             add_block = use_bb;
1059         }
1060
1061       /* If there was a live on entry use, set the bit.  */
1062       if (add_block)
1063         {
1064           global = true;
1065           bitmap_set_bit (&live->livein[add_block->index], p);
1066         }
1067     }
1068
1069   /* If SSA_NAME is live on entry to at least one block, fill in all the live
1070      on entry blocks between the def and all the uses.  */
1071   if (global)
1072     bitmap_set_bit (live->global, p);
1073 }
1074
1075
1076 /* Calculate the live on exit vectors based on the entry info in LIVEINFO.  */
1077
1078 static void
1079 calculate_live_on_exit (tree_live_info_p liveinfo)
1080 {
1081   basic_block bb;
1082   edge e;
1083   edge_iterator ei;
1084
1085   /* live on entry calculations used liveout vectors for defs, clear them.  */
1086   FOR_EACH_BB_FN (bb, cfun)
1087     bitmap_clear (&liveinfo->liveout[bb->index]);
1088
1089   /* Set all the live-on-exit bits for uses in PHIs.  */
1090   FOR_EACH_BB_FN (bb, cfun)
1091     {
1092       gphi_iterator gsi;
1093       size_t i;
1094
1095       /* Mark the PHI arguments which are live on exit to the pred block.  */
1096       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1097         {
1098           gphi *phi = gsi.phi ();
1099           for (i = 0; i < gimple_phi_num_args (phi); i++)
1100             {
1101               tree t = PHI_ARG_DEF (phi, i);
1102               int p;
1103
1104               if (TREE_CODE (t) != SSA_NAME)
1105                 continue;
1106
1107               p = var_to_partition (liveinfo->map, t);
1108               if (p == NO_PARTITION)
1109                 continue;
1110               e = gimple_phi_arg_edge (phi, i);
1111               if (e->src != ENTRY_BLOCK_PTR_FOR_FN (cfun))
1112                 bitmap_set_bit (&liveinfo->liveout[e->src->index], p);
1113             }
1114         }
1115
1116       /* Add each successors live on entry to this bock live on exit.  */
1117       FOR_EACH_EDGE (e, ei, bb->succs)
1118         if (e->dest != EXIT_BLOCK_PTR_FOR_FN (cfun))
1119           bitmap_ior_into (&liveinfo->liveout[bb->index],
1120                            live_on_entry (liveinfo, e->dest));
1121     }
1122 }
1123
1124
1125 /* Given partition map MAP, calculate all the live on entry bitmaps for
1126    each partition.  Return a new live info object.  */
1127
1128 tree_live_info_p
1129 calculate_live_ranges (var_map map, bool want_livein)
1130 {
1131   tree var;
1132   unsigned i;
1133   tree_live_info_p live;
1134
1135   live = new_tree_live_info (map);
1136   for (i = 0; i < num_var_partitions (map); i++)
1137     {
1138       var = partition_to_var (map, i);
1139       if (var != NULL_TREE)
1140         set_var_live_on_entry (var, live);
1141     }
1142
1143   live_worklist (live);
1144
1145   if (flag_checking)
1146     verify_live_on_entry (live);
1147
1148   calculate_live_on_exit (live);
1149
1150   if (!want_livein)
1151     {
1152       bitmap_obstack_release (&live->livein_obstack);
1153       free (live->livein);
1154       live->livein = NULL;
1155     }
1156
1157   return live;
1158 }
1159
1160
1161 /* Output partition map MAP to file F.  */
1162
1163 void
1164 dump_var_map (FILE *f, var_map map)
1165 {
1166   int t;
1167   unsigned x, y;
1168   int p;
1169
1170   fprintf (f, "\nPartition map \n\n");
1171
1172   for (x = 0; x < map->num_partitions; x++)
1173     {
1174       if (map->view_to_partition != NULL)
1175         p = map->view_to_partition[x];
1176       else
1177         p = x;
1178
1179       if (ssa_name (p) == NULL_TREE
1180           || virtual_operand_p (ssa_name (p)))
1181         continue;
1182
1183       t = 0;
1184       for (y = 1; y < num_ssa_names; y++)
1185         {
1186           p = partition_find (map->var_partition, y);
1187           if (map->partition_to_view)
1188             p = map->partition_to_view[p];
1189           if (p == (int)x)
1190             {
1191               if (t++ == 0)
1192                 {
1193                   fprintf (f, "Partition %d (", x);
1194                   print_generic_expr (f, partition_to_var (map, p), TDF_SLIM);
1195                   fprintf (f, " - ");
1196                 }
1197               fprintf (f, "%d ", y);
1198             }
1199         }
1200       if (t != 0)
1201         fprintf (f, ")\n");
1202     }
1203   fprintf (f, "\n");
1204 }
1205
1206
1207 /* Generic dump for the above.  */
1208
1209 DEBUG_FUNCTION void
1210 debug (_var_map &ref)
1211 {
1212   dump_var_map (stderr, &ref);
1213 }
1214
1215 DEBUG_FUNCTION void
1216 debug (_var_map *ptr)
1217 {
1218   if (ptr)
1219     debug (*ptr);
1220   else
1221     fprintf (stderr, "<nil>\n");
1222 }
1223
1224
1225 /* Output live range info LIVE to file F, controlled by FLAG.  */
1226
1227 void
1228 dump_live_info (FILE *f, tree_live_info_p live, int flag)
1229 {
1230   basic_block bb;
1231   unsigned i;
1232   var_map map = live->map;
1233   bitmap_iterator bi;
1234
1235   if ((flag & LIVEDUMP_ENTRY) && live->livein)
1236     {
1237       FOR_EACH_BB_FN (bb, cfun)
1238         {
1239           fprintf (f, "\nLive on entry to BB%d : ", bb->index);
1240           EXECUTE_IF_SET_IN_BITMAP (&live->livein[bb->index], 0, i, bi)
1241             {
1242               print_generic_expr (f, partition_to_var (map, i), TDF_SLIM);
1243               fprintf (f, "  ");
1244             }
1245           fprintf (f, "\n");
1246         }
1247     }
1248
1249   if ((flag & LIVEDUMP_EXIT) && live->liveout)
1250     {
1251       FOR_EACH_BB_FN (bb, cfun)
1252         {
1253           fprintf (f, "\nLive on exit from BB%d : ", bb->index);
1254           EXECUTE_IF_SET_IN_BITMAP (&live->liveout[bb->index], 0, i, bi)
1255             {
1256               print_generic_expr (f, partition_to_var (map, i), TDF_SLIM);
1257               fprintf (f, "  ");
1258             }
1259           fprintf (f, "\n");
1260         }
1261     }
1262 }
1263
1264
1265 /* Generic dump for the above.  */
1266
1267 DEBUG_FUNCTION void
1268 debug (tree_live_info_d &ref)
1269 {
1270   dump_live_info (stderr, &ref, 0);
1271 }
1272
1273 DEBUG_FUNCTION void
1274 debug (tree_live_info_d *ptr)
1275 {
1276   if (ptr)
1277     debug (*ptr);
1278   else
1279     fprintf (stderr, "<nil>\n");
1280 }
1281
1282
1283 /* Verify that SSA_VAR is a non-virtual SSA_NAME.  */
1284
1285 void
1286 register_ssa_partition_check (tree ssa_var)
1287 {
1288   gcc_assert (TREE_CODE (ssa_var) == SSA_NAME);
1289   if (virtual_operand_p (ssa_var))
1290     {
1291       fprintf (stderr, "Illegally registering a virtual SSA name :");
1292       print_generic_expr (stderr, ssa_var, TDF_SLIM);
1293       fprintf (stderr, " in the SSA->Normal phase.\n");
1294       internal_error ("SSA corruption");
1295     }
1296 }
1297
1298
1299 /* Verify that the info in LIVE matches the current cfg.  */
1300
1301 static void
1302 verify_live_on_entry (tree_live_info_p live)
1303 {
1304   unsigned i;
1305   tree var;
1306   gimple *stmt;
1307   basic_block bb;
1308   edge e;
1309   int num;
1310   edge_iterator ei;
1311   var_map map = live->map;
1312
1313    /* Check for live on entry partitions and report those with a DEF in
1314       the program. This will typically mean an optimization has done
1315       something wrong.  */
1316   bb = ENTRY_BLOCK_PTR_FOR_FN (cfun);
1317   num = 0;
1318   FOR_EACH_EDGE (e, ei, bb->succs)
1319     {
1320       int entry_block = e->dest->index;
1321       if (e->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1322         continue;
1323       for (i = 0; i < (unsigned)num_var_partitions (map); i++)
1324         {
1325           basic_block tmp;
1326           tree d = NULL_TREE;
1327           bitmap loe;
1328           var = partition_to_var (map, i);
1329           stmt = SSA_NAME_DEF_STMT (var);
1330           tmp = gimple_bb (stmt);
1331           if (SSA_NAME_VAR (var))
1332             d = ssa_default_def (cfun, SSA_NAME_VAR (var));
1333
1334           loe = live_on_entry (live, e->dest);
1335           if (loe && bitmap_bit_p (loe, i))
1336             {
1337               if (!gimple_nop_p (stmt))
1338                 {
1339                   num++;
1340                   print_generic_expr (stderr, var, TDF_SLIM);
1341                   fprintf (stderr, " is defined ");
1342                   if (tmp)
1343                     fprintf (stderr, " in BB%d, ", tmp->index);
1344                   fprintf (stderr, "by:\n");
1345                   print_gimple_stmt (stderr, stmt, 0, TDF_SLIM);
1346                   fprintf (stderr, "\nIt is also live-on-entry to entry BB %d",
1347                            entry_block);
1348                   fprintf (stderr, " So it appears to have multiple defs.\n");
1349                 }
1350               else
1351                 {
1352                   if (d != var)
1353                     {
1354                       num++;
1355                       print_generic_expr (stderr, var, TDF_SLIM);
1356                       fprintf (stderr, " is live-on-entry to BB%d ",
1357                                entry_block);
1358                       if (d)
1359                         {
1360                           fprintf (stderr, " but is not the default def of ");
1361                           print_generic_expr (stderr, d, TDF_SLIM);
1362                           fprintf (stderr, "\n");
1363                         }
1364                       else
1365                         fprintf (stderr, " and there is no default def.\n");
1366                     }
1367                 }
1368             }
1369           else
1370             if (d == var)
1371               {
1372                 /* An undefined local variable does not need to be very
1373                    alive.  */
1374                 if (ssa_undefined_value_p (var, false))
1375                   continue;
1376
1377                 /* The only way this var shouldn't be marked live on entry is
1378                    if it occurs in a PHI argument of the block.  */
1379                 size_t z;
1380                 bool ok = false;
1381                 gphi_iterator gsi;
1382                 for (gsi = gsi_start_phis (e->dest);
1383                      !gsi_end_p (gsi) && !ok;
1384                      gsi_next (&gsi))
1385                   {
1386                     gphi *phi = gsi.phi ();
1387                     for (z = 0; z < gimple_phi_num_args (phi); z++)
1388                       if (var == gimple_phi_arg_def (phi, z))
1389                         {
1390                           ok = true;
1391                           break;
1392                         }
1393                   }
1394                 if (ok)
1395                   continue;
1396                 /* Expand adds unused default defs for PARM_DECLs and
1397                    RESULT_DECLs.  They're ok.  */
1398                 if (has_zero_uses (var)
1399                     && SSA_NAME_VAR (var)
1400                     && !VAR_P (SSA_NAME_VAR (var)))
1401                   continue;
1402                 num++;
1403                 print_generic_expr (stderr, var, TDF_SLIM);
1404                 fprintf (stderr, " is not marked live-on-entry to entry BB%d ",
1405                          entry_block);
1406                 fprintf (stderr, "but it is a default def so it should be.\n");
1407               }
1408         }
1409     }
1410   gcc_assert (num <= 0);
1411 }