[IR] Give catchret an optional 'return value' operand
[oota-llvm.git] / lib / Transforms / Utils / LCSSA.cpp
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/LoopPass.h"
35 #include "llvm/Analysis/ScalarEvolution.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/PredIteratorCache.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Transforms/Utils/LoopUtils.h"
43 #include "llvm/Transforms/Utils/SSAUpdater.h"
44 using namespace llvm;
45
46 #define DEBUG_TYPE "lcssa"
47
48 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
49
50 /// Return true if the specified block is in the list.
51 static bool isExitBlock(BasicBlock *BB,
52                         const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
53   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
54     if (ExitBlocks[i] == BB)
55       return true;
56   return false;
57 }
58
59 /// Given an instruction in the loop, check to see if it has any uses that are
60 /// outside the current loop.  If so, insert LCSSA PHI nodes and rewrite the
61 /// uses.
62 static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT,
63                                const SmallVectorImpl<BasicBlock *> &ExitBlocks,
64                                PredIteratorCache &PredCache, LoopInfo *LI) {
65   SmallVector<Use *, 16> UsesToRewrite;
66
67   BasicBlock *InstBB = Inst.getParent();
68
69   for (Use &U : Inst.uses()) {
70     Instruction *User = cast<Instruction>(U.getUser());
71     BasicBlock *UserBB = User->getParent();
72     if (PHINode *PN = dyn_cast<PHINode>(User))
73       UserBB = PN->getIncomingBlock(U);
74
75     if (InstBB != UserBB && !L.contains(UserBB))
76       UsesToRewrite.push_back(&U);
77   }
78
79   // If there are no uses outside the loop, exit with no change.
80   if (UsesToRewrite.empty())
81     return false;
82
83   ++NumLCSSA; // We are applying the transformation
84
85   // Invoke/CatchPad instructions are special in that their result value is not
86   // available along their unwind edge. The code below tests to see whether
87   // DomBB dominates the value, so adjust DomBB to the normal destination block,
88   // which is effectively where the value is first usable.
89   BasicBlock *DomBB = Inst.getParent();
90   if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst))
91     DomBB = Inv->getNormalDest();
92   if (auto *CPI = dyn_cast<CatchPadInst>(&Inst))
93     DomBB = CPI->getNormalDest();
94
95   DomTreeNode *DomNode = DT.getNode(DomBB);
96
97   SmallVector<PHINode *, 16> AddedPHIs;
98   SmallVector<PHINode *, 8> PostProcessPHIs;
99
100   SSAUpdater SSAUpdate;
101   SSAUpdate.Initialize(Inst.getType(), Inst.getName());
102
103   // Insert the LCSSA phi's into all of the exit blocks dominated by the
104   // value, and add them to the Phi's map.
105   for (SmallVectorImpl<BasicBlock *>::const_iterator BBI = ExitBlocks.begin(),
106                                                      BBE = ExitBlocks.end();
107        BBI != BBE; ++BBI) {
108     BasicBlock *ExitBB = *BBI;
109     if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
110       continue;
111
112     // If we already inserted something for this BB, don't reprocess it.
113     if (SSAUpdate.HasValueForBlock(ExitBB))
114       continue;
115
116     PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB),
117                                   Inst.getName() + ".lcssa", ExitBB->begin());
118
119     // Add inputs from inside the loop for this PHI.
120     for (BasicBlock *Pred : PredCache.get(ExitBB)) {
121       PN->addIncoming(&Inst, Pred);
122
123       // If the exit block has a predecessor not within the loop, arrange for
124       // the incoming value use corresponding to that predecessor to be
125       // rewritten in terms of a different LCSSA PHI.
126       if (!L.contains(Pred))
127         UsesToRewrite.push_back(
128             &PN->getOperandUse(PN->getOperandNumForIncomingValue(
129                  PN->getNumIncomingValues() - 1)));
130     }
131
132     AddedPHIs.push_back(PN);
133
134     // Remember that this phi makes the value alive in this block.
135     SSAUpdate.AddAvailableValue(ExitBB, PN);
136
137     // LoopSimplify might fail to simplify some loops (e.g. when indirect
138     // branches are involved). In such situations, it might happen that an exit
139     // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create
140     // PHIs in such an exit block, we are also inserting PHIs into L2's header.
141     // This could break LCSSA form for L2 because these inserted PHIs can also
142     // have uses outside of L2. Remember all PHIs in such situation as to
143     // revisit than later on. FIXME: Remove this if indirectbr support into
144     // LoopSimplify gets improved.
145     if (auto *OtherLoop = LI->getLoopFor(ExitBB))
146       if (!L.contains(OtherLoop))
147         PostProcessPHIs.push_back(PN);
148   }
149
150   // Rewrite all uses outside the loop in terms of the new PHIs we just
151   // inserted.
152   for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
153     // If this use is in an exit block, rewrite to use the newly inserted PHI.
154     // This is required for correctness because SSAUpdate doesn't handle uses in
155     // the same block.  It assumes the PHI we inserted is at the end of the
156     // block.
157     Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
158     BasicBlock *UserBB = User->getParent();
159     if (PHINode *PN = dyn_cast<PHINode>(User))
160       UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
161
162     if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
163       // Tell the VHs that the uses changed. This updates SCEV's caches.
164       if (UsesToRewrite[i]->get()->hasValueHandle())
165         ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
166       UsesToRewrite[i]->set(UserBB->begin());
167       continue;
168     }
169
170     // Otherwise, do full PHI insertion.
171     SSAUpdate.RewriteUse(*UsesToRewrite[i]);
172   }
173
174   // Post process PHI instructions that were inserted into another disjoint loop
175   // and update their exits properly.
176   for (auto *I : PostProcessPHIs) {
177     if (I->use_empty())
178       continue;
179
180     BasicBlock *PHIBB = I->getParent();
181     Loop *OtherLoop = LI->getLoopFor(PHIBB);
182     SmallVector<BasicBlock *, 8> EBs;
183     OtherLoop->getExitBlocks(EBs);
184     if (EBs.empty())
185       continue;
186
187     // Recurse and re-process each PHI instruction. FIXME: we should really
188     // convert this entire thing to a worklist approach where we process a
189     // vector of instructions...
190     processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI);
191   }
192
193   // Remove PHI nodes that did not have any uses rewritten.
194   for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
195     if (AddedPHIs[i]->use_empty())
196       AddedPHIs[i]->eraseFromParent();
197   }
198
199   return true;
200 }
201
202 /// Return true if the specified block dominates at least
203 /// one of the blocks in the specified list.
204 static bool
205 blockDominatesAnExit(BasicBlock *BB,
206                      DominatorTree &DT,
207                      const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
208   DomTreeNode *DomNode = DT.getNode(BB);
209   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
210     if (DT.dominates(DomNode, DT.getNode(ExitBlocks[i])))
211       return true;
212
213   return false;
214 }
215
216 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
217                      ScalarEvolution *SE) {
218   bool Changed = false;
219
220   // Get the set of exiting blocks.
221   SmallVector<BasicBlock *, 8> ExitBlocks;
222   L.getExitBlocks(ExitBlocks);
223
224   if (ExitBlocks.empty())
225     return false;
226
227   PredIteratorCache PredCache;
228
229   // Look at all the instructions in the loop, checking to see if they have uses
230   // outside the loop.  If so, rewrite those uses.
231   for (Loop::block_iterator BBI = L.block_begin(), BBE = L.block_end();
232        BBI != BBE; ++BBI) {
233     BasicBlock *BB = *BBI;
234
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 (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
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.
265 bool 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::iterator I = L.begin(), E = L.end(); I != E; ++I)
271     Changed |= formLCSSARecursively(**I, DT, LI, SE);
272
273   Changed |= formLCSSA(L, DT, LI, SE);
274   return Changed;
275 }
276
277 namespace {
278 struct 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<AliasAnalysis>();
301     AU.addPreserved<ScalarEvolution>();
302   }
303 };
304 }
305
306 char LCSSA::ID = 0;
307 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
308 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
309 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
310 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
311
312 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
313 char &llvm::LCSSAID = LCSSA::ID;
314
315
316 /// Process all loops in the function, inner-most out.
317 bool LCSSA::runOnFunction(Function &F) {
318   bool Changed = false;
319   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
320   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
321   SE = getAnalysisIfAvailable<ScalarEvolution>();
322
323   // Simplify each loop nest in the function.
324   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
325     Changed |= formLCSSARecursively(**I, *DT, LI, SE);
326
327   return Changed;
328 }
329