1.. _loop-terminology:
2
3===========================================
4LLVM Loop Terminology (and Canonical Forms)
5===========================================
6
7.. contents::
8   :local:
9
10Loop Definition
11===============
12
13Loops are an important concept for a code optimizer. In LLVM, detection
14of loops in a control-flow graph is done by :ref:`loopinfo`. It is based
15on the following definition.
16
17A loop is a subset of nodes from the control-flow graph (CFG; where
18nodes represent basic blocks) with the following properties:
19
201. The induced subgraph (which is the subgraph that contains all the
21   edges from the CFG within the loop) is strongly connected
22   (every node is reachable from all others).
23
242. All edges from outside the subset into the subset point to the same
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).
28
293. The loop is the maximum subset with these properties. That is, no
30   additional nodes from the CFG can be added such that the induced
31   subgraph would still be strongly connected and the header would
32   remain the same.
33
34In computer science literature, this is often called a *natural loop*.
35In LLVM, this is the only definition of a loop.
36
37
38Terminology
39-----------
40
41The definition of a loop comes with some additional terminology:
42
43* An **entering block** (or **loop predecessor**) is a non-loop node
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.
48
49* A **latch** is a loop node that has an edge to the header.
50
51* A **backedge** is an edge from a latch to the header.
52
53* An **exiting edge** is an edge from inside the loop to a node outside
54  of the loop. The source of such an edge is called an **exiting block**, its
55  target is an **exit block**.
56
57.. image:: ./loop-terminology.svg
58   :width: 400 px
59
60
61Important Notes
62---------------
63
64This loop definition has some noteworthy consequences:
65
66* A node can be the header of at most one loop. As such, a loop can be
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.
69
70
71* For basic blocks that are not reachable from the function's entry, the
72  concept of loops is undefined. This follows from the concept of
73  dominance being undefined as well.
74
75
76* The smallest loop consists of a single basic block that branches to
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.
81
82.. image:: ./loop-single.svg
83   :width: 300 px
84
85In this case, the role of header, exiting block and latch fall to the
86same node. :ref:`loopinfo` reports this as:
87
88.. code-block:: console
89
90  $ opt input.ll -loops -analyze
91  Loop at depth 1 containing: %for.body<header><latch><exiting>
92
93
94* Loops can be nested inside each other. That is, a loop's node set can
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.
98
99.. image:: ./loop-nested.svg
100   :width: 350 px
101
102
103* It is not possible that two loops share only a few of their nodes.
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.
107
108.. image:: ./loop-nonmaximal.svg
109   :width: 250 px
110
111
112* It is also possible that two logical loops share a header, but are
113  considered a single loop by LLVM:
114
115.. code-block:: C
116
117  for (int i = 0; i < 128; ++i)
118    for (int j = 0; j < 128; ++j)
119      body(i,j);
120
121which might be represented in LLVM-IR as follows. Note that there is
122only a single header and hence just a single loop.
123
124.. image:: ./loop-merge.svg
125   :width: 400 px
126
127The :ref:`LoopSimplify <loop-terminology-loop-simplify>` pass will
128detect the loop and ensure separate headers for the outer and inner loop.
129
130.. image:: ./loop-separate.svg
131   :width: 400 px
132
133* A cycle in the CFG does not imply there is a loop. The example below
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**.
136
137.. image:: ./loop-irreducible.svg
138   :width: 150 px
139
140The term reducible results from the ability to collapse the CFG into a
141single node by successively replacing one of three base structures with
142a single node: A sequential execution of basic blocks, a conditional
143branching (or switch) with re-joining, and a basic block looping on itself.
144`Wikipedia <https://en.wikipedia.org/wiki/Control-flow_graph#Reducibility>`_
145has a more formal definition, which basically says that every cycle has
146a dominating header.
147
148
149* Irreducible control-flow can occur at any level of the loop nesting.
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.
154
155
156* Exiting edges are not the only way to break out of a loop. Other
157  possibilities are unreachable terminators, [[noreturn]] functions,
158  exceptions, signals, and your computer's power button.
159
160
161* A basic block "inside" the loop that does not have a path back to the
162  loop (i.e. to a latch or header) is not considered part of the loop.
163  This is illustrated by the following code.
164
165.. code-block:: C
166
167  for (unsigned i = 0; i <= n; ++i) {
168    if (c1) {
169      // When reaching this block, we will have exited the loop.
170      do_something();
171      break;
172    }
173    if (c2) {
174      // abort(), never returns, so we have exited the loop.
175      abort();
176    }
177    if (c3) {
178      // The unreachable allows the compiler to assume that this will not rejoin the loop.
179      do_something();
180      __builtin_unreachable();
181    }
182    if (c4) {
183      // This statically infinite loop is not nested because control-flow will not continue with the for-loop.
184      while(true) {
185        do_something();
186      }
187    }
188  }
189
190
191* There is no requirement for the control flow to eventually leave the
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
196  below.
197
198.. code-block:: C
199
200  for (unsigned i = 0; i <= n; ++i)
201    body(i);
202
203It is possible for the optimizer to turn a dynamically infinite loop
204into a statically infinite loop, for instance when it can prove that the
205exiting condition is always false. Because the exiting edge is never
206taken, the optimizer can change the conditional branch into an
207unconditional one.
208
209Note that under some circumstances the compiler may assume that a loop will
210eventually terminate without proving it. For instance, it may remove a loop
211that does not do anything in its body. If the loop was infinite, this
212optimization resulted in an "infinite" performance speed-up. A call
213to the intrinsic :ref:`llvm.sideeffect<llvm_sideeffect>` can be added
214into the loop to ensure that the optimizer does not make this assumption
215without proof.
216
217
218* The number of executions of the loop header before leaving the loop is
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:
221
222.. image:: ./loop-guard.svg
223   :width: 500 px
224
225Since the first thing a loop header might do is to check whether there
226is another execution and if not, immediately exit without doing any work
227(also see :ref:`loop-terminology-loop-rotate`), loop trip count is not
228the best measure of a loop's number of iterations. For instance, the
229number 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
231at all.
232
233.. code-block:: C
234
235  for (int i = 0; i < n; ++i)
236    body(i);
237
238A better measure is the **backedge-taken count**, which is the number of
239times any of the backedges is taken before the loop. It is one less than
240the trip count for executions that enter the header.
241
242
243.. _loopinfo:
244
245LoopInfo
246========
247
248LoopInfo is the core analysis for obtaining information about loops.
249There are few key implications of the definitions given above which
250are important for working successfully with this interface.
251
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.
255
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.
259
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.
264
265
266.. _loop-terminology-loop-simplify:
267
268Loop Simplify Form
269==================
270
271The Loop Simplify Form is a canonical form that makes
272several analyses and transformations simpler and more effective.
273It is ensured by the LoopSimplify
274(:ref:`-loop-simplify <passes-loop-simplify>`) pass and is automatically
275added by the pass managers when scheduling a LoopPass.
276This pass is implemented in
277`LoopSimplify.h <https://llvm.org/doxygen/LoopSimplify_8h_source.html>`_.
278When it is successful, the loop has:
279
280* A preheader.
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.
285
286.. _loop-terminology-lcssa:
287
288Loop Closed SSA (LCSSA)
289=======================
290
291A program is in Loop Closed SSA Form if it is in SSA form
292and all values that are defined in a loop are used only inside
293this loop.
294
295Programs written in LLVM IR are always in SSA form but not necessarily
296in LCSSA. To achieve the latter, for each value that is live across the
297loop 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.
299In particular, consider the following loop:
300
301.. code-block:: C
302
303    c = ...;
304    for (...) {
305      if (c)
306        X1 = ...
307      else
308        X2 = ...
309      X3 = phi(X1, X2);  // X3 defined
310    }
311
312    ... = X3 + 4;  // X3 used, i.e. live
313                   // outside the loop
314
315In the inner loop, the X3 is defined inside the loop, but used
316outside of it. In Loop Closed SSA form, this would be represented as follows:
317
318.. code-block:: C
319
320    c = ...;
321    for (...) {
322      if (c)
323        X1 = ...
324      else
325        X2 = ...
326      X3 = phi(X1, X2);
327    }
328    X4 = phi(X3);
329
330    ... = X4 + 4;
331
332This is still valid LLVM; the extra phi nodes are purely redundant,
333but all LoopPass'es are required to preserve them.
334This form is ensured by the LCSSA (:ref:`-lcssa <passes-lcssa>`)
335pass and is added automatically by the LoopPassManager when
336scheduling a LoopPass.
337After the loop optimizations are done, these extra phi nodes
338will be deleted by :ref:`-instcombine <passes-instcombine>`.
339
340Note that an exit block is outside of a loop, so how can such a phi "close"
341the value inside the loop since it uses it outside of it ? First of all,
342for phi nodes, as
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
345corresponding predecessor block to the current block". Now, an
346edge to an exit block is considered outside of the loop because
347if we take that edge, it leads us clearly out of the loop.
348
349However, an edge doesn't actually contain any IR, so in source code,
350we have to choose a convention of whether the use happens in
351the current block or in the respective predecessor. For LCSSA's purpose,
352we consider the use happens in the latter (so as to consider the
353use inside) [#point-of-use-phis]_.
354
355The major benefit of LCSSA is that it makes many other loop optimizations
356simpler.
357
358First of all, a simple observation is that if one needs to see all
359the outside users, they can just iterate over all the (loop closing)
360PHI nodes in the exit blocks (the alternative would be to
361scan the def-use chain [#def-use-chain]_ of all instructions in the loop).
362
363Then, consider for example
364:ref:`-loop-unswitch <passes-loop-unswitch>` ing the loop above.
365Because it is in LCSSA form, we know that any value defined inside of
366the loop will be used either only inside the loop or in a loop closing
367PHI node. In this case, the only loop closing PHI node is X4.
368This means that we can just copy the loop and change the X4
369accordingly, like so:
370
371.. code-block:: C
372
373    c = ...;
374    if (c) {
375      for (...) {
376        if (true)
377          X1 = ...
378        else
379          X2 = ...
380        X3 = phi(X1, X2);
381      }
382    } else {
383      for (...) {
384        if (false)
385          X1' = ...
386        else
387          X2' = ...
388        X3' = phi(X1', X2');
389      }
390    }
391    X4 = phi(X3, X3')
392
393Now, all uses of X4 will get the updated value (in general,
394if a loop is in LCSSA form, in any loop transformation,
395we only need to update the loop closing PHI nodes for the changes
396to take effect).  If we did not have Loop Closed SSA form, it means that X3 could
397possibly be used outside the loop. So, we would have to introduce the
398X4 (which is the new X3) and replace all uses of X3 with that.
399However, we should note that because LLVM keeps a def-use chain
400[#def-use-chain]_ for each Value, we wouldn't need
401to perform data-flow analysis to find and replace all the uses
402(there is even a utility function, replaceAllUsesWith(),
403that performs this transformation by iterating the def-use chain).
404
405Another important advantage is that the behavior of all uses
406of an induction variable is the same.  Without this, you need to
407distinguish the case when the variable is used outside of
408the loop it is defined in, for example:
409
410.. code-block:: C
411
412  for (i = 0; i < 100; i++) {
413    for (j = 0; j < 100; j++) {
414      k = i + j;
415      use(k);    // use 1
416    }
417    use(k);      // use 2
418  }
419
420Looking from the outer loop with the normal SSA form, the first use of k
421is not well-behaved, while the second one is an induction variable with
422base 100 and step 1.  Although, in practice, and in the LLVM context,
423such 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
426expressions in loops.
427
428In general, it's easier to use SCEV in loops that are in LCSSA form.
429The evolution of a scalar (loop-variant) expression that
430SCEV can analyze is, by definition, relative to a loop.
431An expression is represented in LLVM by an
432`llvm::Instruction <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`_.
433If the expression is inside two (or more) loops (which can only
434happen if the loops are nested, like in the example above) and you want
435to get an analysis of its evolution (from SCEV),
436you have to also specify relative to what Loop you want it.
437Specifically, you have to use
438`getSCEVAtScope() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a21d6ee82eed29080d911dbb548a8bb68>`_.
439
440However, if all loops are in LCSSA form, each expression is actually
441represented by two different llvm::Instructions.  One inside the loop
442and one outside, which is the loop-closing PHI node and represents
443the value of the expression after the last iteration (effectively,
444we break each loop-variant expression into two expressions and so, every
445expression is at most in one loop).  You can now just use
446`getSCEV() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a30bd18ac905eacf3601bc6a553a9ff49>`_.
447and which of these two llvm::Instructions you pass to it disambiguates
448the context / scope / relative loop.
449
450.. rubric:: Footnotes
451
452.. [#lcssa-construction] To insert these loop-closing PHI nodes, one has to
453  (re-)compute dominance frontiers (if the loop has multiple exits).
454
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).
474
475
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.
480
481"More Canonical" Loops
482======================
483
484.. _loop-terminology-loop-rotate:
485
486Rotated Loops
487-------------
488
489Loops are rotated by the LoopRotate (:ref:`loop-rotate <passes-loop-rotate>`)
490pass, which converts loops into do/while style loops and is
491implemented in
492`LoopRotation.h <https://llvm.org/doxygen/LoopRotation_8h_source.html>`_.  Example:
493
494.. code-block:: C
495
496  void test(int n) {
497    for (int i = 0; i < n; i += 1)
498      // Loop body
499  }
500
501is transformed to:
502
503.. code-block:: C
504
505  void test(int n) {
506    int i = 0;
507    do {
508      // Loop body
509      i += 1;
510    } while (i < n);
511  }
512
513**Warning**: This transformation is valid only if the compiler
514can prove that the loop body will be executed at least once. Otherwise,
515it has to insert a guard which will test it at runtime. In the example
516above, that would be:
517
518.. code-block:: C
519
520  void test(int n) {
521    int i = 0;
522    if (n > 0) {
523      do {
524        // Loop body
525        i += 1;
526      } while (i < n);
527    }
528  }
529
530It's important to understand the effect of loop rotation
531at the LLVM IR level. We follow with the previous examples
532in LLVM IR while also providing a graphical representation
533of the control-flow graphs (CFG). You can get the same graphical
534results by utilizing the :ref:`view-cfg <passes-view-cfg>` pass.
535
536The initial **for** loop could be translated to:
537
538.. code-block:: none
539
540  define void @test(i32 %n) {
541  entry:
542    br label %for.header
543
544  for.header:
545    %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
546    %cond = icmp slt i32 %i, %n
547    br i1 %cond, label %body, label %exit
548
549  body:
550    ; Loop body
551    br label %latch
552
553  latch:
554    %i.next = add nsw i32 %i, 1
555    br label %for.header
556
557  exit:
558    ret void
559  }
560
561.. image:: ./loop-terminology-initial-loop.png
562  :width: 400 px
563
564Before we explain how LoopRotate will actually
565transform this loop, here's how we could convert
566it (by hand) to a do-while style loop.
567
568.. code-block:: none
569
570  define void @test(i32 %n) {
571  entry:
572    br label %body
573
574  body:
575    %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
576    ; Loop body
577    br label %latch
578
579  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
583
584  exit:
585    ret void
586  }
587
588.. image:: ./loop-terminology-rotated-loop.png
589  :width: 400 px
590
591Note two things:
592
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.
600
601This is how LoopRotate transforms this loop:
602
603.. code-block:: none
604
605  define void @test(i32 %n) {
606  entry:
607    %guard_cond = icmp slt i32 0, %n
608    br i1 %guard_cond, label %loop.preheader, label %exit
609
610  loop.preheader:
611    br label %body
612
613  body:
614    %i2 = phi i32 [ 0, %loop.preheader ], [ %i.next, %latch ]
615    br label %latch
616
617  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
621
622  loop.exit:
623    br label %exit
624
625  exit:
626    ret void
627  }
628
629.. image:: ./loop-terminology-guarded-loop.png
630  :width: 500 px
631
632The result is a little bit more complicated than we may expect
633because LoopRotate ensures that the loop is in
634:ref:`Loop Simplify Form <loop-terminology-loop-simplify>`
635after rotation.
636In this case, it inserted the %loop.preheader basic block so
637that the loop has a preheader and it introduced the %loop.exit
638basic block so that the loop has dedicated exits
639(otherwise, %exit would be jumped from both %latch and %entry,
640but %entry is not contained in the loop).
641Note that a loop has to be in Loop Simplify Form beforehand
642too for LoopRotate to be applied successfully.
643
644The main advantage of this form is that it allows hoisting
645invariant instructions, especially loads, into the preheader.
646That could be done in non-rotated loops as well but with
647some disadvantages.  Let's illustrate them with an example:
648
649.. code-block:: C
650
651  for (int i = 0; i < n; ++i) {
652    auto v = *p;
653    use(v);
654  }
655
656We assume that loading from p is invariant and use(v) is some
657statement that uses v.
658If we wanted to execute the load only once we could move it
659"out" of the loop body, resulting in this:
660
661.. code-block:: C
662
663  auto v = *p;
664  for (int i = 0; i < n; ++i) {
665    use(v);
666  }
667
668However, now, in the case that n <= 0, in the initial form,
669the loop body would never execute, and so, the load would
670never execute.  This is a problem mainly for semantic reasons.
671Consider the case in which n <= 0 and loading from p is invalid.
672In the initial program there would be no error.  However, with this
673transformation we would introduce one, effectively breaking
674the initial semantics.
675
676To avoid both of these problems, we can insert a guard:
677
678.. code-block:: C
679
680  if (n > 0) {  // loop guard
681    auto v = *p;
682    for (int i = 0; i < n; ++i) {
683      use(v);
684    }
685  }
686
687This is certainly better but it could be improved slightly. Notice
688that the check for whether n is bigger than 0 is executed twice (and
689n does not change in between).  Once when we check the guard condition
690and once in the first execution of the loop.  To avoid that, we could
691do an unconditional first execution and insert the loop condition
692in the end. This effectively means transforming the loop into a do-while loop:
693
694.. code-block:: C
695
696  if (0 < n) {
697    auto v = *p;
698    do {
699      use(v);
700      ++i;
701    } while (i < n);
702  }
703
704Note that LoopRotate does not generally do such
705hoisting.  Rather, it is an enabling transformation for other
706passes like Loop-Invariant Code Motion (:ref:`-licm <passes-licm>`).
707