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