blob: ed721666638f3dd889b7dc91d310870523918642 [file] [log] [blame]
Dmitri Gribenkoe4b3e942012-12-11 15:29:37 +00001..
2 If Passes.html is up to date, the following "one-liner" should print
3 an empty diff.
4
5 egrep -e '^<tr><td><a href="#.*">-.*</a></td><td>.*</td></tr>$' \
6 -e '^ <a name=".*">.*</a>$' < Passes.html >html; \
7 perl >help <<'EOT' && diff -u help html; rm -f help html
8 open HTML, "<Passes.html" or die "open: Passes.html: $!\n";
9 while (<HTML>) {
10 m:^<tr><td><a href="#(.*)">-.*</a></td><td>.*</td></tr>$: or next;
11 $order{$1} = sprintf("%03d", 1 + int %order);
12 }
13 open HELP, "../Release/bin/opt -help|" or die "open: opt -help: $!\n";
14 while (<HELP>) {
15 m:^ -([^ ]+) +- (.*)$: or next;
16 my $o = $order{$1};
17 $o = "000" unless defined $o;
18 push @x, "$o<tr><td><a href=\"#$1\">-$1</a></td><td>$2</td></tr>\n";
19 push @y, "$o <a name=\"$1\">-$1: $2</a>\n";
20 }
21 @x = map { s/^\d\d\d//; $_ } sort @x;
22 @y = map { s/^\d\d\d//; $_ } sort @y;
23 print @x, @y;
24 EOT
25
26 This (real) one-liner can also be helpful when converting comments to HTML:
27
28 perl -e '$/ = undef; for (split(/\n/, <>)) { s:^ *///? ?::; print " <p>\n" if !$on && $_ =~ /\S/; print " </p>\n" if $on && $_ =~ /^\s*$/; print " $_\n"; $on = ($_ =~ /\S/); } print " </p>\n" if $on'
29
30====================================
31LLVM's Analysis and Transform Passes
32====================================
33
34.. contents::
35 :local:
36
37Written by `Reid Spencer <mailto:rspencer@x10sys.com>`_
38 and Gordon Henriksen
39
40Introduction
41============
42
43This document serves as a high level summary of the optimization features that
44LLVM provides. Optimizations are implemented as Passes that traverse some
45portion of a program to either collect information or transform the program.
46The table below divides the passes that LLVM provides into three categories.
47Analysis passes compute information that other passes can use or for debugging
48or program visualization purposes. Transform passes can use (or invalidate)
49the analysis passes. Transform passes all mutate the program in some way.
50Utility passes provides some utility but don't otherwise fit categorization.
51For example passes to extract functions to bitcode or write a module to bitcode
52are neither analysis nor transform passes. The table of contents above
53provides a quick summary of each pass and links to the more complete pass
54description later in the document.
55
56Analysis Passes
57===============
58
59This section describes the LLVM Analysis Passes.
60
61``-aa-eval``: Exhaustive Alias Analysis Precision Evaluator
62-----------------------------------------------------------
63
64This is a simple N^2 alias analysis accuracy evaluator. Basically, for each
65function in the program, it simply queries to see how the alias analysis
66implementation answers alias queries between each pair of pointers in the
67function.
68
69This is inspired and adapted from code by: Naveen Neelakantam, Francesco
70Spadini, and Wojciech Stryjewski.
71
72``-basicaa``: Basic Alias Analysis (stateless AA impl)
73------------------------------------------------------
74
75A basic alias analysis pass that implements identities (two different globals
76cannot alias, etc), but does no stateful analysis.
77
78``-basiccg``: Basic CallGraph Construction
79------------------------------------------
80
81Yet to be written.
82
83``-count-aa``: Count Alias Analysis Query Responses
84---------------------------------------------------
85
86A pass which can be used to count how many alias queries are being made and how
87the alias analysis implementation being used responds.
88
89``-da``: Dependence Analysis
90----------------------------
91
92Dependence analysis framework, which is used to detect dependences in memory
93accesses.
94
95``-debug-aa``: AA use debugger
96------------------------------
97
98This simple pass checks alias analysis users to ensure that if they create a
99new value, they do not query AA without informing it of the value. It acts as
100a shim over any other AA pass you want.
101
102Yes keeping track of every value in the program is expensive, but this is a
103debugging pass.
104
105``-domfrontier``: Dominance Frontier Construction
106-------------------------------------------------
107
108This pass is a simple dominator construction algorithm for finding forward
109dominator frontiers.
110
111``-domtree``: Dominator Tree Construction
112-----------------------------------------
113
114This pass is a simple dominator construction algorithm for finding forward
115dominators.
116
117
118``-dot-callgraph``: Print Call Graph to "dot" file
119--------------------------------------------------
120
121This pass, only available in ``opt``, prints the call graph into a ``.dot``
122graph. This graph can then be processed with the "dot" tool to convert it to
123postscript or some other suitable format.
124
125``-dot-cfg``: Print CFG of function to "dot" file
126-------------------------------------------------
127
128This pass, only available in ``opt``, prints the control flow graph into a
129``.dot`` graph. This graph can then be processed with the :program:`dot` tool
130to convert it to postscript or some other suitable format.
131
132``-dot-cfg-only``: Print CFG of function to "dot" file (with no function bodies)
133--------------------------------------------------------------------------------
134
135This pass, only available in ``opt``, prints the control flow graph into a
136``.dot`` graph, omitting the function bodies. This graph can then be processed
137with the :program:`dot` tool to convert it to postscript or some other suitable
138format.
139
140``-dot-dom``: Print dominance tree of function to "dot" file
141------------------------------------------------------------
142
143This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
144graph. This graph can then be processed with the :program:`dot` tool to
145convert it to postscript or some other suitable format.
146
147``-dot-dom-only``: Print dominance tree of function to "dot" file (with no function bodies)
148-------------------------------------------------------------------------------------------
149
150This pass, only available in ``opt``, prints the dominator tree into a ``.dot``
151graph, omitting the function bodies. This graph can then be processed with the
152:program:`dot` tool to convert it to postscript or some other suitable format.
153
154``-dot-postdom``: Print postdominance tree of function to "dot" file
155--------------------------------------------------------------------
156
157This pass, only available in ``opt``, prints the post dominator tree into a
158``.dot`` graph. This graph can then be processed with the :program:`dot` tool
159to convert it to postscript or some other suitable format.
160
161``-dot-postdom-only``: Print postdominance tree of function to "dot" file (with no function bodies)
162---------------------------------------------------------------------------------------------------
163
164This pass, only available in ``opt``, prints the post dominator tree into a
165``.dot`` graph, omitting the function bodies. This graph can then be processed
166with the :program:`dot` tool to convert it to postscript or some other suitable
167format.
168
169``-globalsmodref-aa``: Simple mod/ref analysis for globals
170----------------------------------------------------------
171
172This simple pass provides alias and mod/ref information for global values that
173do not have their address taken, and keeps track of whether functions read or
174write memory (are "pure"). For this simple (but very common) case, we can
175provide pretty accurate and useful information.
176
177``-instcount``: Counts the various types of ``Instruction``\ s
178--------------------------------------------------------------
179
180This pass collects the count of all instructions and reports them.
181
182``-intervals``: Interval Partition Construction
183-----------------------------------------------
184
185This analysis calculates and represents the interval partition of a function,
186or a preexisting interval partition.
187
188In this way, the interval partition may be used to reduce a flow graph down to
189its degenerate single node interval partition (unless it is irreducible).
190
191``-iv-users``: Induction Variable Users
192---------------------------------------
193
194Bookkeeping for "interesting" users of expressions computed from induction
195variables.
196
197``-lazy-value-info``: Lazy Value Information Analysis
198-----------------------------------------------------
199
200Interface for lazy computation of value constraint information.
201
202``-libcall-aa``: LibCall Alias Analysis
203---------------------------------------
204
205LibCall Alias Analysis.
206
207``-lint``: Statically lint-checks LLVM IR
208-----------------------------------------
209
210This pass statically checks for common and easily-identified constructs which
211produce undefined or likely unintended behavior in LLVM IR.
212
213It is not a guarantee of correctness, in two ways. First, it isn't
214comprehensive. There are checks which could be done statically which are not
215yet implemented. Some of these are indicated by TODO comments, but those
216aren't comprehensive either. Second, many conditions cannot be checked
217statically. This pass does no dynamic instrumentation, so it can't check for
218all possible problems.
219
220Another limitation is that it assumes all code will be executed. A store
221through a null pointer in a basic block which is never reached is harmless, but
222this pass will warn about it anyway.
223
224Optimization passes may make conditions that this pass checks for more or less
225obvious. If an optimization pass appears to be introducing a warning, it may
226be that the optimization pass is merely exposing an existing condition in the
227code.
228
229This code may be run before :ref:`instcombine <passes-instcombine>`. In many
230cases, instcombine checks for the same kinds of things and turns instructions
231with undefined behavior into unreachable (or equivalent). Because of this,
232this pass makes some effort to look through bitcasts and so on.
233
234``-loops``: Natural Loop Information
235------------------------------------
236
237This analysis is used to identify natural loops and determine the loop depth of
238various nodes of the CFG. Note that the loops identified may actually be
239several natural loops that share the same header node... not just a single
240natural loop.
241
242``-memdep``: Memory Dependence Analysis
243---------------------------------------
244
245An analysis that determines, for a given memory operation, what preceding
246memory operations it depends on. It builds on alias analysis information, and
247tries to provide a lazy, caching interface to a common kind of alias
248information query.
249
250``-module-debuginfo``: Decodes module-level debug info
251------------------------------------------------------
252
253This pass decodes the debug info metadata in a module and prints in a
254(sufficiently-prepared-) human-readable form.
255
256For example, run this pass from ``opt`` along with the ``-analyze`` option, and
257it'll print to standard output.
258
259``-no-aa``: No Alias Analysis (always returns 'may' alias)
260----------------------------------------------------------
261
262This is the default implementation of the Alias Analysis interface. It always
263returns "I don't know" for alias queries. NoAA is unlike other alias analysis
264implementations, in that it does not chain to a previous analysis. As such it
265doesn't follow many of the rules that other alias analyses must.
266
267``-no-profile``: No Profile Information
268---------------------------------------
269
270The default "no profile" implementation of the abstract ``ProfileInfo``
271interface.
272
273``-postdomfrontier``: Post-Dominance Frontier Construction
274----------------------------------------------------------
275
276This pass is a simple post-dominator construction algorithm for finding
277post-dominator frontiers.
278
279``-postdomtree``: Post-Dominator Tree Construction
280--------------------------------------------------
281
282This pass is a simple post-dominator construction algorithm for finding
283post-dominators.
284
285``-print-alias-sets``: Alias Set Printer
286----------------------------------------
287
288Yet to be written.
289
290``-print-callgraph``: Print a call graph
291----------------------------------------
292
293This pass, only available in ``opt``, prints the call graph to standard error
294in a human-readable form.
295
296``-print-callgraph-sccs``: Print SCCs of the Call Graph
297-------------------------------------------------------
298
299This pass, only available in ``opt``, prints the SCCs of the call graph to
300standard error in a human-readable form.
301
302``-print-cfg-sccs``: Print SCCs of each function CFG
303----------------------------------------------------
304
305This pass, only available in ``opt``, printsthe SCCs of each function CFG to
306standard error in a human-readable fom.
307
308``-print-dbginfo``: Print debug info in human readable form
309-----------------------------------------------------------
310
311Pass that prints instructions, and associated debug info:
312
313#. source/line/col information
314#. original variable name
315#. original type name
316
317``-print-dom-info``: Dominator Info Printer
318-------------------------------------------
319
320Dominator Info Printer.
321
322``-print-externalfnconstants``: Print external fn callsites passed constants
323----------------------------------------------------------------------------
324
325This pass, only available in ``opt``, prints out call sites to external
326functions that are called with constant arguments. This can be useful when
327looking for standard library functions we should constant fold or handle in
328alias analyses.
329
330``-print-function``: Print function to stderr
331---------------------------------------------
332
333The ``PrintFunctionPass`` class is designed to be pipelined with other
334``FunctionPasses``, and prints out the functions of the module as they are
335processed.
336
337``-print-module``: Print module to stderr
338-----------------------------------------
339
340This pass simply prints out the entire module when it is executed.
341
342.. _passes-print-used-types:
343
344``-print-used-types``: Find Used Types
345--------------------------------------
346
347This pass is used to seek out all of the types in use by the program. Note
348that this analysis explicitly does not include types only used by the symbol
349table.
350
351``-profile-estimator``: Estimate profiling information
352------------------------------------------------------
353
354Profiling information that estimates the profiling information in a very crude
355and unimaginative way.
356
357``-profile-loader``: Load profile information from ``llvmprof.out``
358-------------------------------------------------------------------
359
360A concrete implementation of profiling information that loads the information
361from a profile dump file.
362
363``-profile-verifier``: Verify profiling information
364---------------------------------------------------
365
366Pass that checks profiling information for plausibility.
367
368``-regions``: Detect single entry single exit regions
369-----------------------------------------------------
370
371The ``RegionInfo`` pass detects single entry single exit regions in a function,
372where a region is defined as any subgraph that is connected to the remaining
373graph at only two spots. Furthermore, an hierarchical region tree is built.
374
375``-scalar-evolution``: Scalar Evolution Analysis
376------------------------------------------------
377
378The ``ScalarEvolution`` analysis can be used to analyze and catagorize scalar
379expressions in loops. It specializes in recognizing general induction
380variables, representing them with the abstract and opaque ``SCEV`` class.
381Given this analysis, trip counts of loops and other important properties can be
382obtained.
383
384This analysis is primarily useful for induction variable substitution and
385strength reduction.
386
387``-scev-aa``: ScalarEvolution-based Alias Analysis
388--------------------------------------------------
389
390Simple alias analysis implemented in terms of ``ScalarEvolution`` queries.
391
392This differs from traditional loop dependence analysis in that it tests for
393dependencies within a single iteration of a loop, rather than dependencies
394between different iterations.
395
396``ScalarEvolution`` has a more complete understanding of pointer arithmetic
397than ``BasicAliasAnalysis``' collection of ad-hoc analyses.
398
399``-targetdata``: Target Data Layout
400-----------------------------------
401
402Provides other passes access to information on how the size and alignment
403required by the target ABI for various data types.
404
405Transform Passes
406================
407
408This section describes the LLVM Transform Passes.
409
410``-adce``: Aggressive Dead Code Elimination
411-------------------------------------------
412
413ADCE aggressively tries to eliminate code. This pass is similar to :ref:`DCE
414<passes-dce>` but it assumes that values are dead until proven otherwise. This
415is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of
416values.
417
418``-always-inline``: Inliner for ``always_inline`` functions
419-----------------------------------------------------------
420
421A custom inliner that handles only functions that are marked as "always
422inline".
423
424``-argpromotion``: Promote 'by reference' arguments to scalars
425--------------------------------------------------------------
426
427This pass promotes "by reference" arguments to be "by value" arguments. In
428practice, this means looking for internal functions that have pointer
429arguments. If it can prove, through the use of alias analysis, that an
430argument is *only* loaded, then it can pass the value into the function instead
431of the address of the value. This can cause recursive simplification of code
432and lead to the elimination of allocas (especially in C++ template code like
433the STL).
434
435This pass also handles aggregate arguments that are passed into a function,
436scalarizing them if the elements of the aggregate are only loaded. Note that
437it refuses to scalarize aggregates which would require passing in more than
438three operands to the function, because passing thousands of operands for a
439large array or structure is unprofitable!
440
441Note that this transformation could also be done for arguments that are only
442stored to (returning the value instead), but does not currently. This case
443would be best handled when and if LLVM starts supporting multiple return values
444from functions.
445
446``-bb-vectorize``: Basic-Block Vectorization
447--------------------------------------------
448
449This pass combines instructions inside basic blocks to form vector
450instructions. It iterates over each basic block, attempting to pair compatible
451instructions, repeating this process until no additional pairs are selected for
452vectorization. When the outputs of some pair of compatible instructions are
453used as inputs by some other pair of compatible instructions, those pairs are
454part of a potential vectorization chain. Instruction pairs are only fused into
455vector instructions when they are part of a chain longer than some threshold
456length. Moreover, the pass attempts to find the best possible chain for each
457pair of compatible instructions. These heuristics are intended to prevent
458vectorization in cases where it would not yield a performance increase of the
459resulting code.
460
461``-block-placement``: Profile Guided Basic Block Placement
462----------------------------------------------------------
463
464This pass is a very simple profile guided basic block placement algorithm. The
465idea is to put frequently executed blocks together at the start of the function
466and hopefully increase the number of fall-through conditional branches. If
467there is no profile information for a particular function, this pass basically
468orders blocks in depth-first order.
469
470``-break-crit-edges``: Break critical edges in CFG
471--------------------------------------------------
472
473Break all of the critical edges in the CFG by inserting a dummy basic block.
474It may be "required" by passes that cannot deal with critical edges. This
475transformation obviously invalidates the CFG, but can update forward dominator
476(set, immediate dominators, tree, and frontier) information.
477
478``-codegenprepare``: Optimize for code generation
479-------------------------------------------------
480
481This pass munges the code in the input function to better prepare it for
482SelectionDAG-based code generation. This works around limitations in it's
483basic-block-at-a-time approach. It should eventually be removed.
484
485``-constmerge``: Merge Duplicate Global Constants
486-------------------------------------------------
487
488Merges duplicate global constants together into a single constant that is
489shared. This is useful because some passes (i.e., TraceValues) insert a lot of
490string constants into the program, regardless of whether or not an existing
491string is available.
492
493``-constprop``: Simple constant propagation
494-------------------------------------------
495
496This file implements constant propagation and merging. It looks for
497instructions involving only constant operands and replaces them with a constant
498value instead of an instruction. For example:
499
500.. code-block:: llvm
501
502 add i32 1, 2
503
504becomes
505
506.. code-block:: llvm
507
508 i32 3
509
510NOTE: this pass has a habit of making definitions be dead. It is a good idea
511to to run a :ref:`Dead Instruction Elimination <passes-die>` pass sometime
512after running this pass.
513
514.. _passes-dce:
515
516``-dce``: Dead Code Elimination
517-------------------------------
518
519Dead code elimination is similar to :ref:`dead instruction elimination
520<passes-die>`, but it rechecks instructions that were used by removed
521instructions to see if they are newly dead.
522
523``-deadargelim``: Dead Argument Elimination
524-------------------------------------------
525
526This pass deletes dead arguments from internal functions. Dead argument
527elimination removes arguments which are directly dead, as well as arguments
528only passed into function calls as dead arguments of other functions. This
529pass also deletes dead arguments in a similar way.
530
531This pass is often useful as a cleanup pass to run after aggressive
532interprocedural passes, which add possibly-dead arguments.
533
534``-deadtypeelim``: Dead Type Elimination
535----------------------------------------
536
537This pass is used to cleanup the output of GCC. It eliminate names for types
538that are unused in the entire translation unit, using the :ref:`find used types
539<passes-print-used-types>` pass.
540
541.. _passes-die:
542
543``-die``: Dead Instruction Elimination
544--------------------------------------
545
546Dead instruction elimination performs a single pass over the function, removing
547instructions that are obviously dead.
548
549``-dse``: Dead Store Elimination
550--------------------------------
551
552A trivial dead store elimination that only considers basic-block local
553redundant stores.
554
555``-functionattrs``: Deduce function attributes
556----------------------------------------------
557
558A simple interprocedural pass which walks the call-graph, looking for functions
559which do not access or only read non-local memory, and marking them
560``readnone``/``readonly``. In addition, it marks function arguments (of
561pointer type) "``nocapture``" if a call to the function does not create any
562copies of the pointer value that outlive the call. This more or less means
563that the pointer is only dereferenced, and not returned from the function or
564stored in a global. This pass is implemented as a bottom-up traversal of the
565call-graph.
566
567``-globaldce``: Dead Global Elimination
568---------------------------------------
569
570This transform is designed to eliminate unreachable internal globals from the
571program. It uses an aggressive algorithm, searching out globals that are known
572to be alive. After it finds all of the globals which are needed, it deletes
573whatever is left over. This allows it to delete recursive chunks of the
574program which are unreachable.
575
576``-globalopt``: Global Variable Optimizer
577-----------------------------------------
578
579This pass transforms simple global variables that never have their address
580taken. If obviously true, it marks read/write globals as constant, deletes
581variables only stored to, etc.
582
583``-gvn``: Global Value Numbering
584--------------------------------
585
586This pass performs global value numbering to eliminate fully and partially
587redundant instructions. It also performs redundant load elimination.
588
589.. _passes-indvars:
590
591``-indvars``: Canonicalize Induction Variables
592----------------------------------------------
593
594This transformation analyzes and transforms the induction variables (and
595computations derived from them) into simpler forms suitable for subsequent
596analysis and transformation.
597
598This transformation makes the following changes to each loop with an
599identifiable induction variable:
600
601* All loops are transformed to have a *single* canonical induction variable
602 which starts at zero and steps by one.
603* The canonical induction variable is guaranteed to be the first PHI node in
604 the loop header block.
605* Any pointer arithmetic recurrences are raised to use array subscripts.
606
607If the trip count of a loop is computable, this pass also makes the following
608changes:
609
610* The exit condition for the loop is canonicalized to compare the induction
611 value against the exit value. This turns loops like:
612
613 .. code-block:: c++
614
615 for (i = 7; i*i < 1000; ++i)
616
617 into
618
619 .. code-block:: c++
620
621 for (i = 0; i != 25; ++i)
622
623* Any use outside of the loop of an expression derived from the indvar is
624 changed to compute the derived value outside of the loop, eliminating the
625 dependence on the exit value of the induction variable. If the only purpose
626 of the loop is to compute the exit value of some derived expression, this
627 transformation will make the loop dead.
628
629This transformation should be followed by strength reduction after all of the
630desired loop transformations have been performed. Additionally, on targets
631where it is profitable, the loop could be transformed to count down to zero
632(the "do loop" optimization).
633
634``-inline``: Function Integration/Inlining
635------------------------------------------
636
637Bottom-up inlining of functions into callees.
638
639``-insert-edge-profiling``: Insert instrumentation for edge profiling
640---------------------------------------------------------------------
641
642This pass instruments the specified program with counters for edge profiling.
643Edge profiling can give a reasonable approximation of the hot paths through a
644program, and is used for a wide variety of program transformations.
645
646Note that this implementation is very naïve. It inserts a counter for *every*
647edge in the program, instead of using control flow information to prune the
648number of counters inserted.
649
650``-insert-optimal-edge-profiling``: Insert optimal instrumentation for edge profiling
651-------------------------------------------------------------------------------------
652
653This pass instruments the specified program with counters for edge profiling.
654Edge profiling can give a reasonable approximation of the hot paths through a
655program, and is used for a wide variety of program transformations.
656
657.. _passes-instcombine:
658
659``-instcombine``: Combine redundant instructions
660------------------------------------------------
661
662Combine instructions to form fewer, simple instructions. This pass does not
663modify the CFG This pass is where algebraic simplification happens.
664
665This pass combines things like:
666
667.. code-block:: llvm
668
669 %Y = add i32 %X, 1
670 %Z = add i32 %Y, 1
671
672into:
673
674.. code-block:: llvm
675
676 %Z = add i32 %X, 2
677
678This is a simple worklist driven algorithm.
679
680This pass guarantees that the following canonicalizations are performed on the
681program:
682
683#. If a binary operator has a constant operand, it is moved to the right-hand
684 side.
685#. Bitwise operators with constant operands are always grouped so that shifts
686 are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s.
687#. Compare instructions are converted from ``<``, ``>``, ``≤``, or ``≥`` to
688 ``=`` or ``≠`` if possible.
689#. All ``cmp`` instructions on boolean values are replaced with logical
690 operations.
691#. ``add X, X`` is represented as ``mul X, 2`` ⇒ ``shl X, 1``
692#. Multiplies with a constant power-of-two argument are transformed into
693 shifts.
694#. … etc.
695
696``-internalize``: Internalize Global Symbols
697--------------------------------------------
698
699This pass loops over all of the functions in the input module, looking for a
700main function. If a main function is found, all other functions and all global
701variables with initializers are marked as internal.
702
703``-ipconstprop``: Interprocedural constant propagation
704------------------------------------------------------
705
706This pass implements an *extremely* simple interprocedural constant propagation
707pass. It could certainly be improved in many different ways, like using a
708worklist. This pass makes arguments dead, but does not remove them. The
709existing dead argument elimination pass should be run after this to clean up
710the mess.
711
712``-ipsccp``: Interprocedural Sparse Conditional Constant Propagation
713--------------------------------------------------------------------
714
715An interprocedural variant of :ref:`Sparse Conditional Constant Propagation
716<passes-sccp>`.
717
718``-jump-threading``: Jump Threading
719-----------------------------------
720
721Jump threading tries to find distinct threads of control flow running through a
722basic block. This pass looks at blocks that have multiple predecessors and
723multiple successors. If one or more of the predecessors of the block can be
724proven to always cause a jump to one of the successors, we forward the edge
725from the predecessor to the successor by duplicating the contents of this
726block.
727
728An example of when this can occur is code like this:
729
730.. code-block:: c++
731
732 if () { ...
733 X = 4;
734 }
735 if (X < 3) {
736
737In this case, the unconditional branch at the end of the first if can be
738revectored to the false side of the second if.
739
740``-lcssa``: Loop-Closed SSA Form Pass
741-------------------------------------
742
743This pass transforms loops by placing phi nodes at the end of the loops for all
744values that are live across the loop boundary. For example, it turns the left
745into the right code:
746
747.. code-block:: c++
748
749 for (...) for (...)
750 if (c) if (c)
751 X1 = ... X1 = ...
752 else else
753 X2 = ... X2 = ...
754 X3 = phi(X1, X2) X3 = phi(X1, X2)
755 ... = X3 + 4 X4 = phi(X3)
756 ... = X4 + 4
757
758This is still valid LLVM; the extra phi nodes are purely redundant, and will be
759trivially eliminated by ``InstCombine``. The major benefit of this
760transformation is that it makes many other loop optimizations, such as
761``LoopUnswitch``\ ing, simpler.
762
763.. _passes-licm:
764
765``-licm``: Loop Invariant Code Motion
766-------------------------------------
767
768This pass performs loop invariant code motion, attempting to remove as much
769code from the body of a loop as possible. It does this by either hoisting code
770into the preheader block, or by sinking code to the exit blocks if it is safe.
771This pass also promotes must-aliased memory locations in the loop to live in
772registers, thus hoisting and sinking "invariant" loads and stores.
773
774This pass uses alias analysis for two purposes:
775
776#. Moving loop invariant loads and calls out of loops. If we can determine
777 that a load or call inside of a loop never aliases anything stored to, we
778 can hoist it or sink it like any other instruction.
779
780#. Scalar Promotion of Memory. If there is a store instruction inside of the
781 loop, we try to move the store to happen AFTER the loop instead of inside of
782 the loop. This can only happen if a few conditions are true:
783
784 #. The pointer stored through is loop invariant.
785 #. There are no stores or loads in the loop which *may* alias the pointer.
786 There are no calls in the loop which mod/ref the pointer.
787
788 If these conditions are true, we can promote the loads and stores in the
789 loop of the pointer to use a temporary alloca'd variable. We then use the
790 :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate
791 SSA form for the variable.
792
793``-loop-deletion``: Delete dead loops
794-------------------------------------
795
796This file implements the Dead Loop Deletion Pass. This pass is responsible for
797eliminating loops with non-infinite computable trip counts that have no side
798effects or volatile instructions, and do not contribute to the computation of
799the function's return value.
800
801.. _passes-loop-extract:
802
803``-loop-extract``: Extract loops into new functions
804---------------------------------------------------
805
806A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract
807each top-level loop into its own new function. If the loop is the *only* loop
808in a given function, it is not touched. This is a pass most useful for
809debugging via bugpoint.
810
811``-loop-extract-single``: Extract at most one loop into a new function
812----------------------------------------------------------------------
813
814Similar to :ref:`Extract loops into new functions <passes-loop-extract>`, this
815pass extracts one natural loop from the program into a function if it can.
816This is used by :program:`bugpoint`.
817
818``-loop-reduce``: Loop Strength Reduction
819-----------------------------------------
820
821This pass performs a strength reduction on array references inside loops that
822have as one or more of their components the loop induction variable. This is
823accomplished by creating a new value to hold the initial value of the array
824access for the first iteration, and then creating a new GEP instruction in the
825loop to increment the value by the appropriate amount.
826
827``-loop-rotate``: Rotate Loops
828------------------------------
829
830A simple loop rotation transformation.
831
832``-loop-simplify``: Canonicalize natural loops
833----------------------------------------------
834
835This pass performs several transformations to transform natural loops into a
836simpler form, which makes subsequent analyses and transformations simpler and
837more effective.
838
839Loop pre-header insertion guarantees that there is a single, non-critical entry
840edge from outside of the loop to the loop header. This simplifies a number of
841analyses and transformations, such as :ref:`LICM <passes-licm>`.
842
843Loop exit-block insertion guarantees that all exit blocks from the loop (blocks
844which are outside of the loop that have predecessors inside of the loop) only
845have predecessors from inside of the loop (and are thus dominated by the loop
846header). This simplifies transformations such as store-sinking that are built
847into LICM.
848
849This pass also guarantees that loops will have exactly one backedge.
850
851Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks
852which are split out but end up being unnecessary, so usage of this pass should
853not pessimize generated code.
854
855This pass obviously modifies the CFG, but updates loop information and
856dominator information.
857
858``-loop-unroll``: Unroll loops
859------------------------------
860
861This pass implements a simple loop unroller. It works best when loops have
862been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to
863determine the trip counts of loops easily.
864
865``-loop-unswitch``: Unswitch loops
866----------------------------------
867
868This pass transforms loops that contain branches on loop-invariant conditions
869to have multiple loops. For example, it turns the left into the right code:
870
871.. code-block:: c++
872
873 for (...) if (lic)
874 A for (...)
875 if (lic) A; B; C
876 B else
877 C for (...)
878 A; C
879
880This can increase the size of the code exponentially (doubling it every time a
881loop is unswitched) so we only unswitch if the resultant code will be smaller
882than a threshold.
883
884This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist
885invariant conditions out of the loop, to make the unswitching opportunity
886obvious.
887
888``-loweratomic``: Lower atomic intrinsics to non-atomic form
889------------------------------------------------------------
890
891This pass lowers atomic intrinsics to non-atomic form for use in a known
892non-preemptible environment.
893
894The pass does not verify that the environment is non-preemptible (in general
895this would require knowledge of the entire call graph of the program including
896any libraries which may not be available in bitcode form); it simply lowers
897every atomic intrinsic.
898
899``-lowerinvoke``: Lower invoke and unwind, for unwindless code generators
900-------------------------------------------------------------------------
901
902This transformation is designed for use by code generators which do not yet
903support stack unwinding. This pass supports two models of exception handling
904lowering, the "cheap" support and the "expensive" support.
905
906"Cheap" exception handling support gives the program the ability to execute any
907program which does not "throw an exception", by turning "``invoke``"
908instructions into calls and by turning "``unwind``" instructions into calls to
909``abort()``. If the program does dynamically use the "``unwind``" instruction,
910the program will print a message then abort.
911
912"Expensive" exception handling support gives the full exception handling
913support to the program at the cost of making the "``invoke``" instruction
914really expensive. It basically inserts ``setjmp``/``longjmp`` calls to emulate
915the exception handling as necessary.
916
917Because the "expensive" support slows down programs a lot, and EH is only used
918for a subset of the programs, it must be specifically enabled by the
919``-enable-correct-eh-support`` option.
920
921Note that after this pass runs the CFG is not entirely accurate (exceptional
922control flow edges are not correct anymore) so only very simple things should
923be done after the ``lowerinvoke`` pass has run (like generation of native
924code). This should not be used as a general purpose "my LLVM-to-LLVM pass
925doesn't support the ``invoke`` instruction yet" lowering pass.
926
927``-lowerswitch``: Lower ``SwitchInst``\ s to branches
928-----------------------------------------------------
929
930Rewrites switch instructions with a sequence of branches, which allows targets
931to get away with not implementing the switch instruction until it is
932convenient.
933
934.. _passes-mem2reg:
935
936``-mem2reg``: Promote Memory to Register
937----------------------------------------
938
939This file promotes memory references to be register references. It promotes
940alloca instructions which only have loads and stores as uses. An ``alloca`` is
941transformed by using dominator frontiers to place phi nodes, then traversing
942the function in depth-first order to rewrite loads and stores as appropriate.
943This is just the standard SSA construction algorithm to construct "pruned" SSA
944form.
945
946``-memcpyopt``: MemCpy Optimization
947-----------------------------------
948
949This pass performs various transformations related to eliminating ``memcpy``
950calls, or transforming sets of stores into ``memset``\ s.
951
952``-mergefunc``: Merge Functions
953-------------------------------
954
955This pass looks for equivalent functions that are mergable and folds them.
956
957A hash is computed from the function, based on its type and number of basic
958blocks.
959
960Once all hashes are computed, we perform an expensive equality comparison on
961each function pair. This takes n^2/2 comparisons per bucket, so it's important
962that the hash function be high quality. The equality comparison iterates
963through each instruction in each basic block.
964
965When a match is found the functions are folded. If both functions are
966overridable, we move the functionality into a new internal function and leave
967two overridable thunks to it.
968
969``-mergereturn``: Unify function exit nodes
970-------------------------------------------
971
972Ensure that functions have at most one ``ret`` instruction in them.
973Additionally, it keeps track of which node is the new exit node of the CFG.
974
975``-partial-inliner``: Partial Inliner
976-------------------------------------
977
978This pass performs partial inlining, typically by inlining an ``if`` statement
979that surrounds the body of the function.
980
981``-prune-eh``: Remove unused exception handling info
982----------------------------------------------------
983
984This file implements a simple interprocedural pass which walks the call-graph,
985turning invoke instructions into call instructions if and only if the callee
986cannot throw an exception. It implements this as a bottom-up traversal of the
987call-graph.
988
989``-reassociate``: Reassociate expressions
990-----------------------------------------
991
992This pass reassociates commutative expressions in an order that is designed to
993promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc.
994
995For example: 4 + (x + 5) ⇒ x + (4 + 5)
996
997In the implementation of this algorithm, constants are assigned rank = 0,
998function arguments are rank = 1, and other values are assigned ranks
999corresponding to the reverse post order traversal of current function (starting
1000at 2), which effectively gives values in deep loops higher rank than values not
1001in loops.
1002
1003``-reg2mem``: Demote all values to stack slots
1004----------------------------------------------
1005
1006This file demotes all registers to memory references. It is intended to be the
1007inverse of :ref:`mem2reg <passes-mem2reg>`. By converting to ``load``
1008instructions, the only values live across basic blocks are ``alloca``
1009instructions and ``load`` instructions before ``phi`` nodes. It is intended
1010that this should make CFG hacking much easier. To make later hacking easier,
1011the entry block is split into two, such that all introduced ``alloca``
1012instructions (and nothing else) are in the entry block.
1013
1014``-scalarrepl``: Scalar Replacement of Aggregates (DT)
1015------------------------------------------------------
1016
1017The well-known scalar replacement of aggregates transformation. This transform
1018breaks up ``alloca`` instructions of aggregate type (structure or array) into
1019individual ``alloca`` instructions for each member if possible. Then, if
1020possible, it transforms the individual ``alloca`` instructions into nice clean
1021scalar SSA form.
1022
1023This combines a simple scalar replacement of aggregates algorithm with the
1024:ref:`mem2reg <passes-mem2reg>` algorithm because often interact, especially
1025for C++ programs. As such, iterating between ``scalarrepl``, then
1026:ref:`mem2reg <passes-mem2reg>` until we run out of things to promote works
1027well.
1028
1029.. _passes-sccp:
1030
1031``-sccp``: Sparse Conditional Constant Propagation
1032--------------------------------------------------
1033
1034Sparse conditional constant propagation and merging, which can be summarized
1035as:
1036
1037* Assumes values are constant unless proven otherwise
1038* Assumes BasicBlocks are dead unless proven otherwise
1039* Proves values to be constant, and replaces them with constants
1040* Proves conditional branches to be unconditional
1041
1042Note that this pass has a habit of making definitions be dead. It is a good
1043idea to to run a :ref:`DCE <passes-dce>` pass sometime after running this pass.
1044
1045``-simplify-libcalls``: Simplify well-known library calls
1046---------------------------------------------------------
1047
1048Applies a variety of small optimizations for calls to specific well-known
1049function calls (e.g. runtime library functions). For example, a call
1050``exit(3)`` that occurs within the ``main()`` function can be transformed into
1051simply ``return 3``.
1052
1053.. _passes-simplifycfg:
1054
1055``-simplifycfg``: Simplify the CFG
1056----------------------------------
1057
1058Performs dead code elimination and basic block merging. Specifically:
1059
1060* Removes basic blocks with no predecessors.
1061* Merges a basic block into its predecessor if there is only one and the
1062 predecessor only has one successor.
1063* Eliminates PHI nodes for basic blocks with a single predecessor.
1064* Eliminates a basic block that only contains an unconditional branch.
1065
1066``-sink``: Code sinking
1067-----------------------
1068
1069This pass moves instructions into successor blocks, when possible, so that they
1070aren't executed on paths where their results aren't needed.
1071
1072``-strip``: Strip all symbols from a module
1073-------------------------------------------
1074
1075Performs code stripping. This transformation can delete:
1076
1077* names for virtual registers
1078* symbols for internal globals and functions
1079* debug information
1080
1081Note that this transformation makes code much less readable, so it should only
1082be used in situations where the strip utility would be used, such as reducing
1083code size or making it harder to reverse engineer code.
1084
1085``-strip-dead-debug-info``: Strip debug info for unused symbols
1086---------------------------------------------------------------
1087
1088.. FIXME: this description is the same as for -strip
1089
1090performs code stripping. this transformation can delete:
1091
1092* names for virtual registers
1093* symbols for internal globals and functions
1094* debug information
1095
1096note that this transformation makes code much less readable, so it should only
1097be used in situations where the strip utility would be used, such as reducing
1098code size or making it harder to reverse engineer code.
1099
1100``-strip-dead-prototypes``: Strip Unused Function Prototypes
1101------------------------------------------------------------
1102
1103This pass loops over all of the functions in the input module, looking for dead
1104declarations and removes them. Dead declarations are declarations of functions
1105for which no implementation is available (i.e., declarations for unused library
1106functions).
1107
1108``-strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics
1109-------------------------------------------------------------------
1110
1111.. FIXME: this description is the same as for -strip
1112
1113This pass implements code stripping. Specifically, it can delete:
1114
1115#. names for virtual registers
1116#. symbols for internal globals and functions
1117#. debug information
1118
1119Note that this transformation makes code much less readable, so it should only
1120be used in situations where the 'strip' utility would be used, such as reducing
1121code size or making it harder to reverse engineer code.
1122
1123``-strip-nondebug``: Strip all symbols, except dbg symbols, from a module
1124-------------------------------------------------------------------------
1125
1126.. FIXME: this description is the same as for -strip
1127
1128This pass implements code stripping. Specifically, it can delete:
1129
1130#. names for virtual registers
1131#. symbols for internal globals and functions
1132#. debug information
1133
1134Note that this transformation makes code much less readable, so it should only
1135be used in situations where the 'strip' utility would be used, such as reducing
1136code size or making it harder to reverse engineer code.
1137
1138``-tailcallelim``: Tail Call Elimination
1139----------------------------------------
1140
1141This file transforms calls of the current function (self recursion) followed by
1142a return instruction with a branch to the entry of the function, creating a
1143loop. This pass also implements the following extensions to the basic
1144algorithm:
1145
1146#. Trivial instructions between the call and return do not prevent the
1147 transformation from taking place, though currently the analysis cannot
1148 support moving any really useful instructions (only dead ones).
1149#. This pass transforms functions that are prevented from being tail recursive
1150 by an associative expression to use an accumulator variable, thus compiling
1151 the typical naive factorial or fib implementation into efficient code.
1152#. TRE is performed if the function returns void, if the return returns the
1153 result returned by the call, or if the function returns a run-time constant
1154 on all exits from the function. It is possible, though unlikely, that the
1155 return returns something else (like constant 0), and can still be TRE'd. It
1156 can be TRE'd if *all other* return instructions in the function return the
1157 exact same value.
1158#. If it can prove that callees do not access theier caller stack frame, they
1159 are marked as eligible for tail call elimination (by the code generator).
1160
1161Utility Passes
1162==============
1163
1164This section describes the LLVM Utility Passes.
1165
1166``-deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)
1167------------------------------------------------------------------------
1168
1169Same as dead argument elimination, but deletes arguments to functions which are
1170external. This is only for use by :doc:`bugpoint <Bugpoint>`.
1171
1172``-extract-blocks``: Extract Basic Blocks From Module (for bugpoint use)
1173------------------------------------------------------------------------
1174
1175This pass is used by bugpoint to extract all blocks from the module into their
1176own functions.
1177
1178``-instnamer``: Assign names to anonymous instructions
1179------------------------------------------------------
1180
1181This is a little utility pass that gives instructions names, this is mostly
1182useful when diffing the effect of an optimization because deleting an unnamed
1183instruction can change all other instruction numbering, making the diff very
1184noisy.
1185
1186``-preverify``: Preliminary module verification
1187-----------------------------------------------
1188
1189Ensures that the module is in the form required by the :ref:`Module Verifier
1190<passes-verify>` pass. Running the verifier runs this pass automatically, so
1191there should be no need to use it directly.
1192
1193.. _passes-verify:
1194
1195``-verify``: Module Verifier
1196----------------------------
1197
1198Verifies an LLVM IR code. This is useful to run after an optimization which is
1199undergoing testing. Note that llvm-as verifies its input before emitting
1200bitcode, and also that malformed bitcode is likely to make LLVM crash. All
1201language front-ends are therefore encouraged to verify their output before
1202performing optimizing transformations.
1203
1204#. Both of a binary operator's parameters are of the same type.
1205#. Verify that the indices of mem access instructions match other operands.
1206#. Verify that arithmetic and other things are only performed on first-class
1207 types. Verify that shifts and logicals only happen on integrals f.e.
1208#. All of the constants in a switch statement are of the correct type.
1209#. The code is in valid SSA form.
1210#. It is illegal to put a label into any other type (like a structure) or to
1211 return one.
1212#. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is
1213 invalid.
1214#. PHI nodes must have an entry for each predecessor, with no extras.
1215#. PHI nodes must be the first thing in a basic block, all grouped together.
1216#. PHI nodes must have at least one entry.
1217#. All basic blocks should only end with terminator insts, not contain them.
1218#. The entry node to a function must not have predecessors.
1219#. All Instructions must be embedded into a basic block.
1220#. Functions cannot take a void-typed parameter.
1221#. Verify that a function's argument list agrees with its declared type.
1222#. It is illegal to specify a name for a void value.
1223#. It is illegal to have an internal global value with no initializer.
1224#. It is illegal to have a ``ret`` instruction that returns a value that does
1225 not agree with the function return value type.
1226#. Function call argument types match the function prototype.
1227#. All other things that are tested by asserts spread about the code.
1228
1229Note that this does not provide full security verification (like Java), but
1230instead just tries to ensure that code is well-formed.
1231
1232``-view-cfg``: View CFG of function
1233-----------------------------------
1234
1235Displays the control flow graph using the GraphViz tool.
1236
1237``-view-cfg-only``: View CFG of function (with no function bodies)
1238------------------------------------------------------------------
1239
1240Displays the control flow graph using the GraphViz tool, but omitting function
1241bodies.
1242
1243``-view-dom``: View dominance tree of function
1244----------------------------------------------
1245
1246Displays the dominator tree using the GraphViz tool.
1247
1248``-view-dom-only``: View dominance tree of function (with no function bodies)
1249-----------------------------------------------------------------------------
1250
1251Displays the dominator tree using the GraphViz tool, but omitting function
1252bodies.
1253
1254``-view-postdom``: View postdominance tree of function
1255------------------------------------------------------
1256
1257Displays the post dominator tree using the GraphViz tool.
1258
1259``-view-postdom-only``: View postdominance tree of function (with no function bodies)
1260-------------------------------------------------------------------------------------
1261
1262Displays the post dominator tree using the GraphViz tool, but omitting function
1263bodies.
1264