blob: 076f89e3374d80edf18278759aa3c3806943cb70 [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"
Devang Patel80198932007-07-06 21:39:20 +000022#include "llvm/Analysis/LoopInfo.h"
23#include "llvm/Analysis/Dominators.h"
Chris Lattneree6e10b2008-11-27 08:18:12 +000024#include "llvm/Target/TargetData.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000025#include "llvm/Transforms/Utils/Local.h"
26#include "llvm/Support/ValueHandle.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000027#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner71af9b02008-12-03 06:40:52 +000030/// DeleteDeadBlock - Delete the specified block, which must have no
31/// predecessors.
32void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000033 assert((pred_begin(BB) == pred_end(BB) ||
34 // Can delete self loop.
35 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000036 TerminatorInst *BBTerm = BB->getTerminator();
Devang Patel5622f072009-02-24 00:05:16 +000037
Chris Lattner2b1ba242008-12-03 06:37:44 +000038 // Loop through all of our successors and make sure they know that one
39 // of their predecessors is going away.
40 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
41 BBTerm->getSuccessor(i)->removePredecessor(BB);
42
43 // Zap all the instructions in the block.
44 while (!BB->empty()) {
45 Instruction &I = BB->back();
46 // If this instruction is used, replace uses with an arbitrary value.
47 // Because control flow can't get here, we don't care what we replace the
48 // value with. Note that since this block is unreachable, and all values
49 // contained within it must dominate their uses, that all uses will
50 // eventually be removed (they are themselves dead).
51 if (!I.use_empty())
52 I.replaceAllUsesWith(UndefValue::get(I.getType()));
53 BB->getInstList().pop_back();
54 }
Devang Patel5622f072009-02-24 00:05:16 +000055
Chris Lattner2b1ba242008-12-03 06:37:44 +000056 // Zap the block!
57 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000058}
59
Chris Lattner29874e02008-12-03 19:44:02 +000060/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
61/// any single-entry PHI nodes in it, fold them away. This handles the case
62/// when all entries to the PHI nodes in a block are guaranteed equal, such as
63/// when the block has exactly one predecessor.
64void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
65 if (!isa<PHINode>(BB->begin()))
66 return;
67
68 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
69 if (PN->getIncomingValue(0) != PN)
70 PN->replaceAllUsesWith(PN->getIncomingValue(0));
71 else
72 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
73 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 Gohmanf9a77b72009-05-03 05:46:20 +000081/// it is ultimately unused or if it reaches an unused cycle. If a
82/// ValueDeletionListener is specified, it is notified of the deletions.
83void llvm::DeleteDeadPHIs(BasicBlock *BB, ValueDeletionListener *VDL) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000084 // Recursively deleting a PHI may cause multiple PHIs to be deleted
85 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
86 SmallVector<WeakVH, 8> PHIs;
87 for (BasicBlock::iterator I = BB->begin();
88 PHINode *PN = dyn_cast<PHINode>(I); ++I)
89 PHIs.push_back(PN);
90
91 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
92 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohmanf9a77b72009-05-03 05:46:20 +000093 RecursivelyDeleteDeadPHINode(PN, VDL);
Dan Gohmanafc36a92009-05-02 18:29:22 +000094}
95
Owen Andersonb31b06d2008-07-17 00:01:40 +000096/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
97/// if possible. The return value indicates success or failure.
98bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +000099 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +0000100 // Can't merge the entry block.
101 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000102
Owen Anderson11f2ec82008-07-17 19:42:29 +0000103 BasicBlock *PredBB = *PI++;
104 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
105 if (*PI != PredBB) {
106 PredBB = 0; // There are multiple different predecessors...
107 break;
108 }
Owen Andersonb31b06d2008-07-17 00:01:40 +0000109
Owen Anderson11f2ec82008-07-17 19:42:29 +0000110 // Can't merge if there are multiple predecessors.
111 if (!PredBB) return false;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +0000112 // Don't break self-loops.
113 if (PredBB == BB) return false;
114 // Don't break invokes.
115 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000116
117 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
118 BasicBlock* OnlySucc = BB;
119 for (; SI != SE; ++SI)
120 if (*SI != OnlySucc) {
121 OnlySucc = 0; // There are multiple distinct successors!
122 break;
123 }
124
125 // Can't merge if there are multiple successors.
126 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000127
128 // Can't merge if there is PHI loop.
129 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
130 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
131 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
132 if (PN->getIncomingValue(i) == PN)
133 return false;
134 } else
135 break;
136 }
137
Owen Andersonb31b06d2008-07-17 00:01:40 +0000138 // Begin by getting rid of unneeded PHIs.
139 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
140 PN->replaceAllUsesWith(PN->getIncomingValue(0));
141 BB->getInstList().pop_front(); // Delete the phi node...
142 }
143
144 // Delete the unconditional branch from the predecessor...
145 PredBB->getInstList().pop_back();
146
147 // Move all definitions in the successor to the predecessor...
148 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
149
150 // Make all PHI nodes that referred to BB now refer to Pred as their
151 // source...
152 BB->replaceAllUsesWith(PredBB);
153
Owen Anderson11f2ec82008-07-17 19:42:29 +0000154 // Inherit predecessors name if it exists.
155 if (!PredBB->hasName())
156 PredBB->takeName(BB);
157
Owen Andersonb31b06d2008-07-17 00:01:40 +0000158 // Finally, erase the old block and update dominator info.
159 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000160 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000161 DomTreeNode* DTN = DT->getNode(BB);
162 DomTreeNode* PredDTN = DT->getNode(PredBB);
163
164 if (DTN) {
165 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
166 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
167 DE = Children.end(); DI != DE; ++DI)
168 DT->changeImmediateDominator(*DI, PredDTN);
169
170 DT->eraseNode(BB);
171 }
172 }
173 }
174
175 BB->eraseFromParent();
176
177
178 return true;
179}
180
Chris Lattner0f67dd62005-04-21 16:04:49 +0000181/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
182/// with a value, then remove and delete the original instruction.
183///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000184void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
185 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000186 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000187 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000188 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000189
Chris Lattner86cc4232007-02-11 01:37:51 +0000190 // Make sure to propagate a name if there is one already.
191 if (I.hasName() && !V->hasName())
192 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000193
Misha Brukman5560c9d2003-08-18 14:43:39 +0000194 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000195 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000196}
197
198
Chris Lattner0f67dd62005-04-21 16:04:49 +0000199/// ReplaceInstWithInst - Replace the instruction specified by BI with the
200/// instruction specified by I. The original instruction is deleted and BI is
201/// updated to point to the new instruction.
202///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000203void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
204 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000205 assert(I->getParent() == 0 &&
206 "ReplaceInstWithInst: Instruction already inserted into basic block!");
207
208 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000209 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000210
211 // Replace all uses of the old instruction, and delete it.
212 ReplaceInstWithValue(BIL, BI, I);
213
214 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000215 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000216}
217
Chris Lattner0f67dd62005-04-21 16:04:49 +0000218/// ReplaceInstWithInst - Replace the instruction specified by From with the
219/// instruction specified by To.
220///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000221void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000222 BasicBlock::iterator BI(From);
223 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000224}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000225
Chris Lattner0f67dd62005-04-21 16:04:49 +0000226/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000227/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000228/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000229/// may have to be changed. In the case where the last successor of the block
230/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000231/// surprising change in program behavior if it is not expected.
232///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000233void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000234 assert(SuccNum < TI->getNumSuccessors() &&
235 "Trying to remove a nonexistant successor!");
236
237 // If our old successor block contains any PHI nodes, remove the entry in the
238 // PHI nodes that comes from this branch...
239 //
240 BasicBlock *BB = TI->getParent();
241 TI->getSuccessor(SuccNum)->removePredecessor(BB);
242
243 TerminatorInst *NewTI = 0;
244 switch (TI->getOpcode()) {
245 case Instruction::Br:
246 // If this is a conditional branch... convert to unconditional branch.
247 if (TI->getNumSuccessors() == 2) {
248 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
249 } else { // Otherwise convert to a return instruction...
250 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000251
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000252 // Create a value to return... if the function doesn't return null...
253 if (BB->getParent()->getReturnType() != Type::VoidTy)
254 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
255
256 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000257 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000258 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000259 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000260
261 case Instruction::Invoke: // Should convert to call
262 case Instruction::Switch: // Should remove entry
263 default:
264 case Instruction::Ret: // Cannot happen, has no successors!
265 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
266 abort();
267 }
268
269 if (NewTI) // If it's a different instruction, replace.
270 ReplaceInstWithInst(TI, NewTI);
271}
Brian Gaeked0fde302003-11-11 22:41:34 +0000272
Devang Patel80198932007-07-06 21:39:20 +0000273/// SplitEdge - Split the edge connecting specified block. Pass P must
274/// not be NULL.
275BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
276 TerminatorInst *LatchTerm = BB->getTerminator();
277 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000278#ifndef NDEBUG
279 unsigned e = LatchTerm->getNumSuccessors();
280#endif
281 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000282 assert(i != e && "Didn't find edge?");
283 if (LatchTerm->getSuccessor(i) == Succ) {
284 SuccNum = i;
285 break;
286 }
287 }
288
289 // If this is a critical edge, let SplitCriticalEdge do it.
290 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
291 return LatchTerm->getSuccessor(SuccNum);
292
293 // If the edge isn't critical, then BB has a single successor or Succ has a
294 // single pred. Split the block.
295 BasicBlock::iterator SplitPoint;
296 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
297 // If the successor only has a single pred, split the top of the successor
298 // block.
299 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000300 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000301 return SplitBlock(Succ, Succ->begin(), P);
302 } else {
303 // Otherwise, if BB has a single successor, split it at the bottom of the
304 // block.
305 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
306 "Should have a single succ!");
307 return SplitBlock(BB, BB->getTerminator(), P);
308 }
309}
310
311/// SplitBlock - Split the specified block at the specified instruction - every
312/// thing before SplitPt stays in Old and everything starting with SplitPt moves
313/// to a new block. The two blocks are joined by an unconditional branch and
314/// the loop info is updated.
315///
316BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000317 BasicBlock::iterator SplitIt = SplitPt;
318 while (isa<PHINode>(SplitIt))
319 ++SplitIt;
320 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
321
322 // The new block lives in whichever loop the old one did.
Duncan Sands1465d612009-01-28 13:14:17 +0000323 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000324 if (Loop *L = LI->getLoopFor(Old))
325 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000326
Duncan Sands1465d612009-01-28 13:14:17 +0000327 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000328 {
329 // Old dominates New. New node domiantes all other nodes dominated by Old.
330 DomTreeNode *OldNode = DT->getNode(Old);
331 std::vector<DomTreeNode *> Children;
332 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
333 I != E; ++I)
334 Children.push_back(*I);
335
336 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
337
338 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
339 E = Children.end(); I != E; ++I)
340 DT->changeImmediateDominator(*I, NewNode);
341 }
Devang Patel80198932007-07-06 21:39:20 +0000342
Duncan Sands1465d612009-01-28 13:14:17 +0000343 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000344 DF->splitBlock(Old);
345
346 return New;
347}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000348
349
350/// SplitBlockPredecessors - This method transforms BB by introducing a new
351/// basic block into the function, and moving some of the predecessors of BB to
352/// be predecessors of the new block. The new predecessors are indicated by the
353/// Preds array, which has NumPreds elements in it. The new block is given a
354/// suffix of 'Suffix'.
355///
356/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
357/// DominanceFrontier, but no other analyses.
358BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
359 BasicBlock *const *Preds,
360 unsigned NumPreds, const char *Suffix,
361 Pass *P) {
362 // Create new basic block, insert right before the original block.
363 BasicBlock *NewBB =
364 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
365
366 // The new block unconditionally branches to the old block.
367 BranchInst *BI = BranchInst::Create(BB, NewBB);
368
369 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000370 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000371 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000372
373 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000374 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000375 if (DT)
376 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000377 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000378 DF->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000379 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000380
381
382 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
383 // node becomes an incoming value for BB's phi node. However, if the Preds
384 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
385 // account for the newly created predecessor.
386 if (NumPreds == 0) {
387 // Insert dummy values as the incoming value.
388 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
389 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
390 return NewBB;
391 }
392
393 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
394 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
395 PHINode *PN = cast<PHINode>(I++);
396
397 // Check to see if all of the values coming in are the same. If so, we
398 // don't need to create a new PHI node.
399 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
400 for (unsigned i = 1; i != NumPreds; ++i)
401 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
402 InVal = 0;
403 break;
404 }
405
406 if (InVal) {
407 // If all incoming values for the new PHI would be the same, just don't
408 // make a new PHI. Instead, just remove the incoming values from the old
409 // PHI.
410 for (unsigned i = 0; i != NumPreds; ++i)
411 PN->removeIncomingValue(Preds[i], false);
412 } else {
413 // If the values coming into the block are not the same, we need a PHI.
414 // Create the new PHI node, insert it into NewBB at the end of the block
415 PHINode *NewPHI =
416 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
417 if (AA) AA->copyValue(PN, NewPHI);
418
419 // Move all of the PHI values for 'Preds' to the new PHI.
420 for (unsigned i = 0; i != NumPreds; ++i) {
421 Value *V = PN->removeIncomingValue(Preds[i], false);
422 NewPHI->addIncoming(V, Preds[i]);
423 }
424 InVal = NewPHI;
425 }
426
427 // Add an incoming value to the PHI node in the loop for the preheader
428 // edge.
429 PN->addIncoming(InVal, NewBB);
430
431 // Check to see if we can eliminate this phi node.
432 if (Value *V = PN->hasConstantValue(DT != 0)) {
433 Instruction *I = dyn_cast<Instruction>(V);
434 if (!I || DT == 0 || DT->dominates(I, PN)) {
435 PN->replaceAllUsesWith(V);
436 if (AA) AA->deleteValue(PN);
437 PN->eraseFromParent();
438 }
439 }
440 }
441
442 return NewBB;
443}
Chris Lattner52c95852008-11-27 08:10:05 +0000444
Chris Lattner4aebaee2008-11-27 08:56:30 +0000445/// AreEquivalentAddressValues - Test if A and B will obviously have the same
446/// value. This includes recognizing that %t0 and %t1 will have the same
447/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000448/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000449/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000450/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000451/// %t2 = load i32* %t1
452///
453static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
454 // Test if the values are trivially equivalent.
455 if (A == B) return true;
456
457 // Test if the values come form identical arithmetic instructions.
458 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
459 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
460 if (const Instruction *BI = dyn_cast<Instruction>(B))
461 if (cast<Instruction>(A)->isIdenticalTo(BI))
462 return true;
463
464 // Otherwise they may not be equivalent.
465 return false;
466}
467
Chris Lattner52c95852008-11-27 08:10:05 +0000468/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
469/// instruction before ScanFrom) checking to see if we have the value at the
470/// memory address *Ptr locally available within a small number of instructions.
471/// If the value is available, return it.
472///
473/// If not, return the iterator for the last validated instruction that the
474/// value would be live through. If we scanned the entire block and didn't find
475/// something that invalidates *Ptr or provides it, ScanFrom would be left at
476/// begin() and this returns null. ScanFrom could also be left
477///
478/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
479/// it is set to 0, it will scan the whole block. You can also optionally
480/// specify an alias analysis implementation, which makes this more precise.
481Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
482 BasicBlock::iterator &ScanFrom,
483 unsigned MaxInstsToScan,
484 AliasAnalysis *AA) {
485 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000486
487 // If we're using alias analysis to disambiguate get the size of *Ptr.
488 unsigned AccessSize = 0;
489 if (AA) {
490 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
491 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
492 }
Chris Lattner52c95852008-11-27 08:10:05 +0000493
494 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000495 // We must ignore debug info directives when counting (otherwise they
496 // would affect codegen).
497 Instruction *Inst = --ScanFrom;
498 if (isa<DbgInfoIntrinsic>(Inst))
499 continue;
Dale Johannesend9c05d72009-03-04 02:06:53 +0000500 // We skip pointer-to-pointer bitcasts, which are NOPs.
501 // It is necessary for correctness to skip those that feed into a
502 // llvm.dbg.declare, as these are not present when debugging is off.
503 if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000504 continue;
505
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000506 // Restore ScanFrom to expected value in case next test succeeds
507 ScanFrom++;
508
Chris Lattner52c95852008-11-27 08:10:05 +0000509 // Don't scan huge blocks.
510 if (MaxInstsToScan-- == 0) return 0;
511
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000512 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000513 // If this is a load of Ptr, the loaded value is available.
514 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000515 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000516 return LI;
517
518 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
519 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000520 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000521 return SI->getOperand(0);
522
523 // If Ptr is an alloca and this is a store to a different alloca, ignore
524 // the store. This is a trivial form of alias analysis that is important
525 // for reg2mem'd code.
526 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
527 (isa<AllocaInst>(SI->getOperand(1)) ||
528 isa<GlobalVariable>(SI->getOperand(1))))
529 continue;
530
Chris Lattneree6e10b2008-11-27 08:18:12 +0000531 // If we have alias analysis and it says the store won't modify the loaded
532 // value, ignore the store.
533 if (AA &&
534 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
535 continue;
536
Chris Lattner52c95852008-11-27 08:10:05 +0000537 // Otherwise the store that may or may not alias the pointer, bail out.
538 ++ScanFrom;
539 return 0;
540 }
541
Chris Lattner52c95852008-11-27 08:10:05 +0000542 // If this is some other instruction that may clobber Ptr, bail out.
543 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000544 // If alias analysis claims that it really won't modify the load,
545 // ignore it.
546 if (AA &&
547 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
548 continue;
549
Chris Lattner52c95852008-11-27 08:10:05 +0000550 // May modify the pointer, bail out.
551 ++ScanFrom;
552 return 0;
553 }
554 }
555
556 // Got to the start of the block, we didn't find it, but are done for this
557 // block.
558 return 0;
559}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000560
561/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
562/// make a copy of the stoppoint before InsertPos (presumably before copying
563/// or moving I).
564void llvm::CopyPrecedingStopPoint(Instruction *I,
565 BasicBlock::iterator InsertPos) {
566 if (I != I->getParent()->begin()) {
567 BasicBlock::iterator BBI = I; --BBI;
568 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
Dale Johannesen4945c652009-03-03 21:26:39 +0000569 CallInst *newDSPI = DSPI->clone();
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000570 newDSPI->insertBefore(InsertPos);
571 }
572 }
573}