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    c = ...;
236    if (c) {
237      for (...) {
238        if (true)
239          X1 = ...
240        else
241          X2 = ...
242        X3 = phi(X1, X2);
243      }
244    } else {
245      for (...) {
246        if (false)
247          X1' = ...
248        else
249          X2' = ...
250        X3' = phi(X1', X2');
251      }
252    }
253    X4 = phi(X3, X3')
254
255Now, all uses of X4 will get the updated value (in general,
256if a loop is in LCSSA form, in any loop transformation,
257we only need to update the loop closing PHI nodes for the changes
258to take effect).  If we did not have Loop Closed SSA form, it means that X3 could
259possibly be used outside the loop. So, we would have to introduce the
260X4 (which is the new X3) and replace all uses of X3 with that.
261However, we should note that because LLVM keeps a def-use chain
262[#def-use-chain]_ for each Value, we wouldn't need
263to perform data-flow analysis to find and replace all the uses
264(there is even a utility function, replaceAllUsesWith(),
265that performs this transformation by iterating the def-use chain).
266
267Another important advantage is that the behavior of all uses
268of an induction variable is the same.  Without this, you need to
269distinguish the case when the variable is used outside of
270the loop it is defined in, for example:
271
272.. code-block:: C
273
274  for (i = 0; i < 100; i++) {
275    for (j = 0; j < 100; j++) {
276      k = i + j;
277      use(k);    // use 1
278    }
279    use(k);      // use 2
280  }
281
282Looking from the outer loop with the normal SSA form, the first use of k
283is not well-behaved, while the second one is an induction variable with
284base 100 and step 1.  Although, in practice, and in the LLVM context,
285such cases can be handled effectively by SCEV. Scalar Evolution
286(:ref:`scalar-evolution <passes-scalar-evolution>`) or SCEV, is a
287(analysis) pass that analyzes and categorizes the evolution of scalar
288expressions in loops.
289
290In general, it's easier to use SCEV in loops that are in LCSSA form.
291The evolution of a scalar (loop-variant) expression that
292SCEV can analyze is, by definition, relative to a loop.
293An expression is represented in LLVM by an
294`llvm::Instruction <https://llvm.org/doxygen/classllvm_1_1Instruction.html>`.
295If the expression is inside two (or more) loops (which can only
296happen if the loops are nested, like in the example above) and you want
297to get an analysis of its evolution (from SCEV),
298you have to also specify relative to what Loop you want it.
299Specifically, you have to use
300`getSCEVAtScope() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a21d6ee82eed29080d911dbb548a8bb68>`_.
301
302However, if all loops are in LCSSA form, each expression is actually
303represented by two different llvm::Instructions.  One inside the loop
304and one outside, which is the loop-closing PHI node and represents
305the value of the expression after the last iteration (effectively,
306we break each loop-variant expression into two expressions and so, every
307expression is at most in one loop).  You can now just use
308`getSCEV() <https://llvm.org/doxygen/classllvm_1_1ScalarEvolution.html#a30bd18ac905eacf3601bc6a553a9ff49>`_.
309and which of these two llvm::Instructions you pass to it disambiguates
310the context / scope / relative loop.
311
312.. rubric:: Footnotes
313
314.. [#lcssa-construction] To insert these loop-closing PHI nodes, one has to
315  (re-)compute dominance frontiers (if the loop has multiple exits).
316
317.. [#def-use-chain] A property of SSA is that there exists a def-use chain
318  for each definition, which is a list of all the uses of this definition.
319  LLVM implements this property by keeping a list of all the uses of a Value
320  in an internal data structure.
321
322"More Canonical" Loops
323======================
324
325.. _loop-terminology-loop-rotate:
326
327Rotated Loops
328-------------
329
330Loops are rotated by the LoopRotate (:ref:`loop-rotate <passes-loop-rotate>`)
331pass, which converts loops into do/while style loops and is
332implemented in
333`LoopRotation.h <https://llvm.org/doxygen/LoopRotation_8h_source.html>`_.  Example:
334
335.. code-block:: C
336
337  void test(int n) {
338    for (int i = 0; i < n; i += 1)
339      // Loop body
340  }
341
342is transformed to:
343
344.. code-block:: C
345
346  void test(int n) {
347    int i = 0;
348    do {
349      // Loop body
350      i += 1;
351    } while (i < n);
352  }
353
354**Warning**: This transformation is valid only if the compiler
355can prove that the loop body will be executed at least once. Otherwise,
356it has to insert a guard which will test it at runtime. In the example
357above, that would be:
358
359.. code-block:: C
360
361  void test(int n) {
362    int i = 0;
363    if (n > 0) {
364      do {
365        // Loop body
366        i += 1;
367      } while (i < n);
368    }
369  }
370
371It's important to understand the effect of loop rotation
372at the LLVM IR level. We follow with the previous examples
373in LLVM IR while also providing a graphical representation
374of the control-flow graphs (CFG). You can get the same graphical
375results by utilizing the :ref:`view-cfg <passes-view-cfg>` pass.
376
377The initial **for** loop could be translated to:
378
379.. code-block:: none
380
381  define void @test(i32 %n) {
382  entry:
383    br label %for.header
384
385  for.header:
386    %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
387    %cond = icmp slt i32 %i, %n
388    br i1 %cond, label %body, label %exit
389
390  body:
391    ; Loop body
392    br label %latch
393
394  latch:
395    %i.next = add nsw i32 %i, 1
396    br label %for.header
397
398  exit:
399    ret void
400  }
401
402.. image:: ./loop-terminology-initial-loop.png
403  :width: 400 px
404
405Before we explain how LoopRotate will actually
406transform this loop, here's how we could convert
407it (by hand) to a do-while style loop.
408
409.. code-block:: none
410
411  define void @test(i32 %n) {
412  entry:
413    br label %body
414
415  body:
416    %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
417    ; Loop body
418    br label %latch
419
420  latch:
421    %i.next = add nsw i32 %i, 1
422    %cond = icmp slt i32 %i.next, %n
423    br i1 %cond, label %body, label %exit
424
425  exit:
426    ret void
427  }
428
429.. image:: ./loop-terminology-rotated-loop.png
430  :width: 400 px
431
432Note two things:
433
434* The condition check was moved to the "bottom" of the loop, i.e.
435  the latch. This is something that LoopRotate does by copying the header
436  of the loop to the latch.
437* The compiler in this case can't deduce that the loop will
438  definitely execute at least once so the above transformation
439  is not valid. As mentioned above, a guard has to be inserted,
440  which is something that LoopRotate will do.
441
442This is how LoopRotate transforms this loop:
443
444.. code-block:: none
445
446  define void @test(i32 %n) {
447  entry:
448    %guard_cond = icmp slt i32 0, %n
449    br i1 %guard_cond, label %loop.preheader, label %exit
450
451  loop.preheader:
452    br label %body
453
454  body:
455    %i2 = phi i32 [ 0, %loop.preheader ], [ %i.next, %latch ]
456    br label %latch
457
458  latch:
459    %i.next = add nsw i32 %i2, 1
460    %cond = icmp slt i32 %i.next, %n
461    br i1 %cond, label %body, label %loop.exit
462
463  loop.exit:
464    br label %exit
465
466  exit:
467    ret void
468  }
469
470.. image:: ./loop-terminology-guarded-loop.png
471  :width: 500 px
472
473The result is a little bit more complicated than we may expect
474because LoopRotate ensures that the loop is in
475:ref:`Loop Simplify Form <loop-terminology-loop-simplify>`
476after rotation.
477In this case, it inserted the %loop.preheader basic block so
478that the loop has a preheader and it introduced the %loop.exit
479basic block so that the loop has dedicated exits
480(otherwise, %exit would be jumped from both %latch and %entry,
481but %entry is not contained in the loop).
482Note that a loop has to be in Loop Simplify Form beforehand
483too for LoopRotate to be applied successfully.
484
485The main advantage of this form is that it allows hoisting
486invariant instructions, especially loads, into the preheader.
487That could be done in non-rotated loops as well but with
488some disadvantages.  Let's illustrate them with an example:
489
490.. code-block:: C
491
492  for (int i = 0; i < n; ++i) {
493    auto v = *p;
494    use(v);
495  }
496
497We assume that loading from p is invariant and use(v) is some
498statement that uses v.
499If we wanted to execute the load only once we could move it
500"out" of the loop body, resulting in this:
501
502.. code-block:: C
503
504  auto v = *p;
505  for (int i = 0; i < n; ++i) {
506    use(v);
507  }
508
509However, now, in the case that n <= 0, in the initial form,
510the loop body would never execute, and so, the load would
511never execute.  This is a problem mainly for semantic reasons.
512Consider the case in which n <= 0 and loading from p is invalid.
513In the initial program there would be no error.  However, with this
514transformation we would introduce one, effectively breaking
515the initial semantics.
516
517To avoid both of these problems, we can insert a guard:
518
519.. code-block:: C
520
521  if (n > 0) {  // loop guard
522    auto v = *p;
523    for (int i = 0; i < n; ++i) {
524      use(v);
525    }
526  }
527
528This is certainly better but it could be improved slightly. Notice
529that the check for whether n is bigger than 0 is executed twice (and
530n does not change in between).  Once when we check the guard condition
531and once in the first execution of the loop.  To avoid that, we could
532do an unconditional first execution and insert the loop condition
533in the end. This effectively means transforming the loop into a do-while loop:
534
535.. code-block:: C
536
537  if (0 < n) {
538    auto v = *p;
539    do {
540      use(v);
541      ++i;
542    } while (i < n);
543  }
544
545Note that LoopRotate does not generally do such
546hoisting.  Rather, it is an enabling transformation for other
547passes like Loop-Invariant Code Motion (:ref:`-licm <passes-licm>`).
548