1.. _loop-terminology:
2
3===========================================
4LLVM Loop Terminology (and Canonical Forms)
5===========================================
6
7.. contents::
8   :local:
9
10Introduction
11============
12
13Loops are a core concept in any optimizer.  This page spells out some
14of the common terminology used within LLVM code to describe loop
15structures.
16
17First, let's start with the basics. In LLVM, a Loop is a maximal set of basic
18blocks that form a strongly connected component (SCC) in the Control
19Flow Graph (CFG) where there exists a dedicated entry/header block that
20dominates all other blocks within the loop. Thus, without leaving the
21loop, one can reach every block in the loop from the header block and
22the header block from every block in the loop.
23
24Note that there are some important implications of this definition:
25
26* Not all SCCs are loops.  There exist SCCs that do not meet the
27  dominance requirement and such are not considered loops.
28
29* Loops can contain non-loop SCCs and non-loop SCCs may contain
30  loops.  Loops may also contain sub-loops.
31
32* A header block is uniquely associated with one loop.  There can be
33  multiple SCC within that loop, but the strongly connected component
34  (SCC) formed from their union must always be unique.
35
36* Given the use of dominance in the definition, all loops are
37  statically reachable from the entry of the function.
38
39* Every loop must have a header block, and some set of predecessors
40  outside the loop.  A loop is allowed to be statically infinite, so
41  there need not be any exiting edges.
42
43* Any two loops are either fully disjoint (no intersecting blocks), or
44  one must be a sub-loop of the other.
45
46* Loops in a function form a forest. One implication of this fact
47  is that a loop either has no parent or a single parent.
48
49A loop may have an arbitrary number of exits, both explicit (via
50control flow) and implicit (via throwing calls which transfer control
51out of the containing function).  There is no special requirement on
52the form or structure of exit blocks (the block outside the loop which
53is branched to).  They may have multiple predecessors, phis, etc...
54
55Key Terminology
56===============
57
58**Header Block** - The basic block which dominates all other blocks
59contained within the loop.  As such, it is the first one executed if
60the loop executes at all.  Note that a block can be the header of
61two separate loops at the same time, but only if one is a sub-loop
62of the other.
63
64**Exiting Block** - A basic block contained within a given loop which has
65at least one successor outside of the loop and one successor inside the
66loop.  (The latter is a consequence of the block being contained within
67an SCC which is part of the loop.)  That is, it has a successor which
68is an Exit Block.
69
70**Exit Block** - A basic block outside of the associated loop which has a
71predecessor inside the loop.  That is, it has a predecessor which is
72an Exiting Block.
73
74**Latch Block** - A basic block within the loop whose successors include
75the header block of the loop.  Thus, a latch is a source of backedge.
76A loop may have multiple latch blocks.  A latch block may be either
77conditional or unconditional.
78
79**Backedge(s)** - The edge(s) in the CFG from latch blocks to the header
80block.  Note that there can be multiple such edges, and even multiple
81such edges leaving a single latch block.
82
83**Loop Predecessor** -  The predecessor blocks of the loop header which
84are not contained by the loop itself.  These are the only blocks
85through which execution can enter the loop.  When used in the
86singular form implies that there is only one such unique block.
87
88**Preheader Block** - A preheader is a (singular) loop predecessor which
89ends in an unconditional transfer of control to the loop header.  Note
90that not all loops have such blocks.
91
92**Backedge Taken Count** - The number of times the backedge will execute
93before some interesting event happens.  Commonly used without
94qualification of the event as a shorthand for when some exiting block
95branches to some exit block. May be zero, or not statically computable.
96
97**Iteration Count** - The number of times the header will execute before
98some interesting event happens.  Commonly used without qualification to
99refer to the iteration count at which the loop exits.  Will always be
100one greater than the backedge taken count.  *Warning*: Preceding
101statement is true in the *integer domain*; if you're dealing with fixed
102width integers (such as LLVM Values or SCEVs), you need to be cautious
103of overflow when converting one to the other.
104
105It's important to note that the same basic block can play multiple
106roles in the same loop, or in different loops at once.  For example, a
107single block can be the header for two nested loops at once, while
108also being an exiting block for the inner one only, and an exit block
109for a sibling loop.  Example:
110
111.. code-block:: C
112
113  while (..) {
114    for (..) {}
115    do {
116      do {
117        // <-- block of interest
118        if (exit) break;
119      } while (..);
120    } while (..)
121  }
122
123LoopInfo
124========
125
126LoopInfo is the core analysis for obtaining information about loops.
127There are few key implications of the definitions given above which
128are important for working successfully with this interface.
129
130* LoopInfo does not contain information about non-loop cycles.  As a
131  result, it is not suitable for any algorithm which requires complete
132  cycle detection for correctness.
133
134* LoopInfo provides an interface for enumerating all top level loops
135  (e.g. those not contained in any other loop).  From there, you may
136  walk the tree of sub-loops rooted in that top level loop.
137
138* Loops which become statically unreachable during optimization *must*
139  be removed from LoopInfo. If this can not be done for some reason,
140  then the optimization is *required* to preserve the static
141  reachability of the loop.
142
143
144.. _loop-terminology-loop-simplify:
145
146Loop Simplify Form
147==================
148
149The Loop Simplify Form is a canonical form that makes
150several analyses and transformations simpler and more effective.
151It is ensured by the LoopSimplify
152(:ref:`-loop-simplify <passes-loop-simplify>`) pass and is automatically
153added by the pass managers when scheduling a LoopPass.
154This pass is implemented in
155`LoopSimplify.h <https://llvm.org/doxygen/LoopSimplify_8h_source.html>`_.
156When it is successful, the loop has:
157
158* A preheader.
159* A single backedge (which implies that there is a single latch).
160* Dedicated exits. That is, no exit block for the loop
161  has a predecessor that is outside the loop. This implies
162  that all exit blocks are dominated by the loop header.
163
164.. _loop-terminology-lcssa:
165
166Loop Closed SSA (LCSSA)
167=======================
168
169A program is in Loop Closed SSA Form if it is in SSA form
170and all values that are defined in a loop are used only inside
171this loop.
172Programs written in LLVM IR are always in SSA form but not necessarily
173in LCSSA. To achieve the latter, single entry PHI nodes are inserted
174at the end of the loops for all values that are live
175across the loop boundary [#lcssa-construction]_.
176In particular, consider the following loop:
177
178.. code-block:: C
179
180    c = ...;
181    for (...) {
182      if (c)
183        X1 = ...
184      else
185        X2 = ...
186      X3 = phi(X1, X2);  // X3 defined
187    }
188
189    ... = X3 + 4;  // X3 used, i.e. live
190                   // outside the loop
191
192In the inner loop, the X3 is defined inside the loop, but used
193outside of it. In Loop Closed SSA form, this would be represented as follows:
194
195.. code-block:: C
196
197    c = ...;
198    for (...) {
199      if (c)
200        X1 = ...
201      else
202        X2 = ...
203      X3 = phi(X1, X2);
204    }
205    X4 = phi(X3);
206
207    ... = X4 + 4;
208
209This is still valid LLVM; the extra phi nodes are purely redundant,
210but all LoopPass'es are required to preserve them.
211This form is ensured by the LCSSA (:ref:`-lcssa <passes-lcssa>`)
212pass and is added automatically by the LoopPassManager when
213scheduling a LoopPass.
214After the loop optimizations are done, these extra phi nodes
215will be deleted by :ref:`-instcombine <passes-instcombine>`.
216
217The major benefit of this transformation is that it makes many other
218loop optimizations simpler.
219
220First of all, a simple observation is that if one needs to see all
221the outside users, they can just iterate over all the (loop closing)
222PHI nodes in the exit blocks (the alternative would be to
223scan the def-use chain [#def-use-chain]_ of all instructions in the loop).
224
225Then, consider for example
226:ref:`-loop-unswitch <passes-loop-unswitch>` ing the loop above.
227Because it is in LCSSA form, we know that any value defined inside of
228the loop will be used either only inside the loop or in a loop closing
229PHI node. In this case, the only loop closing PHI node is X4.
230This means that we can just copy the loop and change the X4
231accordingly, like so:
232
233.. code-block:: C
234
235  for (...) {
236    c = ...;
237    if (c) {
238      for (...) {
239        if (true)
240          X1 = ...
241        else
242          X2 = ...
243        X3 = phi(X1, X2);
244      }
245    } else {
246      for (...) {
247        if (false)
248          X1' = ...
249        else
250          X2' = ...
251        X3' = phi(X1', X2');
252      }
253    }
254    X4 = phi(X3, X3')
255
256Now, all uses of X4 will get the updated value (in general,
257if a loop is in LCSSA form, in any loop transformation,
258we only need to update the loop closing PHI nodes for the changes
259to take effect).  If we did not have Loop Closed SSA form, it means that X3 could
260possibly be used outside the loop. So, we would have to introduce the
261X4 (which is the new X3) and replace all uses of X3 with that.
262However, we should note that because LLVM keeps a def-use chain
263[#def-use-chain]_ for each Value, we wouldn't need
264to perform data-flow analysis to find and replace all the uses
265(there is even a utility function, replaceAllUsesWith(),
266that performs this transformation by iterating the def-use chain).
267
268Another important advantage is that the behavior of all uses
269of an induction variable is the same.  Without this, you need to
270distinguish the case when the variable is used outside of
271the loop it is defined in, for example:
272
273.. code-block:: C
274
275  for (i = 0; i < 100; i++) {
276    for (j = 0; j < 100; j++) {
277      k = i + j;
278      use(k);    // use 1
279    }
280    use(k);      // use 2
281  }
282
283Looking from the outer loop with the normal SSA form, the first use of k
284is not well-behaved, while the second one is an induction variable with
285base 100 and step 1.  Although, in practice, and in the LLVM context,
286such cases can be handled effectively by SCEV. Scalar Evolution
287(:ref:`scalar-evolution <passes-scalar-evolution>`) or SCEV, is a
288(analysis) pass that analyzes and categorizes the evolution of scalar
289expressions in loops.
290
291In general, it's easier to use SCEV in loops that are in LCSSA form.
292The evolution of a scalar (loop-variant) expression that
293SCEV can analyze is, by definition, relative to a loop.
294An expression is represented in LLVM by an
295`llvm::Instruction <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`.
296If the expression is inside two (or more) loops (which can only
297happen if the loops are nested, like in the example above) and you want
298to get an analysis of its evolution (from SCEV),
299you have to also specify relative to what Loop you want it.
300Specifically, you have to use
301`getSCEVAtScope() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a21d6ee82eed29080d911dbb548a8bb68>`_.
302
303However, if all loops are in LCSSA form, each expression is actually
304represented by two different llvm::Instructions.  One inside the loop
305and one outside, which is the loop-closing PHI node and represents
306the value of the expression after the last iteration (effectively,
307we break each loop-variant expression into two expressions and so, every
308expression is at most in one loop).  You can now just use
309`getSCEV() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a30bd18ac905eacf3601bc6a553a9ff49>`_.
310and which of these two llvm::Instructions you pass to it disambiguates
311the context / scope / relative loop.
312
313.. rubric:: Footnotes
314
315.. [#lcssa-construction] To insert these loop-closing PHI nodes, one has to
316  (re-)compute dominance frontiers (if the loop has multiple exits).
317
318.. [#def-use-chain] A property of SSA is that there exists a def-use chain
319  for each definition, which is a list of all the uses of this definition.
320  LLVM implements this property by keeping a list of all the uses of a Value
321  in an internal data structure.
322
323"More Canonical" Loops
324======================
325
326.. _loop-terminology-loop-rotate:
327
328Rotated Loops
329-------------
330
331Loops are rotated by the LoopRotate (:ref:`loop-rotate <passes-loop-rotate>`)
332pass, which converts loops into do/while style loops and is
333implemented in
334`LoopRotation.h <https://llvm.org/doxygen/LoopRotation_8h_source.html>`_.  Example:
335
336.. code-block:: C
337
338  void test(int n) {
339    for (int i = 0; i < n; i += 1)
340      // Loop body
341  }
342
343is transformed to:
344
345.. code-block:: C
346
347  void test(int n) {
348    int i = 0;
349    do {
350      // Loop body
351      i += 1;
352    } while (i < n);
353  }
354
355**Warning**: This transformation is valid only if the compiler
356can prove that the loop body will be executed at least once. Otherwise,
357it has to insert a guard which will test it at runtime. In the example
358above, that would be:
359
360.. code-block:: C
361
362  void test(int n) {
363    int i = 0;
364    if (n > 0) {
365      do {
366        // Loop body
367        i += 1;
368      } while (i < n);
369    }
370  }
371
372It's important to understand the effect of loop rotation
373at the LLVM IR level. We follow with the previous examples
374in LLVM IR while also providing a graphical representation
375of the control-flow graphs (CFG). You can get the same graphical
376results by utilizing the :ref:`view-cfg <passes-view-cfg>` pass.
377
378The initial **for** loop could be translated to:
379
380.. code-block:: none
381
382  define void @test(i32 %n) {
383  entry:
384    br label %for.header
385
386  for.header:
387    %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
388    %cond = icmp slt i32 %i, %n
389    br i1 %cond, label %body, label %exit
390
391  body:
392    ; Loop body
393    br label %latch
394
395  latch:
396    %i.next = add nsw i32 %i, 1
397    br label %for.header
398
399  exit:
400    ret void
401  }
402
403.. image:: ./loop-terminology-initial-loop.png
404  :width: 400 px
405
406Before we explain how LoopRotate will actually
407transform this loop, here's how we could convert
408it (by hand) to a do-while style loop.
409
410.. code-block:: none
411
412  define void @test(i32 %n) {
413  entry:
414    br label %body
415
416  body:
417    %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
418    ; Loop body
419    br label %latch
420
421  latch:
422    %i.next = add nsw i32 %i, 1
423    %cond = icmp slt i32 %i.next, %n
424    br i1 %cond, label %body, label %exit
425
426  exit:
427    ret void
428  }
429
430.. image:: ./loop-terminology-rotated-loop.png
431  :width: 400 px
432
433Note two things:
434
435* The condition check was moved to the "bottom" of the loop, i.e.
436  the latch. This is something that LoopRotate does by copying the header
437  of the loop to the latch.
438* The compiler in this case can't deduce that the loop will
439  definitely execute at least once so the above transformation
440  is not valid. As mentioned above, a guard has to be inserted,
441  which is something that LoopRotate will do.
442
443This is how LoopRotate transforms this loop:
444
445.. code-block:: none
446
447  define void @test(i32 %n) {
448  entry:
449    %guard_cond = icmp slt i32 0, %n
450    br i1 %guard_cond, label %loop.preheader, label %exit
451
452  loop.preheader:
453    br label %body
454
455  body:
456    %i2 = phi i32 [ 0, %loop.preheader ], [ %i.next, %latch ]
457    br label %latch
458
459  latch:
460    %i.next = add nsw i32 %i2, 1
461    %cond = icmp slt i32 %i.next, %n
462    br i1 %cond, label %body, label %loop.exit
463
464  loop.exit:
465    br label %exit
466
467  exit:
468    ret void
469  }
470
471.. image:: ./loop-terminology-guarded-loop.png
472  :width: 500 px
473
474The result is a little bit more complicated than we may expect
475because LoopRotate ensures that the loop is in
476:ref:`Loop Simplify Form <loop-terminology-loop-simplify>`
477after rotation.
478In this case, it inserted the %loop.preheader basic block so
479that the loop has a preheader and it introduced the %loop.exit
480basic block so that the loop has dedicated exits
481(otherwise, %exit would be jumped from both %latch and %entry,
482but %entry is not contained in the loop).
483Note that a loop has to be in Loop Simplify Form beforehand
484too for LoopRotate to be applied successfully.
485
486The main advantage of this form is that it allows hoisting
487invariant instructions, especially loads, into the preheader.
488That could be done in non-rotated loops as well but with
489some disadvantages.  Let's illustrate them with an example:
490
491.. code-block:: C
492
493  for (int i = 0; i < n; ++i) {
494    auto v = *p;
495    use(v);
496  }
497
498We assume that loading from p is invariant and use(v) is some
499statement that uses v.
500If we wanted to execute the load only once we could move it
501"out" of the loop body, resulting in this:
502
503.. code-block:: C
504
505  auto v = *p;
506  for (int i = 0; i < n; ++i) {
507    use(v);
508  }
509
510However, now, in the case that n <= 0, in the initial form,
511the loop body would never execute, and so, the load would
512never execute.  This is a problem mainly for semantic reasons.
513Consider the case in which n <= 0 and loading from p is invalid.
514In the initial program there would be no error.  However, with this
515transformation we would introduce one, effectively breaking
516the initial semantics.
517
518To avoid both of these problems, we can insert a guard:
519
520.. code-block:: C
521
522  if (n > 0) {  // loop guard
523    auto v = *p;
524    for (int i = 0; i < n; ++i) {
525      use(v);
526    }
527  }
528
529This is certainly better but it could be improved slightly. Notice
530that the check for whether n is bigger than 0 is executed twice (and
531n does not change in between).  Once when we check the guard condition
532and once in the first execution of the loop.  To avoid that, we could
533do an unconditional first execution and insert the loop condition
534in the end. This effectively means transforming the loop into a do-while loop:
535
536.. code-block:: C
537
538  if (0 < n) {
539    auto v = *p;
540    do {
541      use(v);
542      ++i;
543    } while (i < n);
544  }
545
546Note that LoopRotate does not generally do such
547hoisting.  Rather, it is an enabling transformation for other
548passes like Loop-Invariant Code Motion (:ref:`-licm <passes-licm>`).
549