1//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops by placing phi nodes at the end of the loops for
11// all values that are live across the loop boundary.  For example, it turns
12// the left into the right code:
13//
14// for (...)                for (...)
15//   if (c)                   if (c)
16//     X1 = ...                 X1 = ...
17//   else                     else
18//     X2 = ...                 X2 = ...
19//   X3 = phi(X1, X2)         X3 = phi(X1, X2)
20// ... = X3 + 4             X4 = phi(X3)
21//                          ... = X4 + 4
22//
23// This is still valid LLVM; the extra phi nodes are purely redundant, and will
24// be trivially eliminated by InstCombine.  The major benefit of this
25// transformation is that it makes many other loop optimizations, such as
26// LoopUnswitching, simpler.
27//
28//===----------------------------------------------------------------------===//
29
30#include "llvm/Transforms/Scalar.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Analysis/AliasAnalysis.h"
34#include "llvm/Analysis/GlobalsModRef.h"
35#include "llvm/Analysis/LoopPass.h"
36#include "llvm/Analysis/ScalarEvolution.h"
37#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
38#include "llvm/IR/Constants.h"
39#include "llvm/IR/Dominators.h"
40#include "llvm/IR/Function.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/PredIteratorCache.h"
43#include "llvm/Pass.h"
44#include "llvm/Transforms/Utils/LoopUtils.h"
45#include "llvm/Transforms/Utils/SSAUpdater.h"
46using namespace llvm;
47
48#define DEBUG_TYPE "lcssa"
49
50STATISTIC(NumLCSSA, "Number of live out of a loop variables");
51
52/// Return true if the specified block is in the list.
53static bool isExitBlock(BasicBlock *BB,
54                        const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
55  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
56    if (ExitBlocks[i] == BB)
57      return true;
58  return false;
59}
60
61/// Given an instruction in the loop, check to see if it has any uses that are
62/// outside the current loop.  If so, insert LCSSA PHI nodes and rewrite the
63/// uses.
64static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT,
65                               const SmallVectorImpl<BasicBlock *> &ExitBlocks,
66                               PredIteratorCache &PredCache, LoopInfo *LI) {
67  SmallVector<Use *, 16> UsesToRewrite;
68
69  // Tokens cannot be used in PHI nodes, so we skip over them.
70  // We can run into tokens which are live out of a loop with catchswitch
71  // instructions in Windows EH if the catchswitch has one catchpad which
72  // is inside the loop and another which is not.
73  if (Inst.getType()->isTokenTy())
74    return false;
75
76  BasicBlock *InstBB = Inst.getParent();
77
78  for (Use &U : Inst.uses()) {
79    Instruction *User = cast<Instruction>(U.getUser());
80    BasicBlock *UserBB = User->getParent();
81    if (PHINode *PN = dyn_cast<PHINode>(User))
82      UserBB = PN->getIncomingBlock(U);
83
84    if (InstBB != UserBB && !L.contains(UserBB))
85      UsesToRewrite.push_back(&U);
86  }
87
88  // If there are no uses outside the loop, exit with no change.
89  if (UsesToRewrite.empty())
90    return false;
91
92  ++NumLCSSA; // We are applying the transformation
93
94  // Invoke instructions are special in that their result value is not available
95  // along their unwind edge. The code below tests to see whether DomBB
96  // dominates the value, so adjust DomBB to the normal destination block,
97  // which is effectively where the value is first usable.
98  BasicBlock *DomBB = Inst.getParent();
99  if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst))
100    DomBB = Inv->getNormalDest();
101
102  DomTreeNode *DomNode = DT.getNode(DomBB);
103
104  SmallVector<PHINode *, 16> AddedPHIs;
105  SmallVector<PHINode *, 8> PostProcessPHIs;
106
107  SSAUpdater SSAUpdate;
108  SSAUpdate.Initialize(Inst.getType(), Inst.getName());
109
110  // Insert the LCSSA phi's into all of the exit blocks dominated by the
111  // value, and add them to the Phi's map.
112  for (BasicBlock *ExitBB : ExitBlocks) {
113    if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
114      continue;
115
116    // If we already inserted something for this BB, don't reprocess it.
117    if (SSAUpdate.HasValueForBlock(ExitBB))
118      continue;
119
120    PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB),
121                                  Inst.getName() + ".lcssa", &ExitBB->front());
122
123    // Add inputs from inside the loop for this PHI.
124    for (BasicBlock *Pred : PredCache.get(ExitBB)) {
125      PN->addIncoming(&Inst, Pred);
126
127      // If the exit block has a predecessor not within the loop, arrange for
128      // the incoming value use corresponding to that predecessor to be
129      // rewritten in terms of a different LCSSA PHI.
130      if (!L.contains(Pred))
131        UsesToRewrite.push_back(
132            &PN->getOperandUse(PN->getOperandNumForIncomingValue(
133                 PN->getNumIncomingValues() - 1)));
134    }
135
136    AddedPHIs.push_back(PN);
137
138    // Remember that this phi makes the value alive in this block.
139    SSAUpdate.AddAvailableValue(ExitBB, PN);
140
141    // LoopSimplify might fail to simplify some loops (e.g. when indirect
142    // branches are involved). In such situations, it might happen that an exit
143    // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create
144    // PHIs in such an exit block, we are also inserting PHIs into L2's header.
145    // This could break LCSSA form for L2 because these inserted PHIs can also
146    // have uses outside of L2. Remember all PHIs in such situation as to
147    // revisit than later on. FIXME: Remove this if indirectbr support into
148    // LoopSimplify gets improved.
149    if (auto *OtherLoop = LI->getLoopFor(ExitBB))
150      if (!L.contains(OtherLoop))
151        PostProcessPHIs.push_back(PN);
152  }
153
154  // Rewrite all uses outside the loop in terms of the new PHIs we just
155  // inserted.
156  for (Use *UseToRewrite : UsesToRewrite) {
157    // If this use is in an exit block, rewrite to use the newly inserted PHI.
158    // This is required for correctness because SSAUpdate doesn't handle uses in
159    // the same block.  It assumes the PHI we inserted is at the end of the
160    // block.
161    Instruction *User = cast<Instruction>(UseToRewrite->getUser());
162    BasicBlock *UserBB = User->getParent();
163    if (PHINode *PN = dyn_cast<PHINode>(User))
164      UserBB = PN->getIncomingBlock(*UseToRewrite);
165
166    if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
167      // Tell the VHs that the uses changed. This updates SCEV's caches.
168      if (UseToRewrite->get()->hasValueHandle())
169        ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front());
170      UseToRewrite->set(&UserBB->front());
171      continue;
172    }
173
174    // Otherwise, do full PHI insertion.
175    SSAUpdate.RewriteUse(*UseToRewrite);
176  }
177
178  // Post process PHI instructions that were inserted into another disjoint loop
179  // and update their exits properly.
180  for (auto *I : PostProcessPHIs) {
181    if (I->use_empty())
182      continue;
183
184    BasicBlock *PHIBB = I->getParent();
185    Loop *OtherLoop = LI->getLoopFor(PHIBB);
186    SmallVector<BasicBlock *, 8> EBs;
187    OtherLoop->getExitBlocks(EBs);
188    if (EBs.empty())
189      continue;
190
191    // Recurse and re-process each PHI instruction. FIXME: we should really
192    // convert this entire thing to a worklist approach where we process a
193    // vector of instructions...
194    processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI);
195  }
196
197  // Remove PHI nodes that did not have any uses rewritten.
198  for (PHINode *PN : AddedPHIs)
199    if (PN->use_empty())
200      PN->eraseFromParent();
201
202  return true;
203}
204
205/// Return true if the specified block dominates at least
206/// one of the blocks in the specified list.
207static bool
208blockDominatesAnExit(BasicBlock *BB,
209                     DominatorTree &DT,
210                     const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
211  DomTreeNode *DomNode = DT.getNode(BB);
212  for (BasicBlock *ExitBB : ExitBlocks)
213    if (DT.dominates(DomNode, DT.getNode(ExitBB)))
214      return true;
215
216  return false;
217}
218
219bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
220                     ScalarEvolution *SE) {
221  bool Changed = false;
222
223  // Get the set of exiting blocks.
224  SmallVector<BasicBlock *, 8> ExitBlocks;
225  L.getExitBlocks(ExitBlocks);
226
227  if (ExitBlocks.empty())
228    return false;
229
230  PredIteratorCache PredCache;
231
232  // Look at all the instructions in the loop, checking to see if they have uses
233  // outside the loop.  If so, rewrite those uses.
234  for (BasicBlock *BB : L.blocks()) {
235    // For large loops, avoid use-scanning by using dominance information:  In
236    // particular, if a block does not dominate any of the loop exits, then none
237    // of the values defined in the block could be used outside the loop.
238    if (!blockDominatesAnExit(BB, DT, ExitBlocks))
239      continue;
240
241    for (Instruction &I : *BB) {
242      // Reject two common cases fast: instructions with no uses (like stores)
243      // and instructions with one use that is in the same block as this.
244      if (I.use_empty() ||
245          (I.hasOneUse() && I.user_back()->getParent() == BB &&
246           !isa<PHINode>(I.user_back())))
247        continue;
248
249      Changed |= processInstruction(L, I, DT, ExitBlocks, PredCache, LI);
250    }
251  }
252
253  // If we modified the code, remove any caches about the loop from SCEV to
254  // avoid dangling entries.
255  // FIXME: This is a big hammer, can we clear the cache more selectively?
256  if (SE && Changed)
257    SE->forgetLoop(&L);
258
259  assert(L.isLCSSAForm(DT));
260
261  return Changed;
262}
263
264/// Process a loop nest depth first.
265bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
266                                ScalarEvolution *SE) {
267  bool Changed = false;
268
269  // Recurse depth-first through inner loops.
270  for (Loop *SubLoop : L.getSubLoops())
271    Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE);
272
273  Changed |= formLCSSA(L, DT, LI, SE);
274  return Changed;
275}
276
277namespace {
278struct LCSSA : public FunctionPass {
279  static char ID; // Pass identification, replacement for typeid
280  LCSSA() : FunctionPass(ID) {
281    initializeLCSSAPass(*PassRegistry::getPassRegistry());
282  }
283
284  // Cached analysis information for the current function.
285  DominatorTree *DT;
286  LoopInfo *LI;
287  ScalarEvolution *SE;
288
289  bool runOnFunction(Function &F) override;
290
291  /// This transformation requires natural loop information & requires that
292  /// loop preheaders be inserted into the CFG.  It maintains both of these,
293  /// as well as the CFG.  It also requires dominator information.
294  void getAnalysisUsage(AnalysisUsage &AU) const override {
295    AU.setPreservesCFG();
296
297    AU.addRequired<DominatorTreeWrapperPass>();
298    AU.addRequired<LoopInfoWrapperPass>();
299    AU.addPreservedID(LoopSimplifyID);
300    AU.addPreserved<AAResultsWrapperPass>();
301    AU.addPreserved<GlobalsAAWrapperPass>();
302    AU.addPreserved<ScalarEvolutionWrapperPass>();
303    AU.addPreserved<SCEVAAWrapperPass>();
304  }
305};
306}
307
308char LCSSA::ID = 0;
309INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
310INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
311INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
312INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
313INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
314INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
315
316Pass *llvm::createLCSSAPass() { return new LCSSA(); }
317char &llvm::LCSSAID = LCSSA::ID;
318
319
320/// Process all loops in the function, inner-most out.
321bool LCSSA::runOnFunction(Function &F) {
322  bool Changed = false;
323  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
324  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
325  auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
326  SE = SEWP ? &SEWP->getSE() : nullptr;
327
328  // Simplify each loop nest in the function.
329  for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
330    Changed |= formLCSSARecursively(**I, *DT, LI, SE);
331
332  return Changed;
333}
334
335