blob: 1a255a4bc01adf2606a8169d3cebac835f0d21c1 [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"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000018#include "llvm/Constant.h"
19#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000020#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/Dominators.h"
Chris Lattneree6e10b2008-11-27 08:18:12 +000023#include "llvm/Target/TargetData.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000024#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner71af9b02008-12-03 06:40:52 +000027/// DeleteDeadBlock - Delete the specified block, which must have no
28/// predecessors.
29void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner15efa1a2008-12-03 07:43:05 +000030 assert(pred_begin(BB) == pred_end(BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000031 TerminatorInst *BBTerm = BB->getTerminator();
32
33 // Loop through all of our successors and make sure they know that one
34 // of their predecessors is going away.
35 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
36 BBTerm->getSuccessor(i)->removePredecessor(BB);
37
38 // Zap all the instructions in the block.
39 while (!BB->empty()) {
40 Instruction &I = BB->back();
41 // If this instruction is used, replace uses with an arbitrary value.
42 // Because control flow can't get here, we don't care what we replace the
43 // value with. Note that since this block is unreachable, and all values
44 // contained within it must dominate their uses, that all uses will
45 // eventually be removed (they are themselves dead).
46 if (!I.use_empty())
47 I.replaceAllUsesWith(UndefValue::get(I.getType()));
48 BB->getInstList().pop_back();
49 }
50
51 // Zap the block!
52 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000053}
54
Owen Andersonb31b06d2008-07-17 00:01:40 +000055/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
56/// if possible. The return value indicates success or failure.
57bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +000058 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +000059 // Can't merge the entry block.
60 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +000061
Owen Anderson11f2ec82008-07-17 19:42:29 +000062 BasicBlock *PredBB = *PI++;
63 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
64 if (*PI != PredBB) {
65 PredBB = 0; // There are multiple different predecessors...
66 break;
67 }
Owen Andersonb31b06d2008-07-17 00:01:40 +000068
Owen Anderson11f2ec82008-07-17 19:42:29 +000069 // Can't merge if there are multiple predecessors.
70 if (!PredBB) return false;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +000071 // Don't break self-loops.
72 if (PredBB == BB) return false;
73 // Don't break invokes.
74 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +000075
76 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
77 BasicBlock* OnlySucc = BB;
78 for (; SI != SE; ++SI)
79 if (*SI != OnlySucc) {
80 OnlySucc = 0; // There are multiple distinct successors!
81 break;
82 }
83
84 // Can't merge if there are multiple successors.
85 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +000086
87 // Can't merge if there is PHI loop.
88 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
89 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
90 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
91 if (PN->getIncomingValue(i) == PN)
92 return false;
93 } else
94 break;
95 }
96
Owen Andersonb31b06d2008-07-17 00:01:40 +000097 // Begin by getting rid of unneeded PHIs.
98 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
99 PN->replaceAllUsesWith(PN->getIncomingValue(0));
100 BB->getInstList().pop_front(); // Delete the phi node...
101 }
102
103 // Delete the unconditional branch from the predecessor...
104 PredBB->getInstList().pop_back();
105
106 // Move all definitions in the successor to the predecessor...
107 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
108
109 // Make all PHI nodes that referred to BB now refer to Pred as their
110 // source...
111 BB->replaceAllUsesWith(PredBB);
112
Owen Anderson11f2ec82008-07-17 19:42:29 +0000113 // Inherit predecessors name if it exists.
114 if (!PredBB->hasName())
115 PredBB->takeName(BB);
116
Owen Andersonb31b06d2008-07-17 00:01:40 +0000117 // Finally, erase the old block and update dominator info.
118 if (P) {
119 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
120 DomTreeNode* DTN = DT->getNode(BB);
121 DomTreeNode* PredDTN = DT->getNode(PredBB);
122
123 if (DTN) {
124 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
125 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
126 DE = Children.end(); DI != DE; ++DI)
127 DT->changeImmediateDominator(*DI, PredDTN);
128
129 DT->eraseNode(BB);
130 }
131 }
132 }
133
134 BB->eraseFromParent();
135
136
137 return true;
138}
139
Chris Lattner0f67dd62005-04-21 16:04:49 +0000140/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
141/// with a value, then remove and delete the original instruction.
142///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000143void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
144 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000145 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000146 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000147 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000148
Chris Lattner86cc4232007-02-11 01:37:51 +0000149 // Make sure to propagate a name if there is one already.
150 if (I.hasName() && !V->hasName())
151 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000152
Misha Brukman5560c9d2003-08-18 14:43:39 +0000153 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000154 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000155}
156
157
Chris Lattner0f67dd62005-04-21 16:04:49 +0000158/// ReplaceInstWithInst - Replace the instruction specified by BI with the
159/// instruction specified by I. The original instruction is deleted and BI is
160/// updated to point to the new instruction.
161///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000162void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
163 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000164 assert(I->getParent() == 0 &&
165 "ReplaceInstWithInst: Instruction already inserted into basic block!");
166
167 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000168 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000169
170 // Replace all uses of the old instruction, and delete it.
171 ReplaceInstWithValue(BIL, BI, I);
172
173 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000174 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000175}
176
Chris Lattner0f67dd62005-04-21 16:04:49 +0000177/// ReplaceInstWithInst - Replace the instruction specified by From with the
178/// instruction specified by To.
179///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000180void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000181 BasicBlock::iterator BI(From);
182 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000183}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000184
Chris Lattner0f67dd62005-04-21 16:04:49 +0000185/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000186/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000187/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000188/// may have to be changed. In the case where the last successor of the block
189/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000190/// surprising change in program behavior if it is not expected.
191///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000192void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000193 assert(SuccNum < TI->getNumSuccessors() &&
194 "Trying to remove a nonexistant successor!");
195
196 // If our old successor block contains any PHI nodes, remove the entry in the
197 // PHI nodes that comes from this branch...
198 //
199 BasicBlock *BB = TI->getParent();
200 TI->getSuccessor(SuccNum)->removePredecessor(BB);
201
202 TerminatorInst *NewTI = 0;
203 switch (TI->getOpcode()) {
204 case Instruction::Br:
205 // If this is a conditional branch... convert to unconditional branch.
206 if (TI->getNumSuccessors() == 2) {
207 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
208 } else { // Otherwise convert to a return instruction...
209 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000210
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000211 // Create a value to return... if the function doesn't return null...
212 if (BB->getParent()->getReturnType() != Type::VoidTy)
213 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
214
215 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000216 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000217 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000218 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000219
220 case Instruction::Invoke: // Should convert to call
221 case Instruction::Switch: // Should remove entry
222 default:
223 case Instruction::Ret: // Cannot happen, has no successors!
224 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
225 abort();
226 }
227
228 if (NewTI) // If it's a different instruction, replace.
229 ReplaceInstWithInst(TI, NewTI);
230}
Brian Gaeked0fde302003-11-11 22:41:34 +0000231
Devang Patel80198932007-07-06 21:39:20 +0000232/// SplitEdge - Split the edge connecting specified block. Pass P must
233/// not be NULL.
234BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
235 TerminatorInst *LatchTerm = BB->getTerminator();
236 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000237#ifndef NDEBUG
238 unsigned e = LatchTerm->getNumSuccessors();
239#endif
240 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000241 assert(i != e && "Didn't find edge?");
242 if (LatchTerm->getSuccessor(i) == Succ) {
243 SuccNum = i;
244 break;
245 }
246 }
247
248 // If this is a critical edge, let SplitCriticalEdge do it.
249 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
250 return LatchTerm->getSuccessor(SuccNum);
251
252 // If the edge isn't critical, then BB has a single successor or Succ has a
253 // single pred. Split the block.
254 BasicBlock::iterator SplitPoint;
255 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
256 // If the successor only has a single pred, split the top of the successor
257 // block.
258 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000259 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000260 return SplitBlock(Succ, Succ->begin(), P);
261 } else {
262 // Otherwise, if BB has a single successor, split it at the bottom of the
263 // block.
264 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
265 "Should have a single succ!");
266 return SplitBlock(BB, BB->getTerminator(), P);
267 }
268}
269
270/// SplitBlock - Split the specified block at the specified instruction - every
271/// thing before SplitPt stays in Old and everything starting with SplitPt moves
272/// to a new block. The two blocks are joined by an unconditional branch and
273/// the loop info is updated.
274///
275BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000276 BasicBlock::iterator SplitIt = SplitPt;
277 while (isa<PHINode>(SplitIt))
278 ++SplitIt;
279 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
280
281 // The new block lives in whichever loop the old one did.
Owen Andersona90793b2008-10-03 06:55:35 +0000282 if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
283 if (Loop *L = LI->getLoopFor(Old))
284 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000285
Devang Patela8a8a362007-07-19 02:29:24 +0000286 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
287 {
288 // Old dominates New. New node domiantes all other nodes dominated by Old.
289 DomTreeNode *OldNode = DT->getNode(Old);
290 std::vector<DomTreeNode *> Children;
291 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
292 I != E; ++I)
293 Children.push_back(*I);
294
295 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
296
297 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
298 E = Children.end(); I != E; ++I)
299 DT->changeImmediateDominator(*I, NewNode);
300 }
Devang Patel80198932007-07-06 21:39:20 +0000301
302 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
303 DF->splitBlock(Old);
304
305 return New;
306}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000307
308
309/// SplitBlockPredecessors - This method transforms BB by introducing a new
310/// basic block into the function, and moving some of the predecessors of BB to
311/// be predecessors of the new block. The new predecessors are indicated by the
312/// Preds array, which has NumPreds elements in it. The new block is given a
313/// suffix of 'Suffix'.
314///
315/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
316/// DominanceFrontier, but no other analyses.
317BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
318 BasicBlock *const *Preds,
319 unsigned NumPreds, const char *Suffix,
320 Pass *P) {
321 // Create new basic block, insert right before the original block.
322 BasicBlock *NewBB =
323 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
324
325 // The new block unconditionally branches to the old block.
326 BranchInst *BI = BranchInst::Create(BB, NewBB);
327
328 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000329 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000330 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000331
332 // Update dominator tree and dominator frontier if available.
333 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
334 if (DT)
335 DT->splitBlock(NewBB);
336 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
337 DF->splitBlock(NewBB);
338 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
339
340
341 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
342 // node becomes an incoming value for BB's phi node. However, if the Preds
343 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
344 // account for the newly created predecessor.
345 if (NumPreds == 0) {
346 // Insert dummy values as the incoming value.
347 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
348 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
349 return NewBB;
350 }
351
352 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
353 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
354 PHINode *PN = cast<PHINode>(I++);
355
356 // Check to see if all of the values coming in are the same. If so, we
357 // don't need to create a new PHI node.
358 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
359 for (unsigned i = 1; i != NumPreds; ++i)
360 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
361 InVal = 0;
362 break;
363 }
364
365 if (InVal) {
366 // If all incoming values for the new PHI would be the same, just don't
367 // make a new PHI. Instead, just remove the incoming values from the old
368 // PHI.
369 for (unsigned i = 0; i != NumPreds; ++i)
370 PN->removeIncomingValue(Preds[i], false);
371 } else {
372 // If the values coming into the block are not the same, we need a PHI.
373 // Create the new PHI node, insert it into NewBB at the end of the block
374 PHINode *NewPHI =
375 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
376 if (AA) AA->copyValue(PN, NewPHI);
377
378 // Move all of the PHI values for 'Preds' to the new PHI.
379 for (unsigned i = 0; i != NumPreds; ++i) {
380 Value *V = PN->removeIncomingValue(Preds[i], false);
381 NewPHI->addIncoming(V, Preds[i]);
382 }
383 InVal = NewPHI;
384 }
385
386 // Add an incoming value to the PHI node in the loop for the preheader
387 // edge.
388 PN->addIncoming(InVal, NewBB);
389
390 // Check to see if we can eliminate this phi node.
391 if (Value *V = PN->hasConstantValue(DT != 0)) {
392 Instruction *I = dyn_cast<Instruction>(V);
393 if (!I || DT == 0 || DT->dominates(I, PN)) {
394 PN->replaceAllUsesWith(V);
395 if (AA) AA->deleteValue(PN);
396 PN->eraseFromParent();
397 }
398 }
399 }
400
401 return NewBB;
402}
Chris Lattner52c95852008-11-27 08:10:05 +0000403
Chris Lattner4aebaee2008-11-27 08:56:30 +0000404/// AreEquivalentAddressValues - Test if A and B will obviously have the same
405/// value. This includes recognizing that %t0 and %t1 will have the same
406/// value in code like this:
407/// %t0 = getelementptr @a, 0, 3
408/// store i32 0, i32* %t0
409/// %t1 = getelementptr @a, 0, 3
410/// %t2 = load i32* %t1
411///
412static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
413 // Test if the values are trivially equivalent.
414 if (A == B) return true;
415
416 // Test if the values come form identical arithmetic instructions.
417 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
418 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
419 if (const Instruction *BI = dyn_cast<Instruction>(B))
420 if (cast<Instruction>(A)->isIdenticalTo(BI))
421 return true;
422
423 // Otherwise they may not be equivalent.
424 return false;
425}
426
Chris Lattner52c95852008-11-27 08:10:05 +0000427/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
428/// instruction before ScanFrom) checking to see if we have the value at the
429/// memory address *Ptr locally available within a small number of instructions.
430/// If the value is available, return it.
431///
432/// If not, return the iterator for the last validated instruction that the
433/// value would be live through. If we scanned the entire block and didn't find
434/// something that invalidates *Ptr or provides it, ScanFrom would be left at
435/// begin() and this returns null. ScanFrom could also be left
436///
437/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
438/// it is set to 0, it will scan the whole block. You can also optionally
439/// specify an alias analysis implementation, which makes this more precise.
440Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
441 BasicBlock::iterator &ScanFrom,
442 unsigned MaxInstsToScan,
443 AliasAnalysis *AA) {
444 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000445
446 // If we're using alias analysis to disambiguate get the size of *Ptr.
447 unsigned AccessSize = 0;
448 if (AA) {
449 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
450 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
451 }
Chris Lattner52c95852008-11-27 08:10:05 +0000452
453 while (ScanFrom != ScanBB->begin()) {
454 // Don't scan huge blocks.
455 if (MaxInstsToScan-- == 0) return 0;
456
457 Instruction *Inst = --ScanFrom;
458
459 // If this is a load of Ptr, the loaded value is available.
460 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000461 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000462 return LI;
463
464 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
465 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000466 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000467 return SI->getOperand(0);
468
469 // If Ptr is an alloca and this is a store to a different alloca, ignore
470 // the store. This is a trivial form of alias analysis that is important
471 // for reg2mem'd code.
472 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
473 (isa<AllocaInst>(SI->getOperand(1)) ||
474 isa<GlobalVariable>(SI->getOperand(1))))
475 continue;
476
Chris Lattneree6e10b2008-11-27 08:18:12 +0000477 // If we have alias analysis and it says the store won't modify the loaded
478 // value, ignore the store.
479 if (AA &&
480 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
481 continue;
482
Chris Lattner52c95852008-11-27 08:10:05 +0000483 // Otherwise the store that may or may not alias the pointer, bail out.
484 ++ScanFrom;
485 return 0;
486 }
487
Chris Lattner52c95852008-11-27 08:10:05 +0000488 // If this is some other instruction that may clobber Ptr, bail out.
489 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000490 // If alias analysis claims that it really won't modify the load,
491 // ignore it.
492 if (AA &&
493 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
494 continue;
495
Chris Lattner52c95852008-11-27 08:10:05 +0000496 // May modify the pointer, bail out.
497 ++ScanFrom;
498 return 0;
499 }
500 }
501
502 // Got to the start of the block, we didn't find it, but are done for this
503 // block.
504 return 0;
505}