1@c markers: BUG TODO
2
3@c Copyright (C) 1988-2022 Free Software Foundation, Inc.
4@c This is part of the GCC manual.
5@c For copying conditions, see the file gcc.texi.
6
7@node Passes
8@chapter Passes and Files of the Compiler
9@cindex passes and files of the compiler
10@cindex files and passes of the compiler
11@cindex compiler passes and files
12@cindex pass dumps
13
14This chapter is dedicated to giving an overview of the optimization and
15code generation passes of the compiler.  In the process, it describes
16some of the language front end interface, though this description is no
17where near complete.
18
19@menu
20* Parsing pass::         The language front end turns text into bits.
21* Gimplification pass::  The bits are turned into something we can optimize.
22* Pass manager::         Sequencing the optimization passes.
23* IPA passes::           Inter-procedural optimizations.
24* Tree SSA passes::      Optimizations on a high-level representation.
25* RTL passes::           Optimizations on a low-level representation.
26* Optimization info::    Dumping optimization information from passes.
27@end menu
28
29@node Parsing pass
30@section Parsing pass
31@cindex GENERIC
32@findex lang_hooks.parse_file
33The language front end is invoked only once, via
34@code{lang_hooks.parse_file}, to parse the entire input.  The language
35front end may use any intermediate language representation deemed
36appropriate.  The C front end uses GENERIC trees (@pxref{GENERIC}), plus
37a double handful of language specific tree codes defined in
38@file{c-common.def}.  The Fortran front end uses a completely different
39private representation.
40
41@cindex GIMPLE
42@cindex gimplification
43@cindex gimplifier
44@cindex language-independent intermediate representation
45@cindex intermediate representation lowering
46@cindex lowering, language-dependent intermediate representation
47At some point the front end must translate the representation used in the
48front end to a representation understood by the language-independent
49portions of the compiler.  Current practice takes one of two forms.
50The C front end manually invokes the gimplifier (@pxref{GIMPLE}) on each function,
51and uses the gimplifier callbacks to convert the language-specific tree
52nodes directly to GIMPLE before passing the function off to be compiled.
53The Fortran front end converts from a private representation to GENERIC,
54which is later lowered to GIMPLE when the function is compiled.  Which
55route to choose probably depends on how well GENERIC (plus extensions)
56can be made to match up with the source language and necessary parsing
57data structures.
58
59BUG: Gimplification must occur before nested function lowering,
60and nested function lowering must be done by the front end before
61passing the data off to cgraph.
62
63TODO: Cgraph should control nested function lowering.  It would
64only be invoked when it is certain that the outer-most function
65is used.
66
67TODO: Cgraph needs a gimplify_function callback.  It should be
68invoked when (1) it is certain that the function is used, (2)
69warning flags specified by the user require some amount of
70compilation in order to honor, (3) the language indicates that
71semantic analysis is not complete until gimplification occurs.
72Hum@dots{} this sounds overly complicated.  Perhaps we should just
73have the front end gimplify always; in most cases it's only one
74function call.
75
76The front end needs to pass all function definitions and top level
77declarations off to the middle-end so that they can be compiled and
78emitted to the object file.  For a simple procedural language, it is
79usually most convenient to do this as each top level declaration or
80definition is seen.  There is also a distinction to be made between
81generating functional code and generating complete debug information.
82The only thing that is absolutely required for functional code is that
83function and data @emph{definitions} be passed to the middle-end.  For
84complete debug information, function, data and type declarations
85should all be passed as well.
86
87@findex rest_of_decl_compilation
88@findex rest_of_type_compilation
89@findex cgraph_finalize_function
90In any case, the front end needs each complete top-level function or
91data declaration, and each data definition should be passed to
92@code{rest_of_decl_compilation}.  Each complete type definition should
93be passed to @code{rest_of_type_compilation}.  Each function definition
94should be passed to @code{cgraph_finalize_function}.
95
96TODO: I know rest_of_compilation currently has all sorts of
97RTL generation semantics.  I plan to move all code generation
98bits (both Tree and RTL) to compile_function.  Should we hide
99cgraph from the front ends and move back to rest_of_compilation
100as the official interface?  Possibly we should rename all three
101interfaces such that the names match in some meaningful way and
102that is more descriptive than "rest_of".
103
104The middle-end will, at its option, emit the function and data
105definitions immediately or queue them for later processing.
106
107@node Gimplification pass
108@section Gimplification pass
109
110@cindex gimplification
111@cindex GIMPLE
112@dfn{Gimplification} is a whimsical term for the process of converting
113the intermediate representation of a function into the GIMPLE language
114(@pxref{GIMPLE}).  The term stuck, and so words like ``gimplification'',
115``gimplify'', ``gimplifier'' and the like are sprinkled throughout this
116section of code.
117
118While a front end may certainly choose to generate GIMPLE directly if
119it chooses, this can be a moderately complex process unless the
120intermediate language used by the front end is already fairly simple.
121Usually it is easier to generate GENERIC trees plus extensions
122and let the language-independent gimplifier do most of the work.
123
124@findex gimplify_function_tree
125@findex gimplify_expr
126@findex lang_hooks.gimplify_expr
127The main entry point to this pass is @code{gimplify_function_tree}
128located in @file{gimplify.cc}.  From here we process the entire
129function gimplifying each statement in turn.  The main workhorse
130for this pass is @code{gimplify_expr}.  Approximately everything
131passes through here at least once, and it is from here that we
132invoke the @code{lang_hooks.gimplify_expr} callback.
133
134The callback should examine the expression in question and return
135@code{GS_UNHANDLED} if the expression is not a language specific
136construct that requires attention.  Otherwise it should alter the
137expression in some way to such that forward progress is made toward
138producing valid GIMPLE@.  If the callback is certain that the
139transformation is complete and the expression is valid GIMPLE, it
140should return @code{GS_ALL_DONE}.  Otherwise it should return
141@code{GS_OK}, which will cause the expression to be processed again.
142If the callback encounters an error during the transformation (because
143the front end is relying on the gimplification process to finish
144semantic checks), it should return @code{GS_ERROR}.
145
146@node Pass manager
147@section Pass manager
148
149The pass manager is located in @file{passes.cc}, @file{tree-optimize.c}
150and @file{tree-pass.h}.
151It processes passes as described in @file{passes.def}.
152Its job is to run all of the individual passes in the correct order,
153and take care of standard bookkeeping that applies to every pass.
154
155The theory of operation is that each pass defines a structure that
156represents everything we need to know about that pass---when it
157should be run, how it should be run, what intermediate language
158form or on-the-side data structures it needs.  We register the pass
159to be run in some particular order, and the pass manager arranges
160for everything to happen in the correct order.
161
162The actuality doesn't completely live up to the theory at present.
163Command-line switches and @code{timevar_id_t} enumerations must still
164be defined elsewhere.  The pass manager validates constraints but does
165not attempt to (re-)generate data structures or lower intermediate
166language form based on the requirements of the next pass.  Nevertheless,
167what is present is useful, and a far sight better than nothing at all.
168
169Each pass should have a unique name.
170Each pass may have its own dump file (for GCC debugging purposes).
171Passes with a name starting with a star do not dump anything.
172Sometimes passes are supposed to share a dump file / option name.
173To still give these unique names, you can use a prefix that is delimited
174by a space from the part that is used for the dump file / option name.
175E.g. When the pass name is "ud dce", the name used for dump file/options
176is "dce".
177
178TODO: describe the global variables set up by the pass manager,
179and a brief description of how a new pass should use it.
180I need to look at what info RTL passes use first@enddots{}
181
182@node IPA passes
183@section Inter-procedural optimization passes
184@cindex IPA passes
185@cindex inter-procedural optimization passes
186
187The inter-procedural optimization (IPA) passes use call graph
188information to perform transformations across function boundaries.
189IPA is a critical part of link-time optimization (LTO) and
190whole-program (WHOPR) optimization, and these passes are structured
191with the needs of LTO and WHOPR in mind by dividing their operations
192into stages.  For detailed discussion of the LTO/WHOPR IPA pass stages
193and interfaces, see @ref{IPA}.
194
195The following briefly describes the inter-procedural optimization (IPA)
196passes, which are split into small IPA passes, regular IPA passes,
197and late IPA passes, according to the LTO/WHOPR processing model.
198
199@menu
200* Small IPA passes::
201* Regular IPA passes::
202* Late IPA passes::
203@end menu
204
205@node Small IPA passes
206@subsection Small IPA passes
207@cindex small IPA passes
208A small IPA pass is a pass derived from @code{simple_ipa_opt_pass}.
209As described in @ref{IPA}, it does everything at once and
210defines only the @emph{Execute} stage.  During this
211stage it accesses and modifies the function bodies.
212No @code{generate_summary}, @code{read_summary}, or @code{write_summary}
213hooks are defined.
214
215@itemize @bullet
216@item IPA free lang data
217
218This pass frees resources that are used by the front end but are
219not needed once it is done.  It is located in @file{tree.cc} and is described by
220@code{pass_ipa_free_lang_data}.
221
222@item IPA function and variable visibility
223
224This is a local function pass handling visibilities of all symbols.  This
225happens before LTO streaming, so @option{-fwhole-program} should be ignored
226at this level.  It is located in @file{ipa-visibility.cc} and is described by
227@code{pass_ipa_function_and_variable_visibility}.
228
229@item IPA remove symbols
230
231This pass performs reachability analysis and reclaims all unreachable nodes.
232It is located in @file{passes.cc} and is described by
233@code{pass_ipa_remove_symbols}.
234
235@item IPA OpenACC
236
237This is a pass group for OpenACC processing.  It is located in
238@file{tree-ssa-loop.cc} and is described by @code{pass_ipa_oacc}.
239
240@item IPA points-to analysis
241
242This is a tree-based points-to analysis pass. The idea behind this analyzer
243is to generate set constraints from the program, then solve the resulting
244constraints in order to generate the points-to sets.  It is located in
245@file{tree-ssa-structalias.cc} and is described by @code{pass_ipa_pta}.
246
247@item IPA OpenACC kernels
248
249This is a pass group for processing OpenACC kernels regions.  It is a
250subpass of the IPA OpenACC pass group that runs on offloaded functions
251containing OpenACC kernels loops.  It is located in
252@file{tree-ssa-loop.cc} and is described by
253@code{pass_ipa_oacc_kernels}.
254
255@item Target clone
256
257This is a pass for parsing functions with multiple target attributes.
258It is located in @file{multiple_target.cc} and is described by
259@code{pass_target_clone}.
260
261@item IPA auto profile
262
263This pass uses AutoFDO profiling data to annotate the control flow graph.
264It is located in @file{auto-profile.cc} and is described by
265@code{pass_ipa_auto_profile}.
266
267@item IPA tree profile
268
269This pass does profiling for all functions in the call graph.
270It calculates branch
271probabilities and basic block execution counts. It is located
272in @file{tree-profile.cc} and is described by @code{pass_ipa_tree_profile}.
273
274@item IPA free function summary
275
276This pass is a small IPA pass when argument @code{small_p} is true.
277It releases inline function summaries and call summaries.
278It is located in @file{ipa-fnsummary.cc} and is described by
279@code{pass_ipa_free_free_fn_summary}.
280
281@item IPA increase alignment
282
283This pass increases the alignment of global arrays to improve
284vectorization. It is located in @file{tree-vectorizer.cc}
285and is described by @code{pass_ipa_increase_alignment}.
286
287@item IPA transactional memory
288
289This pass is for transactional memory support.
290It is located in @file{trans-mem.cc} and is described by
291@code{pass_ipa_tm}.
292
293@item IPA lower emulated TLS
294
295This pass lowers thread-local storage (TLS) operations
296to emulation functions provided by libgcc.
297It is located in @file{tree-emutls.cc} and is described by
298@code{pass_ipa_lower_emutls}.
299
300@end itemize
301
302@node Regular IPA passes
303@subsection Regular IPA passes
304@cindex regular IPA passes
305
306A regular IPA pass is a pass derived from @code{ipa_opt_pass_d} that
307is executed in WHOPR compilation. Regular IPA passes may have summary
308hooks implemented in any of the LGEN, WPA or LTRANS stages (@pxref{IPA}).
309
310@itemize @bullet
311@item IPA whole program visibility
312
313This pass performs various optimizations involving symbol visibility
314with @option{-fwhole-program}, including symbol privatization,
315discovering local functions, and dismantling comdat groups.  It is
316located in @file{ipa-visibility.cc} and is described by
317@code{pass_ipa_whole_program_visibility}.
318
319@item IPA profile
320
321The IPA profile pass propagates profiling frequencies across the call
322graph.  It is located in @file{ipa-profile.cc} and is described by
323@code{pass_ipa_profile}.
324
325@item IPA identical code folding
326
327This is the inter-procedural identical code folding pass.
328The goal of this transformation is to discover functions
329and read-only variables that have exactly the same semantics.  It is
330located in @file{ipa-icf.cc} and is described by @code{pass_ipa_icf}.
331
332@item IPA devirtualization
333
334This pass performs speculative devirtualization based on the type
335inheritance graph.  When a polymorphic call has only one likely target
336in the unit, it is turned into a speculative call. It is located in
337@file{ipa-devirt.cc} and is described by @code{pass_ipa_devirt}.
338
339@item IPA constant propagation
340
341The goal of this pass is to discover functions that are always invoked
342with some arguments with the same known constant values and to modify
343the functions accordingly.  It can also do partial specialization and
344type-based devirtualization.  It is located in @file{ipa-cp.cc} and is
345described by @code{pass_ipa_cp}.
346
347@item IPA scalar replacement of aggregates
348
349This pass can replace an aggregate parameter with a set of other parameters
350representing part of the original, turning those passed by reference
351into new ones which pass the value directly.  It also removes unused
352function return values and unused function parameters.  This pass is
353located in @file{ipa-sra.cc} and is described by @code{pass_ipa_sra}.
354
355@item IPA constructor/destructor merge
356
357This pass merges multiple constructors and destructors for static
358objects into single functions.  It's only run at LTO time unless the
359target doesn't support constructors and destructors natively.  The
360pass is located in @file{ipa.cc} and is described by
361@code{pass_ipa_cdtor_merge}.
362
363@item IPA function summary
364
365This pass provides function analysis for inter-procedural passes.
366It collects estimates of function body size, execution time, and frame
367size for each function.  It also estimates information about function
368calls: call statement size, time and how often the parameters change
369for each call.  It is located in @file{ipa-fnsummary.cc} and is
370described by @code{pass_ipa_fn_summary}.
371
372@item IPA inline
373
374The IPA inline pass handles function inlining with whole-program
375knowledge. Small functions that are candidates for inlining are
376ordered in increasing badness, bounded by unit growth parameters.
377Unreachable functions are removed from the call graph.  Functions called
378once and not exported from the unit are inlined.  This pass is located in
379@file{ipa-inline.cc} and is described by @code{pass_ipa_inline}.
380
381@item IPA pure/const analysis
382
383This pass marks functions as being either const (@code{TREE_READONLY}) or
384pure (@code{DECL_PURE_P}).  The per-function information is produced
385by @code{pure_const_generate_summary}, then the global information is computed
386by performing a transitive closure over the call graph.   It is located in
387@file{ipa-pure-const.cc} and is described by @code{pass_ipa_pure_const}.
388
389@item IPA free function summary
390
391This pass is a regular IPA pass when argument @code{small_p} is false.
392It releases inline function summaries and call summaries.
393It is located in @file{ipa-fnsummary.cc} and is described by
394@code{pass_ipa_free_fn_summary}.
395
396@item IPA reference
397
398This pass gathers information about how variables whose scope is
399confined to the compilation unit are used.  It is located in
400@file{ipa-reference.cc} and is described by @code{pass_ipa_reference}.
401
402@item IPA single use
403
404This pass checks whether variables are used by a single function.
405It is located in @file{ipa.cc} and is described by
406@code{pass_ipa_single_use}.
407
408@item IPA comdats
409
410This pass looks for static symbols that are used exclusively
411within one comdat group, and moves them into that comdat group. It is
412located in @file{ipa-comdats.cc} and is described by
413@code{pass_ipa_comdats}.
414
415@end itemize
416
417@node Late IPA passes
418@subsection Late IPA passes
419@cindex late IPA passes
420
421Late IPA passes are simple IPA passes executed after
422the regular passes.  In WHOPR mode the passes are executed after
423partitioning and thus see just parts of the compiled unit.
424
425@itemize @bullet
426@item Materialize all clones
427
428Once all functions from compilation unit are in memory, produce all clones
429and update all calls.  It is located in @file{ipa.cc} and is described by
430@code{pass_materialize_all_clones}.
431
432@item IPA points-to analysis
433
434Points-to analysis; this is the same as the points-to-analysis pass
435run with the small IPA passes (@pxref{Small IPA passes}).
436
437@item OpenMP simd clone
438
439This is the OpenMP constructs' SIMD clone pass.  It creates the appropriate
440SIMD clones for functions tagged as elemental SIMD functions.
441It is located in @file{omp-simd-clone.cc} and is described by
442@code{pass_omp_simd_clone}.
443
444@end itemize
445
446@node Tree SSA passes
447@section Tree SSA passes
448
449The following briefly describes the Tree optimization passes that are
450run after gimplification and what source files they are located in.
451
452@itemize @bullet
453@item Remove useless statements
454
455This pass is an extremely simple sweep across the gimple code in which
456we identify obviously dead code and remove it.  Here we do things like
457simplify @code{if} statements with constant conditions, remove
458exception handling constructs surrounding code that obviously cannot
459throw, remove lexical bindings that contain no variables, and other
460assorted simplistic cleanups.  The idea is to get rid of the obvious
461stuff quickly rather than wait until later when it's more work to get
462rid of it.  This pass is located in @file{tree-cfg.cc} and described by
463@code{pass_remove_useless_stmts}.
464
465@item OpenMP lowering
466
467If OpenMP generation (@option{-fopenmp}) is enabled, this pass lowers
468OpenMP constructs into GIMPLE.
469
470Lowering of OpenMP constructs involves creating replacement
471expressions for local variables that have been mapped using data
472sharing clauses, exposing the control flow of most synchronization
473directives and adding region markers to facilitate the creation of the
474control flow graph.  The pass is located in @file{omp-low.cc} and is
475described by @code{pass_lower_omp}.
476
477@item OpenMP expansion
478
479If OpenMP generation (@option{-fopenmp}) is enabled, this pass expands
480parallel regions into their own functions to be invoked by the thread
481library.  The pass is located in @file{omp-low.cc} and is described by
482@code{pass_expand_omp}.
483
484@item Lower control flow
485
486This pass flattens @code{if} statements (@code{COND_EXPR})
487and moves lexical bindings (@code{BIND_EXPR}) out of line.  After
488this pass, all @code{if} statements will have exactly two @code{goto}
489statements in its @code{then} and @code{else} arms.  Lexical binding
490information for each statement will be found in @code{TREE_BLOCK} rather
491than being inferred from its position under a @code{BIND_EXPR}.  This
492pass is found in @file{gimple-low.cc} and is described by
493@code{pass_lower_cf}.
494
495@item Lower exception handling control flow
496
497This pass decomposes high-level exception handling constructs
498(@code{TRY_FINALLY_EXPR} and @code{TRY_CATCH_EXPR}) into a form
499that explicitly represents the control flow involved.  After this
500pass, @code{lookup_stmt_eh_region} will return a non-negative
501number for any statement that may have EH control flow semantics;
502examine @code{tree_can_throw_internal} or @code{tree_can_throw_external}
503for exact semantics.  Exact control flow may be extracted from
504@code{foreach_reachable_handler}.  The EH region nesting tree is defined
505in @file{except.h} and built in @file{except.cc}.  The lowering pass
506itself is in @file{tree-eh.cc} and is described by @code{pass_lower_eh}.
507
508@item Build the control flow graph
509
510This pass decomposes a function into basic blocks and creates all of
511the edges that connect them.  It is located in @file{tree-cfg.cc} and
512is described by @code{pass_build_cfg}.
513
514@item Find all referenced variables
515
516This pass walks the entire function and collects an array of all
517variables referenced in the function, @code{referenced_vars}.  The
518index at which a variable is found in the array is used as a UID
519for the variable within this function.  This data is needed by the
520SSA rewriting routines.  The pass is located in @file{tree-dfa.cc}
521and is described by @code{pass_referenced_vars}.
522
523@item Enter static single assignment form
524
525This pass rewrites the function such that it is in SSA form.  After
526this pass, all @code{is_gimple_reg} variables will be referenced by
527@code{SSA_NAME}, and all occurrences of other variables will be
528annotated with @code{VDEFS} and @code{VUSES}; PHI nodes will have
529been inserted as necessary for each basic block.  This pass is
530located in @file{tree-ssa.cc} and is described by @code{pass_build_ssa}.
531
532@item Warn for uninitialized variables
533
534This pass scans the function for uses of @code{SSA_NAME}s that
535are fed by default definition.  For non-parameter variables, such
536uses are uninitialized.  The pass is run twice, before and after
537optimization (if turned on).  In the first pass we only warn for uses that are
538positively uninitialized; in the second pass we warn for uses that
539are possibly uninitialized.  The pass is located in @file{tree-ssa.cc}
540and is defined by @code{pass_early_warn_uninitialized} and
541@code{pass_late_warn_uninitialized}.
542
543@item Dead code elimination
544
545This pass scans the function for statements without side effects whose
546result is unused.  It does not do memory life analysis, so any value
547that is stored in memory is considered used.  The pass is run multiple
548times throughout the optimization process.  It is located in
549@file{tree-ssa-dce.cc} and is described by @code{pass_dce}.
550
551@item Dominator optimizations
552
553This pass performs trivial dominator-based copy and constant propagation,
554expression simplification, and jump threading.  It is run multiple times
555throughout the optimization process.  It is located in @file{tree-ssa-dom.cc}
556and is described by @code{pass_dominator}.
557
558@item Forward propagation of single-use variables
559
560This pass attempts to remove redundant computation by substituting
561variables that are used once into the expression that uses them and
562seeing if the result can be simplified.  It is located in
563@file{tree-ssa-forwprop.cc} and is described by @code{pass_forwprop}.
564
565@item Copy Renaming
566
567This pass attempts to change the name of compiler temporaries involved in
568copy operations such that SSA->normal can coalesce the copy away.  When compiler
569temporaries are copies of user variables, it also renames the compiler
570temporary to the user variable resulting in better use of user symbols.  It is
571located in @file{tree-ssa-copyrename.c} and is described by
572@code{pass_copyrename}.
573
574@item PHI node optimizations
575
576This pass recognizes forms of PHI inputs that can be represented as
577conditional expressions and rewrites them into straight line code.
578It is located in @file{tree-ssa-phiopt.cc} and is described by
579@code{pass_phiopt}.
580
581@item May-alias optimization
582
583This pass performs a flow sensitive SSA-based points-to analysis.
584The resulting may-alias, must-alias, and escape analysis information
585is used to promote variables from in-memory addressable objects to
586non-aliased variables that can be renamed into SSA form.  We also
587update the @code{VDEF}/@code{VUSE} memory tags for non-renameable
588aggregates so that we get fewer false kills.  The pass is located
589in @file{tree-ssa-alias.cc} and is described by @code{pass_may_alias}.
590
591Interprocedural points-to information is located in
592@file{tree-ssa-structalias.cc} and described by @code{pass_ipa_pta}.
593
594@item Profiling
595
596This pass instruments the function in order to collect runtime block
597and value profiling data.  Such data may be fed back into the compiler
598on a subsequent run so as to allow optimization based on expected
599execution frequencies.  The pass is located in @file{tree-profile.cc} and
600is described by @code{pass_ipa_tree_profile}.
601
602@item Static profile estimation
603
604This pass implements series of heuristics to guess propababilities
605of branches.  The resulting predictions are turned into edge profile
606by propagating branches across the control flow graphs.
607The pass is located in @file{tree-profile.cc} and is described by
608@code{pass_profile}.
609
610@item Lower complex arithmetic
611
612This pass rewrites complex arithmetic operations into their component
613scalar arithmetic operations.  The pass is located in @file{tree-complex.cc}
614and is described by @code{pass_lower_complex}.
615
616@item Scalar replacement of aggregates
617
618This pass rewrites suitable non-aliased local aggregate variables into
619a set of scalar variables.  The resulting scalar variables are
620rewritten into SSA form, which allows subsequent optimization passes
621to do a significantly better job with them.  The pass is located in
622@file{tree-sra.cc} and is described by @code{pass_sra}.
623
624@item Dead store elimination
625
626This pass eliminates stores to memory that are subsequently overwritten
627by another store, without any intervening loads.  The pass is located
628in @file{tree-ssa-dse.cc} and is described by @code{pass_dse}.
629
630@item Tail recursion elimination
631
632This pass transforms tail recursion into a loop.  It is located in
633@file{tree-tailcall.cc} and is described by @code{pass_tail_recursion}.
634
635@item Forward store motion
636
637This pass sinks stores and assignments down the flowgraph closer to their
638use point.  The pass is located in @file{tree-ssa-sink.cc} and is
639described by @code{pass_sink_code}.
640
641@item Partial redundancy elimination
642
643This pass eliminates partially redundant computations, as well as
644performing load motion.  The pass is located in @file{tree-ssa-pre.cc}
645and is described by @code{pass_pre}.
646
647Just before partial redundancy elimination, if
648@option{-funsafe-math-optimizations} is on, GCC tries to convert
649divisions to multiplications by the reciprocal.  The pass is located
650in @file{tree-ssa-math-opts.cc} and is described by
651@code{pass_cse_reciprocal}.
652
653@item Full redundancy elimination
654
655This is a simpler form of PRE that only eliminates redundancies that
656occur on all paths.  It is located in @file{tree-ssa-pre.cc} and
657described by @code{pass_fre}.
658
659@item Loop optimization
660
661The main driver of the pass is placed in @file{tree-ssa-loop.cc}
662and described by @code{pass_loop}.
663
664The optimizations performed by this pass are:
665
666Loop invariant motion.  This pass moves only invariants that
667would be hard to handle on RTL level (function calls, operations that expand to
668nontrivial sequences of insns).  With @option{-funswitch-loops} it also moves
669operands of conditions that are invariant out of the loop, so that we can use
670just trivial invariantness analysis in loop unswitching.  The pass also includes
671store motion.  The pass is implemented in @file{tree-ssa-loop-im.cc}.
672
673Canonical induction variable creation.  This pass creates a simple counter
674for number of iterations of the loop and replaces the exit condition of the
675loop using it, in case when a complicated analysis is necessary to determine
676the number of iterations.  Later optimizations then may determine the number
677easily.  The pass is implemented in @file{tree-ssa-loop-ivcanon.cc}.
678
679Induction variable optimizations.  This pass performs standard induction
680variable optimizations, including strength reduction, induction variable
681merging and induction variable elimination.  The pass is implemented in
682@file{tree-ssa-loop-ivopts.cc}.
683
684Loop unswitching.  This pass moves the conditional jumps that are invariant
685out of the loops.  To achieve this, a duplicate of the loop is created for
686each possible outcome of conditional jump(s).  The pass is implemented in
687@file{tree-ssa-loop-unswitch.cc}.
688
689Loop splitting.  If a loop contains a conditional statement that is
690always true for one part of the iteration space and false for the other
691this pass splits the loop into two, one dealing with one side the other
692only with the other, thereby removing one inner-loop conditional.  The
693pass is implemented in @file{tree-ssa-loop-split.cc}.
694
695The optimizations also use various utility functions contained in
696@file{tree-ssa-loop-manip.cc}, @file{cfgloop.cc}, @file{cfgloopanal.cc} and
697@file{cfgloopmanip.cc}.
698
699Vectorization.  This pass transforms loops to operate on vector types
700instead of scalar types.  Data parallelism across loop iterations is exploited
701to group data elements from consecutive iterations into a vector and operate
702on them in parallel.  Depending on available target support the loop is
703conceptually unrolled by a factor @code{VF} (vectorization factor), which is
704the number of elements operated upon in parallel in each iteration, and the
705@code{VF} copies of each scalar operation are fused to form a vector operation.
706Additional loop transformations such as peeling and versioning may take place
707to align the number of iterations, and to align the memory accesses in the
708loop.
709The pass is implemented in @file{tree-vectorizer.cc} (the main driver),
710@file{tree-vect-loop.cc} and @file{tree-vect-loop-manip.cc} (loop specific parts
711and general loop utilities), @file{tree-vect-slp} (loop-aware SLP
712functionality), @file{tree-vect-stmts.cc}, @file{tree-vect-data-refs.cc} and
713@file{tree-vect-slp-patterns.cc} containing the SLP pattern matcher.
714Analysis of data references is in @file{tree-data-ref.cc}.
715
716SLP Vectorization.  This pass performs vectorization of straight-line code. The
717pass is implemented in @file{tree-vectorizer.cc} (the main driver),
718@file{tree-vect-slp.cc}, @file{tree-vect-stmts.cc} and
719@file{tree-vect-data-refs.cc}.
720
721Autoparallelization.  This pass splits the loop iteration space to run
722into several threads.  The pass is implemented in @file{tree-parloops.cc}.
723
724Graphite is a loop transformation framework based on the polyhedral
725model.  Graphite stands for Gimple Represented as Polyhedra.  The
726internals of this infrastructure are documented in
727@w{@uref{https://gcc.gnu.org/wiki/Graphite}}.  The passes working on
728this representation are implemented in the various @file{graphite-*}
729files.
730
731@item Tree level if-conversion for vectorizer
732
733This pass applies if-conversion to simple loops to help vectorizer.
734We identify if convertible loops, if-convert statements and merge
735basic blocks in one big block.  The idea is to present loop in such
736form so that vectorizer can have one to one mapping between statements
737and available vector operations.  This pass is located in
738@file{tree-if-conv.cc} and is described by @code{pass_if_conversion}.
739
740@item Conditional constant propagation
741
742This pass relaxes a lattice of values in order to identify those
743that must be constant even in the presence of conditional branches.
744The pass is located in @file{tree-ssa-ccp.cc} and is described
745by @code{pass_ccp}.
746
747A related pass that works on memory loads and stores, and not just
748register values, is located in @file{tree-ssa-ccp.cc} and described by
749@code{pass_store_ccp}.
750
751@item Conditional copy propagation
752
753This is similar to constant propagation but the lattice of values is
754the ``copy-of'' relation.  It eliminates redundant copies from the
755code.  The pass is located in @file{tree-ssa-copy.cc} and described by
756@code{pass_copy_prop}.
757
758A related pass that works on memory copies, and not just register
759copies, is located in @file{tree-ssa-copy.cc} and described by
760@code{pass_store_copy_prop}.
761
762@item Value range propagation
763
764This transformation is similar to constant propagation but
765instead of propagating single constant values, it propagates
766known value ranges.  The implementation is based on Patterson's
767range propagation algorithm (Accurate Static Branch Prediction by
768Value Range Propagation, J. R. C. Patterson, PLDI '95).  In
769contrast to Patterson's algorithm, this implementation does not
770propagate branch probabilities nor it uses more than a single
771range per SSA name. This means that the current implementation
772cannot be used for branch prediction (though adapting it would
773not be difficult).  The pass is located in @file{tree-vrp.cc} and is
774described by @code{pass_vrp}.
775
776@item Folding built-in functions
777
778This pass simplifies built-in functions, as applicable, with constant
779arguments or with inferable string lengths.  It is located in
780@file{tree-ssa-ccp.cc} and is described by @code{pass_fold_builtins}.
781
782@item Split critical edges
783
784This pass identifies critical edges and inserts empty basic blocks
785such that the edge is no longer critical.  The pass is located in
786@file{tree-cfg.cc} and is described by @code{pass_split_crit_edges}.
787
788@item Control dependence dead code elimination
789
790This pass is a stronger form of dead code elimination that can
791eliminate unnecessary control flow statements.   It is located
792in @file{tree-ssa-dce.cc} and is described by @code{pass_cd_dce}.
793
794@item Tail call elimination
795
796This pass identifies function calls that may be rewritten into
797jumps.  No code transformation is actually applied here, but the
798data and control flow problem is solved.  The code transformation
799requires target support, and so is delayed until RTL@.  In the
800meantime @code{CALL_EXPR_TAILCALL} is set indicating the possibility.
801The pass is located in @file{tree-tailcall.cc} and is described by
802@code{pass_tail_calls}.  The RTL transformation is handled by
803@code{fixup_tail_calls} in @file{calls.cc}.
804
805@item Warn for function return without value
806
807For non-void functions, this pass locates return statements that do
808not specify a value and issues a warning.  Such a statement may have
809been injected by falling off the end of the function.  This pass is
810run last so that we have as much time as possible to prove that the
811statement is not reachable.  It is located in @file{tree-cfg.cc} and
812is described by @code{pass_warn_function_return}.
813
814@item Leave static single assignment form
815
816This pass rewrites the function such that it is in normal form.  At
817the same time, we eliminate as many single-use temporaries as possible,
818so the intermediate language is no longer GIMPLE, but GENERIC@.  The
819pass is located in @file{tree-outof-ssa.cc} and is described by
820@code{pass_del_ssa}.
821
822@item Merge PHI nodes that feed into one another
823
824This is part of the CFG cleanup passes.  It attempts to join PHI nodes
825from a forwarder CFG block into another block with PHI nodes.  The
826pass is located in @file{tree-cfgcleanup.cc} and is described by
827@code{pass_merge_phi}.
828
829@item Return value optimization
830
831If a function always returns the same local variable, and that local
832variable is an aggregate type, then the variable is replaced with the
833return value for the function (i.e., the function's DECL_RESULT).  This
834is equivalent to the C++ named return value optimization applied to
835GIMPLE@.  The pass is located in @file{tree-nrv.cc} and is described by
836@code{pass_nrv}.
837
838@item Return slot optimization
839
840If a function returns a memory object and is called as @code{var =
841foo()}, this pass tries to change the call so that the address of
842@code{var} is sent to the caller to avoid an extra memory copy.  This
843pass is located in @code{tree-nrv.cc} and is described by
844@code{pass_return_slot}.
845
846@item Optimize calls to @code{__builtin_object_size}
847
848This is a propagation pass similar to CCP that tries to remove calls
849to @code{__builtin_object_size} when the size of the object can be
850computed at compile-time.  This pass is located in
851@file{tree-object-size.cc} and is described by
852@code{pass_object_sizes}.
853
854@item Loop invariant motion
855
856This pass removes expensive loop-invariant computations out of loops.
857The pass is located in @file{tree-ssa-loop.cc} and described by
858@code{pass_lim}.
859
860@item Loop nest optimizations
861
862This is a family of loop transformations that works on loop nests.  It
863includes loop interchange, scaling, skewing and reversal and they are
864all geared to the optimization of data locality in array traversals
865and the removal of dependencies that hamper optimizations such as loop
866parallelization and vectorization.  The pass is located in
867@file{tree-loop-linear.c} and described by
868@code{pass_linear_transform}.
869
870@item Removal of empty loops
871
872This pass removes loops with no code in them.  The pass is located in
873@file{tree-ssa-loop-ivcanon.cc} and described by
874@code{pass_empty_loop}.
875
876@item Unrolling of small loops
877
878This pass completely unrolls loops with few iterations.  The pass
879is located in @file{tree-ssa-loop-ivcanon.cc} and described by
880@code{pass_complete_unroll}.
881
882@item Predictive commoning
883
884This pass makes the code reuse the computations from the previous
885iterations of the loops, especially loads and stores to memory.
886It does so by storing the values of these computations to a bank
887of temporary variables that are rotated at the end of loop.  To avoid
888the need for this rotation, the loop is then unrolled and the copies
889of the loop body are rewritten to use the appropriate version of
890the temporary variable.  This pass is located in @file{tree-predcom.cc}
891and described by @code{pass_predcom}.
892
893@item Array prefetching
894
895This pass issues prefetch instructions for array references inside
896loops.  The pass is located in @file{tree-ssa-loop-prefetch.cc} and
897described by @code{pass_loop_prefetch}.
898
899@item Reassociation
900
901This pass rewrites arithmetic expressions to enable optimizations that
902operate on them, like redundancy elimination and vectorization.  The
903pass is located in @file{tree-ssa-reassoc.cc} and described by
904@code{pass_reassoc}.
905
906@item Optimization of @code{stdarg} functions
907
908This pass tries to avoid the saving of register arguments into the
909stack on entry to @code{stdarg} functions.  If the function doesn't
910use any @code{va_start} macros, no registers need to be saved.  If
911@code{va_start} macros are used, the @code{va_list} variables don't
912escape the function, it is only necessary to save registers that will
913be used in @code{va_arg} macros.  For instance, if @code{va_arg} is
914only used with integral types in the function, floating point
915registers don't need to be saved.  This pass is located in
916@code{tree-stdarg.cc} and described by @code{pass_stdarg}.
917
918@end itemize
919
920@node RTL passes
921@section RTL passes
922
923The following briefly describes the RTL generation and optimization
924passes that are run after the Tree optimization passes.
925
926@itemize @bullet
927@item RTL generation
928
929@c Avoiding overfull is tricky here.
930The source files for RTL generation include
931@file{stmt.cc},
932@file{calls.cc},
933@file{expr.cc},
934@file{explow.cc},
935@file{expmed.cc},
936@file{function.cc},
937@file{optabs.cc}
938and @file{emit-rtl.cc}.
939Also, the file
940@file{insn-emit.cc}, generated from the machine description by the
941program @code{genemit}, is used in this pass.  The header file
942@file{expr.h} is used for communication within this pass.
943
944@findex genflags
945@findex gencodes
946The header files @file{insn-flags.h} and @file{insn-codes.h},
947generated from the machine description by the programs @code{genflags}
948and @code{gencodes}, tell this pass which standard names are available
949for use and which patterns correspond to them.
950
951@item Generation of exception landing pads
952
953This pass generates the glue that handles communication between the
954exception handling library routines and the exception handlers within
955the function.  Entry points in the function that are invoked by the
956exception handling library are called @dfn{landing pads}.  The code
957for this pass is located in @file{except.cc}.
958
959@item Control flow graph cleanup
960
961This pass removes unreachable code, simplifies jumps to next, jumps to
962jump, jumps across jumps, etc.  The pass is run multiple times.
963For historical reasons, it is occasionally referred to as the ``jump
964optimization pass''.  The bulk of the code for this pass is in
965@file{cfgcleanup.cc}, and there are support routines in @file{cfgrtl.cc}
966and @file{jump.cc}.
967
968@item Forward propagation of single-def values
969
970This pass attempts to remove redundant computation by substituting
971variables that come from a single definition, and
972seeing if the result can be simplified.  It performs copy propagation
973and addressing mode selection.  The pass is run twice, with values
974being propagated into loops only on the second run.  The code is
975located in @file{fwprop.cc}.
976
977@item Common subexpression elimination
978
979This pass removes redundant computation within basic blocks, and
980optimizes addressing modes based on cost.  The pass is run twice.
981The code for this pass is located in @file{cse.cc}.
982
983@item Global common subexpression elimination
984
985This pass performs two
986different types of GCSE  depending on whether you are optimizing for
987size or not (LCM based GCSE tends to increase code size for a gain in
988speed, while Morel-Renvoise based GCSE does not).
989When optimizing for size, GCSE is done using Morel-Renvoise Partial
990Redundancy Elimination, with the exception that it does not try to move
991invariants out of loops---that is left to  the loop optimization pass.
992If MR PRE GCSE is done, code hoisting (aka unification) is also done, as
993well as load motion.
994If you are optimizing for speed, LCM (lazy code motion) based GCSE is
995done.  LCM is based on the work of Knoop, Ruthing, and Steffen.  LCM
996based GCSE also does loop invariant code motion.  We also perform load
997and store motion when optimizing for speed.
998Regardless of which type of GCSE is used, the GCSE pass also performs
999global constant and  copy propagation.
1000The source file for this pass is @file{gcse.cc}, and the LCM routines
1001are in @file{lcm.cc}.
1002
1003@item Loop optimization
1004
1005This pass performs several loop related optimizations.
1006The source files @file{cfgloopanal.cc} and @file{cfgloopmanip.cc} contain
1007generic loop analysis and manipulation code.  Initialization and finalization
1008of loop structures is handled by @file{loop-init.cc}.
1009A loop invariant motion pass is implemented in @file{loop-invariant.cc}.
1010Basic block level optimizations---unrolling, and peeling loops---
1011are implemented in @file{loop-unroll.cc}.
1012Replacing of the exit condition of loops by special machine-dependent
1013instructions is handled by @file{loop-doloop.cc}.
1014
1015@item Jump bypassing
1016
1017This pass is an aggressive form of GCSE that transforms the control
1018flow graph of a function by propagating constants into conditional
1019branch instructions.  The source file for this pass is @file{gcse.cc}.
1020
1021@item If conversion
1022
1023This pass attempts to replace conditional branches and surrounding
1024assignments with arithmetic, boolean value producing comparison
1025instructions, and conditional move instructions.  In the very last
1026invocation after reload/LRA, it will generate predicated instructions
1027when supported by the target.  The code is located in @file{ifcvt.cc}.
1028
1029@item Web construction
1030
1031This pass splits independent uses of each pseudo-register.  This can
1032improve effect of the other transformation, such as CSE or register
1033allocation.  The code for this pass is located in @file{web.cc}.
1034
1035@item Instruction combination
1036
1037This pass attempts to combine groups of two or three instructions that
1038are related by data flow into single instructions.  It combines the
1039RTL expressions for the instructions by substitution, simplifies the
1040result using algebra, and then attempts to match the result against
1041the machine description.  The code is located in @file{combine.cc}.
1042
1043@item Mode switching optimization
1044
1045This pass looks for instructions that require the processor to be in a
1046specific ``mode'' and minimizes the number of mode changes required to
1047satisfy all users.  What these modes are, and what they apply to are
1048completely target-specific.  The code for this pass is located in
1049@file{mode-switching.cc}.
1050
1051@cindex modulo scheduling
1052@cindex sms, swing, software pipelining
1053@item Modulo scheduling
1054
1055This pass looks at innermost loops and reorders their instructions
1056by overlapping different iterations.  Modulo scheduling is performed
1057immediately before instruction scheduling.  The code for this pass is
1058located in @file{modulo-sched.cc}.
1059
1060@item Instruction scheduling
1061
1062This pass looks for instructions whose output will not be available by
1063the time that it is used in subsequent instructions.  Memory loads and
1064floating point instructions often have this behavior on RISC machines.
1065It re-orders instructions within a basic block to try to separate the
1066definition and use of items that otherwise would cause pipeline
1067stalls.  This pass is performed twice, before and after register
1068allocation.  The code for this pass is located in @file{haifa-sched.cc},
1069@file{sched-deps.cc}, @file{sched-ebb.cc}, @file{sched-rgn.cc} and
1070@file{sched-vis.c}.
1071
1072@item Register allocation
1073
1074These passes make sure that all occurrences of pseudo registers are
1075eliminated, either by allocating them to a hard register, replacing
1076them by an equivalent expression (e.g.@: a constant) or by placing
1077them on the stack.  This is done in several subpasses:
1078
1079@itemize @bullet
1080@item
1081The integrated register allocator (@acronym{IRA}).  It is called
1082integrated because coalescing, register live range splitting, and hard
1083register preferencing are done on-the-fly during coloring.  It also
1084has better integration with the reload/LRA pass.  Pseudo-registers spilled
1085by the allocator or the reload/LRA have still a chance to get
1086hard-registers if the reload/LRA evicts some pseudo-registers from
1087hard-registers.  The allocator helps to choose better pseudos for
1088spilling based on their live ranges and to coalesce stack slots
1089allocated for the spilled pseudo-registers.  IRA is a regional
1090register allocator which is transformed into Chaitin-Briggs allocator
1091if there is one region.  By default, IRA chooses regions using
1092register pressure but the user can force it to use one region or
1093regions corresponding to all loops.
1094
1095Source files of the allocator are @file{ira.cc}, @file{ira-build.cc},
1096@file{ira-costs.cc}, @file{ira-conflicts.cc}, @file{ira-color.cc},
1097@file{ira-emit.cc}, @file{ira-lives}, plus header files @file{ira.h}
1098and @file{ira-int.h} used for the communication between the allocator
1099and the rest of the compiler and between the IRA files.
1100
1101@cindex reloading
1102@item
1103Reloading.  This pass renumbers pseudo registers with the hardware
1104registers numbers they were allocated.  Pseudo registers that did not
1105get hard registers are replaced with stack slots.  Then it finds
1106instructions that are invalid because a value has failed to end up in
1107a register, or has ended up in a register of the wrong kind.  It fixes
1108up these instructions by reloading the problematical values
1109temporarily into registers.  Additional instructions are generated to
1110do the copying.
1111
1112The reload pass also optionally eliminates the frame pointer and inserts
1113instructions to save and restore call-clobbered registers around calls.
1114
1115Source files are @file{reload.cc} and @file{reload1.cc}, plus the header
1116@file{reload.h} used for communication between them.
1117
1118@cindex Local Register Allocator (LRA)
1119@item
1120This pass is a modern replacement of the reload pass.  Source files
1121are @file{lra.cc}, @file{lra-assign.c}, @file{lra-coalesce.cc},
1122@file{lra-constraints.cc}, @file{lra-eliminations.cc},
1123@file{lra-lives.cc}, @file{lra-remat.cc}, @file{lra-spills.cc}, the
1124header @file{lra-int.h} used for communication between them, and the
1125header @file{lra.h} used for communication between LRA and the rest of
1126compiler.
1127
1128Unlike the reload pass, intermediate LRA decisions are reflected in
1129RTL as much as possible.  This reduces the number of target-dependent
1130macros and hooks, leaving instruction constraints as the primary
1131source of control.
1132
1133LRA is run on targets for which TARGET_LRA_P returns true.
1134@end itemize
1135
1136@item Basic block reordering
1137
1138This pass implements profile guided code positioning.  If profile
1139information is not available, various types of static analysis are
1140performed to make the predictions normally coming from the profile
1141feedback (IE execution frequency, branch probability, etc).  It is
1142implemented in the file @file{bb-reorder.cc}, and the various
1143prediction routines are in @file{predict.cc}.
1144
1145@item Variable tracking
1146
1147This pass computes where the variables are stored at each
1148position in code and generates notes describing the variable locations
1149to RTL code.  The location lists are then generated according to these
1150notes to debug information if the debugging information format supports
1151location lists.  The code is located in @file{var-tracking.cc}.
1152
1153@item Delayed branch scheduling
1154
1155This optional pass attempts to find instructions that can go into the
1156delay slots of other instructions, usually jumps and calls.  The code
1157for this pass is located in @file{reorg.cc}.
1158
1159@item Branch shortening
1160
1161On many RISC machines, branch instructions have a limited range.
1162Thus, longer sequences of instructions must be used for long branches.
1163In this pass, the compiler figures out what how far each instruction
1164will be from each other instruction, and therefore whether the usual
1165instructions, or the longer sequences, must be used for each branch.
1166The code for this pass is located in @file{final.cc}.
1167
1168@item Register-to-stack conversion
1169
1170Conversion from usage of some hard registers to usage of a register
1171stack may be done at this point.  Currently, this is supported only
1172for the floating-point registers of the Intel 80387 coprocessor.  The
1173code for this pass is located in @file{reg-stack.cc}.
1174
1175@item Final
1176
1177This pass outputs the assembler code for the function.  The source files
1178are @file{final.cc} plus @file{insn-output.cc}; the latter is generated
1179automatically from the machine description by the tool @file{genoutput}.
1180The header file @file{conditions.h} is used for communication between
1181these files.
1182
1183@item Debugging information output
1184
1185This is run after final because it must output the stack slot offsets
1186for pseudo registers that did not get hard registers.  Source files
1187are @file{dbxout.cc} for DBX symbol table format, @file{dwarfout.c} for
1188DWARF symbol table format, files @file{dwarf2out.cc} and @file{dwarf2asm.cc}
1189for DWARF2 symbol table format, and @file{vmsdbgout.cc} for VMS debug
1190symbol table format.
1191
1192@end itemize
1193
1194@node Optimization info
1195@section Optimization info
1196@include optinfo.texi
1197