blob: e7f33d30b66c14ae93034e6fcd0b31dbca8d08b8 [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"
Owen Anderson0a205a42009-07-05 22:41:43 +000019#include "llvm/LLVMContext.h"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000020#include "llvm/Constant.h"
21#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000022#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000023#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/Dominators.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.
67void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
Chris Lattner29874e02008-12-03 19:44:02 +000068 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
69 if (PN->getIncomingValue(0) != PN)
70 PN->replaceAllUsesWith(PN->getIncomingValue(0));
71 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000072 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner29874e02008-12-03 19:44:02 +000073 PN->eraseFromParent();
74 }
75}
76
77
Dan Gohmanafc36a92009-05-02 18:29:22 +000078/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
79/// is dead. Also recursively delete any operands that become dead as
80/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman35738ac2009-05-04 22:30:44 +000081/// it is ultimately unused or if it reaches an unused cycle.
82void llvm::DeleteDeadPHIs(BasicBlock *BB) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000083 // Recursively deleting a PHI may cause multiple PHIs to be deleted
84 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
85 SmallVector<WeakVH, 8> PHIs;
86 for (BasicBlock::iterator I = BB->begin();
87 PHINode *PN = dyn_cast<PHINode>(I); ++I)
88 PHIs.push_back(PN);
89
90 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
91 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohman35738ac2009-05-04 22:30:44 +000092 RecursivelyDeleteDeadPHINode(PN);
Dan Gohmanafc36a92009-05-02 18:29:22 +000093}
94
Dan Gohmanf230d8a2009-10-31 16:08:00 +000095/// MergeBlockIntoPredecessor - Folds a basic block into its predecessor if it
96/// only has one predecessor, and that predecessor only has one successor.
97/// If a Pass is given, the LoopInfo and DominatorTree analyses will be kept
98/// current. Returns the combined block, or null if no merging was performed.
99BasicBlock *llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
100 // Don't merge if the block has multiple predecessors.
101 BasicBlock *PredBB = BB->getSinglePredecessor();
102 if (!PredBB) return 0;
103 // Don't merge if the predecessor has multiple successors.
104 if (PredBB->getTerminator()->getNumSuccessors() != 1) return 0;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +0000105 // Don't break self-loops.
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000106 if (PredBB == BB) return 0;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +0000107 // Don't break invokes.
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000108 if (isa<InvokeInst>(PredBB->getTerminator())) return 0;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000109
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000110 // Resolve any PHI nodes at the start of the block. They are all
111 // guaranteed to have exactly one entry if they exist, unless there are
112 // multiple duplicate (but guaranteed to be equal) entries for the
113 // incoming edges. This occurs when there are multiple edges from
114 // PredBB to BB.
115 FoldSingleEntryPHINodes(BB);
Devang Patele435a5d2008-09-09 01:06:56 +0000116
Owen Andersonb31b06d2008-07-17 00:01:40 +0000117 // Delete the unconditional branch from the predecessor...
118 PredBB->getInstList().pop_back();
119
120 // Move all definitions in the successor to the predecessor...
121 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
122
123 // Make all PHI nodes that referred to BB now refer to Pred as their
124 // source...
125 BB->replaceAllUsesWith(PredBB);
126
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000127 // If the predecessor doesn't have a name, take the successor's name.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000128 if (!PredBB->hasName())
129 PredBB->takeName(BB);
130
Owen Andersonb31b06d2008-07-17 00:01:40 +0000131 // Finally, erase the old block and update dominator info.
132 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000133 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000134 DomTreeNode* DTN = DT->getNode(BB);
135 DomTreeNode* PredDTN = DT->getNode(PredBB);
136
137 if (DTN) {
138 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
139 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
140 DE = Children.end(); DI != DE; ++DI)
141 DT->changeImmediateDominator(*DI, PredDTN);
142
143 DT->eraseNode(BB);
144 }
145 }
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000146 // Notify LoopInfo that the block is removed.
147 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
148 LI->removeBlock(BB);
Owen Andersonb31b06d2008-07-17 00:01:40 +0000149 }
150
151 BB->eraseFromParent();
152
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000153 return PredBB;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000154}
155
Chris Lattner0f67dd62005-04-21 16:04:49 +0000156/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
157/// with a value, then remove and delete the original instruction.
158///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000159void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
160 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000161 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000162 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000163 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000164
Chris Lattner86cc4232007-02-11 01:37:51 +0000165 // Make sure to propagate a name if there is one already.
166 if (I.hasName() && !V->hasName())
167 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000168
Misha Brukman5560c9d2003-08-18 14:43:39 +0000169 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000170 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000171}
172
173
Chris Lattner0f67dd62005-04-21 16:04:49 +0000174/// ReplaceInstWithInst - Replace the instruction specified by BI with the
175/// instruction specified by I. The original instruction is deleted and BI is
176/// updated to point to the new instruction.
177///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000178void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
179 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000180 assert(I->getParent() == 0 &&
181 "ReplaceInstWithInst: Instruction already inserted into basic block!");
182
183 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000184 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000185
186 // Replace all uses of the old instruction, and delete it.
187 ReplaceInstWithValue(BIL, BI, I);
188
189 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000190 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000191}
192
Chris Lattner0f67dd62005-04-21 16:04:49 +0000193/// ReplaceInstWithInst - Replace the instruction specified by From with the
194/// instruction specified by To.
195///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000196void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000197 BasicBlock::iterator BI(From);
198 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000199}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000200
Chris Lattner0f67dd62005-04-21 16:04:49 +0000201/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000202/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000203/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000204/// may have to be changed. In the case where the last successor of the block
205/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000206/// surprising change in program behavior if it is not expected.
207///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000208void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000209 assert(SuccNum < TI->getNumSuccessors() &&
210 "Trying to remove a nonexistant successor!");
211
212 // If our old successor block contains any PHI nodes, remove the entry in the
213 // PHI nodes that comes from this branch...
214 //
215 BasicBlock *BB = TI->getParent();
216 TI->getSuccessor(SuccNum)->removePredecessor(BB);
217
218 TerminatorInst *NewTI = 0;
219 switch (TI->getOpcode()) {
220 case Instruction::Br:
221 // If this is a conditional branch... convert to unconditional branch.
222 if (TI->getNumSuccessors() == 2) {
223 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
224 } else { // Otherwise convert to a return instruction...
225 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000226
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000227 // Create a value to return... if the function doesn't return null...
Owen Anderson1d0be152009-08-13 21:58:54 +0000228 if (BB->getParent()->getReturnType() != Type::getVoidTy(TI->getContext()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000229 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000230
231 // Create the return...
Owen Anderson1d0be152009-08-13 21:58:54 +0000232 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000233 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000234 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000235
236 case Instruction::Invoke: // Should convert to call
237 case Instruction::Switch: // Should remove entry
238 default:
239 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000240 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000241 }
242
243 if (NewTI) // If it's a different instruction, replace.
244 ReplaceInstWithInst(TI, NewTI);
245}
Brian Gaeked0fde302003-11-11 22:41:34 +0000246
Devang Patel80198932007-07-06 21:39:20 +0000247/// SplitEdge - Split the edge connecting specified block. Pass P must
248/// not be NULL.
249BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
250 TerminatorInst *LatchTerm = BB->getTerminator();
251 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000252#ifndef NDEBUG
253 unsigned e = LatchTerm->getNumSuccessors();
254#endif
255 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000256 assert(i != e && "Didn't find edge?");
257 if (LatchTerm->getSuccessor(i) == Succ) {
258 SuccNum = i;
259 break;
260 }
261 }
262
263 // If this is a critical edge, let SplitCriticalEdge do it.
264 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
265 return LatchTerm->getSuccessor(SuccNum);
266
267 // If the edge isn't critical, then BB has a single successor or Succ has a
268 // single pred. Split the block.
269 BasicBlock::iterator SplitPoint;
270 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
271 // If the successor only has a single pred, split the top of the successor
272 // block.
273 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000274 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000275 return SplitBlock(Succ, Succ->begin(), P);
276 } else {
277 // Otherwise, if BB has a single successor, split it at the bottom of the
278 // block.
279 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
280 "Should have a single succ!");
281 return SplitBlock(BB, BB->getTerminator(), P);
282 }
283}
284
285/// SplitBlock - Split the specified block at the specified instruction - every
286/// thing before SplitPt stays in Old and everything starting with SplitPt moves
287/// to a new block. The two blocks are joined by an unconditional branch and
288/// the loop info is updated.
289///
290BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000291 BasicBlock::iterator SplitIt = SplitPt;
292 while (isa<PHINode>(SplitIt))
293 ++SplitIt;
294 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
295
Dan Gohman5c89b522009-09-08 15:45:00 +0000296 // The new block lives in whichever loop the old one did. This preserves
297 // LCSSA as well, because we force the split point to be after any PHI nodes.
Duncan Sands1465d612009-01-28 13:14:17 +0000298 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000299 if (Loop *L = LI->getLoopFor(Old))
300 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000301
Duncan Sands1465d612009-01-28 13:14:17 +0000302 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000303 {
304 // Old dominates New. New node domiantes all other nodes dominated by Old.
305 DomTreeNode *OldNode = DT->getNode(Old);
306 std::vector<DomTreeNode *> Children;
307 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
308 I != E; ++I)
309 Children.push_back(*I);
310
311 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
312
313 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
314 E = Children.end(); I != E; ++I)
315 DT->changeImmediateDominator(*I, NewNode);
316 }
Devang Patel80198932007-07-06 21:39:20 +0000317
Duncan Sands1465d612009-01-28 13:14:17 +0000318 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000319 DF->splitBlock(Old);
320
321 return New;
322}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000323
324
325/// SplitBlockPredecessors - This method transforms BB by introducing a new
326/// basic block into the function, and moving some of the predecessors of BB to
327/// be predecessors of the new block. The new predecessors are indicated by the
328/// Preds array, which has NumPreds elements in it. The new block is given a
329/// suffix of 'Suffix'.
330///
Dan Gohman5c89b522009-09-08 15:45:00 +0000331/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
332/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
333/// In particular, it does not preserve LoopSimplify (because it's
334/// complicated to handle the case where one of the edges being split
335/// is an exit of a loop with other exits).
336///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000337BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
338 BasicBlock *const *Preds,
339 unsigned NumPreds, const char *Suffix,
340 Pass *P) {
341 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000342 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
343 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000344
345 // The new block unconditionally branches to the old block.
346 BranchInst *BI = BranchInst::Create(BB, NewBB);
347
Dan Gohman5c89b522009-09-08 15:45:00 +0000348 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
349 Loop *L = LI ? LI->getLoopFor(BB) : 0;
350 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
351
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000352 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000353 // While here, if we need to preserve loop analyses, collect
354 // some information about how this split will affect loops.
355 bool HasLoopExit = false;
356 bool IsLoopEntry = !!L;
357 bool SplitMakesNewLoopHeader = false;
358 for (unsigned i = 0; i != NumPreds; ++i) {
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000359 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000360
361 if (LI) {
362 // If we need to preserve LCSSA, determine if any of
363 // the preds is a loop exit.
364 if (PreserveLCSSA)
365 if (Loop *PL = LI->getLoopFor(Preds[i]))
366 if (!PL->contains(BB))
367 HasLoopExit = true;
368 // If we need to preserve LoopInfo, note whether any of the
369 // preds crosses an interesting loop boundary.
370 if (L) {
371 if (L->contains(Preds[i]))
372 IsLoopEntry = false;
373 else
374 SplitMakesNewLoopHeader = true;
375 }
376 }
377 }
378
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000379 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000380 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000381 if (DT)
382 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000383 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000384 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000385
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000386 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
387 // node becomes an incoming value for BB's phi node. However, if the Preds
388 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
389 // account for the newly created predecessor.
390 if (NumPreds == 0) {
391 // Insert dummy values as the incoming value.
392 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000393 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000394 return NewBB;
395 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000396
397 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
398
399 if (L) {
400 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000401 // Add the new block to the nearest enclosing loop (and not an
402 // adjacent loop). To find this, examine each of the predecessors and
403 // determine which loops enclose them, and select the most-nested loop
404 // which contains the loop containing the block being split.
405 Loop *InnermostPredLoop = 0;
406 for (unsigned i = 0; i != NumPreds; ++i)
407 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
408 // Seek a loop which actually contains the block being split (to
409 // avoid adjacent loops).
410 while (PredLoop && !PredLoop->contains(BB))
411 PredLoop = PredLoop->getParentLoop();
412 // Select the most-nested of these loops which contains the block.
413 if (PredLoop &&
414 PredLoop->contains(BB) &&
415 (!InnermostPredLoop ||
416 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
417 InnermostPredLoop = PredLoop;
418 }
419 if (InnermostPredLoop)
420 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000421 } else {
422 L->addBasicBlockToLoop(NewBB, LI->getBase());
423 if (SplitMakesNewLoopHeader)
424 L->moveToHeader(NewBB);
425 }
426 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000427
428 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
429 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
430 PHINode *PN = cast<PHINode>(I++);
431
432 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000433 // don't need to create a new PHI node, unless it's needed for LCSSA.
434 Value *InVal = 0;
435 if (!HasLoopExit) {
436 InVal = PN->getIncomingValueForBlock(Preds[0]);
437 for (unsigned i = 1; i != NumPreds; ++i)
438 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
439 InVal = 0;
440 break;
441 }
442 }
443
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000444 if (InVal) {
445 // If all incoming values for the new PHI would be the same, just don't
446 // make a new PHI. Instead, just remove the incoming values from the old
447 // PHI.
448 for (unsigned i = 0; i != NumPreds; ++i)
449 PN->removeIncomingValue(Preds[i], false);
450 } else {
451 // If the values coming into the block are not the same, we need a PHI.
452 // Create the new PHI node, insert it into NewBB at the end of the block
453 PHINode *NewPHI =
454 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
455 if (AA) AA->copyValue(PN, NewPHI);
456
457 // Move all of the PHI values for 'Preds' to the new PHI.
458 for (unsigned i = 0; i != NumPreds; ++i) {
459 Value *V = PN->removeIncomingValue(Preds[i], false);
460 NewPHI->addIncoming(V, Preds[i]);
461 }
462 InVal = NewPHI;
463 }
464
465 // Add an incoming value to the PHI node in the loop for the preheader
466 // edge.
467 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000468 }
469
470 return NewBB;
471}
Chris Lattner52c95852008-11-27 08:10:05 +0000472
Mike Stumpfe095f32009-05-04 18:40:41 +0000473/// FindFunctionBackedges - Analyze the specified function to find all of the
474/// loop backedges in the function and return them. This is a relatively cheap
475/// (compared to computing dominators and loop info) analysis.
476///
477/// The output is added to Result, as pairs of <from,to> edge info.
478void llvm::FindFunctionBackedges(const Function &F,
479 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
480 const BasicBlock *BB = &F.getEntryBlock();
481 if (succ_begin(BB) == succ_end(BB))
482 return;
483
484 SmallPtrSet<const BasicBlock*, 8> Visited;
485 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
486 SmallPtrSet<const BasicBlock*, 8> InStack;
487
488 Visited.insert(BB);
489 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
490 InStack.insert(BB);
491 do {
492 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
493 const BasicBlock *ParentBB = Top.first;
494 succ_const_iterator &I = Top.second;
495
496 bool FoundNew = false;
497 while (I != succ_end(ParentBB)) {
498 BB = *I++;
499 if (Visited.insert(BB)) {
500 FoundNew = true;
501 break;
502 }
503 // Successor is in VisitStack, it's a back edge.
504 if (InStack.count(BB))
505 Result.push_back(std::make_pair(ParentBB, BB));
506 }
507
508 if (FoundNew) {
509 // Go down one level if there is a unvisited successor.
510 InStack.insert(BB);
511 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
512 } else {
513 // Go up one level.
514 InStack.erase(VisitStack.pop_back_val().first);
515 }
516 } while (!VisitStack.empty());
517
518
519}
520
521
522
Chris Lattner4aebaee2008-11-27 08:56:30 +0000523/// AreEquivalentAddressValues - Test if A and B will obviously have the same
524/// value. This includes recognizing that %t0 and %t1 will have the same
525/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000526/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000527/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000528/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000529/// %t2 = load i32* %t1
530///
531static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
532 // Test if the values are trivially equivalent.
533 if (A == B) return true;
534
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000535 // Test if the values come from identical arithmetic instructions.
536 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
537 // this function is only used when one address use dominates the
538 // other, which means that they'll always either have the same
539 // value or one of them will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +0000540 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
541 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
542 if (const Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000543 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000544 return true;
545
546 // Otherwise they may not be equivalent.
547 return false;
548}
549
Chris Lattner52c95852008-11-27 08:10:05 +0000550/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
551/// instruction before ScanFrom) checking to see if we have the value at the
552/// memory address *Ptr locally available within a small number of instructions.
553/// If the value is available, return it.
554///
555/// If not, return the iterator for the last validated instruction that the
556/// value would be live through. If we scanned the entire block and didn't find
557/// something that invalidates *Ptr or provides it, ScanFrom would be left at
558/// begin() and this returns null. ScanFrom could also be left
559///
560/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
561/// it is set to 0, it will scan the whole block. You can also optionally
562/// specify an alias analysis implementation, which makes this more precise.
563Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
564 BasicBlock::iterator &ScanFrom,
565 unsigned MaxInstsToScan,
566 AliasAnalysis *AA) {
567 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000568
569 // If we're using alias analysis to disambiguate get the size of *Ptr.
570 unsigned AccessSize = 0;
571 if (AA) {
572 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000573 AccessSize = AA->getTypeStoreSize(AccessTy);
Chris Lattneree6e10b2008-11-27 08:18:12 +0000574 }
Chris Lattner52c95852008-11-27 08:10:05 +0000575
576 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000577 // We must ignore debug info directives when counting (otherwise they
578 // would affect codegen).
579 Instruction *Inst = --ScanFrom;
580 if (isa<DbgInfoIntrinsic>(Inst))
581 continue;
Dale Johannesend9c05d72009-03-04 02:06:53 +0000582 // We skip pointer-to-pointer bitcasts, which are NOPs.
583 // It is necessary for correctness to skip those that feed into a
584 // llvm.dbg.declare, as these are not present when debugging is off.
585 if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000586 continue;
587
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000588 // Restore ScanFrom to expected value in case next test succeeds
589 ScanFrom++;
590
Chris Lattner52c95852008-11-27 08:10:05 +0000591 // Don't scan huge blocks.
592 if (MaxInstsToScan-- == 0) return 0;
593
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000594 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000595 // If this is a load of Ptr, the loaded value is available.
596 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000597 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000598 return LI;
599
600 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
601 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000602 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000603 return SI->getOperand(0);
604
605 // If Ptr is an alloca and this is a store to a different alloca, ignore
606 // the store. This is a trivial form of alias analysis that is important
607 // for reg2mem'd code.
608 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
609 (isa<AllocaInst>(SI->getOperand(1)) ||
610 isa<GlobalVariable>(SI->getOperand(1))))
611 continue;
612
Chris Lattneree6e10b2008-11-27 08:18:12 +0000613 // If we have alias analysis and it says the store won't modify the loaded
614 // value, ignore the store.
615 if (AA &&
616 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
617 continue;
618
Chris Lattner52c95852008-11-27 08:10:05 +0000619 // Otherwise the store that may or may not alias the pointer, bail out.
620 ++ScanFrom;
621 return 0;
622 }
623
Chris Lattner52c95852008-11-27 08:10:05 +0000624 // If this is some other instruction that may clobber Ptr, bail out.
625 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000626 // If alias analysis claims that it really won't modify the load,
627 // ignore it.
628 if (AA &&
629 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
630 continue;
631
Chris Lattner52c95852008-11-27 08:10:05 +0000632 // May modify the pointer, bail out.
633 ++ScanFrom;
634 return 0;
635 }
636 }
637
638 // Got to the start of the block, we didn't find it, but are done for this
639 // block.
640 return 0;
641}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000642
643/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
644/// make a copy of the stoppoint before InsertPos (presumably before copying
645/// or moving I).
646void llvm::CopyPrecedingStopPoint(Instruction *I,
647 BasicBlock::iterator InsertPos) {
648 if (I != I->getParent()->begin()) {
649 BasicBlock::iterator BBI = I; --BBI;
650 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
Devang Patel50b6e332009-10-27 22:16:29 +0000651 CallInst *newDSPI = cast<CallInst>(DSPI->clone());
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000652 newDSPI->insertBefore(InsertPos);
653 }
654 }
655}