blob: 40d33d15afc2fb394b7d4a901d191d2e9be4fe61 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-05-07 18:07:59 +00009//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
16#include "llvm/Function.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Dale Johannesenbd8e6502009-03-03 01:09:07 +000018#include "llvm/IntrinsicInst.h"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000019#include "llvm/Constant.h"
20#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000021#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9fc5cdf2011-01-02 22:09:33 +000022#include "llvm/Analysis/DominanceFrontier.h"
Chris Lattnerb5b79972011-01-11 08:13:40 +000023#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattneree6e10b2008-11-27 08:18:12 +000025#include "llvm/Target/TargetData.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000026#include "llvm/Transforms/Utils/Local.h"
Dan Gohman5c89b522009-09-08 15:45:00 +000027#include "llvm/Transforms/Scalar.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000029#include "llvm/Support/ValueHandle.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000030#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner71af9b02008-12-03 06:40:52 +000033/// DeleteDeadBlock - Delete the specified block, which must have no
34/// predecessors.
35void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000036 assert((pred_begin(BB) == pred_end(BB) ||
37 // Can delete self loop.
38 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000039 TerminatorInst *BBTerm = BB->getTerminator();
Devang Patel5622f072009-02-24 00:05:16 +000040
Chris Lattner2b1ba242008-12-03 06:37:44 +000041 // Loop through all of our successors and make sure they know that one
42 // of their predecessors is going away.
43 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
44 BBTerm->getSuccessor(i)->removePredecessor(BB);
45
46 // Zap all the instructions in the block.
47 while (!BB->empty()) {
48 Instruction &I = BB->back();
49 // If this instruction is used, replace uses with an arbitrary value.
50 // Because control flow can't get here, we don't care what we replace the
51 // value with. Note that since this block is unreachable, and all values
52 // contained within it must dominate their uses, that all uses will
53 // eventually be removed (they are themselves dead).
54 if (!I.use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000055 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner2b1ba242008-12-03 06:37:44 +000056 BB->getInstList().pop_back();
57 }
Devang Patel5622f072009-02-24 00:05:16 +000058
Chris Lattner2b1ba242008-12-03 06:37:44 +000059 // Zap the block!
60 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000061}
62
Chris Lattner29874e02008-12-03 19:44:02 +000063/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
64/// any single-entry PHI nodes in it, fold them away. This handles the case
65/// when all entries to the PHI nodes in a block are guaranteed equal, such as
66/// when the block has exactly one predecessor.
Chris Lattnerb5b79972011-01-11 08:13:40 +000067void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
68 if (!isa<PHINode>(BB->begin())) return;
69
70 AliasAnalysis *AA = 0;
71 MemoryDependenceAnalysis *MemDep = 0;
72 if (P) {
73 AA = P->getAnalysisIfAvailable<AliasAnalysis>();
74 MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
75 }
76
Chris Lattner29874e02008-12-03 19:44:02 +000077 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
78 if (PN->getIncomingValue(0) != PN)
79 PN->replaceAllUsesWith(PN->getIncomingValue(0));
80 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000081 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattnerb5b79972011-01-11 08:13:40 +000082
83 if (MemDep)
84 MemDep->removeInstruction(PN); // Memdep updates AA itself.
85 else if (AA && isa<PointerType>(PN->getType()))
86 AA->deleteValue(PN);
87
Chris Lattner29874e02008-12-03 19:44:02 +000088 PN->eraseFromParent();
89 }
90}
91
92
Dan Gohmanafc36a92009-05-02 18:29:22 +000093/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
94/// is dead. Also recursively delete any operands that become dead as
95/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman35738ac2009-05-04 22:30:44 +000096/// it is ultimately unused or if it reaches an unused cycle.
Dan Gohman90fe0bd2010-01-05 15:45:31 +000097bool llvm::DeleteDeadPHIs(BasicBlock *BB) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000098 // Recursively deleting a PHI may cause multiple PHIs to be deleted
99 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
100 SmallVector<WeakVH, 8> PHIs;
101 for (BasicBlock::iterator I = BB->begin();
102 PHINode *PN = dyn_cast<PHINode>(I); ++I)
103 PHIs.push_back(PN);
104
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000105 bool Changed = false;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000106 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
107 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000108 Changed |= RecursivelyDeleteDeadPHINode(PN);
109
110 return Changed;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000111}
112
Dan Gohman438b5832009-10-31 17:33:01 +0000113/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
114/// if possible. The return value indicates success or failure.
Chris Lattner88202922009-11-01 04:57:33 +0000115bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
Dan Gohman1c034dc2010-08-17 17:07:02 +0000116 // Don't merge away blocks who have their address taken.
117 if (BB->hasAddressTaken()) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000118
Dan Gohman1c034dc2010-08-17 17:07:02 +0000119 // Can't merge if there are multiple predecessors, or no predecessors.
120 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman438b5832009-10-31 17:33:01 +0000121 if (!PredBB) return false;
Dan Gohman1c034dc2010-08-17 17:07:02 +0000122
Dan Gohman438b5832009-10-31 17:33:01 +0000123 // Don't break self-loops.
124 if (PredBB == BB) return false;
125 // Don't break invokes.
126 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
127
128 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000129 BasicBlock *OnlySucc = BB;
Dan Gohman438b5832009-10-31 17:33:01 +0000130 for (; SI != SE; ++SI)
131 if (*SI != OnlySucc) {
132 OnlySucc = 0; // There are multiple distinct successors!
133 break;
134 }
135
136 // Can't merge if there are multiple successors.
137 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000138
Dan Gohman438b5832009-10-31 17:33:01 +0000139 // Can't merge if there is PHI loop.
140 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
141 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
142 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
143 if (PN->getIncomingValue(i) == PN)
144 return false;
145 } else
146 break;
147 }
148
149 // Begin by getting rid of unneeded PHIs.
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000150 if (isa<PHINode>(BB->front()))
Chris Lattnerb5b79972011-01-11 08:13:40 +0000151 FoldSingleEntryPHINodes(BB, P);
Dan Gohman438b5832009-10-31 17:33:01 +0000152
Owen Andersonb31b06d2008-07-17 00:01:40 +0000153 // Delete the unconditional branch from the predecessor...
154 PredBB->getInstList().pop_back();
155
156 // Move all definitions in the successor to the predecessor...
157 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
158
159 // Make all PHI nodes that referred to BB now refer to Pred as their
160 // source...
161 BB->replaceAllUsesWith(PredBB);
162
Dan Gohman438b5832009-10-31 17:33:01 +0000163 // Inherit predecessors name if it exists.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000164 if (!PredBB->hasName())
165 PredBB->takeName(BB);
166
Owen Andersonb31b06d2008-07-17 00:01:40 +0000167 // Finally, erase the old block and update dominator info.
168 if (P) {
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000169 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
170 if (DomTreeNode *DTN = DT->getNode(BB)) {
171 DomTreeNode *PredDTN = DT->getNode(PredBB);
Owen Andersonb31b06d2008-07-17 00:01:40 +0000172 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
173 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
174 DE = Children.end(); DI != DE; ++DI)
175 DT->changeImmediateDominator(*DI, PredDTN);
176
177 DT->eraseNode(BB);
178 }
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000179
180 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
181 LI->removeBlock(BB);
Owen Andersonb31b06d2008-07-17 00:01:40 +0000182 }
183 }
184
185 BB->eraseFromParent();
Dan Gohman438b5832009-10-31 17:33:01 +0000186 return true;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000187}
188
Chris Lattner0f67dd62005-04-21 16:04:49 +0000189/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
190/// with a value, then remove and delete the original instruction.
191///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000192void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
193 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000194 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000195 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000196 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000197
Chris Lattner86cc4232007-02-11 01:37:51 +0000198 // Make sure to propagate a name if there is one already.
199 if (I.hasName() && !V->hasName())
200 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000201
Misha Brukman5560c9d2003-08-18 14:43:39 +0000202 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000203 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000204}
205
206
Chris Lattner0f67dd62005-04-21 16:04:49 +0000207/// ReplaceInstWithInst - Replace the instruction specified by BI with the
208/// instruction specified by I. The original instruction is deleted and BI is
209/// updated to point to the new instruction.
210///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000211void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
212 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000213 assert(I->getParent() == 0 &&
214 "ReplaceInstWithInst: Instruction already inserted into basic block!");
215
216 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000217 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000218
219 // Replace all uses of the old instruction, and delete it.
220 ReplaceInstWithValue(BIL, BI, I);
221
222 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000223 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000224}
225
Chris Lattner0f67dd62005-04-21 16:04:49 +0000226/// ReplaceInstWithInst - Replace the instruction specified by From with the
227/// instruction specified by To.
228///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000229void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000230 BasicBlock::iterator BI(From);
231 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000232}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000233
Bob Wilsonae23daf2010-02-16 21:06:42 +0000234/// GetSuccessorNumber - Search for the specified successor of basic block BB
235/// and return its position in the terminator instruction's list of
236/// successors. It is an error to call this with a block that is not a
237/// successor.
238unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
Bob Wilsonadb6f222010-02-16 19:49:17 +0000239 TerminatorInst *Term = BB->getTerminator();
Devang Patel8a88a142008-11-03 23:14:09 +0000240#ifndef NDEBUG
Bob Wilsonadb6f222010-02-16 19:49:17 +0000241 unsigned e = Term->getNumSuccessors();
Devang Patel8a88a142008-11-03 23:14:09 +0000242#endif
243 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000244 assert(i != e && "Didn't find edge?");
Bob Wilsonadb6f222010-02-16 19:49:17 +0000245 if (Term->getSuccessor(i) == Succ)
246 return i;
Devang Patel80198932007-07-06 21:39:20 +0000247 }
Bob Wilsonadb6f222010-02-16 19:49:17 +0000248 return 0;
249}
250
251/// SplitEdge - Split the edge connecting specified block. Pass P must
252/// not be NULL.
253BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
Bob Wilsonae23daf2010-02-16 21:06:42 +0000254 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Devang Patel80198932007-07-06 21:39:20 +0000255
256 // If this is a critical edge, let SplitCriticalEdge do it.
Bob Wilsonadb6f222010-02-16 19:49:17 +0000257 TerminatorInst *LatchTerm = BB->getTerminator();
258 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
Devang Patel80198932007-07-06 21:39:20 +0000259 return LatchTerm->getSuccessor(SuccNum);
260
261 // If the edge isn't critical, then BB has a single successor or Succ has a
262 // single pred. Split the block.
263 BasicBlock::iterator SplitPoint;
264 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
265 // If the successor only has a single pred, split the top of the successor
266 // block.
267 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000268 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000269 return SplitBlock(Succ, Succ->begin(), P);
Devang Patel80198932007-07-06 21:39:20 +0000270 }
Chris Lattnerb0433d42011-01-08 18:47:43 +0000271
272 // Otherwise, if BB has a single successor, split it at the bottom of the
273 // block.
274 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
275 "Should have a single succ!");
276 return SplitBlock(BB, BB->getTerminator(), P);
Devang Patel80198932007-07-06 21:39:20 +0000277}
278
279/// SplitBlock - Split the specified block at the specified instruction - every
280/// thing before SplitPt stays in Old and everything starting with SplitPt moves
281/// to a new block. The two blocks are joined by an unconditional branch and
282/// the loop info is updated.
283///
284BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000285 BasicBlock::iterator SplitIt = SplitPt;
286 while (isa<PHINode>(SplitIt))
287 ++SplitIt;
288 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
289
Dan Gohman5c89b522009-09-08 15:45:00 +0000290 // The new block lives in whichever loop the old one did. This preserves
291 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000292 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000293 if (Loop *L = LI->getLoopFor(Old))
294 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000295
Evan Cheng0f1666b2010-04-05 21:16:25 +0000296 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Gabor Greife2d50042010-09-10 22:25:58 +0000297 // Old dominates New. New node dominates all other nodes dominated by Old.
Evan Cheng0f1666b2010-04-05 21:16:25 +0000298 DomTreeNode *OldNode = DT->getNode(Old);
299 std::vector<DomTreeNode *> Children;
300 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
301 I != E; ++I)
302 Children.push_back(*I);
Devang Patela8a8a362007-07-19 02:29:24 +0000303
Evan Cheng0f1666b2010-04-05 21:16:25 +0000304 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
Devang Patela8a8a362007-07-19 02:29:24 +0000305 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
306 E = Children.end(); I != E; ++I)
307 DT->changeImmediateDominator(*I, NewNode);
Evan Cheng0f1666b2010-04-05 21:16:25 +0000308 }
Devang Patel80198932007-07-06 21:39:20 +0000309
Duncan Sands1465d612009-01-28 13:14:17 +0000310 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000311 DF->splitBlock(Old);
312
313 return New;
314}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000315
316
317/// SplitBlockPredecessors - This method transforms BB by introducing a new
318/// basic block into the function, and moving some of the predecessors of BB to
319/// be predecessors of the new block. The new predecessors are indicated by the
320/// Preds array, which has NumPreds elements in it. The new block is given a
321/// suffix of 'Suffix'.
322///
Dan Gohman5c89b522009-09-08 15:45:00 +0000323/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
324/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
325/// In particular, it does not preserve LoopSimplify (because it's
326/// complicated to handle the case where one of the edges being split
327/// is an exit of a loop with other exits).
328///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000329BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
330 BasicBlock *const *Preds,
331 unsigned NumPreds, const char *Suffix,
332 Pass *P) {
333 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000334 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
335 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000336
337 // The new block unconditionally branches to the old block.
338 BranchInst *BI = BranchInst::Create(BB, NewBB);
339
Dan Gohman5c89b522009-09-08 15:45:00 +0000340 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
341 Loop *L = LI ? LI->getLoopFor(BB) : 0;
342 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
343
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000344 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000345 // While here, if we need to preserve loop analyses, collect
346 // some information about how this split will affect loops.
347 bool HasLoopExit = false;
348 bool IsLoopEntry = !!L;
349 bool SplitMakesNewLoopHeader = false;
350 for (unsigned i = 0; i != NumPreds; ++i) {
Dan Gohmanb8eb17c2009-11-05 18:25:44 +0000351 // This is slightly more strict than necessary; the minimum requirement
352 // is that there be no more than one indirectbr branching to BB. And
353 // all BlockAddress uses would need to be updated.
354 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
355 "Cannot split an edge from an IndirectBrInst");
356
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000357 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000358
359 if (LI) {
360 // If we need to preserve LCSSA, determine if any of
361 // the preds is a loop exit.
362 if (PreserveLCSSA)
363 if (Loop *PL = LI->getLoopFor(Preds[i]))
364 if (!PL->contains(BB))
365 HasLoopExit = true;
366 // If we need to preserve LoopInfo, note whether any of the
367 // preds crosses an interesting loop boundary.
368 if (L) {
369 if (L->contains(Preds[i]))
370 IsLoopEntry = false;
371 else
372 SplitMakesNewLoopHeader = true;
373 }
374 }
375 }
376
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000377 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000378 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000379 if (DT)
380 DT->splitBlock(NewBB);
Chris Lattnerc7e31fc2010-08-18 03:13:35 +0000381 if (DominanceFrontier *DF =
382 P ? P->getAnalysisIfAvailable<DominanceFrontier>() : 0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000383 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000384
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000385 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
386 // node becomes an incoming value for BB's phi node. However, if the Preds
387 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
388 // account for the newly created predecessor.
389 if (NumPreds == 0) {
390 // Insert dummy values as the incoming value.
391 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000392 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000393 return NewBB;
394 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000395
396 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
397
398 if (L) {
399 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000400 // Add the new block to the nearest enclosing loop (and not an
401 // adjacent loop). To find this, examine each of the predecessors and
402 // determine which loops enclose them, and select the most-nested loop
403 // which contains the loop containing the block being split.
404 Loop *InnermostPredLoop = 0;
405 for (unsigned i = 0; i != NumPreds; ++i)
406 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
407 // Seek a loop which actually contains the block being split (to
408 // avoid adjacent loops).
409 while (PredLoop && !PredLoop->contains(BB))
410 PredLoop = PredLoop->getParentLoop();
411 // Select the most-nested of these loops which contains the block.
412 if (PredLoop &&
413 PredLoop->contains(BB) &&
414 (!InnermostPredLoop ||
415 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
416 InnermostPredLoop = PredLoop;
417 }
418 if (InnermostPredLoop)
419 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000420 } else {
421 L->addBasicBlockToLoop(NewBB, LI->getBase());
422 if (SplitMakesNewLoopHeader)
423 L->moveToHeader(NewBB);
424 }
425 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000426
427 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
428 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
429 PHINode *PN = cast<PHINode>(I++);
430
431 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000432 // don't need to create a new PHI node, unless it's needed for LCSSA.
433 Value *InVal = 0;
434 if (!HasLoopExit) {
435 InVal = PN->getIncomingValueForBlock(Preds[0]);
436 for (unsigned i = 1; i != NumPreds; ++i)
437 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
438 InVal = 0;
439 break;
440 }
441 }
442
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000443 if (InVal) {
444 // If all incoming values for the new PHI would be the same, just don't
445 // make a new PHI. Instead, just remove the incoming values from the old
446 // PHI.
447 for (unsigned i = 0; i != NumPreds; ++i)
448 PN->removeIncomingValue(Preds[i], false);
449 } else {
450 // If the values coming into the block are not the same, we need a PHI.
451 // Create the new PHI node, insert it into NewBB at the end of the block
452 PHINode *NewPHI =
453 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
454 if (AA) AA->copyValue(PN, NewPHI);
455
456 // Move all of the PHI values for 'Preds' to the new PHI.
457 for (unsigned i = 0; i != NumPreds; ++i) {
458 Value *V = PN->removeIncomingValue(Preds[i], false);
459 NewPHI->addIncoming(V, Preds[i]);
460 }
461 InVal = NewPHI;
462 }
463
464 // Add an incoming value to the PHI node in the loop for the preheader
465 // edge.
466 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000467 }
468
469 return NewBB;
470}
Chris Lattner52c95852008-11-27 08:10:05 +0000471
Mike Stumpfe095f32009-05-04 18:40:41 +0000472/// FindFunctionBackedges - Analyze the specified function to find all of the
473/// loop backedges in the function and return them. This is a relatively cheap
474/// (compared to computing dominators and loop info) analysis.
475///
476/// The output is added to Result, as pairs of <from,to> edge info.
477void llvm::FindFunctionBackedges(const Function &F,
478 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
479 const BasicBlock *BB = &F.getEntryBlock();
480 if (succ_begin(BB) == succ_end(BB))
481 return;
482
483 SmallPtrSet<const BasicBlock*, 8> Visited;
484 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
485 SmallPtrSet<const BasicBlock*, 8> InStack;
486
487 Visited.insert(BB);
488 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
489 InStack.insert(BB);
490 do {
491 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
492 const BasicBlock *ParentBB = Top.first;
493 succ_const_iterator &I = Top.second;
494
495 bool FoundNew = false;
496 while (I != succ_end(ParentBB)) {
497 BB = *I++;
498 if (Visited.insert(BB)) {
499 FoundNew = true;
500 break;
501 }
502 // Successor is in VisitStack, it's a back edge.
503 if (InStack.count(BB))
504 Result.push_back(std::make_pair(ParentBB, BB));
505 }
506
507 if (FoundNew) {
508 // Go down one level if there is a unvisited successor.
509 InStack.insert(BB);
510 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
511 } else {
512 // Go up one level.
513 InStack.erase(VisitStack.pop_back_val().first);
514 }
515 } while (!VisitStack.empty());
516
517
518}