analyzer: fix feasibility false +ve on jumps through function ptrs [PR107582]
[platform/upstream/gcc.git] / gcc / passes.cc
1 /* Top level of GCC compilers (cc1, cc1plus, etc.)
2    Copyright (C) 1987-2022 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 is the top level of cc1/c++.
21    It parses command args, opens files, invokes the various passes
22    in the proper order, and counts the time used by each.
23    Error messages and low-level interface to malloc also handled here.  */
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "backend.h"
29 #include "target.h"
30 #include "rtl.h"
31 #include "tree.h"
32 #include "gimple.h"
33 #include "cfghooks.h"
34 #include "df.h"
35 #include "memmodel.h"
36 #include "tm_p.h"
37 #include "ssa.h"
38 #include "emit-rtl.h"
39 #include "cgraph.h"
40 #include "lto-streamer.h"
41 #include "fold-const.h"
42 #include "varasm.h"
43 #include "output.h"
44 #include "graph.h"
45 #include "debug.h"
46 #include "cfgloop.h"
47 #include "value-prof.h"
48 #include "tree-cfg.h"
49 #include "tree-ssa-loop-manip.h"
50 #include "tree-into-ssa.h"
51 #include "tree-dfa.h"
52 #include "tree-ssa.h"
53 #include "tree-pass.h"
54 #include "plugin.h"
55 #include "ipa-utils.h"
56 #include "tree-pretty-print.h" /* for dump_function_header */
57 #include "context.h"
58 #include "pass_manager.h"
59 #include "cfgrtl.h"
60 #include "tree-ssa-live.h"  /* For remove_unused_locals.  */
61 #include "tree-cfgcleanup.h"
62 #include "insn-addr.h" /* for INSN_ADDRESSES_ALLOC.  */
63 #include "diagnostic-core.h" /* for fnotice */
64 #include "stringpool.h"
65 #include "attribs.h"
66
67 using namespace gcc;
68
69 /* This is used for debugging.  It allows the current pass to printed
70    from anywhere in compilation.
71    The variable current_pass is also used for statistics and plugins.  */
72 opt_pass *current_pass;
73
74 /* Most passes are single-instance (within their context) and thus don't
75    need to implement cloning, but passes that support multiple instances
76    *must* provide their own implementation of the clone method.
77
78    Handle this by providing a default implemenation, but make it a fatal
79    error to call it.  */
80
81 opt_pass *
82 opt_pass::clone ()
83 {
84   internal_error ("pass %s does not support cloning", name);
85 }
86
87 void
88 opt_pass::set_pass_param (unsigned int, bool)
89 {
90   internal_error ("pass %s needs a %<set_pass_param%> implementation "
91                   "to handle the extra argument in %<NEXT_PASS%>", name);
92 }
93
94 bool
95 opt_pass::gate (function *)
96 {
97   return true;
98 }
99
100 unsigned int
101 opt_pass::execute (function *)
102 {
103   return 0;
104 }
105
106 opt_pass::opt_pass (const pass_data &data, context *ctxt)
107   : pass_data (data),
108     sub (NULL),
109     next (NULL),
110     static_pass_number (0),
111     m_ctxt (ctxt)
112 {
113 }
114
115
116 void
117 pass_manager::execute_early_local_passes ()
118 {
119   execute_pass_list (cfun, pass_build_ssa_passes_1->sub);
120   execute_pass_list (cfun, pass_local_optimization_passes_1->sub);
121 }
122
123 unsigned int
124 pass_manager::execute_pass_mode_switching ()
125 {
126   return pass_mode_switching_1->execute (cfun);
127 }
128
129
130 /* Call from anywhere to find out what pass this is.  Useful for
131    printing out debugging information deep inside an service
132    routine.  */
133 void
134 print_current_pass (FILE *file)
135 {
136   if (current_pass)
137     fprintf (file, "current pass = %s (%d)\n",
138              current_pass->name, current_pass->static_pass_number);
139   else
140     fprintf (file, "no current pass.\n");
141 }
142
143
144 /* Call from the debugger to get the current pass name.  */
145 DEBUG_FUNCTION void
146 debug_pass (void)
147 {
148   print_current_pass (stderr);
149 }
150
151
152
153 /* Global variables used to communicate with passes.  */
154 bool in_gimple_form;
155
156
157 /* This is called from various places for FUNCTION_DECL, VAR_DECL,
158    and TYPE_DECL nodes.
159
160    This does nothing for local (non-static) variables, unless the
161    variable is a register variable with DECL_ASSEMBLER_NAME set.  In
162    that case, or if the variable is not an automatic, it sets up the
163    RTL and outputs any assembler code (label definition, storage
164    allocation and initialization).
165
166    DECL is the declaration.  TOP_LEVEL is nonzero
167    if this declaration is not within a function.  */
168
169 void
170 rest_of_decl_compilation (tree decl,
171                           int top_level,
172                           int at_end)
173 {
174   bool finalize = true;
175
176   /* We deferred calling assemble_alias so that we could collect
177      other attributes such as visibility.  Emit the alias now.  */
178   if (!in_lto_p)
179   {
180     tree alias;
181     alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl));
182     if (alias)
183       {
184         alias = TREE_VALUE (TREE_VALUE (alias));
185         alias = get_identifier (TREE_STRING_POINTER (alias));
186         /* A quirk of the initial implementation of aliases required that the
187            user add "extern" to all of them.  Which is silly, but now
188            historical.  Do note that the symbol is in fact locally defined.  */
189         DECL_EXTERNAL (decl) = 0;
190         TREE_STATIC (decl) = 1;
191         assemble_alias (decl, alias);
192         finalize = false;
193       }
194   }
195
196   /* Can't defer this, because it needs to happen before any
197      later function definitions are processed.  */
198   if (HAS_DECL_ASSEMBLER_NAME_P (decl)
199       && DECL_ASSEMBLER_NAME_SET_P (decl)
200       && DECL_REGISTER (decl))
201     make_decl_rtl (decl);
202
203   /* Forward declarations for nested functions are not "external",
204      but we need to treat them as if they were.  */
205   if (TREE_STATIC (decl) || DECL_EXTERNAL (decl)
206       || TREE_CODE (decl) == FUNCTION_DECL)
207     {
208       timevar_push (TV_VARCONST);
209
210       /* Don't output anything when a tentative file-scope definition
211          is seen.  But at end of compilation, do output code for them.
212
213          We do output all variables and rely on
214          callgraph code to defer them except for forward declarations
215          (see gcc.c-torture/compile/920624-1.c) */
216       if ((at_end
217            || !DECL_DEFER_OUTPUT (decl)
218            || DECL_INITIAL (decl))
219           && (!VAR_P (decl) || !DECL_HAS_VALUE_EXPR_P (decl))
220           && !DECL_EXTERNAL (decl))
221         {
222           /* When reading LTO unit, we also read varpool, so do not
223              rebuild it.  */
224           if (in_lto_p && !at_end)
225             ;
226           else if (finalize && TREE_CODE (decl) != FUNCTION_DECL)
227             varpool_node::finalize_decl (decl);
228         }
229
230 #ifdef ASM_FINISH_DECLARE_OBJECT
231       if (decl == last_assemble_variable_decl)
232         {
233           ASM_FINISH_DECLARE_OBJECT (asm_out_file, decl,
234                                      top_level, at_end);
235         }
236 #endif
237
238       /* Now that we have activated any function-specific attributes
239          that might affect function decl, particularly align, relayout it.  */
240       if (TREE_CODE (decl) == FUNCTION_DECL)
241         targetm.target_option.relayout_function (decl);
242
243       timevar_pop (TV_VARCONST);
244     }
245   else if (TREE_CODE (decl) == TYPE_DECL
246            /* Like in rest_of_type_compilation, avoid confusing the debug
247               information machinery when there are errors.  */
248            && !seen_error ())
249     {
250       timevar_push (TV_SYMOUT);
251       debug_hooks->type_decl (decl, !top_level);
252       timevar_pop (TV_SYMOUT);
253     }
254
255   /* Let cgraph know about the existence of variables.  */
256   if (in_lto_p && !at_end)
257     ;
258   else if (VAR_P (decl) && !DECL_EXTERNAL (decl)
259            && TREE_STATIC (decl))
260     varpool_node::get_create (decl);
261
262   /* Generate early debug for global variables.  Any local variables will
263      be handled by either handling reachable functions from
264      finalize_compilation_unit (and by consequence, locally scoped
265      symbols), or by rest_of_type_compilation below.
266
267      For Go's hijack of the debug_hooks to implement -fdump-go-spec, pick up
268      function prototypes.  Go's debug_hooks will not forward them to the
269      wrapped hooks.  */
270   if (!in_lto_p
271       && (TREE_CODE (decl) != FUNCTION_DECL
272           /* This will pick up function prototypes with no bodies,
273              which are not visible in finalize_compilation_unit()
274              while iterating with FOR_EACH_*_FUNCTION through the
275              symbol table.  */
276           || (flag_dump_go_spec != NULL
277               && !DECL_SAVED_TREE (decl)
278               && DECL_STRUCT_FUNCTION (decl) == NULL))
279
280       /* We need to check both decl_function_context and
281          current_function_decl here to make sure local extern
282          declarations end up with the correct context.
283
284          For local extern declarations, decl_function_context is
285          empty, but current_function_decl is set to the function where
286          the extern was declared .  Without the check for
287          !current_function_decl below, the local extern ends up
288          incorrectly with a top-level context.
289
290          For example:
291
292          namespace S
293          {
294            int
295            f()
296            {
297              {
298                int i = 42;
299                {
300                  extern int i; // Local extern declaration.
301                  return i;
302                }
303              }
304            }
305          }
306       */
307       && !decl_function_context (decl)
308       && !current_function_decl
309       && DECL_SOURCE_LOCATION (decl) != BUILTINS_LOCATION
310       && (!decl_type_context (decl)
311           /* If we created a varpool node for the decl make sure to
312              call early_global_decl.  Otherwise we miss changes
313              introduced by member definitions like
314                 struct A { static int staticdatamember; };
315                 int A::staticdatamember;
316              and thus have incomplete early debug and late debug
317              called from varpool node removal fails to handle it
318              properly.  */
319           || (finalize
320               && VAR_P (decl)
321               && TREE_STATIC (decl) && !DECL_EXTERNAL (decl)))
322       /* Avoid confusing the debug information machinery when there are
323          errors.  */
324       && !seen_error ())
325     (*debug_hooks->early_global_decl) (decl);
326 }
327
328 /* Called after finishing a record, union or enumeral type.  */
329
330 void
331 rest_of_type_compilation (tree type, int toplev)
332 {
333   /* Avoid confusing the debug information machinery when there are
334      errors.  */
335   if (seen_error ())
336     return;
337
338   timevar_push (TV_SYMOUT);
339   debug_hooks->type_decl (TYPE_STUB_DECL (type), !toplev);
340   timevar_pop (TV_SYMOUT);
341 }
342
343 \f
344
345 void
346 pass_manager::
347 finish_optimization_passes (void)
348 {
349   int i;
350   struct dump_file_info *dfi;
351   char *name;
352   gcc::dump_manager *dumps = m_ctxt->get_dumps ();
353
354   timevar_push (TV_DUMP);
355   if (profile_arc_flag || flag_test_coverage || flag_branch_probabilities)
356     {
357       dumps->dump_start (pass_profile_1->static_pass_number, NULL);
358       end_branch_prob ();
359       dumps->dump_finish (pass_profile_1->static_pass_number);
360     }
361
362   if (optimize > 0)
363     {
364       dumps->dump_start (pass_combine_1->static_pass_number, NULL);
365       print_combine_total_stats ();
366       dumps->dump_finish (pass_combine_1->static_pass_number);
367     }
368
369   /* Do whatever is necessary to finish printing the graphs.  */
370   for (i = TDI_end; (dfi = dumps->get_dump_file_info (i)) != NULL; ++i)
371     if (dfi->graph_dump_initialized)
372       {
373         name = dumps->get_dump_file_name (dfi);
374         finish_graph_dump_file (name);
375         free (name);
376       }
377
378   timevar_pop (TV_DUMP);
379 }
380
381 static unsigned int
382 execute_build_ssa_passes (void)
383 {
384   /* Once this pass (and its sub-passes) are complete, all functions
385      will be in SSA form.  Technically this state change is happening
386      a tad early, since the sub-passes have not yet run, but since
387      none of the sub-passes are IPA passes and do not create new
388      functions, this is ok.  We're setting this value for the benefit
389      of IPA passes that follow.  */
390   if (symtab->state < IPA_SSA)
391     symtab->state = IPA_SSA;
392   return 0;
393 }
394
395 namespace {
396
397 const pass_data pass_data_build_ssa_passes =
398 {
399   SIMPLE_IPA_PASS, /* type */
400   "build_ssa_passes", /* name */
401   OPTGROUP_NONE, /* optinfo_flags */
402   TV_EARLY_LOCAL, /* tv_id */
403   0, /* properties_required */
404   0, /* properties_provided */
405   0, /* properties_destroyed */
406   0, /* todo_flags_start */
407   /* todo_flags_finish is executed before subpases. For this reason
408      it makes no sense to remove unreachable functions here.  */
409   0, /* todo_flags_finish */
410 };
411
412 class pass_build_ssa_passes : public simple_ipa_opt_pass
413 {
414 public:
415   pass_build_ssa_passes (gcc::context *ctxt)
416     : simple_ipa_opt_pass (pass_data_build_ssa_passes, ctxt)
417   {}
418
419   /* opt_pass methods: */
420   bool gate (function *) final override
421     {
422       /* Don't bother doing anything if the program has errors.  */
423       return (!seen_error () && !in_lto_p);
424     }
425
426   unsigned int execute (function *) final override
427     {
428       return execute_build_ssa_passes ();
429     }
430
431 }; // class pass_build_ssa_passes
432
433 const pass_data pass_data_local_optimization_passes =
434 {
435   SIMPLE_IPA_PASS, /* type */
436   "opt_local_passes", /* name */
437   OPTGROUP_NONE, /* optinfo_flags */
438   TV_NONE, /* tv_id */
439   0, /* properties_required */
440   0, /* properties_provided */
441   0, /* properties_destroyed */
442   0, /* todo_flags_start */
443   0, /* todo_flags_finish */
444 };
445
446 class pass_local_optimization_passes : public simple_ipa_opt_pass
447 {
448 public:
449   pass_local_optimization_passes (gcc::context *ctxt)
450     : simple_ipa_opt_pass (pass_data_local_optimization_passes, ctxt)
451   {}
452
453   /* opt_pass methods: */
454   bool gate (function *) final override
455     {
456       /* Don't bother doing anything if the program has errors.  */
457       return (!seen_error () && !in_lto_p);
458     }
459
460 }; // class pass_local_optimization_passes
461
462 const pass_data pass_data_ipa_remove_symbols =
463 {
464   SIMPLE_IPA_PASS, /* type */
465   "remove_symbols", /* name */
466   OPTGROUP_NONE, /* optinfo_flags */
467   TV_NONE, /* tv_id */
468   0, /* properties_required */
469   0, /* properties_provided */
470   0, /* properties_destroyed */
471   0, /* todo_flags_start */
472   TODO_remove_functions | TODO_dump_symtab, /* todo_flags_finish */
473 };
474
475 class pass_ipa_remove_symbols : public simple_ipa_opt_pass
476 {
477 public:
478   pass_ipa_remove_symbols (gcc::context *ctxt)
479     : simple_ipa_opt_pass (pass_data_ipa_remove_symbols, ctxt)
480   {}
481
482   /* opt_pass methods: */
483   bool gate (function *) final override
484     {
485       /* Don't bother doing anything if the program has errors.  */
486       return (!seen_error () && !in_lto_p);
487     }
488
489 }; // class pass_local_optimization_passes
490
491 } // anon namespace
492
493 simple_ipa_opt_pass *
494 make_pass_build_ssa_passes (gcc::context *ctxt)
495 {
496   return new pass_build_ssa_passes (ctxt);
497 }
498
499 simple_ipa_opt_pass *
500 make_pass_local_optimization_passes (gcc::context *ctxt)
501 {
502   return new pass_local_optimization_passes (ctxt);
503 }
504
505 simple_ipa_opt_pass *
506 make_pass_ipa_remove_symbols (gcc::context *ctxt)
507 {
508   return new pass_ipa_remove_symbols (ctxt);
509 }
510
511 namespace {
512
513 const pass_data pass_data_all_early_optimizations =
514 {
515   GIMPLE_PASS, /* type */
516   "early_optimizations", /* name */
517   OPTGROUP_NONE, /* optinfo_flags */
518   TV_NONE, /* tv_id */
519   0, /* properties_required */
520   0, /* properties_provided */
521   0, /* properties_destroyed */
522   0, /* todo_flags_start */
523   0, /* todo_flags_finish */
524 };
525
526 class pass_all_early_optimizations : public gimple_opt_pass
527 {
528 public:
529   pass_all_early_optimizations (gcc::context *ctxt)
530     : gimple_opt_pass (pass_data_all_early_optimizations, ctxt)
531   {}
532
533   /* opt_pass methods: */
534   bool gate (function *) final override
535     {
536       return (optimize >= 1
537               /* Don't bother doing anything if the program has errors.  */
538               && !seen_error ());
539     }
540
541 }; // class pass_all_early_optimizations
542
543 } // anon namespace
544
545 static gimple_opt_pass *
546 make_pass_all_early_optimizations (gcc::context *ctxt)
547 {
548   return new pass_all_early_optimizations (ctxt);
549 }
550
551 namespace {
552
553 const pass_data pass_data_all_optimizations =
554 {
555   GIMPLE_PASS, /* type */
556   "*all_optimizations", /* name */
557   OPTGROUP_NONE, /* optinfo_flags */
558   TV_OPTIMIZE, /* tv_id */
559   0, /* properties_required */
560   0, /* properties_provided */
561   0, /* properties_destroyed */
562   0, /* todo_flags_start */
563   0, /* todo_flags_finish */
564 };
565
566 class pass_all_optimizations : public gimple_opt_pass
567 {
568 public:
569   pass_all_optimizations (gcc::context *ctxt)
570     : gimple_opt_pass (pass_data_all_optimizations, ctxt)
571   {}
572
573   /* opt_pass methods: */
574   bool gate (function *) final override
575   {
576     return optimize >= 1 && !optimize_debug;
577   }
578
579 }; // class pass_all_optimizations
580
581 } // anon namespace
582
583 static gimple_opt_pass *
584 make_pass_all_optimizations (gcc::context *ctxt)
585 {
586   return new pass_all_optimizations (ctxt);
587 }
588
589 namespace {
590
591 const pass_data pass_data_all_optimizations_g =
592 {
593   GIMPLE_PASS, /* type */
594   "*all_optimizations_g", /* name */
595   OPTGROUP_NONE, /* optinfo_flags */
596   TV_OPTIMIZE, /* tv_id */
597   0, /* properties_required */
598   0, /* properties_provided */
599   0, /* properties_destroyed */
600   0, /* todo_flags_start */
601   0, /* todo_flags_finish */
602 };
603
604 class pass_all_optimizations_g : public gimple_opt_pass
605 {
606 public:
607   pass_all_optimizations_g (gcc::context *ctxt)
608     : gimple_opt_pass (pass_data_all_optimizations_g, ctxt)
609   {}
610
611   /* opt_pass methods: */
612   bool gate (function *) final override
613   {
614     return optimize >= 1 && optimize_debug;
615   }
616
617 }; // class pass_all_optimizations_g
618
619 } // anon namespace
620
621 static gimple_opt_pass *
622 make_pass_all_optimizations_g (gcc::context *ctxt)
623 {
624   return new pass_all_optimizations_g (ctxt);
625 }
626
627 namespace {
628
629 const pass_data pass_data_rest_of_compilation =
630 {
631   RTL_PASS, /* type */
632   "*rest_of_compilation", /* name */
633   OPTGROUP_NONE, /* optinfo_flags */
634   TV_REST_OF_COMPILATION, /* tv_id */
635   PROP_rtl, /* properties_required */
636   0, /* properties_provided */
637   0, /* properties_destroyed */
638   0, /* todo_flags_start */
639   0, /* todo_flags_finish */
640 };
641
642 class pass_rest_of_compilation : public rtl_opt_pass
643 {
644 public:
645   pass_rest_of_compilation (gcc::context *ctxt)
646     : rtl_opt_pass (pass_data_rest_of_compilation, ctxt)
647   {}
648
649   /* opt_pass methods: */
650   bool gate (function *) final override
651     {
652       /* Early return if there were errors.  We can run afoul of our
653          consistency checks, and there's not really much point in fixing them.  */
654       return !(rtl_dump_and_exit || flag_syntax_only || seen_error ());
655     }
656
657 }; // class pass_rest_of_compilation
658
659 } // anon namespace
660
661 static rtl_opt_pass *
662 make_pass_rest_of_compilation (gcc::context *ctxt)
663 {
664   return new pass_rest_of_compilation (ctxt);
665 }
666
667 namespace {
668
669 const pass_data pass_data_postreload =
670 {
671   RTL_PASS, /* type */
672   "*all-postreload", /* name */
673   OPTGROUP_NONE, /* optinfo_flags */
674   TV_POSTRELOAD, /* tv_id */
675   PROP_rtl, /* properties_required */
676   0, /* properties_provided */
677   0, /* properties_destroyed */
678   0, /* todo_flags_start */
679   0, /* todo_flags_finish */
680 };
681
682 class pass_postreload : public rtl_opt_pass
683 {
684 public:
685   pass_postreload (gcc::context *ctxt)
686     : rtl_opt_pass (pass_data_postreload, ctxt)
687   {}
688
689   /* opt_pass methods: */
690   bool gate (function *) final override { return reload_completed; }
691
692 }; // class pass_postreload
693
694 } // anon namespace
695
696 static rtl_opt_pass *
697 make_pass_postreload (gcc::context *ctxt)
698 {
699   return new pass_postreload (ctxt);
700 }
701
702 namespace {
703
704 const pass_data pass_data_late_compilation =
705 {
706   RTL_PASS, /* type */
707   "*all-late_compilation", /* name */
708   OPTGROUP_NONE, /* optinfo_flags */
709   TV_LATE_COMPILATION, /* tv_id */
710   PROP_rtl, /* properties_required */
711   0, /* properties_provided */
712   0, /* properties_destroyed */
713   0, /* todo_flags_start */
714   0, /* todo_flags_finish */
715 };
716
717 class pass_late_compilation : public rtl_opt_pass
718 {
719 public:
720   pass_late_compilation (gcc::context *ctxt)
721     : rtl_opt_pass (pass_data_late_compilation, ctxt)
722   {}
723
724   /* opt_pass methods: */
725   bool gate (function *) final override
726   {
727     return reload_completed || targetm.no_register_allocation;
728   }
729
730 }; // class pass_late_compilation
731
732 } // anon namespace
733
734 static rtl_opt_pass *
735 make_pass_late_compilation (gcc::context *ctxt)
736 {
737   return new pass_late_compilation (ctxt);
738 }
739
740 /* Pre-SLP scalar cleanup, it has several cleanup passes like FRE, DSE.  */
741
742 namespace {
743
744 const pass_data pass_data_pre_slp_scalar_cleanup =
745 {
746   GIMPLE_PASS, /* type */
747   "*pre_slp_scalar_cleanup", /* name */
748   OPTGROUP_LOOP, /* optinfo_flags */
749   TV_SCALAR_CLEANUP, /* tv_id */
750   ( PROP_cfg | PROP_ssa ), /* properties_required */
751   0, /* properties_provided */
752   0, /* properties_destroyed */
753   0, /* todo_flags_start */
754   0, /* todo_flags_finish */
755 };
756
757 class pass_pre_slp_scalar_cleanup : public gimple_opt_pass
758 {
759 public:
760   pass_pre_slp_scalar_cleanup (gcc::context *ctxt)
761     : gimple_opt_pass (pass_data_pre_slp_scalar_cleanup, ctxt)
762   {
763   }
764
765   bool
766   gate (function *fun) final override
767   {
768     return flag_tree_slp_vectorize
769            && (fun->pending_TODOs & PENDING_TODO_force_next_scalar_cleanup);
770   }
771
772   unsigned int
773   execute (function *fun) final override
774   {
775     fun->pending_TODOs &= ~PENDING_TODO_force_next_scalar_cleanup;
776     return 0;
777   }
778
779 }; // class pass_pre_slp_scalar_cleanup
780
781 } // anon namespace
782
783 gimple_opt_pass *
784 make_pass_pre_slp_scalar_cleanup (gcc::context *ctxt)
785 {
786   return new pass_pre_slp_scalar_cleanup (ctxt);
787 }
788
789 /* Set the static pass number of pass PASS to ID and record that
790    in the mapping from static pass number to pass.  */
791
792 void
793 pass_manager::
794 set_pass_for_id (int id, opt_pass *pass)
795 {
796   pass->static_pass_number = id;
797   if (passes_by_id_size <= id)
798     {
799       passes_by_id = XRESIZEVEC (opt_pass *, passes_by_id, id + 1);
800       memset (passes_by_id + passes_by_id_size, 0,
801               (id + 1 - passes_by_id_size) * sizeof (void *));
802       passes_by_id_size = id + 1;
803     }
804   passes_by_id[id] = pass;
805 }
806
807 /* Return the pass with the static pass number ID.  */
808
809 opt_pass *
810 pass_manager::get_pass_for_id (int id) const
811 {
812   if (id >= passes_by_id_size)
813     return NULL;
814   return passes_by_id[id];
815 }
816
817 /* Iterate over the pass tree allocating dump file numbers.  We want
818    to do this depth first, and independent of whether the pass is
819    enabled or not.  */
820
821 void
822 register_one_dump_file (opt_pass *pass)
823 {
824   g->get_passes ()->register_one_dump_file (pass);
825 }
826
827 void
828 pass_manager::register_one_dump_file (opt_pass *pass)
829 {
830   char *dot_name, *flag_name, *glob_name;
831   const char *name, *full_name, *prefix;
832
833   /* Buffer big enough to format a 32-bit UINT_MAX into.  */
834   char num[11];
835   dump_kind dkind;
836   int id;
837   optgroup_flags_t optgroup_flags = OPTGROUP_NONE;
838   gcc::dump_manager *dumps = m_ctxt->get_dumps ();
839
840   /* See below in next_pass_1.  */
841   num[0] = '\0';
842   if (pass->static_pass_number != -1)
843     sprintf (num, "%u", ((int) pass->static_pass_number < 0
844                          ? 1 : pass->static_pass_number));
845
846   /* The name is both used to identify the pass for the purposes of plugins,
847      and to specify dump file name and option.
848      The latter two might want something short which is not quite unique; for
849      that reason, we may have a disambiguating prefix, followed by a space
850      to mark the start of the following dump file name / option string.  */
851   name = strchr (pass->name, ' ');
852   name = name ? name + 1 : pass->name;
853   dot_name = concat (".", name, num, NULL);
854   if (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS)
855     {
856       prefix = "ipa-";
857       dkind = DK_ipa;
858       optgroup_flags |= OPTGROUP_IPA;
859     }
860   else if (pass->type == GIMPLE_PASS)
861     {
862       prefix = "tree-";
863       dkind = DK_tree;
864     }
865   else
866     {
867       prefix = "rtl-";
868       dkind = DK_rtl;
869     }
870
871   flag_name = concat (prefix, name, num, NULL);
872   glob_name = concat (prefix, name, NULL);
873   optgroup_flags |= pass->optinfo_flags;
874   /* For any passes that do not have an optgroup set, and which are not
875      IPA passes setup above, set the optgroup to OPTGROUP_OTHER so that
876      any dump messages are emitted properly under -fopt-info(-optall).  */
877   if (optgroup_flags == OPTGROUP_NONE)
878     optgroup_flags = OPTGROUP_OTHER;
879   id = dumps->dump_register (dot_name, flag_name, glob_name, dkind,
880                              optgroup_flags,
881                              true);
882   set_pass_for_id (id, pass);
883   full_name = concat (prefix, pass->name, num, NULL);
884   register_pass_name (pass, full_name);
885   free (CONST_CAST (char *, full_name));
886 }
887
888 /* Register the dump files for the pass_manager starting at PASS. */
889
890 void
891 pass_manager::register_dump_files (opt_pass *pass)
892 {
893   do
894     {
895       if (pass->name && pass->name[0] != '*')
896         register_one_dump_file (pass);
897
898       if (pass->sub)
899         register_dump_files (pass->sub);
900
901       pass = pass->next;
902     }
903   while (pass);
904 }
905
906 /* Register PASS with NAME.  */
907
908 void
909 pass_manager::register_pass_name (opt_pass *pass, const char *name)
910 {
911   if (!m_name_to_pass_map)
912     m_name_to_pass_map = new hash_map<free_string_hash, opt_pass *> (256);
913
914   if (m_name_to_pass_map->get (name))
915     return; /* Ignore plugin passes.  */
916
917   const char *unique_name = xstrdup (name);
918   m_name_to_pass_map->put (unique_name, pass);
919 }
920
921 /* Map from pass id to canonicalized pass name.  */
922
923 typedef const char *char_ptr;
924 static vec<char_ptr> pass_tab;
925
926 /* Callback function for traversing NAME_TO_PASS_MAP.  */
927
928 bool
929 passes_pass_traverse (const char *const &name, opt_pass *const &pass, void *)
930 {
931   gcc_assert (pass->static_pass_number > 0);
932   gcc_assert (pass_tab.exists ());
933
934   pass_tab[pass->static_pass_number] = name;
935
936   return 1;
937 }
938
939 /* The function traverses NAME_TO_PASS_MAP and creates a pass info
940    table for dumping purpose.  */
941
942 void
943 pass_manager::create_pass_tab (void) const
944 {
945   if (!flag_dump_passes)
946     return;
947
948   pass_tab.safe_grow_cleared (passes_by_id_size + 1, true);
949   m_name_to_pass_map->traverse <void *, passes_pass_traverse> (NULL);
950 }
951
952 static bool override_gate_status (opt_pass *, tree, bool);
953
954 /* Dump the instantiated name for PASS. IS_ON indicates if PASS
955    is turned on or not.  */
956
957 static void
958 dump_one_pass (opt_pass *pass, int pass_indent)
959 {
960   int indent = 3 * pass_indent;
961   const char *pn;
962   bool is_on, is_really_on;
963
964   is_on = pass->gate (cfun);
965   is_really_on = override_gate_status (pass, current_function_decl, is_on);
966
967   if (pass->static_pass_number <= 0)
968     pn = pass->name;
969   else
970     pn = pass_tab[pass->static_pass_number];
971
972   fprintf (stderr, "%*s%-40s%*s:%s%s\n", indent, " ", pn,
973            (15 - indent < 0 ? 0 : 15 - indent), " ",
974            is_on ? "  ON" : "  OFF",
975            ((!is_on) == (!is_really_on) ? ""
976             : (is_really_on ? " (FORCED_ON)" : " (FORCED_OFF)")));
977 }
978
979 /* Dump pass list PASS with indentation INDENT.  */
980
981 static void
982 dump_pass_list (opt_pass *pass, int indent)
983 {
984   do
985     {
986       dump_one_pass (pass, indent);
987       if (pass->sub)
988         dump_pass_list (pass->sub, indent + 1);
989       pass = pass->next;
990     }
991   while (pass);
992 }
993
994 /* Dump all optimization passes.  */
995
996 void
997 dump_passes (void)
998 {
999   g->get_passes ()->dump_passes ();
1000 }
1001
1002 void
1003 pass_manager::dump_passes () const
1004 {
1005   push_dummy_function (true);
1006   cgraph_node *node = cgraph_node::get_create (current_function_decl);
1007
1008   create_pass_tab ();
1009
1010   dump_pass_list (all_lowering_passes, 1);
1011   dump_pass_list (all_small_ipa_passes, 1);
1012   dump_pass_list (all_regular_ipa_passes, 1);
1013   dump_pass_list (all_late_ipa_passes, 1);
1014   dump_pass_list (all_passes, 1);
1015
1016   node->remove ();
1017   pop_dummy_function ();
1018 }
1019
1020 /* Returns the pass with NAME.  */
1021
1022 opt_pass *
1023 pass_manager::get_pass_by_name (const char *name)
1024 {
1025   opt_pass **p = m_name_to_pass_map->get (name);
1026   if (p)
1027     return *p;
1028
1029   return NULL;
1030 }
1031
1032
1033 /* Range [start, last].  */
1034
1035 struct uid_range
1036 {
1037   unsigned int start;
1038   unsigned int last;
1039   const char *assem_name;
1040   struct uid_range *next;
1041 };
1042
1043 typedef struct uid_range *uid_range_p;
1044
1045
1046 static vec<uid_range_p> enabled_pass_uid_range_tab;
1047 static vec<uid_range_p> disabled_pass_uid_range_tab;
1048
1049
1050 /* Parse option string for -fdisable- and -fenable-
1051    The syntax of the options:
1052
1053    -fenable-<pass_name>
1054    -fdisable-<pass_name>
1055
1056    -fenable-<pass_name>=s1:e1,s2:e2,...
1057    -fdisable-<pass_name>=s1:e1,s2:e2,...
1058 */
1059
1060 static void
1061 enable_disable_pass (const char *arg, bool is_enable)
1062 {
1063   opt_pass *pass;
1064   char *range_str, *phase_name;
1065   char *argstr = xstrdup (arg);
1066   vec<uid_range_p> *tab = 0;
1067
1068   range_str = strchr (argstr,'=');
1069   if (range_str)
1070     {
1071       *range_str = '\0';
1072       range_str++;
1073     }
1074
1075   phase_name = argstr;
1076   if (!*phase_name)
1077     {
1078       if (is_enable)
1079         error ("unrecognized option %<-fenable%>");
1080       else
1081         error ("unrecognized option %<-fdisable%>");
1082       free (argstr);
1083       return;
1084     }
1085   pass = g->get_passes ()->get_pass_by_name (phase_name);
1086   if (!pass || pass->static_pass_number == -1)
1087     {
1088       if (is_enable)
1089         error ("unknown pass %s specified in %<-fenable%>", phase_name);
1090       else
1091         error ("unknown pass %s specified in %<-fdisable%>", phase_name);
1092       free (argstr);
1093       return;
1094     }
1095
1096   if (is_enable)
1097     tab = &enabled_pass_uid_range_tab;
1098   else
1099     tab = &disabled_pass_uid_range_tab;
1100
1101   if ((unsigned) pass->static_pass_number >= tab->length ())
1102     tab->safe_grow_cleared (pass->static_pass_number + 1, true);
1103
1104   if (!range_str)
1105     {
1106       uid_range_p slot;
1107       uid_range_p new_range = XCNEW (struct uid_range);
1108
1109       new_range->start = 0;
1110       new_range->last = (unsigned)-1;
1111
1112       slot = (*tab)[pass->static_pass_number];
1113       new_range->next = slot;
1114       (*tab)[pass->static_pass_number] = new_range;
1115       if (is_enable)
1116         inform (UNKNOWN_LOCATION, "enable pass %s for functions in the range "
1117                 "of [%u, %u]", phase_name, new_range->start, new_range->last);
1118       else
1119         inform (UNKNOWN_LOCATION, "disable pass %s for functions in the range "
1120                 "of [%u, %u]", phase_name, new_range->start, new_range->last);
1121     }
1122   else
1123     {
1124       char *next_range = NULL;
1125       char *one_range = range_str;
1126       char *end_val = NULL;
1127
1128       do
1129         {
1130           uid_range_p slot;
1131           uid_range_p new_range;
1132           char *invalid = NULL;
1133           long start;
1134           char *func_name = NULL;
1135
1136           next_range = strchr (one_range, ',');
1137           if (next_range)
1138             {
1139               *next_range = '\0';
1140               next_range++;
1141             }
1142
1143           end_val = strchr (one_range, ':');
1144           if (end_val)
1145             {
1146               *end_val = '\0';
1147               end_val++;
1148             }
1149           start = strtol (one_range, &invalid, 10);
1150           if (*invalid || start < 0)
1151             {
1152               if (end_val || (one_range[0] >= '0'
1153                               && one_range[0] <= '9'))
1154                 {
1155                   error ("Invalid range %s in option %s",
1156                          one_range,
1157                          is_enable ? "-fenable" : "-fdisable");
1158                   free (argstr);
1159                   return;
1160                 }
1161               func_name = one_range;
1162             }
1163           if (!end_val)
1164             {
1165               new_range = XCNEW (struct uid_range);
1166               if (!func_name)
1167                 {
1168                   new_range->start = (unsigned) start;
1169                   new_range->last = (unsigned) start;
1170                 }
1171               else
1172                 {
1173                   new_range->start = (unsigned) -1;
1174                   new_range->last = (unsigned) -1;
1175                   new_range->assem_name = xstrdup (func_name);
1176                 }
1177             }
1178           else
1179             {
1180               long last = strtol (end_val, &invalid, 10);
1181               if (*invalid || last < start)
1182                 {
1183                   error ("Invalid range %s in option %s",
1184                          end_val,
1185                          is_enable ? "-fenable" : "-fdisable");
1186                   free (argstr);
1187                   return;
1188                 }
1189               new_range = XCNEW (struct uid_range);
1190               new_range->start = (unsigned) start;
1191               new_range->last = (unsigned) last;
1192             }
1193
1194           slot = (*tab)[pass->static_pass_number];
1195           new_range->next = slot;
1196           (*tab)[pass->static_pass_number] = new_range;
1197           if (is_enable)
1198             {
1199               if (new_range->assem_name)
1200                 inform (UNKNOWN_LOCATION,
1201                         "enable pass %s for function %s",
1202                         phase_name, new_range->assem_name);
1203               else
1204                 inform (UNKNOWN_LOCATION,
1205                         "enable pass %s for functions in the range of [%u, %u]",
1206                         phase_name, new_range->start, new_range->last);
1207             }
1208           else
1209             {
1210               if (new_range->assem_name)
1211                 inform (UNKNOWN_LOCATION,
1212                         "disable pass %s for function %s",
1213                         phase_name, new_range->assem_name);
1214               else
1215                 inform (UNKNOWN_LOCATION,
1216                         "disable pass %s for functions in the range of [%u, %u]",
1217                         phase_name, new_range->start, new_range->last);
1218             }
1219
1220           one_range = next_range;
1221         } while (next_range);
1222     }
1223
1224   free (argstr);
1225 }
1226
1227 /* Enable pass specified by ARG.  */
1228
1229 void
1230 enable_pass (const char *arg)
1231 {
1232   enable_disable_pass (arg, true);
1233 }
1234
1235 /* Disable pass specified by ARG.  */
1236
1237 void
1238 disable_pass (const char *arg)
1239 {
1240   enable_disable_pass (arg, false);
1241 }
1242
1243 /* Returns true if PASS is explicitly enabled/disabled for FUNC.  */
1244
1245 static bool
1246 is_pass_explicitly_enabled_or_disabled (opt_pass *pass,
1247                                         tree func,
1248                                         vec<uid_range_p> tab)
1249 {
1250   uid_range_p slot, range;
1251   int cgraph_uid;
1252   const char *aname = NULL;
1253
1254   if (!tab.exists ()
1255       || (unsigned) pass->static_pass_number >= tab.length ()
1256       || pass->static_pass_number == -1)
1257     return false;
1258
1259   slot = tab[pass->static_pass_number];
1260   if (!slot)
1261     return false;
1262
1263   cgraph_uid = func ? cgraph_node::get (func)->get_uid () : 0;
1264   if (func && DECL_ASSEMBLER_NAME_SET_P (func))
1265     aname = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (func));
1266
1267   range = slot;
1268   while (range)
1269     {
1270       if ((unsigned) cgraph_uid >= range->start
1271           && (unsigned) cgraph_uid <= range->last)
1272         return true;
1273       if (range->assem_name && aname
1274           && !strcmp (range->assem_name, aname))
1275         return true;
1276       range = range->next;
1277     }
1278
1279   return false;
1280 }
1281
1282
1283 /* Update static_pass_number for passes (and the flag
1284    TODO_mark_first_instance).
1285
1286    Passes are constructed with static_pass_number preinitialized to 0
1287
1288    This field is used in two different ways: initially as instance numbers
1289    of their kind, and then as ids within the entire pass manager.
1290
1291    Within pass_manager::pass_manager:
1292
1293    * In add_pass_instance(), as called by next_pass_1 in
1294      NEXT_PASS in init_optimization_passes
1295
1296    * When the initial instance of a pass within a pass manager is seen,
1297      it is flagged, and its static_pass_number is set to -1
1298
1299    * On subsequent times that it is seen, the static pass number
1300      is decremented each time, so that if there are e.g. 4 dups,
1301      they have static_pass_number -4, 2, 3, 4 respectively (note
1302      how the initial one is negative and gives the count); these
1303      can be thought of as instance numbers of the specific pass
1304
1305    * Within the register_dump_files () traversal, set_pass_for_id()
1306      is called on each pass, using these instance numbers to create
1307      dumpfile switches, and then overwriting them with a pass id,
1308      which are global to the whole pass manager (based on
1309      (TDI_end + current value of extra_dump_files_in_use) )  */
1310
1311 static void
1312 add_pass_instance (opt_pass *new_pass, bool track_duplicates,
1313                    opt_pass *initial_pass)
1314 {
1315   /* Are we dealing with the first pass of its kind, or a clone?  */
1316   if (new_pass != initial_pass)
1317     {
1318       /* We're dealing with a clone.  */
1319       new_pass->todo_flags_start &= ~TODO_mark_first_instance;
1320
1321       /* Indicate to register_dump_files that this pass has duplicates,
1322          and so it should rename the dump file.  The first instance will
1323          be -1, and be number of duplicates = -static_pass_number - 1.
1324          Subsequent instances will be > 0 and just the duplicate number.  */
1325       if ((new_pass->name && new_pass->name[0] != '*') || track_duplicates)
1326         {
1327           initial_pass->static_pass_number -= 1;
1328           new_pass->static_pass_number = -initial_pass->static_pass_number;
1329         }
1330     }
1331   else
1332     {
1333       /* We're dealing with the first pass of its kind.  */
1334       new_pass->todo_flags_start |= TODO_mark_first_instance;
1335       new_pass->static_pass_number = -1;
1336
1337       invoke_plugin_callbacks (PLUGIN_NEW_PASS, new_pass);
1338     }
1339 }
1340
1341 /* Add a pass to the pass list. Duplicate the pass if it's already
1342    in the list.  */
1343
1344 static opt_pass **
1345 next_pass_1 (opt_pass **list, opt_pass *pass, opt_pass *initial_pass)
1346 {
1347   /* Every pass should have a name so that plugins can refer to them.  */
1348   gcc_assert (pass->name != NULL);
1349
1350   add_pass_instance (pass, false, initial_pass);
1351   *list = pass;
1352
1353   return &(*list)->next;
1354 }
1355
1356 /* List node for an inserted pass instance. We need to keep track of all
1357    the newly-added pass instances (with 'added_pass_nodes' defined below)
1358    so that we can register their dump files after pass-positioning is finished.
1359    Registering dumping files needs to be post-processed or the
1360    static_pass_number of the opt_pass object would be modified and mess up
1361    the dump file names of future pass instances to be added.  */
1362
1363 struct pass_list_node
1364 {
1365   opt_pass *pass;
1366   struct pass_list_node *next;
1367 };
1368
1369 static struct pass_list_node *added_pass_nodes = NULL;
1370 static struct pass_list_node *prev_added_pass_node;
1371
1372 /* Insert the pass at the proper position. Return true if the pass
1373    is successfully added.
1374
1375    NEW_PASS_INFO - new pass to be inserted
1376    PASS_LIST - root of the pass list to insert the new pass to  */
1377
1378 static bool
1379 position_pass (struct register_pass_info *new_pass_info, opt_pass **pass_list)
1380 {
1381   opt_pass *pass = *pass_list, *prev_pass = NULL;
1382   bool success = false;
1383
1384   for ( ; pass; prev_pass = pass, pass = pass->next)
1385     {
1386       /* Check if the current pass is of the same type as the new pass and
1387          matches the name and the instance number of the reference pass.  */
1388       if (pass->type == new_pass_info->pass->type
1389           && pass->name
1390           && !strcmp (pass->name, new_pass_info->reference_pass_name)
1391           && ((new_pass_info->ref_pass_instance_number == 0)
1392               || (new_pass_info->ref_pass_instance_number ==
1393                   pass->static_pass_number)
1394               || (new_pass_info->ref_pass_instance_number == 1
1395                   && pass->todo_flags_start & TODO_mark_first_instance)))
1396         {
1397           opt_pass *new_pass;
1398           struct pass_list_node *new_pass_node;
1399
1400           if (new_pass_info->ref_pass_instance_number == 0)
1401             {
1402               new_pass = new_pass_info->pass->clone ();
1403               add_pass_instance (new_pass, true, new_pass_info->pass);
1404             }
1405           else
1406             {
1407               new_pass = new_pass_info->pass;
1408               add_pass_instance (new_pass, true, new_pass);
1409             }
1410
1411           /* Insert the new pass instance based on the positioning op.  */
1412           switch (new_pass_info->pos_op)
1413             {
1414               case PASS_POS_INSERT_AFTER:
1415                 new_pass->next = pass->next;
1416                 pass->next = new_pass;
1417
1418                 /* Skip newly inserted pass to avoid repeated
1419                    insertions in the case where the new pass and the
1420                    existing one have the same name.  */
1421                 pass = new_pass;
1422                 break;
1423               case PASS_POS_INSERT_BEFORE:
1424                 new_pass->next = pass;
1425                 if (prev_pass)
1426                   prev_pass->next = new_pass;
1427                 else
1428                   *pass_list = new_pass;
1429                 break;
1430               case PASS_POS_REPLACE:
1431                 new_pass->next = pass->next;
1432                 if (prev_pass)
1433                   prev_pass->next = new_pass;
1434                 else
1435                   *pass_list = new_pass;
1436                 new_pass->sub = pass->sub;
1437                 new_pass->tv_id = pass->tv_id;
1438                 pass = new_pass;
1439                 break;
1440               default:
1441                 error ("invalid pass positioning operation");
1442                 return false;
1443             }
1444
1445           /* Save the newly added pass (instance) in the added_pass_nodes
1446              list so that we can register its dump file later. Note that
1447              we cannot register the dump file now because doing so will modify
1448              the static_pass_number of the opt_pass object and therefore
1449              mess up the dump file name of future instances.  */
1450           new_pass_node = XCNEW (struct pass_list_node);
1451           new_pass_node->pass = new_pass;
1452           if (!added_pass_nodes)
1453             added_pass_nodes = new_pass_node;
1454           else
1455             prev_added_pass_node->next = new_pass_node;
1456           prev_added_pass_node = new_pass_node;
1457
1458           success = true;
1459         }
1460
1461       if (pass->sub && position_pass (new_pass_info, &pass->sub))
1462         success = true;
1463     }
1464
1465   return success;
1466 }
1467
1468 /* Hooks a new pass into the pass lists.
1469
1470    PASS_INFO   - pass information that specifies the opt_pass object,
1471                  reference pass, instance number, and how to position
1472                  the pass  */
1473
1474 void
1475 register_pass (struct register_pass_info *pass_info)
1476 {
1477   g->get_passes ()->register_pass (pass_info);
1478 }
1479
1480 void
1481 register_pass (opt_pass* pass, pass_positioning_ops pos,
1482                const char* ref_pass_name, int ref_pass_inst_number)
1483 {
1484   register_pass_info i;
1485   i.pass = pass;
1486   i.reference_pass_name = ref_pass_name;
1487   i.ref_pass_instance_number = ref_pass_inst_number;
1488   i.pos_op = pos;
1489
1490   g->get_passes ()->register_pass (&i);
1491 }
1492
1493 void
1494 pass_manager::register_pass (struct register_pass_info *pass_info)
1495 {
1496   bool all_instances, success;
1497
1498   /* The checks below could fail in buggy plugins.  Existing GCC
1499      passes should never fail these checks, so we mention plugin in
1500      the messages.  */
1501   if (!pass_info->pass)
1502       fatal_error (input_location, "plugin cannot register a missing pass");
1503
1504   if (!pass_info->pass->name)
1505       fatal_error (input_location, "plugin cannot register an unnamed pass");
1506
1507   if (!pass_info->reference_pass_name)
1508       fatal_error
1509         (input_location,
1510          "plugin cannot register pass %qs without reference pass name",
1511          pass_info->pass->name);
1512
1513   /* Try to insert the new pass to the pass lists.  We need to check
1514      all five lists as the reference pass could be in one (or all) of
1515      them.  */
1516   all_instances = pass_info->ref_pass_instance_number == 0;
1517   success = position_pass (pass_info, &all_lowering_passes);
1518   if (!success || all_instances)
1519     success |= position_pass (pass_info, &all_small_ipa_passes);
1520   if (!success || all_instances)
1521     success |= position_pass (pass_info, &all_regular_ipa_passes);
1522   if (!success || all_instances)
1523     success |= position_pass (pass_info, &all_late_ipa_passes);
1524   if (!success || all_instances)
1525     success |= position_pass (pass_info, &all_passes);
1526   if (!success)
1527     fatal_error
1528       (input_location,
1529        "pass %qs not found but is referenced by new pass %qs",
1530        pass_info->reference_pass_name, pass_info->pass->name);
1531
1532   /* OK, we have successfully inserted the new pass. We need to register
1533      the dump files for the newly added pass and its duplicates (if any).
1534      While doing so, we also delete the pass_list_node
1535      objects created during pass positioning.  */
1536   gcc::dump_manager *dumps = m_ctxt->get_dumps ();
1537   while (added_pass_nodes)
1538     {
1539       struct pass_list_node *next_node = added_pass_nodes->next;
1540
1541       /* Handle -fdump-* and -fopt-info.  */
1542       dumps->register_pass (added_pass_nodes->pass);
1543
1544       XDELETE (added_pass_nodes);
1545       added_pass_nodes = next_node;
1546     }
1547 }
1548
1549 /* Construct the pass tree.  The sequencing of passes is driven by
1550    the cgraph routines:
1551
1552    finalize_compilation_unit ()
1553        for each node N in the cgraph
1554            cgraph_analyze_function (N)
1555                cgraph_lower_function (N) -> all_lowering_passes
1556
1557    If we are optimizing, compile is then invoked:
1558
1559    compile ()
1560        ipa_passes ()                    -> all_small_ipa_passes
1561                                         -> Analysis of all_regular_ipa_passes
1562         * possible LTO streaming at compilation time *
1563                                         -> Execution of all_regular_ipa_passes
1564         * possible LTO streaming at link time *
1565                                         -> all_late_ipa_passes
1566        expand_all_functions ()
1567            for each node N in the cgraph
1568                expand_function (N)      -> Transformation of all_regular_ipa_passes
1569                                         -> all_passes
1570 */
1571
1572 pass_manager::pass_manager (context *ctxt)
1573 : all_passes (NULL), all_small_ipa_passes (NULL), all_lowering_passes (NULL),
1574   all_regular_ipa_passes (NULL),
1575   all_late_ipa_passes (NULL), passes_by_id (NULL), passes_by_id_size (0),
1576   m_ctxt (ctxt), m_name_to_pass_map (NULL)
1577 {
1578   opt_pass **p;
1579
1580   /* Zero-initialize pass members.  */
1581 #define INSERT_PASSES_AFTER(PASS)
1582 #define PUSH_INSERT_PASSES_WITHIN(PASS)
1583 #define POP_INSERT_PASSES()
1584 #define NEXT_PASS(PASS, NUM) PASS ## _ ## NUM = NULL
1585 #define NEXT_PASS_WITH_ARG(PASS, NUM, ARG) NEXT_PASS (PASS, NUM)
1586 #define TERMINATE_PASS_LIST(PASS)
1587 #include "pass-instances.def"
1588 #undef INSERT_PASSES_AFTER
1589 #undef PUSH_INSERT_PASSES_WITHIN
1590 #undef POP_INSERT_PASSES
1591 #undef NEXT_PASS
1592 #undef NEXT_PASS_WITH_ARG
1593 #undef TERMINATE_PASS_LIST
1594
1595   /* Initialize the pass_lists array.  */
1596 #define DEF_PASS_LIST(LIST) pass_lists[PASS_LIST_NO_##LIST] = &LIST;
1597   GCC_PASS_LISTS
1598 #undef DEF_PASS_LIST
1599
1600   /* Build the tree of passes.  */
1601
1602 #define INSERT_PASSES_AFTER(PASS)               \
1603   {                                             \
1604     opt_pass **p_start;                         \
1605     p_start = p = &(PASS);
1606
1607 #define TERMINATE_PASS_LIST(PASS)               \
1608     gcc_assert (p_start == &PASS);              \
1609     *p = NULL;                                  \
1610   }
1611
1612 #define PUSH_INSERT_PASSES_WITHIN(PASS) \
1613   { \
1614     opt_pass **p = &(PASS ## _1)->sub;
1615
1616 #define POP_INSERT_PASSES() \
1617   }
1618
1619 #define NEXT_PASS(PASS, NUM) \
1620   do { \
1621     gcc_assert (PASS ## _ ## NUM == NULL); \
1622     if ((NUM) == 1)                              \
1623       PASS ## _1 = make_##PASS (m_ctxt);          \
1624     else                                         \
1625       {                                          \
1626         gcc_assert (PASS ## _1);                 \
1627         PASS ## _ ## NUM = PASS ## _1->clone (); \
1628       }                                          \
1629     p = next_pass_1 (p, PASS ## _ ## NUM, PASS ## _1);  \
1630   } while (0)
1631
1632 #define NEXT_PASS_WITH_ARG(PASS, NUM, ARG)              \
1633     do {                                                \
1634       NEXT_PASS (PASS, NUM);                            \
1635       PASS ## _ ## NUM->set_pass_param (0, ARG);        \
1636     } while (0)
1637
1638 #include "pass-instances.def"
1639
1640 #undef INSERT_PASSES_AFTER
1641 #undef PUSH_INSERT_PASSES_WITHIN
1642 #undef POP_INSERT_PASSES
1643 #undef NEXT_PASS
1644 #undef NEXT_PASS_WITH_ARG
1645 #undef TERMINATE_PASS_LIST
1646
1647   /* Register the passes with the tree dump code.  */
1648   register_dump_files (all_lowering_passes);
1649   register_dump_files (all_small_ipa_passes);
1650   register_dump_files (all_regular_ipa_passes);
1651   register_dump_files (all_late_ipa_passes);
1652   register_dump_files (all_passes);
1653 }
1654
1655 static void
1656 delete_pass_tree (opt_pass *pass)
1657 {
1658   while (pass)
1659     {
1660       /* Recurse into child passes.  */
1661       delete_pass_tree (pass->sub);
1662
1663       opt_pass *next = pass->next;
1664
1665       /* Delete this pass.  */
1666       delete pass;
1667
1668       /* Iterate onto sibling passes.  */
1669       pass = next;
1670     }
1671 }
1672
1673 pass_manager::~pass_manager ()
1674 {
1675   XDELETEVEC (passes_by_id);
1676
1677   /* Call delete_pass_tree on each of the pass_lists.  */
1678 #define DEF_PASS_LIST(LIST) \
1679     delete_pass_tree (*pass_lists[PASS_LIST_NO_##LIST]);
1680   GCC_PASS_LISTS
1681 #undef DEF_PASS_LIST
1682
1683   delete m_name_to_pass_map;
1684 }
1685
1686 /* If we are in IPA mode (i.e., current_function_decl is NULL), call
1687    function CALLBACK for every function in the call graph.  Otherwise,
1688    call CALLBACK on the current function.  */
1689
1690 static void
1691 do_per_function (void (*callback) (function *, void *data), void *data)
1692 {
1693   if (current_function_decl)
1694     callback (cfun, data);
1695   else
1696     {
1697       struct cgraph_node *node;
1698       FOR_EACH_DEFINED_FUNCTION (node)
1699         if (node->analyzed && (gimple_has_body_p (node->decl) && !in_lto_p)
1700             && (!node->clone_of || node->decl != node->clone_of->decl))
1701           callback (DECL_STRUCT_FUNCTION (node->decl), data);
1702     }
1703 }
1704
1705 /* Hook called when NODE is removed and therefore should be
1706    excluded from order vector.  DATA is a hash set with removed nodes.  */
1707
1708 static void
1709 remove_cgraph_node_from_order (cgraph_node *node, void *data)
1710 {
1711   hash_set<cgraph_node *> *removed_nodes = (hash_set<cgraph_node *> *)data;
1712   removed_nodes->add (node);
1713 }
1714
1715 /* Hook called when NODE is insert and therefore should be
1716    excluded from removed_nodes.  DATA is a hash set with removed nodes.  */
1717
1718 static void
1719 insert_cgraph_node_to_order (cgraph_node *node, void *data)
1720 {
1721   hash_set<cgraph_node *> *removed_nodes = (hash_set<cgraph_node *> *)data;
1722   removed_nodes->remove (node);
1723 }
1724
1725 /* Hook called when NODE is duplicated and therefore should be
1726    excluded from removed_nodes.  DATA is a hash set with removed nodes.  */
1727
1728 static void
1729 duplicate_cgraph_node_to_order (cgraph_node *node, cgraph_node *node2,
1730                                 void *data)
1731 {
1732   hash_set<cgraph_node *> *removed_nodes = (hash_set<cgraph_node *> *)data;
1733   gcc_checking_assert (!removed_nodes->contains (node));
1734   removed_nodes->remove (node2);
1735 }
1736
1737
1738 /* If we are in IPA mode (i.e., current_function_decl is NULL), call
1739    function CALLBACK for every function in the call graph.  Otherwise,
1740    call CALLBACK on the current function.
1741    This function is global so that plugins can use it.  */
1742 void
1743 do_per_function_toporder (void (*callback) (function *, void *data), void *data)
1744 {
1745   int i;
1746
1747   if (current_function_decl)
1748     callback (cfun, data);
1749   else
1750     {
1751       hash_set<cgraph_node *> removed_nodes;
1752       unsigned nnodes = symtab->cgraph_count;
1753       cgraph_node **order = XNEWVEC (cgraph_node *, nnodes);
1754
1755       nnodes = ipa_reverse_postorder (order);
1756       for (i = nnodes - 1; i >= 0; i--)
1757         order[i]->process = 1;
1758       cgraph_node_hook_list *removal_hook
1759         = symtab->add_cgraph_removal_hook (remove_cgraph_node_from_order,
1760                                            &removed_nodes);
1761       cgraph_node_hook_list *insertion_hook
1762         = symtab->add_cgraph_insertion_hook (insert_cgraph_node_to_order,
1763                                              &removed_nodes);
1764       cgraph_2node_hook_list *duplication_hook
1765         = symtab->add_cgraph_duplication_hook (duplicate_cgraph_node_to_order,
1766                                                &removed_nodes);
1767       for (i = nnodes - 1; i >= 0; i--)
1768         {
1769           cgraph_node *node = order[i];
1770
1771           /* Function could be inlined and removed as unreachable.  */
1772           if (node == NULL || removed_nodes.contains (node))
1773             continue;
1774
1775           node->process = 0;
1776           if (node->has_gimple_body_p ())
1777             {
1778               struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
1779               push_cfun (fn);
1780               callback (fn, data);
1781               pop_cfun ();
1782             }
1783         }
1784       symtab->remove_cgraph_removal_hook (removal_hook);
1785       symtab->remove_cgraph_insertion_hook (insertion_hook);
1786       symtab->remove_cgraph_duplication_hook (duplication_hook);
1787
1788       free (order);
1789     }
1790 }
1791
1792 /* Helper function to perform function body dump.  */
1793
1794 static void
1795 execute_function_dump (function *fn, void *data)
1796 {
1797   opt_pass *pass = (opt_pass *)data;
1798
1799   if (dump_file)
1800     {
1801       push_cfun (fn);
1802
1803       if (fn->curr_properties & PROP_gimple)
1804         dump_function_to_file (fn->decl, dump_file, dump_flags);
1805       else
1806         print_rtl_with_bb (dump_file, get_insns (), dump_flags);
1807
1808       /* Flush the file.  If verification fails, we won't be able to
1809          close the file before aborting.  */
1810       fflush (dump_file);
1811
1812       if ((fn->curr_properties & PROP_cfg)
1813           && (dump_flags & TDF_GRAPH))
1814         {
1815           gcc::dump_manager *dumps = g->get_dumps ();
1816           struct dump_file_info *dfi
1817             = dumps->get_dump_file_info (pass->static_pass_number);
1818           if (!dfi->graph_dump_initialized)
1819             {
1820               clean_graph_dump_file (dump_file_name);
1821               dfi->graph_dump_initialized = true;
1822             }
1823           print_graph_cfg (dump_file_name, fn);
1824         }
1825
1826       pop_cfun ();
1827     }
1828 }
1829
1830 /* This function is called when an internal compiler error is encountered.
1831    Ensure that function dump is made available before compiler is aborted.  */
1832
1833 void
1834 emergency_dump_function ()
1835 {
1836   if (!current_pass)
1837     return;
1838   enum opt_pass_type pt = current_pass->type;
1839   fnotice (stderr, "during %s pass: %s\n",
1840            pt == GIMPLE_PASS ? "GIMPLE" : pt == RTL_PASS ? "RTL" : "IPA",
1841            current_pass->name);
1842   if (!dump_file || !cfun)
1843     return;
1844   fnotice (stderr, "dump file: %s\n", dump_file_name);
1845   fprintf (dump_file, "\n\n\nEMERGENCY DUMP:\n\n");
1846   execute_function_dump (cfun, current_pass);
1847
1848   if (symtab && current_pass->type == IPA_PASS)
1849     symtab->dump (dump_file);
1850 }
1851
1852 static struct profile_record *profile_record;
1853
1854 /* Do profile consistency book-keeping for the pass with static number INDEX.
1855    RUN is true if the pass really runs, or FALSE
1856    if we are only book-keeping on passes that may have selectively disabled
1857    themselves on a given function.  */
1858
1859 static void
1860 check_profile_consistency (int index, bool run)
1861 {
1862   pass_manager *passes = g->get_passes ();
1863   if (index == -1)
1864     return;
1865   if (!profile_record)
1866     profile_record = XCNEWVEC (struct profile_record,
1867                                passes->passes_by_id_size);
1868   gcc_assert (index < passes->passes_by_id_size && index >= 0);
1869   profile_record[index].run |= run;
1870   profile_record_check_consistency (&profile_record[index]);
1871 }
1872
1873 /* Account profile the pass with static number INDEX.
1874    RUN is true if the pass really runs, or FALSE
1875    if we are only book-keeping on passes that may have selectively disabled
1876    themselves on a given function.  */
1877
1878 static void
1879 account_profile (int index, bool run)
1880 {
1881   pass_manager *passes = g->get_passes ();
1882   if (index == -1)
1883     return;
1884   if (!profile_record)
1885     profile_record = XCNEWVEC (struct profile_record,
1886                                passes->passes_by_id_size);
1887   gcc_assert (index < passes->passes_by_id_size && index >= 0);
1888   profile_record[index].run |= run;
1889   profile_record_account_profile (&profile_record[index]);
1890 }
1891
1892 /* Account profile for IPA pass.  Callback for do_per_function.  */
1893
1894 static void
1895 account_profile_1 (function *fn, void *data)
1896 {
1897   opt_pass *pass = (opt_pass *)data;
1898
1899   push_cfun (fn);
1900   check_profile_consistency (pass->static_pass_number, true);
1901   account_profile (pass->static_pass_number, true);
1902   pop_cfun ();
1903 }
1904
1905 /* Account profile chnages to all passes in list starting in SUB.  */
1906
1907 static void
1908 account_profile_in_list (opt_pass *sub)
1909 {
1910   for (; sub; sub = sub->next)
1911     {
1912       check_profile_consistency (sub->static_pass_number, false);
1913       account_profile (sub->static_pass_number, false);
1914       if (sub->sub)
1915         account_profile_in_list (sub->sub);
1916     }
1917 }
1918
1919 /* Output profile consistency.  */
1920
1921 void
1922 dump_profile_report (void)
1923 {
1924   g->get_passes ()->dump_profile_report ();
1925 }
1926
1927 void
1928 pass_manager::dump_profile_report () const
1929 {
1930   int last_count_in = 0, last_prob_out = 0;
1931   double last_dyn_count_in = 0, last_dyn_prob_out = 0;
1932   double last_time = 0;
1933   int last_size = 0;
1934   double rel_time_change, rel_size_change;
1935   gcc::dump_manager *dumps = m_ctxt->get_dumps ();
1936
1937   if (!profile_record)
1938     return;
1939
1940   FILE *dump_file = dump_begin (TDI_profile_report, NULL);
1941   if (dump_file == NULL)
1942     dump_file = stderr;
1943
1944   fprintf (dump_file, "Profile consistency report:\n\n");
1945   fprintf (dump_file,
1946            "Pass dump id and name            |static mismatch            "
1947            "|dynamic mismatch                                     "
1948            "|overall                                       |\n");
1949   fprintf (dump_file,
1950            "                                 |in count     |out prob     "
1951            "|in count                  |out prob                  "
1952            "|size               |time                      |\n");
1953
1954   for (int i = 1; i < passes_by_id_size; i++)
1955     if (profile_record[i].run)
1956       {
1957         if (last_time)
1958           rel_time_change = (profile_record[i].time
1959                              - last_time) * 100 / last_time;
1960         else
1961           rel_time_change = 0;
1962         if (last_size)
1963           rel_size_change = (profile_record[i].size
1964                              - (double)last_size) * 100 / (double)last_size;
1965         else
1966           rel_size_change = 0;
1967
1968         dump_file_info *dfi = dumps->get_dump_file_info (i);
1969
1970         fprintf (dump_file, "%3i%c %-28s| %6i",
1971                  dfi->num,
1972                  passes_by_id[i]->type == GIMPLE_PASS ? 't'
1973                  : passes_by_id[i]->type == RTL_PASS ? 'r'
1974                  : 'i',
1975                  passes_by_id[i]->name,
1976                  profile_record[i].num_mismatched_count_in);
1977         if (profile_record[i].num_mismatched_count_in != last_count_in)
1978           fprintf (dump_file, " %+5i",
1979                    profile_record[i].num_mismatched_count_in
1980                    - last_count_in);
1981         else
1982           fprintf (dump_file, "      ");
1983         fprintf (dump_file, "| %6i",
1984                  profile_record[i].num_mismatched_prob_out);
1985         if (profile_record[i].num_mismatched_prob_out != last_prob_out)
1986           fprintf (dump_file, " %+5i",
1987                    profile_record[i].num_mismatched_prob_out
1988                    - last_prob_out);
1989         else
1990           fprintf (dump_file, "      ");
1991
1992         fprintf (dump_file, "| %12.0f",
1993                  profile_record[i].dyn_mismatched_count_in);
1994         if (profile_record[i].dyn_mismatched_count_in != last_dyn_count_in)
1995           fprintf (dump_file, " %+12.0f",
1996                    profile_record[i].dyn_mismatched_count_in
1997                    - last_dyn_count_in);
1998         else
1999           fprintf (dump_file, "             ");
2000         fprintf (dump_file, "| %12.0f",
2001                  profile_record[i].dyn_mismatched_prob_out);
2002         if (profile_record[i].dyn_mismatched_prob_out != last_dyn_prob_out)
2003           fprintf (dump_file, " %+12.0f",
2004                    profile_record[i].dyn_mismatched_prob_out
2005                    - last_dyn_prob_out);
2006         else
2007           fprintf (dump_file, "             ");
2008
2009         /* Size/time units change across gimple and RTL.  */
2010         if (i == pass_expand_1->static_pass_number)
2011           fprintf (dump_file,
2012                    "|-------------------|--------------------------");
2013         else
2014           {
2015             fprintf (dump_file, "| %8i", profile_record[i].size);
2016             if (rel_size_change)
2017               fprintf (dump_file, " %+8.1f%%", rel_size_change);
2018             else
2019               fprintf (dump_file, "          ");
2020             fprintf (dump_file, "| %12.0f", profile_record[i].time);
2021             /* Time units changes with profile estimate and feedback.  */
2022             if (i == pass_profile_1->static_pass_number
2023                 || i == pass_ipa_tree_profile_1->static_pass_number)
2024               fprintf (dump_file, "-------------");
2025             else if (rel_time_change)
2026               fprintf (dump_file, " %+11.1f%%", rel_time_change);
2027             else
2028               fprintf (dump_file, "             ");
2029           }
2030         fprintf (dump_file, "|\n");
2031         last_prob_out = profile_record[i].num_mismatched_prob_out;
2032         last_count_in = profile_record[i].num_mismatched_count_in;
2033         last_dyn_prob_out = profile_record[i].dyn_mismatched_prob_out;
2034         last_dyn_count_in = profile_record[i].dyn_mismatched_count_in;
2035         last_time = profile_record[i].time;
2036         last_size = profile_record[i].size;
2037       }
2038
2039   dump_end (TDI_profile_report, dump_file);
2040 }
2041
2042 /* Perform all TODO actions that ought to be done on each function.  */
2043
2044 static void
2045 execute_function_todo (function *fn, void *data)
2046 {
2047   bool from_ipa_pass = (cfun == NULL);
2048   unsigned int flags = (size_t)data;
2049   flags &= ~fn->last_verified;
2050   if (!flags)
2051     return;
2052
2053   push_cfun (fn);
2054
2055   /* If we need to cleanup the CFG let it perform a needed SSA update.  */
2056   if (flags & TODO_cleanup_cfg)
2057     cleanup_tree_cfg (flags & TODO_update_ssa_any);
2058   else if (flags & TODO_update_ssa_any)
2059     update_ssa (flags & TODO_update_ssa_any);
2060   gcc_assert (!need_ssa_update_p (fn));
2061
2062   if (flag_tree_pta && (flags & TODO_rebuild_alias))
2063     compute_may_aliases ();
2064
2065   if (optimize && (flags & TODO_update_address_taken))
2066     execute_update_addresses_taken ();
2067
2068   if (flags & TODO_remove_unused_locals)
2069     remove_unused_locals ();
2070
2071   if (flags & TODO_rebuild_frequencies)
2072     rebuild_frequencies ();
2073
2074   if (flags & TODO_rebuild_cgraph_edges)
2075     cgraph_edge::rebuild_edges ();
2076
2077   gcc_assert (dom_info_state (fn, CDI_POST_DOMINATORS) == DOM_NONE);
2078   /* If we've seen errors do not bother running any verifiers.  */
2079   if (flag_checking && !seen_error ())
2080     {
2081       dom_state pre_verify_state = dom_info_state (fn, CDI_DOMINATORS);
2082       dom_state pre_verify_pstate = dom_info_state (fn, CDI_POST_DOMINATORS);
2083
2084       if (flags & TODO_verify_il)
2085         {
2086           if (cfun->curr_properties & PROP_gimple)
2087             {
2088               if (cfun->curr_properties & PROP_cfg)
2089                 /* IPA passes leave stmts to be fixed up, so make sure to
2090                    not verify stmts really throw.  */
2091                 verify_gimple_in_cfg (cfun, !from_ipa_pass);
2092               else
2093                 verify_gimple_in_seq (gimple_body (cfun->decl));
2094             }
2095           if (cfun->curr_properties & PROP_ssa)
2096             /* IPA passes leave stmts to be fixed up, so make sure to
2097                not verify SSA operands whose verifier will choke on that.  */
2098             verify_ssa (true, !from_ipa_pass);
2099           /* IPA passes leave basic-blocks unsplit, so make sure to
2100              not trip on that.  */
2101           if ((cfun->curr_properties & PROP_cfg)
2102               && !from_ipa_pass)
2103             verify_flow_info ();
2104           if (current_loops
2105               && ! loops_state_satisfies_p (LOOPS_NEED_FIXUP))
2106             {
2107               verify_loop_structure ();
2108               if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
2109                 verify_loop_closed_ssa (false);
2110             }
2111           if (cfun->curr_properties & PROP_rtl)
2112             verify_rtl_sharing ();
2113         }
2114
2115       /* Make sure verifiers don't change dominator state.  */
2116       gcc_assert (dom_info_state (fn, CDI_DOMINATORS) == pre_verify_state);
2117       gcc_assert (dom_info_state (fn, CDI_POST_DOMINATORS) == pre_verify_pstate);
2118     }
2119
2120   fn->last_verified = flags & TODO_verify_all;
2121
2122   pop_cfun ();
2123
2124   /* For IPA passes make sure to release dominator info, it can be
2125      computed by non-verifying TODOs.  */
2126   if (from_ipa_pass)
2127     {
2128       free_dominance_info (fn, CDI_DOMINATORS);
2129       free_dominance_info (fn, CDI_POST_DOMINATORS);
2130     }
2131 }
2132
2133 /* Perform all TODO actions.  */
2134 static void
2135 execute_todo (unsigned int flags)
2136 {
2137   if (flag_checking
2138       && cfun
2139       && need_ssa_update_p (cfun))
2140     gcc_assert (flags & TODO_update_ssa_any);
2141
2142   statistics_fini_pass ();
2143
2144   if (flags)
2145     do_per_function (execute_function_todo, (void *)(size_t) flags);
2146
2147   /* At this point we should not have any unreachable code in the
2148      CFG, so it is safe to flush the pending freelist for SSA_NAMES.  */
2149   if (cfun && cfun->gimple_df)
2150     flush_ssaname_freelist ();
2151
2152   /* Always remove functions just as before inlining: IPA passes might be
2153      interested to see bodies of extern inline functions that are not inlined
2154      to analyze side effects.  The full removal is done just at the end
2155      of IPA pass queue.  */
2156   if (flags & TODO_remove_functions)
2157     {
2158       gcc_assert (!cfun);
2159       symtab->remove_unreachable_nodes (dump_file);
2160     }
2161
2162   if ((flags & TODO_dump_symtab) && dump_file && !current_function_decl)
2163     {
2164       gcc_assert (!cfun);
2165       symtab->dump (dump_file);
2166       /* Flush the file.  If verification fails, we won't be able to
2167          close the file before aborting.  */
2168       fflush (dump_file);
2169     }
2170
2171   /* Now that the dumping has been done, we can get rid of the optional
2172      df problems.  */
2173   if (flags & TODO_df_finish)
2174     df_finish_pass ((flags & TODO_df_verify) != 0);
2175 }
2176
2177 /* Verify invariants that should hold between passes.  This is a place
2178    to put simple sanity checks.  */
2179
2180 static void
2181 verify_interpass_invariants (void)
2182 {
2183   gcc_checking_assert (!fold_deferring_overflow_warnings_p ());
2184 }
2185
2186 /* Clear the last verified flag.  */
2187
2188 static void
2189 clear_last_verified (function *fn, void *data ATTRIBUTE_UNUSED)
2190 {
2191   fn->last_verified = 0;
2192 }
2193
2194 /* Helper function. Verify that the properties has been turn into the
2195    properties expected by the pass.  */
2196
2197 static void
2198 verify_curr_properties (function *fn, void *data)
2199 {
2200   unsigned int props = (size_t)data;
2201   gcc_assert ((fn->curr_properties & props) == props);
2202 }
2203
2204 /* Release dump file name if set.  */
2205
2206 static void
2207 release_dump_file_name (void)
2208 {
2209   if (dump_file_name)
2210     {
2211       free (CONST_CAST (char *, dump_file_name));
2212       dump_file_name = NULL;
2213     }
2214 }
2215
2216 /* Initialize pass dump file.  */
2217 /* This is non-static so that the plugins can use it.  */
2218
2219 bool
2220 pass_init_dump_file (opt_pass *pass)
2221 {
2222   /* If a dump file name is present, open it if enabled.  */
2223   if (pass->static_pass_number != -1)
2224     {
2225       timevar_push (TV_DUMP);
2226       gcc::dump_manager *dumps = g->get_dumps ();
2227       bool initializing_dump =
2228         !dumps->dump_initialized_p (pass->static_pass_number);
2229       release_dump_file_name ();
2230       dump_file_name = dumps->get_dump_file_name (pass->static_pass_number);
2231       dumps->dump_start (pass->static_pass_number, &dump_flags);
2232       if (dump_file && current_function_decl && ! (dump_flags & TDF_GIMPLE))
2233         dump_function_header (dump_file, current_function_decl, dump_flags);
2234       if (initializing_dump
2235           && dump_file && (dump_flags & TDF_GRAPH)
2236           && cfun && (cfun->curr_properties & PROP_cfg))
2237         {
2238           clean_graph_dump_file (dump_file_name);
2239           struct dump_file_info *dfi
2240             = dumps->get_dump_file_info (pass->static_pass_number);
2241           dfi->graph_dump_initialized = true;
2242         }
2243       timevar_pop (TV_DUMP);
2244       return initializing_dump;
2245     }
2246   else
2247     return false;
2248 }
2249
2250 /* Flush PASS dump file.  */
2251 /* This is non-static so that plugins can use it.  */
2252
2253 void
2254 pass_fini_dump_file (opt_pass *pass)
2255 {
2256   timevar_push (TV_DUMP);
2257
2258   /* Flush and close dump file.  */
2259   release_dump_file_name ();
2260
2261   g->get_dumps ()->dump_finish (pass->static_pass_number);
2262   timevar_pop (TV_DUMP);
2263 }
2264
2265 /* After executing the pass, apply expected changes to the function
2266    properties. */
2267
2268 static void
2269 update_properties_after_pass (function *fn, void *data)
2270 {
2271   opt_pass *pass = (opt_pass *) data;
2272   fn->curr_properties = (fn->curr_properties | pass->properties_provided)
2273                          & ~pass->properties_destroyed;
2274 }
2275
2276 /* Execute summary generation for all of the passes in IPA_PASS.  */
2277
2278 void
2279 execute_ipa_summary_passes (ipa_opt_pass_d *ipa_pass)
2280 {
2281   while (ipa_pass)
2282     {
2283       opt_pass *pass = ipa_pass;
2284
2285       /* Execute all of the IPA_PASSes in the list.  */
2286       if (ipa_pass->type == IPA_PASS
2287           && pass->gate (cfun)
2288           && ipa_pass->generate_summary)
2289         {
2290           pass_init_dump_file (pass);
2291
2292           /* If a timevar is present, start it.  */
2293           if (pass->tv_id)
2294             timevar_push (pass->tv_id);
2295
2296           current_pass = pass;
2297           ipa_pass->generate_summary ();
2298
2299           /* Stop timevar.  */
2300           if (pass->tv_id)
2301             timevar_pop (pass->tv_id);
2302
2303           pass_fini_dump_file (pass);
2304         }
2305       ipa_pass = (ipa_opt_pass_d *)ipa_pass->next;
2306     }
2307 }
2308
2309 /* Execute IPA_PASS function transform on NODE.  */
2310
2311 static void
2312 execute_one_ipa_transform_pass (struct cgraph_node *node,
2313                                 ipa_opt_pass_d *ipa_pass, bool do_not_collect)
2314 {
2315   opt_pass *pass = ipa_pass;
2316   unsigned int todo_after = 0;
2317
2318   current_pass = pass;
2319   if (!ipa_pass->function_transform)
2320     return;
2321
2322   /* Note that the folders should only create gimple expressions.
2323      This is a hack until the new folder is ready.  */
2324   in_gimple_form = (cfun && (cfun->curr_properties & PROP_gimple)) != 0;
2325
2326   pass_init_dump_file (pass);
2327
2328   /* If a timevar is present, start it.  */
2329   if (pass->tv_id != TV_NONE)
2330     timevar_push (pass->tv_id);
2331
2332   /* Run pre-pass verification.  */
2333   execute_todo (ipa_pass->function_transform_todo_flags_start);
2334
2335   /* Do it!  */
2336   todo_after = ipa_pass->function_transform (node);
2337
2338   /* Run post-pass cleanup and verification.  */
2339   execute_todo (todo_after);
2340   verify_interpass_invariants ();
2341
2342   /* Stop timevar.  */
2343   if (pass->tv_id != TV_NONE)
2344     timevar_pop (pass->tv_id);
2345
2346   if (dump_file)
2347     do_per_function (execute_function_dump, pass);
2348   pass_fini_dump_file (pass);
2349
2350   current_pass = NULL;
2351   redirect_edge_var_map_empty ();
2352
2353   /* Signal this is a suitable GC collection point.  */
2354   if (!do_not_collect && !(todo_after & TODO_do_not_ggc_collect))
2355     ggc_collect ();
2356 }
2357
2358 /* For the current function, execute all ipa transforms. */
2359
2360 void
2361 execute_all_ipa_transforms (bool do_not_collect)
2362 {
2363   struct cgraph_node *node;
2364   node = cgraph_node::get (current_function_decl);
2365
2366
2367   cgraph_node *next_clone;
2368   for (cgraph_node *n = node->clones; n; n = next_clone)
2369     {
2370       next_clone = n->next_sibling_clone;
2371       if (n->decl != node->decl)
2372         n->materialize_clone ();
2373     }
2374
2375   int j = 0;
2376   gcc::pass_manager *passes = g->get_passes ();
2377   bool report = profile_report && (cfun->curr_properties & PROP_gimple) != 0;
2378
2379   if (report)
2380     push_cfun (DECL_STRUCT_FUNCTION (node->decl));
2381
2382   for (auto p : node->ipa_transforms_to_apply)
2383     {
2384       /* To get consistent statistics, we need to account each functio
2385          to each IPA pass.  */
2386       if (report)
2387         {
2388           for (;j < p->static_pass_number; j++)
2389             if (passes->get_pass_for_id (j)
2390                 && passes->get_pass_for_id (j)->type == IPA_PASS
2391                 && ((ipa_opt_pass_d *)passes->get_pass_for_id (j))
2392                    ->function_transform)
2393               {
2394                 check_profile_consistency (j, true);
2395                 account_profile (j, true);
2396               }
2397           gcc_checking_assert (passes->get_pass_for_id (j) == p);
2398         }
2399       execute_one_ipa_transform_pass (node, p, do_not_collect);
2400     }
2401   /* Account remaining IPA passes.  */
2402   if (report)
2403     {
2404       for (;!passes->get_pass_for_id (j)
2405             || passes->get_pass_for_id (j)->type != RTL_PASS; j++)
2406         if (passes->get_pass_for_id (j)
2407             && passes->get_pass_for_id (j)->type == IPA_PASS
2408             && ((ipa_opt_pass_d *)passes->get_pass_for_id (j))
2409                ->function_transform)
2410           {
2411             check_profile_consistency (j, true);
2412             account_profile (j, true);
2413           }
2414       pop_cfun ();
2415     }
2416   node->ipa_transforms_to_apply.release ();
2417 }
2418
2419 /* Check if PASS is explicitly disabled or enabled and return
2420    the gate status.  FUNC is the function to be processed, and
2421    GATE_STATUS is the gate status determined by pass manager by
2422    default.  */
2423
2424 static bool
2425 override_gate_status (opt_pass *pass, tree func, bool gate_status)
2426 {
2427   bool explicitly_enabled = false;
2428   bool explicitly_disabled = false;
2429
2430   explicitly_enabled
2431    = is_pass_explicitly_enabled_or_disabled (pass, func,
2432                                              enabled_pass_uid_range_tab);
2433   explicitly_disabled
2434    = is_pass_explicitly_enabled_or_disabled (pass, func,
2435                                              disabled_pass_uid_range_tab);
2436
2437   gate_status = !explicitly_disabled && (gate_status || explicitly_enabled);
2438
2439   return gate_status;
2440 }
2441
2442 /* Determine if PASS_NAME matches CRITERION.
2443    Not a pure predicate, since it can update CRITERION, to support
2444    matching the Nth invocation of a pass.
2445    Subroutine of should_skip_pass_p.  */
2446
2447 static bool
2448 determine_pass_name_match (const char *pass_name, char *criterion)
2449 {
2450   size_t namelen = strlen (pass_name);
2451   if (! strncmp (pass_name, criterion, namelen))
2452     {
2453       /* The following supports starting with the Nth invocation
2454          of a pass (where N does not necessarily is equal to the
2455          dump file suffix).  */
2456       if (criterion[namelen] == '\0'
2457           || (criterion[namelen] == '1'
2458               && criterion[namelen + 1] == '\0'))
2459         return true;
2460       else
2461         {
2462           if (criterion[namelen + 1] == '\0')
2463             --criterion[namelen];
2464           return false;
2465         }
2466     }
2467   else
2468     return false;
2469 }
2470
2471 /* For skipping passes until "startwith" pass.
2472    Return true iff PASS should be skipped.
2473    Clear cfun->pass_startwith when encountering the "startwith" pass,
2474    so that all subsequent passes are run.  */
2475
2476 static bool
2477 should_skip_pass_p (opt_pass *pass)
2478 {
2479   if (!cfun)
2480     return false;
2481   if (!cfun->pass_startwith)
2482     return false;
2483
2484   /* For __GIMPLE functions, we have to at least start when we leave
2485      SSA.  Hence, we need to detect the "expand" pass, and stop skipping
2486      when we encounter it.  A cheap way to identify "expand" is it to
2487      detect the destruction of PROP_ssa.
2488      For __RTL functions, we invoke "rest_of_compilation" directly, which
2489      is after "expand", and hence we don't reach this conditional.  */
2490   if (pass->properties_destroyed & PROP_ssa)
2491     {
2492       if (!quiet_flag)
2493         fprintf (stderr, "starting anyway when leaving SSA: %s\n", pass->name);
2494       cfun->pass_startwith = NULL;
2495       return false;
2496     }
2497
2498   if (determine_pass_name_match (pass->name, cfun->pass_startwith))
2499     {
2500       if (!quiet_flag)
2501         fprintf (stderr, "found starting pass: %s\n", pass->name);
2502       cfun->pass_startwith = NULL;
2503       return false;
2504     }
2505
2506   /* For GIMPLE passes, run any property provider (but continue skipping
2507      afterwards).
2508      We don't want to force running RTL passes that are property providers:
2509      "expand" is covered above, and the only pass other than "expand" that
2510      provides a property is "into_cfglayout" (PROP_cfglayout), which does
2511      too much for a dumped __RTL function.  */
2512   if (pass->type == GIMPLE_PASS
2513       && pass->properties_provided != 0)
2514     return false;
2515
2516   /* We need to (re-)build cgraph edges as needed.  */
2517   if (strstr (pass->name, "build_cgraph_edges") != NULL)
2518     return false;
2519
2520   /* Don't skip df init; later RTL passes need it.  */
2521   if (strstr (pass->name, "dfinit") != NULL
2522       || strstr (pass->name, "dfinish") != NULL)
2523     return false;
2524
2525   if (!quiet_flag)
2526     fprintf (stderr, "skipping pass: %s\n", pass->name);
2527
2528   /* If we get here, then we have a "startwith" that we haven't seen yet;
2529      skip the pass.  */
2530   return true;
2531 }
2532
2533 /* Skip the given pass, for handling passes before "startwith"
2534    in __GIMPLE and__RTL-marked functions.
2535    In theory, this ought to be a no-op, but some of the RTL passes
2536    need additional processing here.  */
2537
2538 static void
2539 skip_pass (opt_pass *pass)
2540 {
2541   /* Pass "reload" sets the global "reload_completed", and many
2542      things depend on this (e.g. instructions in .md files).  */
2543   if (strcmp (pass->name, "reload") == 0)
2544     reload_completed = 1;
2545
2546   /* Similar for pass "pro_and_epilogue" and the "epilogue_completed" global
2547      variable.  */
2548   if (strcmp (pass->name, "pro_and_epilogue") == 0)
2549     epilogue_completed = 1;
2550
2551   /* The INSN_ADDRESSES vec is normally set up by
2552      shorten_branches; set it up for the benefit of passes that
2553      run after this.  */
2554   if (strcmp (pass->name, "shorten") == 0)
2555     INSN_ADDRESSES_ALLOC (get_max_uid ());
2556
2557   /* Update the cfg hooks as appropriate.  */
2558   if (strcmp (pass->name, "into_cfglayout") == 0)
2559     {
2560       cfg_layout_rtl_register_cfg_hooks ();
2561       cfun->curr_properties |= PROP_cfglayout;
2562     }
2563   if (strcmp (pass->name, "outof_cfglayout") == 0)
2564     {
2565       rtl_register_cfg_hooks ();
2566       cfun->curr_properties &= ~PROP_cfglayout;
2567     }
2568 }
2569
2570 /* Execute PASS. */
2571
2572 bool
2573 execute_one_pass (opt_pass *pass)
2574 {
2575   unsigned int todo_after = 0;
2576
2577   bool gate_status;
2578
2579   /* IPA passes are executed on whole program, so cfun should be NULL.
2580      Other passes need function context set.  */
2581   if (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS)
2582     gcc_assert (!cfun && !current_function_decl);
2583   else
2584     gcc_assert (cfun && current_function_decl);
2585
2586   current_pass = pass;
2587
2588   /* Check whether gate check should be avoided.
2589      User controls the value of the gate through the parameter "gate_status". */
2590   gate_status = pass->gate (cfun);
2591   gate_status = override_gate_status (pass, current_function_decl, gate_status);
2592
2593   /* Override gate with plugin.  */
2594   invoke_plugin_callbacks (PLUGIN_OVERRIDE_GATE, &gate_status);
2595
2596   if (!gate_status)
2597     {
2598       /* Run so passes selectively disabling themselves on a given function
2599          are not miscounted.  */
2600       if (profile_report && cfun && (cfun->curr_properties & PROP_cfg)
2601           && pass->type != IPA_PASS && pass->type != SIMPLE_IPA_PASS)
2602         {
2603           check_profile_consistency (pass->static_pass_number, false);
2604           account_profile (pass->static_pass_number, false);
2605           if (pass->sub)
2606             account_profile_in_list (pass->sub);
2607         }
2608       current_pass = NULL;
2609       return false;
2610     }
2611
2612   if (should_skip_pass_p (pass))
2613     {
2614       skip_pass (pass);
2615       return true;
2616     }
2617
2618   /* Pass execution event trigger: useful to identify passes being
2619      executed.  */
2620   invoke_plugin_callbacks (PLUGIN_PASS_EXECUTION, pass);
2621
2622   if (!quiet_flag && !cfun)
2623     fprintf (stderr, " <%s>", pass->name ? pass->name : "");
2624
2625   /* Note that the folders should only create gimple expressions.
2626      This is a hack until the new folder is ready.  */
2627   in_gimple_form = (cfun && (cfun->curr_properties & PROP_gimple)) != 0;
2628
2629   pass_init_dump_file (pass);
2630
2631   /* If a timevar is present, start it.  */
2632   if (pass->tv_id != TV_NONE)
2633     timevar_push (pass->tv_id);
2634
2635
2636   /* Run pre-pass verification.  */
2637   execute_todo (pass->todo_flags_start);
2638
2639   if (flag_checking)
2640     do_per_function (verify_curr_properties,
2641                      (void *)(size_t)pass->properties_required);
2642
2643   /* Do it!  */
2644   todo_after = pass->execute (cfun);
2645
2646   if (todo_after & TODO_discard_function)
2647     {
2648       /* Stop timevar.  */
2649       if (pass->tv_id != TV_NONE)
2650         timevar_pop (pass->tv_id);
2651
2652       pass_fini_dump_file (pass);
2653
2654       gcc_assert (cfun);
2655       /* As cgraph_node::release_body expects release dominators info,
2656          we have to release it.  */
2657       if (dom_info_available_p (CDI_DOMINATORS))
2658        free_dominance_info (CDI_DOMINATORS);
2659
2660       if (dom_info_available_p (CDI_POST_DOMINATORS))
2661        free_dominance_info (CDI_POST_DOMINATORS);
2662
2663       if (cfun->assume_function)
2664         {
2665           /* For assume functions, don't release body, keep it around.  */
2666           cfun->curr_properties |= PROP_assumptions_done;
2667           pop_cfun ();
2668           current_pass = NULL;
2669           return true;
2670         }
2671
2672       tree fn = cfun->decl;
2673       pop_cfun ();
2674       gcc_assert (!cfun);
2675       cgraph_node::get (fn)->release_body ();
2676
2677       current_pass = NULL;
2678       redirect_edge_var_map_empty ();
2679
2680       ggc_collect ();
2681
2682       return true;
2683     }
2684
2685   do_per_function (clear_last_verified, NULL);
2686
2687   do_per_function (update_properties_after_pass, pass);
2688
2689   /* Run post-pass cleanup and verification.  */
2690   execute_todo (todo_after | pass->todo_flags_finish | TODO_verify_il);
2691   if (profile_report)
2692     {
2693       /* IPA passes are accounted at transform time.  */
2694       if (pass->type == IPA_PASS)
2695         ;
2696       else if (pass->type == SIMPLE_IPA_PASS)
2697         do_per_function (account_profile_1, pass);
2698       else if (cfun && (cfun->curr_properties & PROP_cfg))
2699         {
2700           check_profile_consistency (pass->static_pass_number, true);
2701           account_profile (pass->static_pass_number, true);
2702         }
2703     }
2704
2705   verify_interpass_invariants ();
2706
2707   /* Stop timevar.  */
2708   if (pass->tv_id != TV_NONE)
2709     timevar_pop (pass->tv_id);
2710
2711   if (pass->type == IPA_PASS
2712       && ((ipa_opt_pass_d *)pass)->function_transform)
2713     {
2714       struct cgraph_node *node;
2715       FOR_EACH_FUNCTION_WITH_GIMPLE_BODY (node)
2716         if (!node->inlined_to)
2717           node->ipa_transforms_to_apply.safe_push ((ipa_opt_pass_d *)pass);
2718     }
2719   else if (dump_file)
2720     do_per_function (execute_function_dump, pass);
2721
2722   if (!current_function_decl)
2723     symtab->process_new_functions ();
2724
2725   pass_fini_dump_file (pass);
2726
2727   if (pass->type != SIMPLE_IPA_PASS && pass->type != IPA_PASS)
2728     gcc_assert (!(cfun->curr_properties & PROP_gimple)
2729                 || pass->type != RTL_PASS);
2730
2731   current_pass = NULL;
2732   redirect_edge_var_map_empty ();
2733
2734   /* Signal this is a suitable GC collection point.  */
2735   if (!((todo_after | pass->todo_flags_finish) & TODO_do_not_ggc_collect))
2736     ggc_collect ();
2737
2738   if (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS)
2739     report_heap_memory_use ();
2740   return true;
2741 }
2742
2743 static void
2744 execute_pass_list_1 (opt_pass *pass)
2745 {
2746   do
2747     {
2748       gcc_assert (pass->type == GIMPLE_PASS
2749                   || pass->type == RTL_PASS);
2750
2751       if (cfun == NULL)
2752         return;
2753       if (execute_one_pass (pass) && pass->sub)
2754         execute_pass_list_1 (pass->sub);
2755       pass = pass->next;
2756     }
2757   while (pass);
2758 }
2759
2760 void
2761 execute_pass_list (function *fn, opt_pass *pass)
2762 {
2763   gcc_assert (fn == cfun);
2764   execute_pass_list_1 (pass);
2765   if (cfun && fn->cfg)
2766     {
2767       free_dominance_info (CDI_DOMINATORS);
2768       free_dominance_info (CDI_POST_DOMINATORS);
2769     }
2770 }
2771
2772 /* Write out all LTO data.  */
2773 static void
2774 write_lto (void)
2775 {
2776   timevar_push (TV_IPA_LTO_GIMPLE_OUT);
2777   lto_output ();
2778   timevar_pop (TV_IPA_LTO_GIMPLE_OUT);
2779   timevar_push (TV_IPA_LTO_DECL_OUT);
2780   produce_asm_for_decls ();
2781   timevar_pop (TV_IPA_LTO_DECL_OUT);
2782 }
2783
2784 /* Same as execute_pass_list but assume that subpasses of IPA passes
2785    are local passes. If SET is not NULL, write out summaries of only
2786    those node in SET. */
2787
2788 static void
2789 ipa_write_summaries_2 (opt_pass *pass, struct lto_out_decl_state *state)
2790 {
2791   while (pass)
2792     {
2793       ipa_opt_pass_d *ipa_pass = (ipa_opt_pass_d *)pass;
2794       gcc_assert (!current_function_decl);
2795       gcc_assert (!cfun);
2796       gcc_assert (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS);
2797       if (pass->type == IPA_PASS
2798           && ipa_pass->write_summary
2799           && pass->gate (cfun))
2800         {
2801           /* If a timevar is present, start it.  */
2802           if (pass->tv_id)
2803             timevar_push (pass->tv_id);
2804
2805           pass_init_dump_file (pass);
2806
2807           current_pass = pass;
2808           ipa_pass->write_summary ();
2809
2810           pass_fini_dump_file (pass);
2811
2812           /* If a timevar is present, start it.  */
2813           if (pass->tv_id)
2814             timevar_pop (pass->tv_id);
2815         }
2816
2817       if (pass->sub && pass->sub->type != GIMPLE_PASS)
2818         ipa_write_summaries_2 (pass->sub, state);
2819
2820       pass = pass->next;
2821     }
2822 }
2823
2824 /* Helper function of ipa_write_summaries. Creates and destroys the
2825    decl state and calls ipa_write_summaries_2 for all passes that have
2826    summaries.  SET is the set of nodes to be written.  */
2827
2828 static void
2829 ipa_write_summaries_1 (lto_symtab_encoder_t encoder)
2830 {
2831   pass_manager *passes = g->get_passes ();
2832   struct lto_out_decl_state *state = lto_new_out_decl_state ();
2833   state->symtab_node_encoder = encoder;
2834
2835   lto_output_init_mode_table ();
2836   lto_push_out_decl_state (state);
2837
2838   gcc_assert (!flag_wpa);
2839   ipa_write_summaries_2 (passes->all_regular_ipa_passes, state);
2840
2841   write_lto ();
2842
2843   gcc_assert (lto_get_out_decl_state () == state);
2844   lto_pop_out_decl_state ();
2845   lto_delete_out_decl_state (state);
2846 }
2847
2848 /* Write out summaries for all the nodes in the callgraph.  */
2849
2850 void
2851 ipa_write_summaries (void)
2852 {
2853   lto_symtab_encoder_t encoder;
2854   int i, order_pos;
2855   varpool_node *vnode;
2856   struct cgraph_node *node;
2857   struct cgraph_node **order;
2858
2859   if ((!flag_generate_lto && !flag_generate_offload) || seen_error ())
2860     return;
2861
2862   gcc_assert (!dump_file);
2863   streamer_dump_file = dump_begin (TDI_lto_stream_out, NULL);
2864
2865   select_what_to_stream ();
2866
2867   encoder = lto_symtab_encoder_new (false);
2868
2869   /* Create the callgraph set in the same order used in
2870      cgraph_expand_all_functions.  This mostly facilitates debugging,
2871      since it causes the gimple file to be processed in the same order
2872      as the source code.  */
2873   order = XCNEWVEC (struct cgraph_node *, symtab->cgraph_count);
2874   order_pos = ipa_reverse_postorder (order);
2875   gcc_assert (order_pos == symtab->cgraph_count);
2876
2877   for (i = order_pos - 1; i >= 0; i--)
2878     {
2879       struct cgraph_node *node = order[i];
2880
2881       if ((node->definition || node->declare_variant_alt)
2882           && node->need_lto_streaming)
2883         {
2884           if (gimple_has_body_p (node->decl))
2885             lto_prepare_function_for_streaming (node);
2886           lto_set_symtab_encoder_in_partition (encoder, node);
2887         }
2888     }
2889
2890   FOR_EACH_DEFINED_FUNCTION (node)
2891     if (node->alias && node->need_lto_streaming)
2892       lto_set_symtab_encoder_in_partition (encoder, node);
2893   FOR_EACH_DEFINED_VARIABLE (vnode)
2894     if (vnode->need_lto_streaming)
2895       lto_set_symtab_encoder_in_partition (encoder, vnode);
2896
2897   ipa_write_summaries_1 (compute_ltrans_boundary (encoder));
2898
2899   free (order);
2900   if (streamer_dump_file)
2901     {
2902       dump_end (TDI_lto_stream_out, streamer_dump_file);
2903       streamer_dump_file = NULL;
2904     }
2905 }
2906
2907 /* Same as execute_pass_list but assume that subpasses of IPA passes
2908    are local passes. If SET is not NULL, write out optimization summaries of
2909    only those node in SET. */
2910
2911 static void
2912 ipa_write_optimization_summaries_1 (opt_pass *pass,
2913                                     struct lto_out_decl_state *state)
2914 {
2915   while (pass)
2916     {
2917       ipa_opt_pass_d *ipa_pass = (ipa_opt_pass_d *)pass;
2918       gcc_assert (!current_function_decl);
2919       gcc_assert (!cfun);
2920       gcc_assert (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS);
2921       if (pass->type == IPA_PASS
2922           && ipa_pass->write_optimization_summary
2923           && pass->gate (cfun))
2924         {
2925           /* If a timevar is present, start it.  */
2926           if (pass->tv_id)
2927             timevar_push (pass->tv_id);
2928
2929           pass_init_dump_file (pass);
2930
2931           current_pass = pass;
2932           ipa_pass->write_optimization_summary ();
2933
2934           pass_fini_dump_file (pass);
2935
2936           /* If a timevar is present, start it.  */
2937           if (pass->tv_id)
2938             timevar_pop (pass->tv_id);
2939         }
2940
2941       if (pass->sub && pass->sub->type != GIMPLE_PASS)
2942         ipa_write_optimization_summaries_1 (pass->sub, state);
2943
2944       pass = pass->next;
2945     }
2946 }
2947
2948 /* Write all the optimization summaries for the cgraph nodes in SET.  If SET is
2949    NULL, write out all summaries of all nodes. */
2950
2951 void
2952 ipa_write_optimization_summaries (lto_symtab_encoder_t encoder)
2953 {
2954   struct lto_out_decl_state *state = lto_new_out_decl_state ();
2955   state->symtab_node_encoder = encoder;
2956
2957   lto_output_init_mode_table ();
2958   lto_push_out_decl_state (state);
2959
2960   /* Be sure that we did not forget to renumber stmt uids.  */
2961   gcc_checking_assert (flag_wpa);
2962
2963   gcc_assert (flag_wpa);
2964   pass_manager *passes = g->get_passes ();
2965   ipa_write_optimization_summaries_1 (passes->all_regular_ipa_passes, state);
2966
2967   write_lto ();
2968
2969   gcc_assert (lto_get_out_decl_state () == state);
2970   lto_pop_out_decl_state ();
2971   lto_delete_out_decl_state (state);
2972 }
2973
2974 /* Same as execute_pass_list but assume that subpasses of IPA passes
2975    are local passes.  */
2976
2977 static void
2978 ipa_read_summaries_1 (opt_pass *pass)
2979 {
2980   while (pass)
2981     {
2982       ipa_opt_pass_d *ipa_pass = (ipa_opt_pass_d *) pass;
2983
2984       gcc_assert (!current_function_decl);
2985       gcc_assert (!cfun);
2986       gcc_assert (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS);
2987
2988       if (pass->gate (cfun))
2989         {
2990           if (pass->type == IPA_PASS && ipa_pass->read_summary)
2991             {
2992               /* If a timevar is present, start it.  */
2993               if (pass->tv_id)
2994                 timevar_push (pass->tv_id);
2995               if (!quiet_flag)
2996                 fprintf (stderr, " <%s>", pass->name ? pass->name : "");
2997
2998               pass_init_dump_file (pass);
2999
3000               current_pass = pass;
3001               ipa_pass->read_summary ();
3002
3003               pass_fini_dump_file (pass);
3004
3005               /* Stop timevar.  */
3006               if (pass->tv_id)
3007                 timevar_pop (pass->tv_id);
3008               ggc_grow ();
3009               report_heap_memory_use ();
3010             }
3011
3012           if (pass->sub && pass->sub->type != GIMPLE_PASS)
3013             ipa_read_summaries_1 (pass->sub);
3014         }
3015       pass = pass->next;
3016     }
3017 }
3018
3019
3020 /* Read all the summaries for all_regular_ipa_passes.  */
3021
3022 void
3023 ipa_read_summaries (void)
3024 {
3025   pass_manager *passes = g->get_passes ();
3026   ipa_read_summaries_1 (passes->all_regular_ipa_passes);
3027 }
3028
3029 /* Same as execute_pass_list but assume that subpasses of IPA passes
3030    are local passes.  */
3031
3032 static void
3033 ipa_read_optimization_summaries_1 (opt_pass *pass)
3034 {
3035   while (pass)
3036     {
3037       ipa_opt_pass_d *ipa_pass = (ipa_opt_pass_d *) pass;
3038
3039       gcc_assert (!current_function_decl);
3040       gcc_assert (!cfun);
3041       gcc_assert (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS);
3042
3043       if (pass->gate (cfun))
3044         {
3045           if (pass->type == IPA_PASS && ipa_pass->read_optimization_summary)
3046             {
3047               /* If a timevar is present, start it.  */
3048               if (pass->tv_id)
3049                 timevar_push (pass->tv_id);
3050               if (!quiet_flag)
3051                 fprintf (stderr, " <%s>", pass->name ? pass->name : "");
3052
3053               pass_init_dump_file (pass);
3054
3055               current_pass = pass;
3056               ipa_pass->read_optimization_summary ();
3057
3058               pass_fini_dump_file (pass);
3059
3060               /* Stop timevar.  */
3061               if (pass->tv_id)
3062                 timevar_pop (pass->tv_id);
3063             }
3064
3065           if (pass->sub && pass->sub->type != GIMPLE_PASS)
3066             ipa_read_optimization_summaries_1 (pass->sub);
3067           ggc_grow ();
3068           report_heap_memory_use ();
3069         }
3070       pass = pass->next;
3071     }
3072 }
3073
3074 /* Read all the summaries for all_regular_ipa_passes.  */
3075
3076 void
3077 ipa_read_optimization_summaries (void)
3078 {
3079   pass_manager *passes = g->get_passes ();
3080   ipa_read_optimization_summaries_1 (passes->all_regular_ipa_passes);
3081 }
3082
3083 /* Same as execute_pass_list but assume that subpasses of IPA passes
3084    are local passes.  */
3085 void
3086 execute_ipa_pass_list (opt_pass *pass)
3087 {
3088   do
3089     {
3090       gcc_assert (!current_function_decl);
3091       gcc_assert (!cfun);
3092       gcc_assert (pass->type == SIMPLE_IPA_PASS || pass->type == IPA_PASS);
3093       if (execute_one_pass (pass) && pass->sub)
3094         {
3095           if (pass->sub->type == GIMPLE_PASS)
3096             {
3097               invoke_plugin_callbacks (PLUGIN_EARLY_GIMPLE_PASSES_START, NULL);
3098               do_per_function_toporder ((void (*)(function *, void *))
3099                                           execute_pass_list,
3100                                         pass->sub);
3101               invoke_plugin_callbacks (PLUGIN_EARLY_GIMPLE_PASSES_END, NULL);
3102             }
3103           else if (pass->sub->type == SIMPLE_IPA_PASS
3104                    || pass->sub->type == IPA_PASS)
3105             execute_ipa_pass_list (pass->sub);
3106           else
3107             gcc_unreachable ();
3108         }
3109       gcc_assert (!current_function_decl);
3110       symtab->process_new_functions ();
3111       pass = pass->next;
3112     }
3113   while (pass);
3114 }
3115
3116 /* Execute stmt fixup hooks of all passes in PASS for NODE and STMTS.  */
3117
3118 static void
3119 execute_ipa_stmt_fixups (opt_pass *pass,
3120                          struct cgraph_node *node, gimple **stmts)
3121 {
3122   while (pass)
3123     {
3124       /* Execute all of the IPA_PASSes in the list.  */
3125       if (pass->type == IPA_PASS
3126           && pass->gate (cfun))
3127         {
3128           ipa_opt_pass_d *ipa_pass = (ipa_opt_pass_d *) pass;
3129
3130           if (ipa_pass->stmt_fixup)
3131             {
3132               pass_init_dump_file (pass);
3133               /* If a timevar is present, start it.  */
3134               if (pass->tv_id)
3135                 timevar_push (pass->tv_id);
3136
3137               current_pass = pass;
3138               ipa_pass->stmt_fixup (node, stmts);
3139
3140               /* Stop timevar.  */
3141               if (pass->tv_id)
3142                 timevar_pop (pass->tv_id);
3143               pass_fini_dump_file (pass);
3144             }
3145           if (pass->sub)
3146             execute_ipa_stmt_fixups (pass->sub, node, stmts);
3147         }
3148       pass = pass->next;
3149     }
3150 }
3151
3152 /* Execute stmt fixup hooks of all IPA passes for NODE and STMTS.  */
3153
3154 void
3155 execute_all_ipa_stmt_fixups (struct cgraph_node *node, gimple **stmts)
3156 {
3157   pass_manager *passes = g->get_passes ();
3158   execute_ipa_stmt_fixups (passes->all_regular_ipa_passes, node, stmts);
3159 }
3160
3161
3162 extern void debug_properties (unsigned int);
3163 extern void dump_properties (FILE *, unsigned int);
3164
3165 DEBUG_FUNCTION void
3166 dump_properties (FILE *dump, unsigned int props)
3167 {
3168   fprintf (dump, "Properties:\n");
3169   if (props & PROP_gimple_any)
3170     fprintf (dump, "PROP_gimple_any\n");
3171   if (props & PROP_gimple_lcf)
3172     fprintf (dump, "PROP_gimple_lcf\n");
3173   if (props & PROP_gimple_leh)
3174     fprintf (dump, "PROP_gimple_leh\n");
3175   if (props & PROP_cfg)
3176     fprintf (dump, "PROP_cfg\n");
3177   if (props & PROP_ssa)
3178     fprintf (dump, "PROP_ssa\n");
3179   if (props & PROP_no_crit_edges)
3180     fprintf (dump, "PROP_no_crit_edges\n");
3181   if (props & PROP_rtl)
3182     fprintf (dump, "PROP_rtl\n");
3183   if (props & PROP_gimple_lomp)
3184     fprintf (dump, "PROP_gimple_lomp\n");
3185   if (props & PROP_gimple_lomp_dev)
3186     fprintf (dump, "PROP_gimple_lomp_dev\n");
3187   if (props & PROP_gimple_lcx)
3188     fprintf (dump, "PROP_gimple_lcx\n");
3189   if (props & PROP_gimple_lvec)
3190     fprintf (dump, "PROP_gimple_lvec\n");
3191   if (props & PROP_cfglayout)
3192     fprintf (dump, "PROP_cfglayout\n");
3193 }
3194
3195 DEBUG_FUNCTION void
3196 debug_properties (unsigned int props)
3197 {
3198   dump_properties (stderr, props);
3199 }
3200
3201 /* Called by local passes to see if function is called by already processed nodes.
3202    Because we process nodes in topological order, this means that function is
3203    in recursive cycle or we introduced new direct calls.  */
3204 bool
3205 function_called_by_processed_nodes_p (void)
3206 {
3207   struct cgraph_edge *e;
3208   for (e = cgraph_node::get (current_function_decl)->callers;
3209        e;
3210        e = e->next_caller)
3211     {
3212       if (e->caller->decl == current_function_decl)
3213         continue;
3214       if (!e->caller->has_gimple_body_p ())
3215         continue;
3216       if (TREE_ASM_WRITTEN (e->caller->decl))
3217         continue;
3218       if (!e->caller->process && !e->caller->inlined_to)
3219         break;
3220     }
3221   if (dump_file && e)
3222     {
3223       fprintf (dump_file, "Already processed call to:\n");
3224       e->caller->dump (dump_file);
3225     }
3226   return e != NULL;
3227 }