LLVM API Documentation
00001 //===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements a value numbering pass that value numbers load and call 00011 // instructions. To do this, it finds lexically identical load instructions, 00012 // and uses alias analysis to determine which loads are guaranteed to produce 00013 // the same value. To value number call instructions, it looks for calls to 00014 // functions that do not write to memory which do not have intervening 00015 // instructions that clobber the memory that is read from. 00016 // 00017 // This pass builds off of another value numbering pass to implement value 00018 // numbering for non-load and non-call instructions. It uses Alias Analysis so 00019 // that it can disambiguate the load instructions. The more powerful these base 00020 // analyses are, the more powerful the resultant value numbering will be. 00021 // 00022 //===----------------------------------------------------------------------===// 00023 00024 #include "llvm/Analysis/LoadValueNumbering.h" 00025 #include "llvm/Constants.h" 00026 #include "llvm/Function.h" 00027 #include "llvm/Instructions.h" 00028 #include "llvm/Pass.h" 00029 #include "llvm/Type.h" 00030 #include "llvm/Analysis/ValueNumbering.h" 00031 #include "llvm/Analysis/AliasAnalysis.h" 00032 #include "llvm/Analysis/Dominators.h" 00033 #include "llvm/Support/CFG.h" 00034 #include "llvm/Target/TargetData.h" 00035 #include <set> 00036 #include <algorithm> 00037 using namespace llvm; 00038 00039 namespace { 00040 // FIXME: This should not be a FunctionPass. 00041 struct LoadVN : public FunctionPass, public ValueNumbering { 00042 00043 /// Pass Implementation stuff. This doesn't do any analysis. 00044 /// 00045 bool runOnFunction(Function &) { return false; } 00046 00047 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering 00048 /// and Alias Analysis. 00049 /// 00050 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 00051 00052 /// getEqualNumberNodes - Return nodes with the same value number as the 00053 /// specified Value. This fills in the argument vector with any equal 00054 /// values. 00055 /// 00056 virtual void getEqualNumberNodes(Value *V1, 00057 std::vector<Value*> &RetVals) const; 00058 00059 /// deleteValue - This method should be called whenever an LLVM Value is 00060 /// deleted from the program, for example when an instruction is found to be 00061 /// redundant and is eliminated. 00062 /// 00063 virtual void deleteValue(Value *V) { 00064 getAnalysis<AliasAnalysis>().deleteValue(V); 00065 } 00066 00067 /// copyValue - This method should be used whenever a preexisting value in 00068 /// the program is copied or cloned, introducing a new value. Note that 00069 /// analysis implementations should tolerate clients that use this method to 00070 /// introduce the same value multiple times: if the analysis already knows 00071 /// about a value, it should ignore the request. 00072 /// 00073 virtual void copyValue(Value *From, Value *To) { 00074 getAnalysis<AliasAnalysis>().copyValue(From, To); 00075 } 00076 00077 /// getCallEqualNumberNodes - Given a call instruction, find other calls 00078 /// that have the same value number. 00079 void getCallEqualNumberNodes(CallInst *CI, 00080 std::vector<Value*> &RetVals) const; 00081 }; 00082 00083 // Register this pass... 00084 RegisterOpt<LoadVN> X("load-vn", "Load Value Numbering"); 00085 00086 // Declare that we implement the ValueNumbering interface 00087 RegisterAnalysisGroup<ValueNumbering, LoadVN> Y; 00088 } 00089 00090 FunctionPass *llvm::createLoadValueNumberingPass() { return new LoadVN(); } 00091 00092 00093 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering and 00094 /// Alias Analysis. 00095 /// 00096 void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const { 00097 AU.setPreservesAll(); 00098 AU.addRequiredTransitive<AliasAnalysis>(); 00099 AU.addRequired<ValueNumbering>(); 00100 AU.addRequiredTransitive<DominatorSet>(); 00101 AU.addRequiredTransitive<TargetData>(); 00102 } 00103 00104 static bool isPathTransparentTo(BasicBlock *CurBlock, BasicBlock *Dom, 00105 Value *Ptr, unsigned Size, AliasAnalysis &AA, 00106 std::set<BasicBlock*> &Visited, 00107 std::map<BasicBlock*, bool> &TransparentBlocks){ 00108 // If we have already checked out this path, or if we reached our destination, 00109 // stop searching, returning success. 00110 if (CurBlock == Dom || !Visited.insert(CurBlock).second) 00111 return true; 00112 00113 // Check whether this block is known transparent or not. 00114 std::map<BasicBlock*, bool>::iterator TBI = 00115 TransparentBlocks.lower_bound(CurBlock); 00116 00117 if (TBI == TransparentBlocks.end() || TBI->first != CurBlock) { 00118 // If this basic block can modify the memory location, then the path is not 00119 // transparent! 00120 if (AA.canBasicBlockModify(*CurBlock, Ptr, Size)) { 00121 TransparentBlocks.insert(TBI, std::make_pair(CurBlock, false)); 00122 return false; 00123 } 00124 TransparentBlocks.insert(TBI, std::make_pair(CurBlock, true)); 00125 } else if (!TBI->second) 00126 // This block is known non-transparent, so that path can't be either. 00127 return false; 00128 00129 // The current block is known to be transparent. The entire path is 00130 // transparent if all of the predecessors paths to the parent is also 00131 // transparent to the memory location. 00132 for (pred_iterator PI = pred_begin(CurBlock), E = pred_end(CurBlock); 00133 PI != E; ++PI) 00134 if (!isPathTransparentTo(*PI, Dom, Ptr, Size, AA, Visited, 00135 TransparentBlocks)) 00136 return false; 00137 return true; 00138 } 00139 00140 /// getCallEqualNumberNodes - Given a call instruction, find other calls that 00141 /// have the same value number. 00142 void LoadVN::getCallEqualNumberNodes(CallInst *CI, 00143 std::vector<Value*> &RetVals) const { 00144 Function *CF = CI->getCalledFunction(); 00145 if (CF == 0) return; // Indirect call. 00146 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 00147 AliasAnalysis::ModRefBehavior MRB = AA.getModRefBehavior(CF, CI); 00148 if (MRB != AliasAnalysis::DoesNotAccessMemory && 00149 MRB != AliasAnalysis::OnlyReadsMemory) 00150 return; // Nothing we can do for now. 00151 00152 // Scan all of the arguments of the function, looking for one that is not 00153 // global. In particular, we would prefer to have an argument or instruction 00154 // operand to chase the def-use chains of. 00155 Value *Op = CF; 00156 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) 00157 if (isa<Argument>(CI->getOperand(i)) || 00158 isa<Instruction>(CI->getOperand(i))) { 00159 Op = CI->getOperand(i); 00160 break; 00161 } 00162 00163 // Identify all lexically identical calls in this function. 00164 std::vector<CallInst*> IdenticalCalls; 00165 00166 Function *CIFunc = CI->getParent()->getParent(); 00167 for (Value::use_iterator UI = Op->use_begin(), E = Op->use_end(); UI != E; 00168 ++UI) 00169 if (CallInst *C = dyn_cast<CallInst>(*UI)) 00170 if (C->getNumOperands() == CI->getNumOperands() && 00171 C->getOperand(0) == CI->getOperand(0) && 00172 C->getParent()->getParent() == CIFunc && C != CI) { 00173 bool AllOperandsEqual = true; 00174 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) 00175 if (C->getOperand(i) != CI->getOperand(i)) { 00176 AllOperandsEqual = false; 00177 break; 00178 } 00179 00180 if (AllOperandsEqual) 00181 IdenticalCalls.push_back(C); 00182 } 00183 00184 if (IdenticalCalls.empty()) return; 00185 00186 // Eliminate duplicates, which could occur if we chose a value that is passed 00187 // into a call site multiple times. 00188 std::sort(IdenticalCalls.begin(), IdenticalCalls.end()); 00189 IdenticalCalls.erase(std::unique(IdenticalCalls.begin(),IdenticalCalls.end()), 00190 IdenticalCalls.end()); 00191 00192 // If the call reads memory, we must make sure that there are no stores 00193 // between the calls in question. 00194 // 00195 // FIXME: This should use mod/ref information. What we really care about it 00196 // whether an intervening instruction could modify memory that is read, not 00197 // ANY memory. 00198 // 00199 if (MRB == AliasAnalysis::OnlyReadsMemory) { 00200 DominatorSet &DomSetInfo = getAnalysis<DominatorSet>(); 00201 BasicBlock *CIBB = CI->getParent(); 00202 for (unsigned i = 0; i != IdenticalCalls.size(); ++i) { 00203 CallInst *C = IdenticalCalls[i]; 00204 bool CantEqual = false; 00205 00206 if (DomSetInfo.dominates(CIBB, C->getParent())) { 00207 // FIXME: we currently only handle the case where both calls are in the 00208 // same basic block. 00209 if (CIBB != C->getParent()) { 00210 CantEqual = true; 00211 } else { 00212 Instruction *First = CI, *Second = C; 00213 if (!DomSetInfo.dominates(CI, C)) 00214 std::swap(First, Second); 00215 00216 // Scan the instructions between the calls, checking for stores or 00217 // calls to dangerous functions. 00218 BasicBlock::iterator I = First; 00219 for (++First; I != BasicBlock::iterator(Second); ++I) { 00220 if (isa<StoreInst>(I)) { 00221 // FIXME: We could use mod/ref information to make this much 00222 // better! 00223 CantEqual = true; 00224 break; 00225 } else if (CallInst *CI = dyn_cast<CallInst>(I)) { 00226 if (CI->getCalledFunction() == 0 || 00227 !AA.onlyReadsMemory(CI->getCalledFunction())) { 00228 CantEqual = true; 00229 break; 00230 } 00231 } else if (I->mayWriteToMemory()) { 00232 CantEqual = true; 00233 break; 00234 } 00235 } 00236 } 00237 00238 } else if (DomSetInfo.dominates(C->getParent(), CIBB)) { 00239 // FIXME: We could implement this, but we don't for now. 00240 CantEqual = true; 00241 } else { 00242 // FIXME: if one doesn't dominate the other, we can't tell yet. 00243 CantEqual = true; 00244 } 00245 00246 00247 if (CantEqual) { 00248 // This call does not produce the same value as the one in the query. 00249 std::swap(IdenticalCalls[i--], IdenticalCalls.back()); 00250 IdenticalCalls.pop_back(); 00251 } 00252 } 00253 } 00254 00255 // Any calls that are identical and not destroyed will produce equal values! 00256 for (unsigned i = 0, e = IdenticalCalls.size(); i != e; ++i) 00257 RetVals.push_back(IdenticalCalls[i]); 00258 } 00259 00260 // getEqualNumberNodes - Return nodes with the same value number as the 00261 // specified Value. This fills in the argument vector with any equal values. 00262 // 00263 void LoadVN::getEqualNumberNodes(Value *V, 00264 std::vector<Value*> &RetVals) const { 00265 // If the alias analysis has any must alias information to share with us, we 00266 // can definitely use it. 00267 if (isa<PointerType>(V->getType())) 00268 getAnalysis<AliasAnalysis>().getMustAliases(V, RetVals); 00269 00270 if (!isa<LoadInst>(V)) { 00271 if (CallInst *CI = dyn_cast<CallInst>(V)) 00272 getCallEqualNumberNodes(CI, RetVals); 00273 00274 // Not a load instruction? Just chain to the base value numbering 00275 // implementation to satisfy the request... 00276 assert(&getAnalysis<ValueNumbering>() != (ValueNumbering*)this && 00277 "getAnalysis() returned this!"); 00278 00279 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals); 00280 } 00281 00282 // Volatile loads cannot be replaced with the value of other loads. 00283 LoadInst *LI = cast<LoadInst>(V); 00284 if (LI->isVolatile()) 00285 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals); 00286 00287 Value *LoadPtr = LI->getOperand(0); 00288 BasicBlock *LoadBB = LI->getParent(); 00289 Function *F = LoadBB->getParent(); 00290 00291 // Find out how many bytes of memory are loaded by the load instruction... 00292 unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(LI->getType()); 00293 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 00294 00295 // Figure out if the load is invalidated from the entry of the block it is in 00296 // until the actual instruction. This scans the block backwards from LI. If 00297 // we see any candidate load or store instructions, then we know that the 00298 // candidates have the same value # as LI. 00299 bool LoadInvalidatedInBBBefore = false; 00300 for (BasicBlock::iterator I = LI; I != LoadBB->begin(); ) { 00301 --I; 00302 if (I == LoadPtr) { 00303 // If we run into an allocation of the value being loaded, then the 00304 // contents are not initialized. 00305 if (isa<AllocationInst>(I)) 00306 RetVals.push_back(UndefValue::get(LI->getType())); 00307 00308 // Otherwise, since this is the definition of what we are loading, this 00309 // loaded value cannot occur before this block. 00310 LoadInvalidatedInBBBefore = true; 00311 break; 00312 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 00313 // If this instruction is a candidate load before LI, we know there are no 00314 // invalidating instructions between it and LI, so they have the same 00315 // value number. 00316 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile()) 00317 RetVals.push_back(I); 00318 } 00319 00320 if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) { 00321 // If the invalidating instruction is a store, and its in our candidate 00322 // set, then we can do store-load forwarding: the load has the same value 00323 // # as the stored value. 00324 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 00325 if (SI->getOperand(1) == LoadPtr) 00326 RetVals.push_back(I->getOperand(0)); 00327 00328 LoadInvalidatedInBBBefore = true; 00329 break; 00330 } 00331 } 00332 00333 // Figure out if the load is invalidated between the load and the exit of the 00334 // block it is defined in. While we are scanning the current basic block, if 00335 // we see any candidate loads, then we know they have the same value # as LI. 00336 // 00337 bool LoadInvalidatedInBBAfter = false; 00338 for (BasicBlock::iterator I = LI->getNext(); I != LoadBB->end(); ++I) { 00339 // If this instruction is a load, then this instruction returns the same 00340 // value as LI. 00341 if (isa<LoadInst>(I) && cast<LoadInst>(I)->getOperand(0) == LoadPtr) 00342 RetVals.push_back(I); 00343 00344 if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) { 00345 LoadInvalidatedInBBAfter = true; 00346 break; 00347 } 00348 } 00349 00350 // If the pointer is clobbered on entry and on exit to the function, there is 00351 // no need to do any global analysis at all. 00352 if (LoadInvalidatedInBBBefore && LoadInvalidatedInBBAfter) 00353 return; 00354 00355 // Now that we know the value is not neccesarily killed on entry or exit to 00356 // the BB, find out how many load and store instructions (to this location) 00357 // live in each BB in the function. 00358 // 00359 std::map<BasicBlock*, unsigned> CandidateLoads; 00360 std::set<BasicBlock*> CandidateStores; 00361 00362 for (Value::use_iterator UI = LoadPtr->use_begin(), UE = LoadPtr->use_end(); 00363 UI != UE; ++UI) 00364 if (LoadInst *Cand = dyn_cast<LoadInst>(*UI)) {// Is a load of source? 00365 if (Cand->getParent()->getParent() == F && // In the same function? 00366 // Not in LI's block? 00367 Cand->getParent() != LoadBB && !Cand->isVolatile()) 00368 ++CandidateLoads[Cand->getParent()]; // Got one. 00369 } else if (StoreInst *Cand = dyn_cast<StoreInst>(*UI)) { 00370 if (Cand->getParent()->getParent() == F && !Cand->isVolatile() && 00371 Cand->getOperand(1) == LoadPtr) // It's a store THROUGH the ptr. 00372 CandidateStores.insert(Cand->getParent()); 00373 } 00374 00375 // Get dominators. 00376 DominatorSet &DomSetInfo = getAnalysis<DominatorSet>(); 00377 00378 // TransparentBlocks - For each basic block the load/store is alive across, 00379 // figure out if the pointer is invalidated or not. If it is invalidated, the 00380 // boolean is set to false, if it's not it is set to true. If we don't know 00381 // yet, the entry is not in the map. 00382 std::map<BasicBlock*, bool> TransparentBlocks; 00383 00384 // Loop over all of the basic blocks that also load the value. If the value 00385 // is live across the CFG from the source to destination blocks, and if the 00386 // value is not invalidated in either the source or destination blocks, add it 00387 // to the equivalence sets. 00388 for (std::map<BasicBlock*, unsigned>::iterator 00389 I = CandidateLoads.begin(), E = CandidateLoads.end(); I != E; ++I) { 00390 bool CantEqual = false; 00391 00392 // Right now we only can handle cases where one load dominates the other. 00393 // FIXME: generalize this! 00394 BasicBlock *BB1 = I->first, *BB2 = LoadBB; 00395 if (DomSetInfo.dominates(BB1, BB2)) { 00396 // The other load dominates LI. If the loaded value is killed entering 00397 // the LoadBB block, we know the load is not live. 00398 if (LoadInvalidatedInBBBefore) 00399 CantEqual = true; 00400 } else if (DomSetInfo.dominates(BB2, BB1)) { 00401 std::swap(BB1, BB2); // Canonicalize 00402 // LI dominates the other load. If the loaded value is killed exiting 00403 // the LoadBB block, we know the load is not live. 00404 if (LoadInvalidatedInBBAfter) 00405 CantEqual = true; 00406 } else { 00407 // None of these loads can VN the same. 00408 CantEqual = true; 00409 } 00410 00411 if (!CantEqual) { 00412 // Ok, at this point, we know that BB1 dominates BB2, and that there is 00413 // nothing in the LI block that kills the loaded value. Check to see if 00414 // the value is live across the CFG. 00415 std::set<BasicBlock*> Visited; 00416 for (pred_iterator PI = pred_begin(BB2), E = pred_end(BB2); PI!=E; ++PI) 00417 if (!isPathTransparentTo(*PI, BB1, LoadPtr, LoadSize, AA, 00418 Visited, TransparentBlocks)) { 00419 // None of these loads can VN the same. 00420 CantEqual = true; 00421 break; 00422 } 00423 } 00424 00425 // If the loads can equal so far, scan the basic block that contains the 00426 // loads under consideration to see if they are invalidated in the block. 00427 // For any loads that are not invalidated, add them to the equivalence 00428 // set! 00429 if (!CantEqual) { 00430 unsigned NumLoads = I->second; 00431 if (BB1 == LoadBB) { 00432 // If LI dominates the block in question, check to see if any of the 00433 // loads in this block are invalidated before they are reached. 00434 for (BasicBlock::iterator BBI = I->first->begin(); ; ++BBI) { 00435 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 00436 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile()) { 00437 // The load is in the set! 00438 RetVals.push_back(BBI); 00439 if (--NumLoads == 0) break; // Found last load to check. 00440 } 00441 } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize) 00442 & AliasAnalysis::Mod) { 00443 // If there is a modifying instruction, nothing below it will value 00444 // # the same. 00445 break; 00446 } 00447 } 00448 } else { 00449 // If the block dominates LI, make sure that the loads in the block are 00450 // not invalidated before the block ends. 00451 BasicBlock::iterator BBI = I->first->end(); 00452 while (1) { 00453 --BBI; 00454 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 00455 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile()) { 00456 // The load is the same as this load! 00457 RetVals.push_back(BBI); 00458 if (--NumLoads == 0) break; // Found all of the laods. 00459 } 00460 } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize) 00461 & AliasAnalysis::Mod) { 00462 // If there is a modifying instruction, nothing above it will value 00463 // # the same. 00464 break; 00465 } 00466 } 00467 } 00468 } 00469 } 00470 00471 // Handle candidate stores. If the loaded location is clobbered on entrance 00472 // to the LoadBB, no store outside of the LoadBB can value number equal, so 00473 // quick exit. 00474 if (LoadInvalidatedInBBBefore) 00475 return; 00476 00477 // Stores in the load-bb are handled above. 00478 CandidateStores.erase(LoadBB); 00479 00480 for (std::set<BasicBlock*>::iterator I = CandidateStores.begin(), 00481 E = CandidateStores.end(); I != E; ++I) 00482 if (DomSetInfo.dominates(*I, LoadBB)) { 00483 BasicBlock *StoreBB = *I; 00484 00485 // Check to see if the path from the store to the load is transparent 00486 // w.r.t. the memory location. 00487 bool CantEqual = false; 00488 std::set<BasicBlock*> Visited; 00489 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); 00490 PI != E; ++PI) 00491 if (!isPathTransparentTo(*PI, StoreBB, LoadPtr, LoadSize, AA, 00492 Visited, TransparentBlocks)) { 00493 // None of these stores can VN the same. 00494 CantEqual = true; 00495 break; 00496 } 00497 Visited.clear(); 00498 if (!CantEqual) { 00499 // Okay, the path from the store block to the load block is clear, and 00500 // we know that there are no invalidating instructions from the start 00501 // of the load block to the load itself. Now we just scan the store 00502 // block. 00503 00504 BasicBlock::iterator BBI = StoreBB->end(); 00505 while (1) { 00506 assert(BBI != StoreBB->begin() && 00507 "There is a store in this block of the pointer, but the store" 00508 " doesn't mod the address being stored to?? Must be a bug in" 00509 " the alias analysis implementation!"); 00510 --BBI; 00511 if (AA.getModRefInfo(BBI, LoadPtr, LoadSize) & AliasAnalysis::Mod) { 00512 // If the invalidating instruction is one of the candidates, 00513 // then it provides the value the load loads. 00514 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) 00515 if (SI->getOperand(1) == LoadPtr) 00516 RetVals.push_back(SI->getOperand(0)); 00517 break; 00518 } 00519 } 00520 } 00521 } 00522 }