3 ===========================================
4 LLVM Loop Terminology (and Canonical Forms)
5 ===========================================
13 Loops are an important concept for a code optimizer. In LLVM, detection
14 of loops in a control-flow graph is done by :ref:`loopinfo`. It is based
15 on the following definition.
17 A loop is a subset of nodes from the control-flow graph (CFG; where
18 nodes represent basic blocks) with the following properties:
20 1. The induced subgraph (which is the subgraph that contains all the
\r
21 edges from the CFG within the loop) is strongly connected
22 (every node is reachable from all others).
24 2. All edges from outside the subset into the subset point to the same
\r
25 node, called the **header**. As a consequence, the header dominates
26 all nodes in the loop (i.e. every execution path to any of the loop's
27 node will have to pass through the header).
29 3. The loop is the maximum subset with these properties. That is, no
\r
30 additional nodes from the CFG can be added such that the induced
31 subgraph would still be strongly connected and the header would
34 In computer science literature, this is often called a *natural loop*.
35 In LLVM, this is the only definition of a loop.
41 The definition of a loop comes with some additional terminology:
43 * An **entering block** (or **loop predecessor**) is a non-loop node
\r
44 that has an edge into the loop (necessarily the header). If there is
45 only one entering block entering block, and its only edge is to the
46 header, it is also called the loop's **preheader**. The preheader
47 dominates the loop without itself being part of the loop.
49 * A **latch** is a loop node that has an edge to the header.
51 * A **backedge** is an edge from a latch to the header.
53 * An **exiting edge** is an edge from inside the loop to a node outside
\r
54 of the loop. The source of such an edge is called an **exiting block**, its
55 target is an **exit block**.
57 .. image:: ./loop-terminology.svg
64 This loop definition has some noteworthy consequences:
66 * A node can be the header of at most one loop. As such, a loop can be
\r
67 identified by its header. Due to the header being the only entry into
68 a loop, it can be called a Single-Entry-Multiple-Exits (SEME) region.
71 * For basic blocks that are not reachable from the function's entry, the
\r
72 concept of loops is undefined. This follows from the concept of
73 dominance being undefined as well.
76 * The smallest loop consists of a single basic block that branches to
\r
77 itself. In this case that block is the header, latch (and exiting
78 block if it has another edge to a different block) at the same time.
79 A single block that has no branch to itself is not considered a loop,
80 even though it is trivially strongly connected.
82 .. image:: ./loop-single.svg
85 In this case, the role of header, exiting block and latch fall to the
86 same node. :ref:`loopinfo` reports this as:
88 .. code-block:: console
90 $ opt input.ll -loops -analyze
91 Loop at depth 1 containing: %for.body<header><latch><exiting>
94 * Loops can be nested inside each other. That is, a loop's node set can
\r
95 be a subset of another loop with a different loop header. The loop
96 hierarchy in a function forms a forest: Each top-level loop is the
97 root of the tree of the loops nested inside it.
99 .. image:: ./loop-nested.svg
103 * It is not possible that two loops share only a few of their nodes.
\r
104 Two loops are either disjoint or one is nested inside the other. In
105 the example below the left and right subsets both violate the
106 maximality condition. Only the merge of both sets is considered a loop.
108 .. image:: ./loop-nonmaximal.svg
112 * It is also possible that two logical loops share a header, but are
\r
113 considered a single loop by LLVM:
117 for (int i = 0; i < 128; ++i)
118 for (int j = 0; j < 128; ++j)
121 which might be represented in LLVM-IR as follows. Note that there is
122 only a single header and hence just a single loop.
124 .. image:: ./loop-merge.svg
127 The :ref:`LoopSimplify <loop-terminology-loop-simplify>` pass will
128 detect the loop and ensure separate headers for the outer and inner loop.
130 .. image:: ./loop-separate.svg
133 * A cycle in the CFG does not imply there is a loop. The example below
\r
134 shows such a CFG, where there is no header node that dominates all
135 other nodes in the cycle. This is called **irreducible control-flow**.
137 .. image:: ./loop-irreducible.svg
140 The term reducible results from the ability to collapse the CFG into a
141 single node by successively replacing one of three base structures with
142 a single node: A sequential execution of basic blocks, a conditional
143 branching (or switch) with re-joining, and a basic block looping on itself.
144 `Wikipedia <https://en.wikipedia.org/wiki/Control-flow_graph#Reducibility>`_
145 has a more formal definition, which basically says that every cycle has
149 * Irreducible control-flow can occur at any level of the loop nesting.
\r
150 That is, a loop that itself does not contain any loops can still have
151 cyclic control flow in its body; a loop that is not nested inside
152 another loop can still be part of an outer cycle; and there can be
153 additional cycles between any two loops where one is contained in the other.
156 * Exiting edges are not the only way to break out of a loop. Other
\r
157 possibilities are unreachable terminators, [[noreturn]] functions,
158 exceptions, signals, and your computer's power button.
161 * A basic block "inside" the loop that does not have a path back to the
\r
162 loop (i.e. to a latch or header) is not considered part of the loop.
163 This is illustrated by the following code.
167 for (unsigned i = 0; i <= n; ++i) {
169 // When reaching this block, we will have exited the loop.
174 // abort(), never returns, so we have exited the loop.
178 // The unreachable allows the compiler to assume that this will not rejoin the loop.
180 __builtin_unreachable();
183 // This statically infinite loop is not nested because control-flow will not continue with the for-loop.
191 * There is no requirement for the control flow to eventually leave the
\r
192 loop, i.e. a loop can be infinite. A **statically infinite loop** is a
193 loop that has no exiting edges. A **dynamically infinite loop** has
194 exiting edges, but it is possible to be never taken. This may happen
195 only under some circumstances, such as when n == UINT_MAX in the code
200 for (unsigned i = 0; i <= n; ++i)
203 It is possible for the optimizer to turn a dynamically infinite loop
204 into a statically infinite loop, for instance when it can prove that the
205 exiting condition is always false. Because the exiting edge is never
206 taken, the optimizer can change the conditional branch into an
209 Note that under some circumstances the compiler may assume that a loop will
210 eventually terminate without proving it. For instance, it may remove a loop
211 that does not do anything in its body. If the loop was infinite, this
212 optimization resulted in an "infinite" performance speed-up. A call
213 to the intrinsic :ref:`llvm.sideeffect<llvm_sideeffect>` can be added
214 into the loop to ensure that the optimizer does not make this assumption
218 * The number of executions of the loop header before leaving the loop is
\r
219 the **loop trip count** (or **iteration count**). If the loop should
220 not be executed at all, a **loop guard** must skip the entire loop:
222 .. image:: ./loop-guard.svg
225 Since the first thing a loop header might do is to check whether there
226 is another execution and if not, immediately exit without doing any work
227 (also see :ref:`loop-terminology-loop-rotate`), loop trip count is not
228 the best measure of a loop's number of iterations. For instance, the
229 number of header executions of the code below for a non-positive n
230 (before loop rotation) is 1, even though the loop body is not executed
235 for (int i = 0; i < n; ++i)
238 A better measure is the **backedge-taken count**, which is the number of
239 times any of the backedges is taken before the loop. It is one less than
240 the trip count for executions that enter the header.
248 LoopInfo is the core analysis for obtaining information about loops.
249 There are few key implications of the definitions given above which
250 are important for working successfully with this interface.
252 * LoopInfo does not contain information about non-loop cycles. As a
253 result, it is not suitable for any algorithm which requires complete
254 cycle detection for correctness.
256 * LoopInfo provides an interface for enumerating all top level loops
257 (e.g. those not contained in any other loop). From there, you may
258 walk the tree of sub-loops rooted in that top level loop.
260 * Loops which become statically unreachable during optimization *must*
261 be removed from LoopInfo. If this can not be done for some reason,
262 then the optimization is *required* to preserve the static
263 reachability of the loop.
266 .. _loop-terminology-loop-simplify:
271 The Loop Simplify Form is a canonical form that makes
272 several analyses and transformations simpler and more effective.
273 It is ensured by the LoopSimplify
274 (:ref:`-loop-simplify <passes-loop-simplify>`) pass and is automatically
275 added by the pass managers when scheduling a LoopPass.
276 This pass is implemented in
277 `LoopSimplify.h <https://llvm.org/doxygen/LoopSimplify_8h_source.html>`_.
278 When it is successful, the loop has:
281 * A single backedge (which implies that there is a single latch).
282 * Dedicated exits. That is, no exit block for the loop
283 has a predecessor that is outside the loop. This implies
284 that all exit blocks are dominated by the loop header.
286 .. _loop-terminology-lcssa:
288 Loop Closed SSA (LCSSA)
289 =======================
291 A program is in Loop Closed SSA Form if it is in SSA form
292 and all values that are defined in a loop are used only inside
295 Programs written in LLVM IR are always in SSA form but not necessarily
296 in LCSSA. To achieve the latter, for each value that is live across the
297 loop boundary, single entry PHI nodes are inserted to each of the exit blocks
298 [#lcssa-construction]_ in order to "close" these values inside the loop.
299 In particular, consider the following loop:
309 X3 = phi(X1, X2); // X3 defined
312 ... = X3 + 4; // X3 used, i.e. live
315 In the inner loop, the X3 is defined inside the loop, but used
316 outside of it. In Loop Closed SSA form, this would be represented as follows:
332 This is still valid LLVM; the extra phi nodes are purely redundant,
333 but all LoopPass'es are required to preserve them.
334 This form is ensured by the LCSSA (:ref:`-lcssa <passes-lcssa>`)
335 pass and is added automatically by the LoopPassManager when
336 scheduling a LoopPass.
337 After the loop optimizations are done, these extra phi nodes
338 will be deleted by :ref:`-instcombine <passes-instcombine>`.
340 Note that an exit block is outside of a loop, so how can such a phi "close"
341 the value inside the loop since it uses it outside of it ? First of all,
343 `mentioned in the LangRef <https://llvm.org/docs/LangRef.html#id311>`_:
344 "the use of each incoming value is deemed to occur on the edge from the
345 corresponding predecessor block to the current block". Now, an
346 edge to an exit block is considered outside of the loop because
347 if we take that edge, it leads us clearly out of the loop.
349 However, an edge doesn't actually contain any IR, so in source code,
350 we have to choose a convention of whether the use happens in
351 the current block or in the respective predecessor. For LCSSA's purpose,
352 we consider the use happens in the latter (so as to consider the
353 use inside) [#point-of-use-phis]_.
355 The major benefit of LCSSA is that it makes many other loop optimizations
358 First of all, a simple observation is that if one needs to see all
359 the outside users, they can just iterate over all the (loop closing)
360 PHI nodes in the exit blocks (the alternative would be to
361 scan the def-use chain [#def-use-chain]_ of all instructions in the loop).
363 Then, consider for example
364 :ref:`-loop-unswitch <passes-loop-unswitch>` ing the loop above.
365 Because it is in LCSSA form, we know that any value defined inside of
366 the loop will be used either only inside the loop or in a loop closing
367 PHI node. In this case, the only loop closing PHI node is X4.
368 This means that we can just copy the loop and change the X4
369 accordingly, like so:
393 Now, all uses of X4 will get the updated value (in general,
394 if a loop is in LCSSA form, in any loop transformation,
395 we only need to update the loop closing PHI nodes for the changes
396 to take effect). If we did not have Loop Closed SSA form, it means that X3 could
397 possibly be used outside the loop. So, we would have to introduce the
398 X4 (which is the new X3) and replace all uses of X3 with that.
399 However, we should note that because LLVM keeps a def-use chain
400 [#def-use-chain]_ for each Value, we wouldn't need
401 to perform data-flow analysis to find and replace all the uses
402 (there is even a utility function, replaceAllUsesWith(),
403 that performs this transformation by iterating the def-use chain).
405 Another important advantage is that the behavior of all uses
406 of an induction variable is the same. Without this, you need to
407 distinguish the case when the variable is used outside of
408 the loop it is defined in, for example:
412 for (i = 0; i < 100; i++) {
413 for (j = 0; j < 100; j++) {
420 Looking from the outer loop with the normal SSA form, the first use of k
421 is not well-behaved, while the second one is an induction variable with
422 base 100 and step 1. Although, in practice, and in the LLVM context,
423 such cases can be handled effectively by SCEV. Scalar Evolution
424 (:ref:`scalar-evolution <passes-scalar-evolution>`) or SCEV, is a
425 (analysis) pass that analyzes and categorizes the evolution of scalar
426 expressions in loops.
428 In general, it's easier to use SCEV in loops that are in LCSSA form.
429 The evolution of a scalar (loop-variant) expression that
430 SCEV can analyze is, by definition, relative to a loop.
431 An expression is represented in LLVM by an
432 `llvm::Instruction <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`_.
433 If the expression is inside two (or more) loops (which can only
434 happen if the loops are nested, like in the example above) and you want
435 to get an analysis of its evolution (from SCEV),
436 you have to also specify relative to what Loop you want it.
437 Specifically, you have to use
438 `getSCEVAtScope() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a21d6ee82eed29080d911dbb548a8bb68>`_.
440 However, if all loops are in LCSSA form, each expression is actually
441 represented by two different llvm::Instructions. One inside the loop
442 and one outside, which is the loop-closing PHI node and represents
443 the value of the expression after the last iteration (effectively,
444 we break each loop-variant expression into two expressions and so, every
445 expression is at most in one loop). You can now just use
446 `getSCEV() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a30bd18ac905eacf3601bc6a553a9ff49>`_.
447 and which of these two llvm::Instructions you pass to it disambiguates
448 the context / scope / relative loop.
450 .. rubric:: Footnotes
452 .. [#lcssa-construction] To insert these loop-closing PHI nodes, one has to
453 (re-)compute dominance frontiers (if the loop has multiple exits).
455 .. [#point-of-use-phis] Considering the point of use of a PHI entry value
456 to be in the respective predecessor is a convention across the whole LLVM.
457 The reason is mostly practical; for example it preserves the dominance
458 property of SSA. It is also just an overapproximation of the actual
459 number of uses; the incoming block could branch to another block in which
460 case the value is not actually used but there are no side-effects (it might
461 increase its live range which is not relevant in LCSSA though).
462 Furthermore, we can gain some intuition if we consider liveness:
463 A PHI is *usually* inserted in the current block because the value can't
464 be used from this point and onwards (i.e. the current block is a dominance
465 frontier). It doesn't make sense to consider that the value is used in
466 the current block (because of the PHI) since the value stops being live
467 before the PHI. In some sense the PHI definition just "replaces" the original
468 value definition and doesn't actually use it. It should be stressed that
469 this analogy is only used as an example and does not pose any strict
470 requirements. For example, the value might dominate the current block
471 but we can still insert a PHI (as we do with LCSSA PHI nodes) *and*
472 use the original value afterwards (in which case the two live ranges overlap,
473 although in LCSSA (the whole point is that) we never do that).
476 .. [#def-use-chain] A property of SSA is that there exists a def-use chain
477 for each definition, which is a list of all the uses of this definition.
478 LLVM implements this property by keeping a list of all the uses of a Value
479 in an internal data structure.
481 "More Canonical" Loops
482 ======================
484 .. _loop-terminology-loop-rotate:
489 Loops are rotated by the LoopRotate (:ref:`loop-rotate <passes-loop-rotate>`)
490 pass, which converts loops into do/while style loops and is
492 `LoopRotation.h <https://llvm.org/doxygen/LoopRotation_8h_source.html>`_. Example:
497 for (int i = 0; i < n; i += 1)
513 **Warning**: This transformation is valid only if the compiler
514 can prove that the loop body will be executed at least once. Otherwise,
515 it has to insert a guard which will test it at runtime. In the example
516 above, that would be:
530 It's important to understand the effect of loop rotation
531 at the LLVM IR level. We follow with the previous examples
532 in LLVM IR while also providing a graphical representation
533 of the control-flow graphs (CFG). You can get the same graphical
534 results by utilizing the :ref:`view-cfg <passes-view-cfg>` pass.
536 The initial **for** loop could be translated to:
540 define void @test(i32 %n) {
545 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
546 %cond = icmp slt i32 %i, %n
547 br i1 %cond, label %body, label %exit
554 %i.next = add nsw i32 %i, 1
561 .. image:: ./loop-terminology-initial-loop.png
564 Before we explain how LoopRotate will actually
565 transform this loop, here's how we could convert
566 it (by hand) to a do-while style loop.
570 define void @test(i32 %n) {
575 %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
580 %i.next = add nsw i32 %i, 1
581 %cond = icmp slt i32 %i.next, %n
582 br i1 %cond, label %body, label %exit
588 .. image:: ./loop-terminology-rotated-loop.png
593 * The condition check was moved to the "bottom" of the loop, i.e.
594 the latch. This is something that LoopRotate does by copying the header
595 of the loop to the latch.
596 * The compiler in this case can't deduce that the loop will
597 definitely execute at least once so the above transformation
598 is not valid. As mentioned above, a guard has to be inserted,
599 which is something that LoopRotate will do.
601 This is how LoopRotate transforms this loop:
605 define void @test(i32 %n) {
607 %guard_cond = icmp slt i32 0, %n
608 br i1 %guard_cond, label %loop.preheader, label %exit
614 %i2 = phi i32 [ 0, %loop.preheader ], [ %i.next, %latch ]
618 %i.next = add nsw i32 %i2, 1
619 %cond = icmp slt i32 %i.next, %n
620 br i1 %cond, label %body, label %loop.exit
629 .. image:: ./loop-terminology-guarded-loop.png
632 The result is a little bit more complicated than we may expect
633 because LoopRotate ensures that the loop is in
634 :ref:`Loop Simplify Form <loop-terminology-loop-simplify>`
636 In this case, it inserted the %loop.preheader basic block so
637 that the loop has a preheader and it introduced the %loop.exit
638 basic block so that the loop has dedicated exits
639 (otherwise, %exit would be jumped from both %latch and %entry,
640 but %entry is not contained in the loop).
641 Note that a loop has to be in Loop Simplify Form beforehand
642 too for LoopRotate to be applied successfully.
644 The main advantage of this form is that it allows hoisting
645 invariant instructions, especially loads, into the preheader.
646 That could be done in non-rotated loops as well but with
647 some disadvantages. Let's illustrate them with an example:
651 for (int i = 0; i < n; ++i) {
656 We assume that loading from p is invariant and use(v) is some
657 statement that uses v.
658 If we wanted to execute the load only once we could move it
659 "out" of the loop body, resulting in this:
664 for (int i = 0; i < n; ++i) {
668 However, now, in the case that n <= 0, in the initial form,
669 the loop body would never execute, and so, the load would
670 never execute. This is a problem mainly for semantic reasons.
671 Consider the case in which n <= 0 and loading from p is invalid.
672 In the initial program there would be no error. However, with this
673 transformation we would introduce one, effectively breaking
674 the initial semantics.
676 To avoid both of these problems, we can insert a guard:
680 if (n > 0) { // loop guard
682 for (int i = 0; i < n; ++i) {
687 This is certainly better but it could be improved slightly. Notice
688 that the check for whether n is bigger than 0 is executed twice (and
689 n does not change in between). Once when we check the guard condition
690 and once in the first execution of the loop. To avoid that, we could
691 do an unconditional first execution and insert the loop condition
692 in the end. This effectively means transforming the loop into a do-while loop:
704 Note that LoopRotate does not generally do such
705 hoisting. Rather, it is an enabling transformation for other
706 passes like Loop-Invariant Code Motion (:ref:`-licm <passes-licm>`).