1102 lines · plain
1====================================2LLVM's Analysis and Transform Passes3====================================4 5.. contents::6 :local:7 8.. toctree::9 :hidden:10 11 KernelInfo12 13Introduction14============15.. warning:: This document is not updated frequently, and the list of passes16 is most likely incomplete. It is possible to list passes known by the opt17 tool using ``opt -print-passes``.18 19This document serves as a high-level summary of the optimization features that20LLVM provides. Optimizations are implemented as Passes that traverse some21portion of a program to either collect information or transform the program.22The table below divides the passes that LLVM provides into three categories.23Analysis passes compute information that other passes can use or for debugging24or program visualization purposes. Transform passes can use (or invalidate)25the analysis passes. Transform passes all mutate the program in some way.26Utility passes provide some utility but don't otherwise fit categorization.27For example, passes to extract functions to bitcode or write a module to bitcode28are neither analysis nor transform passes. The table of contents above29provides a quick summary of each pass and links to the more complete pass30description later in the document.31 32Analysis Passes33===============34 35This section describes the LLVM Analysis Passes.36 37``aa-eval``: Exhaustive Alias Analysis Precision Evaluator38----------------------------------------------------------39 40This is a simple N^2 alias analysis accuracy evaluator. Basically, for each41function in the program, it simply queries to see how the alias analysis42implementation answers alias queries between each pair of pointers in the43function.44 45This is inspired and adapted from code by: Naveen Neelakantam, Francesco46Spadini, and Wojciech Stryjewski.47 48``basic-aa``: Basic Alias Analysis (stateless AA impl)49------------------------------------------------------50 51A basic alias analysis pass that implements identities (two different globals52cannot alias, etc), but does no stateful analysis.53 54``basiccg``: Basic CallGraph Construction55-----------------------------------------56 57Yet to be written.58 59.. _passes-da:60 61``da``: Dependence Analysis62---------------------------63 64Dependence analysis framework, which is used to detect dependencies in memory65accesses.66 67``domfrontier``: Dominance Frontier Construction68------------------------------------------------69 70This pass is a simple dominator construction algorithm for finding forward71dominator frontiers.72 73``domtree``: Dominator Tree Construction74----------------------------------------75 76This pass is a simple dominator construction algorithm for finding forward77dominators.78 79 80``dot-callgraph``: Print Call Graph to "dot" file81-------------------------------------------------82 83This pass, only available in ``opt``, prints the call graph into a ``.dot``84graph. This graph can then be processed with the "dot" tool to convert it to85postscript or some other suitable format.86 87``dot-cfg``: Print CFG of function to "dot" file88------------------------------------------------89 90This pass, only available in ``opt``, prints the control flow graph into a91``.dot`` graph. This graph can then be processed with the :program:`dot` tool92to convert it to postscript or some other suitable format.93Additionally, the ``-cfg-func-name=<substring>`` option can be used to filter the94functions that are printed. All functions that contain the specified substring95will be printed.96 97``dot-cfg-only``: Print CFG of function to "dot" file (with no function bodies)98-------------------------------------------------------------------------------99 100This pass, only available in ``opt``, prints the control flow graph into a101``.dot`` graph, omitting the function bodies. This graph can then be processed102with the :program:`dot` tool to convert it to postscript or some other suitable103format.104Additionally, the ``-cfg-func-name=<substring>`` option can be used to filter the105functions that are printed. All functions that contain the specified substring106will be printed.107 108``dot-dom``: Print dominance tree of function to "dot" file109-----------------------------------------------------------110 111This pass, only available in ``opt``, prints the dominator tree into a ``.dot``112graph. This graph can then be processed with the :program:`dot` tool to113convert it to postscript or some other suitable format.114 115``dot-dom-only``: Print dominance tree of function to "dot" file (with no function bodies)116------------------------------------------------------------------------------------------117 118This pass, only available in ``opt``, prints the dominator tree into a ``.dot``119graph, omitting the function bodies. This graph can then be processed with the120:program:`dot` tool to convert it to postscript or some other suitable format.121 122``dot-post-dom``: Print postdominance tree of function to "dot" file123--------------------------------------------------------------------124 125This pass, only available in ``opt``, prints the post dominator tree into a126``.dot`` graph. This graph can then be processed with the :program:`dot` tool127to convert it to postscript or some other suitable format.128 129``dot-post-dom-only``: Print postdominance tree of function to "dot" file (with no function bodies)130---------------------------------------------------------------------------------------------------131 132This pass, only available in ``opt``, prints the post dominator tree into a133``.dot`` graph, omitting the function bodies. This graph can then be processed134with the :program:`dot` tool to convert it to postscript or some other suitable135format.136 137``globals-aa``: Simple mod/ref analysis for globals138---------------------------------------------------139 140This simple pass provides alias and mod/ref information for global values that141do not have their address taken, and keeps track of whether functions read or142write memory (are "pure"). For this simple (but very common) case, we can143provide pretty accurate and useful information.144 145``instcount``: Counts the various types of ``Instruction``\ s146-------------------------------------------------------------147 148This pass collects the count of all instructions and reports them.149 150``iv-users``: Induction Variable Users151--------------------------------------152 153Bookkeeping for "interesting" users of expressions computed from induction154variables.155 156``kernel-info``: GPU Kernel Info157--------------------------------158 159Reports various statistics for codes compiled for GPUs. This pass is160:doc:`documented separately<KernelInfo>`.161 162``lazy-value-info``: Lazy Value Information Analysis163----------------------------------------------------164 165Interface for lazy computation of value constraint information.166 167``lint``: Statically lint-checks LLVM IR168----------------------------------------169 170This pass statically checks for common and easily-identified constructs which171produce undefined or likely unintended behavior in LLVM IR.172 173It is not a guarantee of correctness, in two ways. First, it isn't174comprehensive. There are checks which could be done statically which are not175yet implemented. Some of these are indicated by TODO comments, but those176aren't comprehensive either. Second, many conditions cannot be checked177statically. This pass does no dynamic instrumentation, so it can't check for178all possible problems.179 180Another limitation is that it assumes all code will be executed. A store181through a null pointer in a basic block which is never reached is harmless, but182this pass will warn about it anyway.183 184Optimization passes may make conditions that this pass checks for more or less185obvious. If an optimization pass appears to be introducing a warning, it may186be that the optimization pass is merely exposing an existing condition in the187code.188 189This code may be run before :ref:`instcombine <passes-instcombine>`. In many190cases, instcombine checks for the same kinds of things and turns instructions191with undefined behavior into unreachable (or equivalent). Because of this,192this pass makes some effort to look through bitcasts and so on.193 194``loops``: Natural Loop Information195-----------------------------------196 197This analysis is used to identify natural loops and determine the loop depth of198various nodes of the CFG. Note that the loops identified may actually be199several natural loops that share the same header node... not just a single200natural loop.201 202``memdep``: Memory Dependence Analysis203--------------------------------------204 205An analysis that determines, for a given memory operation, what preceding206memory operations it depends on. It builds on alias analysis information, and207tries to provide a lazy, caching interface to a common kind of alias208information query.209 210``print<module-debuginfo>``: Decodes module-level debug info211------------------------------------------------------------212 213This pass decodes the debug info metadata in a module and prints it to standard output in a214(sufficiently-prepared-) human-readable form.215 216``postdomtree``: Post-Dominator Tree Construction217-------------------------------------------------218 219This pass is a simple post-dominator construction algorithm for finding220post-dominators.221 222``print-alias-sets``: Alias Set Printer223---------------------------------------224 225Yet to be written.226 227``print-callgraph``: Print a call graph228---------------------------------------229 230This pass, only available in ``opt``, prints the call graph to standard error231in a human-readable form.232 233``print-callgraph-sccs``: Print SCCs of the Call Graph234------------------------------------------------------235 236This pass, only available in ``opt``, prints the SCCs of the call graph to237standard error in a human-readable form.238 239``print-cfg-sccs``: Print SCCs of each function CFG240---------------------------------------------------241 242This pass, only available in ``opt``, prints the SCCs of each function CFG to243standard error in a human-readable form.244 245``function(print)``: Print function to stderr246---------------------------------------------247 248The ``PrintFunctionPass`` class is designed to be pipelined with other249``FunctionPasses``, and prints out the functions of the module as they are250processed.251 252``module(print)``: Print module to stderr253-----------------------------------------254 255This pass simply prints out the entire module when it is executed.256 257``regions``: Detect single entry single exit regions258----------------------------------------------------259 260The ``RegionInfo`` pass detects single entry single exit regions in a function,261where a region is defined as any subgraph that is connected to the remaining262graph at only two spots. Furthermore, a hierarchical region tree is built.263 264.. _passes-scalar-evolution:265 266``scalar-evolution``: Scalar Evolution Analysis267-----------------------------------------------268 269The ``ScalarEvolution`` analysis can be used to analyze and categorize scalar270expressions in loops. It specializes in recognizing general induction271variables, representing them with the abstract and opaque ``SCEV`` class.272Given this analysis, trip counts of loops and other important properties can be273obtained.274 275This analysis is primarily useful for induction variable substitution and276strength reduction.277 278``scev-aa``: ScalarEvolution-based Alias Analysis279-------------------------------------------------280 281Simple alias analysis implemented in terms of ``ScalarEvolution`` queries.282 283This differs from traditional loop dependence analysis in that it tests for284dependencies within a single iteration of a loop, rather than dependencies285between different iterations.286 287``ScalarEvolution`` has a more complete understanding of pointer arithmetic288than ``BasicAliasAnalysis``' collection of ad-hoc analyses.289 290``stack-safety``: Stack Safety Analysis291---------------------------------------292 293The ``StackSafety`` analysis can be used to determine if stack allocated294variables can be considered safe from memory access bugs.295 296This analysis' primary purpose is to be used by sanitizers to avoid unnecessary297instrumentation of safe variables.298 299Transform Passes300================301 302This section describes the LLVM Transform Passes.303 304``adce``: Aggressive Dead Code Elimination305------------------------------------------306 307ADCE aggressively tries to eliminate code. This pass is similar to :ref:`DCE308<passes-dce>` but it assumes that values are dead until proven otherwise. This309is similar to :ref:`SCCP <passes-sccp>`, except applied to the liveness of310values.311 312``always-inline``: Inliner for ``always_inline`` functions313----------------------------------------------------------314 315A custom inliner that handles only functions that are marked as "always316inline".317 318``argpromotion``: Promote 'by reference' arguments to scalars319-------------------------------------------------------------320 321This pass promotes "by reference" arguments to be "by value" arguments. In322practice, this means looking for internal functions that have pointer323arguments. If it can prove, through the use of alias analysis, that an324argument is *only* loaded, then it can pass the value into the function instead325of the address of the value. This can cause recursive simplification of code326and lead to the elimination of allocas (especially in C++ template code like327the STL).328 329This pass also handles aggregate arguments that are passed into a function,330scalarizing them if the elements of the aggregate are only loaded. Note that331it refuses to scalarize aggregates which would require passing in more than332three operands to the function, because passing thousands of operands for a333large array or structure is unprofitable!334 335Note that this transformation could also be done for arguments that are only336stored to (returning the value instead), but does not currently. This case337would be best handled when and if LLVM starts supporting multiple return values338from functions.339 340``block-placement``: Profile Guided Basic Block Placement341---------------------------------------------------------342 343This pass is a very simple profile guided basic block placement algorithm. The344idea is to put frequently executed blocks together at the start of the function345and hopefully increase the number of fall-through conditional branches. If346there is no profile information for a particular function, this pass basically347orders blocks in depth-first order.348 349``break-crit-edges``: Break critical edges in CFG350-------------------------------------------------351 352Break all of the critical edges in the CFG by inserting a dummy basic block.353It may be "required" by passes that cannot deal with critical edges. This354transformation obviously invalidates the CFG, but can update forward dominator355(set, immediate dominators, tree, and frontier) information.356 357``codegenprepare``: Optimize for code generation358------------------------------------------------359 360This pass munges the code in the input function to better prepare it for361SelectionDAG-based code generation. This works around limitations in its362basic-block-at-a-time approach. It should eventually be removed.363 364``constmerge``: Merge Duplicate Global Constants365------------------------------------------------366 367Merges duplicate global constants together into a single constant that is368shared. This is useful because some passes (i.e., TraceValues) insert a lot of369string constants into the program, regardless of whether or not an existing370string is available.371 372.. _passes-dce:373 374``dce``: Dead Code Elimination375------------------------------376 377Dead code elimination is similar to dead instruction elimination, but it378rechecks instructions that were used by removed instructions to see if they379are newly dead.380 381``deadargelim``: Dead Argument Elimination382------------------------------------------383 384This pass deletes dead arguments from internal functions. Dead argument385elimination removes arguments which are directly dead, as well as arguments386only passed into function calls as dead arguments of other functions. This387pass also deletes dead arguments in a similar way.388 389This pass is often useful as a cleanup pass to run after aggressive390interprocedural passes, which add possibly-dead arguments.391 392``dse``: Dead Store Elimination393-------------------------------394 395A trivial dead store elimination that only considers basic-block local396redundant stores.397 398.. _passes-function-attrs:399 400``function-attrs``: Deduce function attributes401----------------------------------------------402 403A simple interprocedural pass which walks the call-graph, looking for functions404which do not access or only read non-local memory, and marking them405``readnone``/``readonly``. In addition, it marks function arguments (of406pointer type) "``nocapture``" if a call to the function does not create any407copies of the pointer value that outlive the call. This more or less means408that the pointer is only dereferenced, and not returned from the function or409stored in a global. This pass is implemented as a bottom-up traversal of the410call-graph.411 412``globaldce``: Dead Global Elimination413--------------------------------------414 415This transform is designed to eliminate unreachable internal globals from the416program. It uses an aggressive algorithm, searching out globals that are known417to be alive. After it finds all of the globals which are needed, it deletes418whatever is left over. This allows it to delete recursive chunks of the419program which are unreachable.420 421``globalopt``: Global Variable Optimizer422----------------------------------------423 424This pass transforms simple global variables that never have their address425taken. If obviously true, it marks read/write globals as constant, deletes426variables only stored to, etc.427 428``gvn``: Global Value Numbering429-------------------------------430 431This pass performs global value numbering to eliminate fully and partially432redundant instructions. It also performs redundant load elimination.433 434.. _passes-indvars:435 436``indvars``: Canonicalize Induction Variables437---------------------------------------------438 439This transformation analyzes and transforms the induction variables (and440computations derived from them) into simpler forms suitable for subsequent441analysis and transformation.442 443This transformation makes the following changes to each loop with an444identifiable induction variable:445 446* All loops are transformed to have a *single* canonical induction variable447 which starts at zero and steps by one.448* The canonical induction variable is guaranteed to be the first PHI node in449 the loop header block.450* Any pointer arithmetic recurrences are raised to use array subscripts.451 452If the trip count of a loop is computable, this pass also makes the following453changes:454 455* The exit condition for the loop is canonicalized to compare the induction456 value against the exit value. This turns loops like:457 458 .. code-block:: c++459 460 for (i = 7; i*i < 1000; ++i)461 462 into463 464 .. code-block:: c++465 466 for (i = 0; i != 25; ++i)467 468* Any use outside of the loop of an expression derived from the indvar is469 changed to compute the derived value outside of the loop, eliminating the470 dependence on the exit value of the induction variable. If the only purpose471 of the loop is to compute the exit value of some derived expression, this472 transformation will make the loop dead.473 474This transformation should be followed by strength reduction after all of the475desired loop transformations have been performed. Additionally, on targets476where it is profitable, the loop could be transformed to count down to zero477(the "do loop" optimization).478 479``inline``: Function Integration/Inlining480-----------------------------------------481 482Bottom-up inlining of functions into callees.483 484.. _passes-instcombine:485 486``instcombine``: Combine redundant instructions487-----------------------------------------------488 489Combine instructions to form fewer, simpler instructions. This pass does not490modify the CFG. This pass is where algebraic simplification happens.491 492This pass combines things like:493 494.. code-block:: llvm495 496 %Y = add i32 %X, 1497 %Z = add i32 %Y, 1498 499into:500 501.. code-block:: llvm502 503 %Z = add i32 %X, 2504 505This is a simple worklist-driven algorithm.506 507This pass guarantees that the following canonicalizations are performed on the508program:509 510#. If a binary operator has a constant operand, it is moved to the right-hand511 side.512#. Bitwise operators with constant operands are always grouped so that shifts513 are performed first, then ``or``\ s, then ``and``\ s, then ``xor``\ s.514#. Compare instructions are converted from ``<``, ``>``, ``≤``, or ``≥`` to515 ``=`` or ``≠`` if possible.516#. All ``cmp`` instructions on boolean values are replaced with logical517 operations.518#. ``add X, X`` is represented as ``mul X, 2`` ⇒ ``shl X, 1``519#. Multiplies with a constant power-of-two argument are transformed into520 shifts.521#. … etc.522 523This pass can also simplify calls to specific well-known function calls (e.g.524runtime library functions). For example, a call ``exit(3)`` that occurs within525the ``main()`` function can be transformed into simply ``return 3``. Whether or526not library calls are simplified is controlled by the527:ref:`-function-attrs <passes-function-attrs>` pass and LLVM's knowledge of528library calls on different targets.529 530.. _passes-aggressive-instcombine:531 532``aggressive-instcombine``: Combine expression patterns533--------------------------------------------------------534 535Combine expression patterns to form expressions with fewer, simpler instructions.536 537For example, this pass reduces the width of expressions post-dominated by ``TruncInst``538into smaller width when applicable.539 540It differs from instcombine pass in that it can modify CFG and contains pattern541optimization that requires higher complexity than the O(1), thus, it should run fewer542times than instcombine pass.543 544``internalize``: Internalize Global Symbols545-------------------------------------------546 547This pass loops over all of the functions in the input module, looking for a548main function. If a main function is found, all other functions and all global549variables with initializers are marked as internal.550 551``ipsccp``: Interprocedural Sparse Conditional Constant Propagation552-------------------------------------------------------------------553 554An interprocedural variant of :ref:`Sparse Conditional Constant Propagation555<passes-sccp>`.556 557``normalize``: Transforms IR into a normal form that's easier to diff558---------------------------------------------------------------------559 560This pass aims to transform LLVM Modules into a normal form by reordering and561renaming instructions while preserving the same semantics. The normalizer makes562it easier to spot semantic differences while diffing two modules which have563undergone two different passes.564 565``jump-threading``: Jump Threading566----------------------------------567 568Jump threading tries to find distinct threads of control flow running through a569basic block. This pass looks at blocks that have multiple predecessors and570multiple successors. If one or more of the predecessors of the block can be571proven to always cause a jump to one of the successors, we forward the edge572from the predecessor to the successor by duplicating the contents of this573block.574 575An example of when this can occur is code like this:576 577.. code-block:: c++578 579 if () { ...580 X = 4;581 }582 if (X < 3) {583 584In this case, the unconditional branch at the end of the first if can be585revectored to the false side of the second if.586 587.. _passes-lcssa:588 589``lcssa``: Loop-Closed SSA Form Pass590------------------------------------591 592This pass transforms loops by placing phi nodes at the end of the loops for all593values that are live across the loop boundary. For example, it turns the left594into the right code:595 596.. code-block:: c++597 598 for (...) for (...)599 if (c) if (c)600 X1 = ... X1 = ...601 else else602 X2 = ... X2 = ...603 X3 = phi(X1, X2) X3 = phi(X1, X2)604 ... = X3 + 4 X4 = phi(X3)605 ... = X4 + 4606 607This is still valid LLVM; the extra phi nodes are purely redundant, and will be608trivially eliminated by ``InstCombine``. The major benefit of this609transformation is that it makes many other loop optimizations, such as610``LoopUnswitch``\ ing, simpler. You can read more in the611:ref:`loop terminology section for the LCSSA form <loop-terminology-lcssa>`.612 613.. _passes-licm:614 615``licm``: Loop Invariant Code Motion616------------------------------------617 618This pass performs loop invariant code motion, attempting to remove as much619code from the body of a loop as possible. It does this by either hoisting code620into the preheader block, or by sinking code to the exit blocks if it is safe.621This pass also promotes must-aliased memory locations in the loop to live in622registers, thus hoisting and sinking "invariant" loads and stores.623 624Hoisting operations out of loops is a canonicalization transform. It enables625and simplifies subsequent optimizations in the middle-end. Rematerialization626of hoisted instructions to reduce register pressure is the responsibility of627the back-end, which has more accurate information about register pressure and628also handles other optimizations than LICM that increase live-ranges.629 630This pass uses alias analysis for two purposes:631 632#. Moving loop invariant loads and calls out of loops. If we can determine633 that a load or call inside of a loop never aliases anything stored to, we634 can hoist it or sink it like any other instruction.635 636#. Scalar Promotion of Memory. If there is a store instruction inside of the637 loop, we try to move the store to happen AFTER the loop instead of inside of638 the loop. This can only happen if a few conditions are true:639 640 #. The pointer stored through is loop invariant.641 #. There are no stores or loads in the loop which *may* alias the pointer.642 There are no calls in the loop which mod/ref the pointer.643 644 If these conditions are true, we can promote the loads and stores in the645 loop of the pointer to use a temporary alloca'd variable. We then use the646 :ref:`mem2reg <passes-mem2reg>` functionality to construct the appropriate647 SSA form for the variable.648 649``loop-deletion``: Delete dead loops650------------------------------------651 652This file implements the Dead Loop Deletion Pass. This pass is responsible for653eliminating loops with non-infinite computable trip counts that have no side654effects or volatile instructions, and do not contribute to the computation of655the function's return value.656 657.. _passes-loop-extract:658 659``loop-extract``: Extract loops into new functions660--------------------------------------------------661 662A pass wrapper around the ``ExtractLoop()`` scalar transformation to extract663each top-level loop into its own new function. If the loop is the *only* loop664in a given function, it is not touched. This is a pass most useful for665debugging via bugpoint.666 667``loop-reduce``: Loop Strength Reduction668----------------------------------------669 670This pass performs a strength reduction on array references inside loops that671have as one or more of their components the loop induction variable. This is672accomplished by creating a new value to hold the initial value of the array673access for the first iteration, and then creating a new GEP instruction in the674loop to increment the value by the appropriate amount.675 676.. _passes-loop-rotate:677 678``loop-rotate``: Rotate Loops679-----------------------------680 681A simple loop rotation transformation. A summary of it can be found in682:ref:`Loop Terminology for Rotated Loops <loop-terminology-loop-rotate>`.683 684 685.. _passes-loop-simplify:686 687``loop-simplify``: Canonicalize natural loops688---------------------------------------------689 690This pass performs several transformations to transform natural loops into a691simpler form, which makes subsequent analyses and transformations simpler and692more effective. A summary of it can be found in693:ref:`Loop Terminology, Loop Simplify Form <loop-terminology-loop-simplify>`.694 695Loop pre-header insertion guarantees that there is a single, non-critical entry696edge from outside of the loop to the loop header. This simplifies a number of697analyses and transformations, such as :ref:`LICM <passes-licm>`.698 699Loop exit-block insertion guarantees that all exit blocks from the loop (blocks700which are outside of the loop that have predecessors inside of the loop) only701have predecessors from inside of the loop (and are thus dominated by the loop702header). This simplifies transformations such as store-sinking that are built703into LICM.704 705This pass also guarantees that loops will have exactly one backedge.706 707Note that the :ref:`simplifycfg <passes-simplifycfg>` pass will clean up blocks708which are split out but end up being unnecessary, so usage of this pass should709not pessimize generated code.710 711This pass obviously modifies the CFG, but updates loop information and712dominator information.713 714``loop-unroll``: Unroll loops715-----------------------------716 717This pass implements a simple loop unroller. It works best when loops have718been canonicalized by the :ref:`indvars <passes-indvars>` pass, allowing it to719determine the trip counts of loops easily.720 721``loop-unroll-and-jam``: Unroll and Jam loops722---------------------------------------------723 724This pass implements a simple unroll and jam classical loop optimisation pass.725It transforms a loop from:726 727.. code-block:: c++728 729 for i.. i+= 1 for i.. i+= 4730 for j.. for j..731 code(i, j) code(i, j)732 code(i+1, j)733 code(i+2, j)734 code(i+3, j)735 remainder loop736 737Which can be seen as unrolling the outer loop and "jamming" (fusing) the inner738loops into one. When variables or loads can be shared in the new inner loop, this739can lead to significant performance improvements. It uses740:ref:`Dependence Analysis <passes-da>` for proving the transformations are safe.741 742``lower-global-dtors``: Lower global destructors743------------------------------------------------744 745This pass lowers global module destructors (``llvm.global_dtors``) by creating746wrapper functions that are registered as global constructors in747``llvm.global_ctors`` and which contain a call to ``__cxa_atexit`` to register748their destructor functions.749 750``lower-atomic``: Lower atomic intrinsics to non-atomic form751------------------------------------------------------------752 753This pass lowers atomic intrinsics to non-atomic form for use in a known754non-preemptible environment.755 756The pass does not verify that the environment is non-preemptible (in general757this would require knowledge of the entire call graph of the program including758any libraries which may not be available in bitcode form); it simply lowers759every atomic intrinsic.760 761``lower-invoke``: Lower invokes to calls, for unwindless code generators762------------------------------------------------------------------------763 764This transformation is designed for use by code generators which do not yet765support stack unwinding. This pass converts ``invoke`` instructions to766``call`` instructions, so that any exception-handling ``landingpad`` blocks767become dead code (which can be removed by running the ``-simplifycfg`` pass768afterwards).769 770``lower-switch``: Lower ``SwitchInst``\ s to branches771-----------------------------------------------------772 773Rewrites switch instructions with a sequence of branches, which allows targets774to get away with not implementing the switch instruction until it is775convenient.776 777.. _passes-mem2reg:778 779``mem2reg``: Promote Memory to Register780---------------------------------------781 782This file promotes memory references to be register references. It promotes783alloca instructions which only have loads and stores as uses. An ``alloca`` is784transformed by using dominator frontiers to place phi nodes, then traversing785the function in depth-first order to rewrite loads and stores as appropriate.786This is just the standard SSA construction algorithm to construct "pruned" SSA787form.788 789``memcpyopt``: MemCpy Optimization790----------------------------------791 792This pass performs various transformations related to eliminating ``memcpy``793calls, or transforming sets of stores into ``memset``\ s.794 795``mergefunc``: Merge Functions796------------------------------797 798This pass looks for equivalent functions that are mergeable and folds them.799 800Total-ordering is introduced among the functions set: we define comparison801that answers for every two functions which of them is greater. It allows to802arrange functions into a binary tree.803 804For every new function we check for equivalent in the tree.805 806If equivalent exists, we fold such functions. If both functions are overridable,807we move the functionality into a new internal function and leave two808overridable thunks to it.809 810If there is no equivalent, then we add this function to tree.811 812Lookup routine has O(log(n)) complexity, while whole merging process has813complexity of O(n*log(n)).814 815Read816:doc:`this <MergeFunctions>`817article for more details.818 819``mergereturn``: Unify function exit nodes820------------------------------------------821 822Ensure that functions have at most one ``ret`` instruction in them.823Additionally, it keeps track of which node is the new exit node of the CFG.824 825``partial-inliner``: Partial Inliner826------------------------------------827 828This pass performs partial inlining, typically by inlining an ``if`` statement829that surrounds the body of the function.830 831``reassociate``: Reassociate expressions832----------------------------------------833 834This pass reassociates commutative expressions in an order that is designed to835promote better constant propagation, GCSE, :ref:`LICM <passes-licm>`, PRE, etc.836 837For example: 4 + (x + 5) ⇒ x + (4 + 5)838 839In the implementation of this algorithm, constants are assigned rank = 0,840function arguments are rank = 1, and other values are assigned ranks841corresponding to the reverse post-order traversal of the current function (starting842at 2), which effectively gives values in deep loops higher rank than values not843in loops.844 845``rel-lookup-table-converter``: Relative lookup table converter846---------------------------------------------------------------847 848This pass converts lookup tables to PIC-friendly relative lookup tables.849 850``reg2mem``: Demote all values to stack slots851---------------------------------------------852 853This file demotes all registers to memory references. It is intended to be the854inverse of :ref:`mem2reg <passes-mem2reg>`. By converting to ``load``855instructions, the only values live across basic blocks are ``alloca``856instructions and ``load`` instructions before ``phi`` nodes. It is intended857that this should make CFG hacking much easier. To make later hacking easier,858the entry block is split into two, such that all introduced ``alloca``859instructions (and nothing else) are in the entry block.860 861``sroa``: Scalar Replacement of Aggregates862------------------------------------------863 864The well-known scalar replacement of aggregates transformation. This transform865breaks up ``alloca`` instructions of aggregate type (structure or array) into866individual ``alloca`` instructions for each member if possible. Then, if867possible, it transforms the individual ``alloca`` instructions into nice clean868scalar SSA form.869 870.. _passes-sccp:871 872``sccp``: Sparse Conditional Constant Propagation873-------------------------------------------------874 875Sparse conditional constant propagation and merging, which can be summarized876as:877 878* Assumes values are constant unless proven otherwise879* Assumes BasicBlocks are dead unless proven otherwise880* Proves values to be constant, and replaces them with constants881* Proves conditional branches to be unconditional882 883Note that this pass has a habit of making definitions be dead. It is a good884idea to run a :ref:`DCE <passes-dce>` pass sometime after running this pass.885 886.. _passes-simplifycfg:887 888``simplifycfg``: Simplify the CFG889---------------------------------890 891Performs dead code elimination and basic block merging. Specifically:892 893* Removes basic blocks with no predecessors.894* Merges a basic block into its predecessor if there is only one and the895 predecessor only has one successor.896* Eliminates PHI nodes for basic blocks with a single predecessor.897* Eliminates a basic block that only contains an unconditional branch.898 899``sink``: Code sinking900----------------------901 902This pass moves instructions into successor blocks, when possible, so that they903aren't executed on paths where their results aren't needed.904 905.. _passes-simple-loop-unswitch:906 907``simple-loop-unswitch``: Unswitch loops908----------------------------------------909 910This pass transforms loops that contain branches on loop-invariant conditions911to have multiple loops. For example, it turns the left into the right code:912 913.. code-block:: c++914 915 for (...) if (lic)916 A for (...)917 if (lic) A; B; C918 B else919 C for (...)920 A; C921 922This can increase the size of the code exponentially (doubling it every time a923loop is unswitched) so we only unswitch if the resultant code will be smaller924than a threshold.925 926This pass expects :ref:`LICM <passes-licm>` to be run before it to hoist927invariant conditions out of the loop, to make the unswitching opportunity928obvious.929 930``strip``: Strip all symbols from a module931------------------------------------------932 933Performs code stripping. This transformation can delete:934 935* names for virtual registers936* symbols for internal globals and functions937* debug information938 939Note that this transformation makes code much less readable, so it should only940be used in situations where the strip utility would be used, such as reducing941code size or making it harder to reverse engineer code.942 943``strip-dead-debug-info``: Strip debug info for unused symbols944--------------------------------------------------------------945 946Performs code stripping. Similar to strip, but only strips debug info for947unused symbols.948 949``strip-dead-prototypes``: Strip Unused Function Prototypes950-----------------------------------------------------------951 952This pass loops over all of the functions in the input module, looking for dead953declarations and removes them. Dead declarations are declarations of functions954for which no implementation is available (i.e., declarations for unused library955functions).956 957``strip-debug-declare``: Strip all ``llvm.dbg.declare`` intrinsics and958``#dbg_declare`` records.959-------------------------------------------------------------------960 961Performs code stripping. Similar to strip, but only strips962``llvm.dbg.declare`` intrinsics.963 964``strip-nondebug``: Strip all symbols, except dbg symbols, from a module965------------------------------------------------------------------------966 967Performs code stripping. Similar to strip, but dbg info is preserved.968 969``tailcallelim``: Tail Call Elimination970---------------------------------------971 972This file transforms calls of the current function (self recursion) followed by973a return instruction with a branch to the entry of the function, creating a974loop. This pass also implements the following extensions to the basic975algorithm:976 977#. Trivial instructions between the call and return do not prevent the978 transformation from taking place, though currently the analysis cannot979 support moving any really useful instructions (only dead ones).980#. This pass transforms functions that are prevented from being tail recursive981 by an associative expression to use an accumulator variable, thus compiling982 the typical naive factorial or fib implementation into efficient code.983#. TRE is performed if the function returns void, if the return returns the984 result returned by the call, or if the function returns a run-time constant985 on all exits from the function. It is possible, though unlikely, that the986 return returns something else (like constant 0), and can still be TRE'd. It987 can be TRE'd if *all other* return instructions in the function return the988 exact same value.989#. If it can prove that callees do not access their caller stack frame, they990 are marked as eligible for tail call elimination (by the code generator).991 992Utility Passes993==============994 995This section describes the LLVM Utility Passes.996 997``deadarghaX0r``: Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)998-----------------------------------------------------------------------999 1000Same as dead argument elimination, but deletes arguments to functions which are1001external. This is only for use by :doc:`bugpoint <Bugpoint>`.1002 1003``extract-blocks``: Extract Basic Blocks From Module (for bugpoint use)1004-----------------------------------------------------------------------1005 1006This pass is used by bugpoint to extract all blocks from the module into their1007own functions.1008 1009``instnamer``: Assign names to anonymous instructions1010-----------------------------------------------------1011 1012This is a little utility pass that gives instructions names, this is mostly1013useful when diffing the effect of an optimization because deleting an unnamed1014instruction can change all other instruction numbering, making the diff very1015noisy.1016 1017.. _passes-verify:1018 1019``verify``: Module Verifier1020---------------------------1021 1022Verifies LLVM IR code. This is useful to run after an optimization which is1023undergoing testing. Note that llvm-as verifies its input before emitting1024bitcode, and also that malformed bitcode is likely to make LLVM crash. All1025language front-ends are therefore encouraged to verify their output before1026performing optimizing transformations.1027 1028#. Both of a binary operator's parameters are of the same type.1029#. Verify that the indices of mem access instructions match other operands.1030#. Verify that arithmetic and other things are only performed on first-class1031 types. Verify that shifts and logicals only happen on integrals f.e.1032#. All of the constants in a switch statement are of the correct type.1033#. The code is in valid SSA form.1034#. It is illegal to put a label into any other type (like a structure) or to1035 return one.1036#. Only phi nodes can be self referential: ``%x = add i32 %x``, ``%x`` is1037 invalid.1038#. PHI nodes must have an entry for each predecessor, with no extras.1039#. PHI nodes must be the first thing in a basic block, all grouped together.1040#. PHI nodes must have at least one entry.1041#. All basic blocks should only end with terminator insts, not contain them.1042#. The entry node to a function must not have predecessors.1043#. All Instructions must be embedded into a basic block.1044#. Functions cannot take a void-typed parameter.1045#. Verify that a function's argument list agrees with its declared type.1046#. It is illegal to specify a name for a void value.1047#. It is illegal to have an internal global value with no initializer.1048#. It is illegal to have a ``ret`` instruction that returns a value that does1049 not agree with the function return value type.1050#. Function call argument types match the function prototype.1051#. All other things that are tested by asserts spread about the code.1052 1053Note that this does not provide full security verification (like Java), but1054instead just tries to ensure that code is well-formed.1055 1056.. _passes-view-cfg:1057 1058``view-cfg``: View CFG of function1059----------------------------------1060 1061Displays the control flow graph using the GraphViz tool.1062Additionally, the ``-cfg-func-name=<substring>`` option can be used to filter the1063functions that are displayed. All functions that contain the specified substring1064will be displayed.1065 1066``view-cfg-only``: View CFG of function (with no function bodies)1067-----------------------------------------------------------------1068 1069Displays the control flow graph using the GraphViz tool, but omitting function1070bodies.1071Additionally, the ``-cfg-func-name=<substring>`` option can be used to filter the1072functions that are displayed. All functions that contain the specified substring1073will be displayed.1074 1075``view-dom``: View dominance tree of function1076---------------------------------------------1077 1078Displays the dominator tree using the GraphViz tool.1079 1080``view-dom-only``: View dominance tree of function (with no function bodies)1081----------------------------------------------------------------------------1082 1083Displays the dominator tree using the GraphViz tool, but omitting function1084bodies.1085 1086``view-post-dom``: View postdominance tree of function1087------------------------------------------------------1088 1089Displays the post dominator tree using the GraphViz tool.1090 1091``view-post-dom-only``: View postdominance tree of function (with no function bodies)1092-------------------------------------------------------------------------------------1093 1094Displays the post dominator tree using the GraphViz tool, but omitting function1095bodies.1096 1097``transform-warning``: Report missed forced transformations1098-----------------------------------------------------------1099 1100Emits warnings about not yet applied forced transformations (e.g. from1101``#pragma omp simd``).1102