blob: 0abb1f440d32a0889d818f8b2f0334a7402c8a04 [file] [log] [blame]
Owen Andersonf3dd3e22006-05-26 21:11:53 +00001//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
Owen Anderson8eca8912006-05-26 13:58:26 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson8eca8912006-05-26 13:58:26 +00007//
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 (...)
Dan Gohmanb5650eb2007-05-11 21:10:54 +000015// if (c) if (c)
Owen Anderson8eca8912006-05-26 13:58:26 +000016// X1 = ... X1 = ...
17// else else
18// X2 = ... X2 = ...
19// X3 = phi(X1, X2) X3 = phi(X1, X2)
Dan Gohman2ad7e732008-06-03 00:57:21 +000020// ... = X3 + 4 X4 = phi(X3)
21// ... = X4 + 4
Owen Anderson8eca8912006-05-26 13:58:26 +000022//
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
Owen Andersonf3dd3e22006-05-26 21:11:53 +000030#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
Chandler Carruth756c22c2014-02-10 19:39:35 +000033#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruthac072702016-02-19 03:12:14 +000034#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000035#include "llvm/Analysis/GlobalsModRef.h"
Devang Patel4cd14132007-07-13 23:57:11 +000036#include "llvm/Analysis/LoopPass.h"
37#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000038#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Function.h"
42#include "llvm/IR/Instructions.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000043#include "llvm/IR/PredIteratorCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Pass.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000045#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/Transforms/Utils/SSAUpdater.h"
Owen Anderson8eca8912006-05-26 13:58:26 +000047using namespace llvm;
48
Chandler Carruth964daaa2014-04-22 02:55:47 +000049#define DEBUG_TYPE "lcssa"
50
Chris Lattner45f966d2006-12-19 22:17:40 +000051STATISTIC(NumLCSSA, "Number of live out of a loop variables");
52
Chandler Carruth8765cf72014-01-25 04:07:24 +000053/// Return true if the specified block is in the list.
Chris Lattner71d353d2009-10-11 02:53:37 +000054static bool isExitBlock(BasicBlock *BB,
Chandler Carruth8765cf72014-01-25 04:07:24 +000055 const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner71d353d2009-10-11 02:53:37 +000056 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
57 if (ExitBlocks[i] == BB)
58 return true;
59 return false;
60}
61
Chandler Carruth8765cf72014-01-25 04:07:24 +000062/// Given an instruction in the loop, check to see if it has any uses that are
63/// outside the current loop. If so, insert LCSSA PHI nodes and rewrite the
64/// uses.
65static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT,
66 const SmallVectorImpl<BasicBlock *> &ExitBlocks,
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +000067 PredIteratorCache &PredCache, LoopInfo *LI) {
Chandler Carruth8765cf72014-01-25 04:07:24 +000068 SmallVector<Use *, 16> UsesToRewrite;
69
Andrew Kaylor123048d2015-12-18 18:12:35 +000070 // Tokens cannot be used in PHI nodes, so we skip over them.
71 // We can run into tokens which are live out of a loop with catchswitch
72 // instructions in Windows EH if the catchswitch has one catchpad which
73 // is inside the loop and another which is not.
74 if (Inst.getType()->isTokenTy())
75 return false;
76
Chandler Carruth8765cf72014-01-25 04:07:24 +000077 BasicBlock *InstBB = Inst.getParent();
78
Chandler Carruthcdf47882014-03-09 03:16:01 +000079 for (Use &U : Inst.uses()) {
80 Instruction *User = cast<Instruction>(U.getUser());
81 BasicBlock *UserBB = User->getParent();
82 if (PHINode *PN = dyn_cast<PHINode>(User))
83 UserBB = PN->getIncomingBlock(U);
Chandler Carruth8765cf72014-01-25 04:07:24 +000084
85 if (InstBB != UserBB && !L.contains(UserBB))
Chandler Carruthcdf47882014-03-09 03:16:01 +000086 UsesToRewrite.push_back(&U);
Chris Lattner71d353d2009-10-11 02:53:37 +000087 }
Gabor Greif42479492010-07-09 14:29:14 +000088
Chris Lattner71d353d2009-10-11 02:53:37 +000089 // If there are no uses outside the loop, exit with no change.
Chandler Carruth8765cf72014-01-25 04:07:24 +000090 if (UsesToRewrite.empty())
91 return false;
92
Owen Andersondad8c572006-05-31 20:55:06 +000093 ++NumLCSSA; // We are applying the transformation
Chris Lattner5a2bc782006-08-02 00:06:09 +000094
David Majnemer8a1c45d2015-12-12 05:38:55 +000095 // Invoke instructions are special in that their result value is not available
96 // along their unwind edge. The code below tests to see whether DomBB
97 // dominates the value, so adjust DomBB to the normal destination block,
David Majnemer0bc0eef2015-08-15 02:46:08 +000098 // which is effectively where the value is first usable.
Chandler Carruth8765cf72014-01-25 04:07:24 +000099 BasicBlock *DomBB = Inst.getParent();
100 if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst))
Dan Gohman7eaf50e2009-06-26 00:31:13 +0000101 DomBB = Inv->getNormalDest();
102
Chandler Carruth8765cf72014-01-25 04:07:24 +0000103 DomTreeNode *DomNode = DT.getNode(DomBB);
Chris Lattner5a2bc782006-08-02 00:06:09 +0000104
Chandler Carruth8765cf72014-01-25 04:07:24 +0000105 SmallVector<PHINode *, 16> AddedPHIs;
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000106 SmallVector<PHINode *, 8> PostProcessPHIs;
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000107
Chris Lattner71d353d2009-10-11 02:53:37 +0000108 SSAUpdater SSAUpdate;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000109 SSAUpdate.Initialize(Inst.getType(), Inst.getName());
110
Chris Lattner71d353d2009-10-11 02:53:37 +0000111 // Insert the LCSSA phi's into all of the exit blocks dominated by the
Dan Gohmanc146c7802009-11-09 18:28:24 +0000112 // value, and add them to the Phi's map.
Sanjoy Das331521c2015-10-25 19:08:32 +0000113 for (BasicBlock *ExitBB : ExitBlocks) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000114 if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
115 continue;
116
Chris Lattner71d353d2009-10-11 02:53:37 +0000117 // If we already inserted something for this BB, don't reprocess it.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000118 if (SSAUpdate.HasValueForBlock(ExitBB))
119 continue;
120
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000121 PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000122 Inst.getName() + ".lcssa", &ExitBB->front());
Chris Lattner984d6e12006-10-31 18:56:48 +0000123
Chris Lattner71d353d2009-10-11 02:53:37 +0000124 // Add inputs from inside the loop for this PHI.
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000125 for (BasicBlock *Pred : PredCache.get(ExitBB)) {
126 PN->addIncoming(&Inst, Pred);
Dan Gohmanc146c7802009-11-09 18:28:24 +0000127
128 // If the exit block has a predecessor not within the loop, arrange for
Dan Gohmanf324dd62009-11-09 18:59:22 +0000129 // the incoming value use corresponding to that predecessor to be
Dan Gohmanc146c7802009-11-09 18:28:24 +0000130 // rewritten in terms of a different LCSSA PHI.
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000131 if (!L.contains(Pred))
Dan Gohmanc146c7802009-11-09 18:28:24 +0000132 UsesToRewrite.push_back(
Chandler Carruth8765cf72014-01-25 04:07:24 +0000133 &PN->getOperandUse(PN->getOperandNumForIncomingValue(
134 PN->getNumIncomingValues() - 1)));
Dan Gohmanc146c7802009-11-09 18:28:24 +0000135 }
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000136
137 AddedPHIs.push_back(PN);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000138
Chris Lattner71d353d2009-10-11 02:53:37 +0000139 // Remember that this phi makes the value alive in this block.
140 SSAUpdate.AddAvailableValue(ExitBB, PN);
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000141
142 // LoopSimplify might fail to simplify some loops (e.g. when indirect
143 // branches are involved). In such situations, it might happen that an exit
144 // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create
145 // PHIs in such an exit block, we are also inserting PHIs into L2's header.
146 // This could break LCSSA form for L2 because these inserted PHIs can also
147 // have uses outside of L2. Remember all PHIs in such situation as to
148 // revisit than later on. FIXME: Remove this if indirectbr support into
149 // LoopSimplify gets improved.
150 if (auto *OtherLoop = LI->getLoopFor(ExitBB))
151 if (!L.contains(OtherLoop))
152 PostProcessPHIs.push_back(PN);
Owen Anderson0ac33692006-06-12 07:10:16 +0000153 }
Benjamin Kramer8682ac12012-10-31 10:01:29 +0000154
Chris Lattner71d353d2009-10-11 02:53:37 +0000155 // Rewrite all uses outside the loop in terms of the new PHIs we just
156 // inserted.
Sanjoy Das331521c2015-10-25 19:08:32 +0000157 for (Use *UseToRewrite : UsesToRewrite) {
Chris Lattner71d353d2009-10-11 02:53:37 +0000158 // If this use is in an exit block, rewrite to use the newly inserted PHI.
159 // This is required for correctness because SSAUpdate doesn't handle uses in
160 // the same block. It assumes the PHI we inserted is at the end of the
161 // block.
Sanjoy Das331521c2015-10-25 19:08:32 +0000162 Instruction *User = cast<Instruction>(UseToRewrite->getUser());
Chris Lattner71d353d2009-10-11 02:53:37 +0000163 BasicBlock *UserBB = User->getParent();
164 if (PHINode *PN = dyn_cast<PHINode>(User))
Sanjoy Das331521c2015-10-25 19:08:32 +0000165 UserBB = PN->getIncomingBlock(*UseToRewrite);
Chris Lattner71d353d2009-10-11 02:53:37 +0000166
Chandler Carruth8765cf72014-01-25 04:07:24 +0000167 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
Benjamin Kramerede2fe3bfd2012-10-31 16:30:03 +0000168 // Tell the VHs that the uses changed. This updates SCEV's caches.
Sanjoy Das331521c2015-10-25 19:08:32 +0000169 if (UseToRewrite->get()->hasValueHandle())
170 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front());
171 UseToRewrite->set(&UserBB->front());
Chris Lattner5a2bc782006-08-02 00:06:09 +0000172 continue;
Owen Andersoncd76fa02006-06-01 06:05:47 +0000173 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000174
Chris Lattner71d353d2009-10-11 02:53:37 +0000175 // Otherwise, do full PHI insertion.
Sanjoy Das331521c2015-10-25 19:08:32 +0000176 SSAUpdate.RewriteUse(*UseToRewrite);
Chris Lattner5a2bc782006-08-02 00:06:09 +0000177 }
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000178
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000179 // Post process PHI instructions that were inserted into another disjoint loop
180 // and update their exits properly.
181 for (auto *I : PostProcessPHIs) {
182 if (I->use_empty())
183 continue;
184
185 BasicBlock *PHIBB = I->getParent();
186 Loop *OtherLoop = LI->getLoopFor(PHIBB);
187 SmallVector<BasicBlock *, 8> EBs;
188 OtherLoop->getExitBlocks(EBs);
189 if (EBs.empty())
190 continue;
191
192 // Recurse and re-process each PHI instruction. FIXME: we should really
193 // convert this entire thing to a worklist approach where we process a
194 // vector of instructions...
195 processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI);
196 }
197
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000198 // Remove PHI nodes that did not have any uses rewritten.
Sanjoy Das331521c2015-10-25 19:08:32 +0000199 for (PHINode *PN : AddedPHIs)
200 if (PN->use_empty())
201 PN->eraseFromParent();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000202
Chris Lattner71d353d2009-10-11 02:53:37 +0000203 return true;
Owen Andersondad8c572006-05-31 20:55:06 +0000204}
Chris Lattner5a2bc782006-08-02 00:06:09 +0000205
Chandler Carruth8765cf72014-01-25 04:07:24 +0000206/// Return true if the specified block dominates at least
207/// one of the blocks in the specified list.
208static bool
209blockDominatesAnExit(BasicBlock *BB,
210 DominatorTree &DT,
211 const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
212 DomTreeNode *DomNode = DT.getNode(BB);
Sanjoy Das331521c2015-10-25 19:08:32 +0000213 for (BasicBlock *ExitBB : ExitBlocks)
214 if (DT.dominates(DomNode, DT.getNode(ExitBB)))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000215 return true;
216
217 return false;
218}
219
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000220bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
221 ScalarEvolution *SE) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000222 bool Changed = false;
223
224 // Get the set of exiting blocks.
225 SmallVector<BasicBlock *, 8> ExitBlocks;
226 L.getExitBlocks(ExitBlocks);
227
228 if (ExitBlocks.empty())
229 return false;
230
231 PredIteratorCache PredCache;
232
233 // Look at all the instructions in the loop, checking to see if they have uses
234 // outside the loop. If so, rewrite those uses.
Sanjoy Das331521c2015-10-25 19:08:32 +0000235 for (BasicBlock *BB : L.blocks()) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000236 // For large loops, avoid use-scanning by using dominance information: In
237 // particular, if a block does not dominate any of the loop exits, then none
238 // of the values defined in the block could be used outside the loop.
239 if (!blockDominatesAnExit(BB, DT, ExitBlocks))
240 continue;
241
Sanjoy Das331521c2015-10-25 19:08:32 +0000242 for (Instruction &I : *BB) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000243 // Reject two common cases fast: instructions with no uses (like stores)
244 // and instructions with one use that is in the same block as this.
Sanjoy Das331521c2015-10-25 19:08:32 +0000245 if (I.use_empty() ||
246 (I.hasOneUse() && I.user_back()->getParent() == BB &&
247 !isa<PHINode>(I.user_back())))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000248 continue;
249
Sanjoy Das331521c2015-10-25 19:08:32 +0000250 Changed |= processInstruction(L, I, DT, ExitBlocks, PredCache, LI);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000251 }
252 }
253
254 // If we modified the code, remove any caches about the loop from SCEV to
255 // avoid dangling entries.
256 // FIXME: This is a big hammer, can we clear the cache more selectively?
257 if (SE && Changed)
258 SE->forgetLoop(&L);
259
260 assert(L.isLCSSAForm(DT));
261
262 return Changed;
263}
264
Chandler Carruthd84f7762014-01-28 01:25:38 +0000265/// Process a loop nest depth first.
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000266bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
Chandler Carruthd84f7762014-01-28 01:25:38 +0000267 ScalarEvolution *SE) {
268 bool Changed = false;
269
270 // Recurse depth-first through inner loops.
Sanjoy Das15c4c462015-10-25 19:27:17 +0000271 for (Loop *SubLoop : L.getSubLoops())
272 Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000273
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000274 Changed |= formLCSSA(L, DT, LI, SE);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000275 return Changed;
276}
277
Chandler Carruth8765cf72014-01-25 04:07:24 +0000278namespace {
279struct LCSSA : public FunctionPass {
280 static char ID; // Pass identification, replacement for typeid
281 LCSSA() : FunctionPass(ID) {
282 initializeLCSSAPass(*PassRegistry::getPassRegistry());
283 }
284
285 // Cached analysis information for the current function.
286 DominatorTree *DT;
287 LoopInfo *LI;
288 ScalarEvolution *SE;
289
Craig Topper3e4c6972014-03-05 09:10:37 +0000290 bool runOnFunction(Function &F) override;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000291
292 /// This transformation requires natural loop information & requires that
293 /// loop preheaders be inserted into the CFG. It maintains both of these,
294 /// as well as the CFG. It also requires dominator information.
Craig Topper3e4c6972014-03-05 09:10:37 +0000295 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000296 AU.setPreservesCFG();
297
298 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000299 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000300 AU.addPreservedID(LoopSimplifyID);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000301 AU.addPreserved<AAResultsWrapperPass>();
Chandler Carruthac072702016-02-19 03:12:14 +0000302 AU.addPreserved<BasicAAWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000303 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000304 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000305 AU.addPreserved<SCEVAAWrapperPass>();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000306 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000307};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000308}
Chandler Carruth8765cf72014-01-25 04:07:24 +0000309
310char LCSSA::ID = 0;
311INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
312INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000313INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000314INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
315INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000316INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
317
318Pass *llvm::createLCSSAPass() { return new LCSSA(); }
319char &llvm::LCSSAID = LCSSA::ID;
320
321
322/// Process all loops in the function, inner-most out.
323bool LCSSA::runOnFunction(Function &F) {
324 bool Changed = false;
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000325 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000326 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000327 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
328 SE = SEWP ? &SEWP->getSE() : nullptr;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000329
330 // Simplify each loop nest in the function.
331 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000332 Changed |= formLCSSARecursively(**I, *DT, LI, SE);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000333
334 return Changed;
335}
336