LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

GlobalsModRef.cpp

Go to the documentation of this file.
00001 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
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 simple pass provides alias and mod/ref information for global values
00011 // that do not have their address taken, and keeps track of whether functions
00012 // read or write memory (are "pure").  For this simple (but very common) case,
00013 // we can provide pretty accurate and useful information.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/Analysis/Passes.h"
00018 #include "llvm/Module.h"
00019 #include "llvm/Pass.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/Constants.h"
00022 #include "llvm/Analysis/AliasAnalysis.h"
00023 #include "llvm/Analysis/CallGraph.h"
00024 #include "llvm/Support/InstIterator.h"
00025 #include "llvm/Support/CommandLine.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include "llvm/ADT/SCCIterator.h"
00028 #include <set>
00029 using namespace llvm;
00030 
00031 namespace {
00032   Statistic<>
00033   NumNonAddrTakenGlobalVars("globalsmodref-aa",
00034                             "Number of global vars without address taken");
00035   Statistic<>
00036   NumNonAddrTakenFunctions("globalsmodref-aa",
00037                            "Number of functions without address taken");
00038   Statistic<>
00039   NumNoMemFunctions("globalsmodref-aa",
00040                     "Number of functions that do not access memory");
00041   Statistic<>
00042   NumReadMemFunctions("globalsmodref-aa",
00043                       "Number of functions that only read memory");
00044 
00045   /// FunctionRecord - One instance of this structure is stored for every
00046   /// function in the program.  Later, the entries for these functions are
00047   /// removed if the function is found to call an external function (in which
00048   /// case we know nothing about it.
00049   struct FunctionRecord {
00050     /// GlobalInfo - Maintain mod/ref info for all of the globals without
00051     /// addresses taken that are read or written (transitively) by this
00052     /// function.
00053     std::map<GlobalValue*, unsigned> GlobalInfo;
00054 
00055     unsigned getInfoForGlobal(GlobalValue *GV) const {
00056       std::map<GlobalValue*, unsigned>::const_iterator I = GlobalInfo.find(GV);
00057       if (I != GlobalInfo.end())
00058         return I->second;
00059       return 0;
00060     }
00061     
00062     /// FunctionEffect - Capture whether or not this function reads or writes to
00063     /// ANY memory.  If not, we can do a lot of aggressive analysis on it.
00064     unsigned FunctionEffect;
00065 
00066     FunctionRecord() : FunctionEffect(0) {}
00067   };
00068 
00069   /// GlobalsModRef - The actual analysis pass.
00070   class GlobalsModRef : public ModulePass, public AliasAnalysis {
00071     /// NonAddressTakenGlobals - The globals that do not have their addresses
00072     /// taken.
00073     std::set<GlobalValue*> NonAddressTakenGlobals;
00074 
00075     /// FunctionInfo - For each function, keep track of what globals are
00076     /// modified or read.
00077     std::map<Function*, FunctionRecord> FunctionInfo;
00078 
00079   public:
00080     bool runOnModule(Module &M) {
00081       InitializeAliasAnalysis(this);                 // set up super class
00082       AnalyzeGlobals(M);                          // find non-addr taken globals
00083       AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
00084       return false;
00085     }
00086 
00087     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00088       AliasAnalysis::getAnalysisUsage(AU);
00089       AU.addRequired<CallGraph>();
00090       AU.setPreservesAll();                         // Does not transform code
00091     }
00092 
00093     //------------------------------------------------
00094     // Implement the AliasAnalysis API
00095     //  
00096     AliasResult alias(const Value *V1, unsigned V1Size,
00097                       const Value *V2, unsigned V2Size);
00098     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
00099     bool hasNoModRefInfoForCalls() const { return false; }
00100 
00101     bool doesNotAccessMemory(Function *F) {
00102       if (FunctionRecord *FR = getFunctionInfo(F))
00103         if (FR->FunctionEffect == 0)
00104           return true;
00105       return AliasAnalysis::doesNotAccessMemory(F);
00106     }
00107     bool onlyReadsMemory(Function *F) {
00108       if (FunctionRecord *FR = getFunctionInfo(F))
00109         if ((FR->FunctionEffect & Mod) == 0)
00110           return true;
00111       return AliasAnalysis::onlyReadsMemory(F);
00112     }
00113 
00114 
00115     virtual void deleteValue(Value *V);
00116     virtual void copyValue(Value *From, Value *To);
00117 
00118   private:
00119     /// getFunctionInfo - Return the function info for the function, or null if
00120     /// the function calls an external function (in which case we don't have
00121     /// anything useful to say about it).
00122     FunctionRecord *getFunctionInfo(Function *F) {
00123       std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F);
00124       if (I != FunctionInfo.end())
00125         return &I->second;
00126       return 0;
00127     }
00128 
00129     void AnalyzeGlobals(Module &M);
00130     void AnalyzeCallGraph(CallGraph &CG, Module &M);
00131     void AnalyzeSCC(std::vector<CallGraphNode *> &SCC);
00132     bool AnalyzeUsesOfGlobal(Value *V, std::vector<Function*> &Readers,
00133                              std::vector<Function*> &Writers);
00134   };
00135   
00136   RegisterOpt<GlobalsModRef> X("globalsmodref-aa",
00137                                "Simple mod/ref analysis for globals");
00138   RegisterAnalysisGroup<AliasAnalysis, GlobalsModRef> Y;
00139 }
00140 
00141 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
00142 
00143 
00144 /// AnalyzeGlobalUses - Scan through the users of all of the internal
00145 /// GlobalValue's in the program.  If none of them have their "Address taken"
00146 /// (really, their address passed to something nontrivial), record this fact,
00147 /// and record the functions that they are used directly in.
00148 void GlobalsModRef::AnalyzeGlobals(Module &M) {
00149   std::vector<Function*> Readers, Writers;
00150   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00151     if (I->hasInternalLinkage()) {
00152       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
00153         // Remember that we are tracking this global.
00154         NonAddressTakenGlobals.insert(I);
00155         ++NumNonAddrTakenFunctions;
00156       }
00157       Readers.clear(); Writers.clear();
00158     }
00159 
00160   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
00161     if (I->hasInternalLinkage()) {
00162       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
00163         // Remember that we are tracking this global, and the mod/ref fns
00164         NonAddressTakenGlobals.insert(I);
00165         for (unsigned i = 0, e = Readers.size(); i != e; ++i)
00166           FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
00167 
00168         if (!I->isConstant())  // No need to keep track of writers to constants
00169           for (unsigned i = 0, e = Writers.size(); i != e; ++i)
00170             FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
00171         ++NumNonAddrTakenGlobalVars;
00172       }
00173       Readers.clear(); Writers.clear();
00174     }
00175 }
00176 
00177 /// AnalyzeUsesOfGlobal - Look at all of the users of the specified global value
00178 /// derived pointer.  If this is used by anything complex (i.e., the address
00179 /// escapes), return true.  Also, while we are at it, keep track of those
00180 /// functions that read and write to the value.
00181 bool GlobalsModRef::AnalyzeUsesOfGlobal(Value *V,
00182                                         std::vector<Function*> &Readers,
00183                                         std::vector<Function*> &Writers) {
00184   if (!isa<PointerType>(V->getType())) return true;
00185 
00186   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
00187     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
00188       Readers.push_back(LI->getParent()->getParent());
00189     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
00190       if (V == SI->getOperand(0)) return true;  // Storing the pointer
00191       Writers.push_back(SI->getParent()->getParent());
00192     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
00193       if (AnalyzeUsesOfGlobal(GEP, Readers, Writers)) return true;
00194     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
00195       // Make sure that this is just the function being called, not that it is
00196       // passing into the function.
00197       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
00198         if (CI->getOperand(i) == V) return true;
00199     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
00200       // Make sure that this is just the function being called, not that it is
00201       // passing into the function.
00202       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
00203         if (CI->getOperand(i) == V) return true;
00204     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
00205       // Make sure that this is just the function being called, not that it is
00206       // passing into the function.
00207       for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
00208         if (II->getOperand(i) == V) return true;
00209     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
00210       if (CE->getOpcode() == Instruction::GetElementPtr ||
00211           CE->getOpcode() == Instruction::Cast) {
00212         if (AnalyzeUsesOfGlobal(CE, Readers, Writers))
00213           return true;
00214       } else {
00215         return true;
00216       }        
00217     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*UI)) {
00218       if (AnalyzeUsesOfGlobal(GV, Readers, Writers)) return true;
00219     } else {
00220       return true;
00221     }
00222   return false;
00223 }
00224 
00225 /// AnalyzeCallGraph - At this point, we know the functions where globals are
00226 /// immediately stored to and read from.  Propagate this information up the call
00227 /// graph to all callers and compute the mod/ref info for all memory for each
00228 /// function.  
00229 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
00230   // We do a bottom-up SCC traversal of the call graph.  In other words, we
00231   // visit all callees before callers (leaf-first).
00232   for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I!=E; ++I)
00233     if ((*I).size() != 1) {
00234       AnalyzeSCC(*I);
00235     } else if (Function *F = (*I)[0]->getFunction()) {
00236       if (!F->isExternal()) {
00237         // Nonexternal function.
00238         AnalyzeSCC(*I);
00239       } else {
00240         // Otherwise external function.  Handle intrinsics and other special
00241         // cases here.
00242         if (getAnalysis<AliasAnalysis>().doesNotAccessMemory(F))
00243           // If it does not access memory, process the function, causing us to
00244           // realize it doesn't do anything (the body is empty).
00245           AnalyzeSCC(*I);
00246         else {
00247           // Otherwise, don't process it.  This will cause us to conservatively
00248           // assume the worst.
00249         }
00250       }
00251     } else {
00252       // Do not process the external node, assume the worst.
00253     }
00254 }
00255 
00256 void GlobalsModRef::AnalyzeSCC(std::vector<CallGraphNode *> &SCC) {
00257   assert(!SCC.empty() && "SCC with no functions?");
00258   FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
00259 
00260   bool CallsExternal = false;
00261   unsigned FunctionEffect = 0;
00262 
00263   // Collect the mod/ref properties due to called functions.  We only compute
00264   // one mod-ref set
00265   for (unsigned i = 0, e = SCC.size(); i != e && !CallsExternal; ++i)
00266     for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
00267          CI != E; ++CI)
00268       if (Function *Callee = (*CI)->getFunction()) {
00269         if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
00270           // Propagate function effect up.
00271           FunctionEffect |= CalleeFR->FunctionEffect;
00272 
00273           // Incorporate callee's effects on globals into our info.
00274           for (std::map<GlobalValue*, unsigned>::iterator GI =
00275                  CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
00276                GI != E; ++GI)
00277             FR.GlobalInfo[GI->first] |= GI->second;
00278 
00279         } else {
00280           CallsExternal = true;
00281           break;
00282         }
00283       } else {
00284         CallsExternal = true;
00285         break;
00286       }
00287 
00288   // If this SCC calls an external function, we can't say anything about it, so
00289   // remove all SCC functions from the FunctionInfo map.
00290   if (CallsExternal) {
00291     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
00292       FunctionInfo.erase(SCC[i]->getFunction());
00293     return;
00294   }
00295   
00296   // Otherwise, unless we already know that this function mod/refs memory, scan
00297   // the function bodies to see if there are any explicit loads or stores.
00298   if (FunctionEffect != ModRef) {
00299     for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
00300       for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
00301              E = inst_end(SCC[i]->getFunction()); 
00302            II != E && FunctionEffect != ModRef; ++II)
00303         if (isa<LoadInst>(*II))
00304           FunctionEffect |= Ref;
00305         else if (isa<StoreInst>(*II))
00306           FunctionEffect |= Mod;
00307   }
00308 
00309   if ((FunctionEffect & Mod) == 0)
00310     ++NumReadMemFunctions;
00311   if (FunctionEffect == 0)
00312     ++NumNoMemFunctions;
00313   FR.FunctionEffect = FunctionEffect;
00314 
00315   // Finally, now that we know the full effect on this SCC, clone the
00316   // information to each function in the SCC.
00317   for (unsigned i = 1, e = SCC.size(); i != e; ++i)
00318     FunctionInfo[SCC[i]->getFunction()] = FR;
00319 }
00320 
00321 
00322 
00323 /// getUnderlyingObject - This traverses the use chain to figure out what object
00324 /// the specified value points to.  If the value points to, or is derived from,
00325 /// a global object, return it.
00326 static const GlobalValue *getUnderlyingObject(const Value *V) {
00327   if (!isa<PointerType>(V->getType())) return 0;
00328 
00329   // If we are at some type of object... return it.
00330   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
00331   
00332   // Traverse through different addressing mechanisms...
00333   if (const Instruction *I = dyn_cast<Instruction>(V)) {
00334     if (isa<CastInst>(I) || isa<GetElementPtrInst>(I))
00335       return getUnderlyingObject(I->getOperand(0));
00336   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00337     if (CE->getOpcode() == Instruction::Cast ||
00338         CE->getOpcode() == Instruction::GetElementPtr)
00339       return getUnderlyingObject(CE->getOperand(0));
00340   }
00341   return 0;
00342 }
00343 
00344 /// alias - If one of the pointers is to a global that we are tracking, and the
00345 /// other is some random pointer, we know there cannot be an alias, because the
00346 /// address of the global isn't taken.
00347 AliasAnalysis::AliasResult
00348 GlobalsModRef::alias(const Value *V1, unsigned V1Size,
00349                      const Value *V2, unsigned V2Size) {
00350   GlobalValue *GV1 = const_cast<GlobalValue*>(getUnderlyingObject(V1));
00351   GlobalValue *GV2 = const_cast<GlobalValue*>(getUnderlyingObject(V2));
00352 
00353   // If the global's address is taken, pretend we don't know it's a pointer to
00354   // the global.
00355   if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
00356   if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
00357 
00358   if ((GV1 || GV2) && GV1 != GV2)
00359     return NoAlias;
00360 
00361   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
00362 }
00363 
00364 AliasAnalysis::ModRefResult
00365 GlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
00366   unsigned Known = ModRef;
00367 
00368   // If we are asking for mod/ref info of a direct call with a pointer to a
00369   // global we are tracking, return information if we have it.
00370   if (GlobalValue *GV = const_cast<GlobalValue*>(getUnderlyingObject(P)))
00371     if (GV->hasInternalLinkage())
00372       if (Function *F = CS.getCalledFunction())
00373         if (NonAddressTakenGlobals.count(GV))
00374           if (FunctionRecord *FR = getFunctionInfo(F))
00375             Known = FR->getInfoForGlobal(GV);
00376 
00377   if (Known == NoModRef)
00378     return NoModRef; // No need to query other mod/ref analyses
00379   return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size));
00380 }
00381 
00382 
00383 //===----------------------------------------------------------------------===//
00384 // Methods to update the analysis as a result of the client transformation.
00385 //
00386 void GlobalsModRef::deleteValue(Value *V) {
00387   if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
00388     NonAddressTakenGlobals.erase(GV);
00389 }
00390 
00391 void GlobalsModRef::copyValue(Value *From, Value *To) {
00392 }