1 //===- IPModRef.cpp - Compute IP Mod/Ref information ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // See high-level comments in include/llvm/Analysis/IPModRef.h
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/IPModRef.h"
15 #include "llvm/Analysis/DataStructure.h"
16 #include "llvm/Analysis/DSGraph.h"
17 #include "llvm/Module.h"
18 #include "llvm/Function.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOther.h"
21 #include "Support/Statistic.h"
22 #include "Support/STLExtras.h"
23 #include "Support/StringExtras.h"
28 //----------------------------------------------------------------------------
29 // Private constants and data
30 //----------------------------------------------------------------------------
32 static RegisterAnalysis<IPModRef>
33 Z("ipmodref", "Interprocedural mod/ref analysis");
36 //----------------------------------------------------------------------------
38 //----------------------------------------------------------------------------
40 void ModRefInfo::print(std::ostream &O,
41 const std::string& sprefix) const
43 O << sprefix << "Modified nodes = " << modNodeSet;
44 O << sprefix << "Referenced nodes = " << refNodeSet;
47 void ModRefInfo::dump() const
52 //----------------------------------------------------------------------------
53 // class FunctionModRefInfo
54 //----------------------------------------------------------------------------
57 // This constructor computes a node numbering for the TD graph.
59 FunctionModRefInfo::FunctionModRefInfo(const Function& func,
62 : F(func), IPModRefObj(ipmro),
63 funcTDGraph(tdgClone),
64 funcModRefInfo(tdgClone->getGraphSize())
66 for (unsigned i=0, N = funcTDGraph->getGraphSize(); i < N; ++i)
67 NodeIds[funcTDGraph->getNodes()[i]] = i;
71 FunctionModRefInfo::~FunctionModRefInfo()
73 for(std::map<const Instruction*, ModRefInfo*>::iterator
74 I=callSiteModRefInfo.begin(), E=callSiteModRefInfo.end(); I != E; ++I)
77 // Empty map just to make problems easier to track down
78 callSiteModRefInfo.clear();
83 unsigned FunctionModRefInfo::getNodeId(const Value* value) const {
84 return getNodeId(funcTDGraph->getNodeForValue(const_cast<Value*>(value))
90 // Compute Mod/Ref bit vectors for the entire function.
91 // These are simply copies of the Read/Write flags from the nodes of
92 // the top-down DS graph.
94 void FunctionModRefInfo::computeModRef(const Function &func)
96 // Mark all nodes in the graph that are marked MOD as being mod
97 // and all those marked REF as being ref.
98 for (unsigned i = 0, N = funcTDGraph->getGraphSize(); i < N; ++i)
100 if (funcTDGraph->getNodes()[i]->isModified())
101 funcModRefInfo.setNodeIsMod(i);
102 if (funcTDGraph->getNodes()[i]->isRead())
103 funcModRefInfo.setNodeIsRef(i);
106 // Compute the Mod/Ref info for all call sites within the function.
107 // The call sites are recorded in the TD graph.
108 const std::vector<DSCallSite>& callSites = funcTDGraph->getFunctionCalls();
109 for (unsigned i = 0, N = callSites.size(); i < N; ++i)
110 computeModRef(callSites[i].getCallSite());
114 // ResolveCallSiteModRefInfo - This method performs the following actions:
116 // 1. It clones the top-down graph for the current function
117 // 2. It clears all of the mod/ref bits in the cloned graph
118 // 3. It then merges the bottom-up graph(s) for the specified call-site into
119 // the clone (bringing new mod/ref bits).
120 // 4. It returns the clone, and a mapping of nodes from the original TDGraph to
121 // the cloned graph with Mod/Ref info for the callsite.
123 // NOTE: Because this clones a dsgraph and returns it, the caller is responsible
124 // for deleting the returned graph!
125 // NOTE: This method may return a null pointer if it is unable to determine the
126 // requested information (because the call site calls an external
127 // function or we cannot determine the complete set of functions invoked).
129 DSGraph* FunctionModRefInfo::ResolveCallSiteModRefInfo(CallSite CS,
130 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
132 // Step #0: Quick check if we are going to fail anyway: avoid
133 // all the graph cloning and map copying in steps #1 and #2.
135 if (const Function *F = CS.getCalledFunction()) {
137 return 0; // We cannot compute Mod/Ref info for this callsite...
139 // Eventually, should check here if any callee is external.
140 // For now we are not handling this case anyway.
141 std::cerr << "IP Mod/Ref indirect call not implemented yet: "
142 << "Being conservative\n";
143 return 0; // We cannot compute Mod/Ref info for this callsite...
146 // Step #1: Clone the top-down graph...
147 DSGraph *Result = new DSGraph(*funcTDGraph, NodeMap);
149 // Step #2: Clear Mod/Ref information...
150 Result->maskNodeTypes(~(DSNode::Modified | DSNode::Read));
152 // Step #3: clone the bottom up graphs for the callees into the caller graph
153 if (Function *F = CS.getCalledFunction())
155 assert(!F->isExternal());
157 // Build up a DSCallSite for our invocation point here...
159 // If the call returns a value, make sure to merge the nodes...
161 if (DS::isPointerType(CS.getInstruction()->getType()))
162 RetVal = Result->getNodeForValue(CS.getInstruction());
164 // Populate the arguments list...
165 std::vector<DSNodeHandle> Args;
166 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
168 if (DS::isPointerType((*I)->getType()))
169 Args.push_back(Result->getNodeForValue(*I));
171 // Build the call site...
172 DSCallSite NCS(CS, RetVal, F, Args);
174 // Perform the merging now of the graph for the callee, which will
175 // come with mod/ref bits set...
176 Result->mergeInGraph(NCS, *F, IPModRefObj.getBUDSGraph(*F),
177 DSGraph::StripAllocaBit
178 | DSGraph::DontCloneCallNodes
179 | DSGraph::DontCloneAuxCallNodes);
182 assert(0 && "See error message");
184 // Remove dead nodes aggressively to match the caller's original graph.
185 Result->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
187 // Step #4: Return the clone + the mapping (by ref)
191 // Compute Mod/Ref bit vectors for a single call site.
192 // These are copies of the Read/Write flags from the nodes of
193 // the graph produced by clearing all flags in the caller's TD graph
194 // and then inlining the callee's BU graph into the caller's TD graph.
197 FunctionModRefInfo::computeModRef(CallSite CS)
199 // Allocate the mod/ref info for the call site. Bits automatically cleared.
200 ModRefInfo* callModRefInfo = new ModRefInfo(funcTDGraph->getGraphSize());
201 callSiteModRefInfo[CS.getInstruction()] = callModRefInfo;
203 // Get a copy of the graph for the callee with the callee inlined
204 hash_map<const DSNode*, DSNodeHandle> NodeMap;
205 DSGraph* csgp = ResolveCallSiteModRefInfo(CS, NodeMap);
207 { // Callee's side effects are unknown: mark all nodes Mod and Ref.
208 // Eventually this should only mark nodes visible to the callee, i.e.,
209 // exclude stack variables not reachable from any outgoing argument
211 callModRefInfo->getModSet().set();
212 callModRefInfo->getRefSet().set();
216 // For all nodes in the graph, extract the mod/ref information
217 const std::vector<DSNode*>& csgNodes = csgp->getNodes();
218 const std::vector<DSNode*>& origNodes = funcTDGraph->getNodes();
219 assert(csgNodes.size() == origNodes.size());
220 for (unsigned i=0, N = origNodes.size(); i < N; ++i)
222 DSNode* csgNode = NodeMap[origNodes[i]].getNode();
223 assert(csgNode && "Inlined and original graphs do not correspond!");
224 if (csgNode->isModified())
225 callModRefInfo->setNodeIsMod(getNodeId(origNodes[i]));
226 if (csgNode->isRead())
227 callModRefInfo->setNodeIsRef(getNodeId(origNodes[i]));
230 // Drop nodemap before we delete the graph...
236 class DSGraphPrintHelper {
237 const DSGraph& tdGraph;
238 std::vector<std::vector<const Value*> > knownValues; // identifiable objects
241 /*ctor*/ DSGraphPrintHelper(const FunctionModRefInfo& fmrInfo)
242 : tdGraph(fmrInfo.getFuncGraph())
244 knownValues.resize(tdGraph.getGraphSize());
246 // For every identifiable value, save Value pointer in knownValues[i]
247 for (hash_map<Value*, DSNodeHandle>::const_iterator
248 I = tdGraph.getScalarMap().begin(),
249 E = tdGraph.getScalarMap().end(); I != E; ++I)
250 if (isa<GlobalValue>(I->first) ||
251 isa<Argument>(I->first) ||
252 isa<LoadInst>(I->first) ||
253 isa<AllocaInst>(I->first) ||
254 isa<MallocInst>(I->first))
256 unsigned nodeId = fmrInfo.getNodeId(I->second.getNode());
257 knownValues[nodeId].push_back(I->first);
261 void printValuesInBitVec(std::ostream &O, const BitSetVector& bv) const
263 assert(bv.size() == knownValues.size());
266 { // No bits are set: just say so and return
272 { // All bits are set: just say so and return
273 O << "\tALL GRAPH NODES.\n";
277 for (unsigned i=0, N=bv.size(); i < N; ++i)
280 O << "\tNode# " << i << " : ";
281 if (! knownValues[i].empty())
282 for (unsigned j=0, NV=knownValues[i].size(); j < NV; j++)
284 const Value* V = knownValues[i][j];
286 if (isa<GlobalValue>(V)) O << "(Global) ";
287 else if (isa<Argument>(V)) O << "(Target of FormalParm) ";
288 else if (isa<LoadInst>(V)) O << "(Target of LoadInst ) ";
289 else if (isa<AllocaInst>(V)) O << "(Target of AllocaInst) ";
290 else if (isa<MallocInst>(V)) O << "(Target of MallocInst) ";
292 if (V->hasName()) O << V->getName();
293 else if (isa<Instruction>(V)) O << *V;
294 else O << "(Value*) 0x" << (void*) V;
296 O << std::string((j < NV-1)? "; " : "\n");
299 tdGraph.getNodes()[i]->print(O, /*graph*/ NULL);
305 // Print the results of the pass.
306 // Currently this just prints bit-vectors and is not very readable.
308 void FunctionModRefInfo::print(std::ostream &O) const
310 DSGraphPrintHelper DPH(*this);
312 O << "========== Mod/ref information for function "
313 << F.getName() << "========== \n\n";
315 // First: Print Globals and Locals modified anywhere in the function.
317 O << " -----Mod/Ref in the body of function " << F.getName()<< ":\n";
319 O << " --Objects modified in the function body:\n";
320 DPH.printValuesInBitVec(O, funcModRefInfo.getModSet());
322 O << " --Objects referenced in the function body:\n";
323 DPH.printValuesInBitVec(O, funcModRefInfo.getRefSet());
325 O << " --Mod and Ref vectors for the nodes listed above:\n";
326 funcModRefInfo.print(O, "\t");
330 // Second: Print Globals and Locals modified at each call site in function
332 for (std::map<const Instruction *, ModRefInfo*>::const_iterator
333 CI = callSiteModRefInfo.begin(), CE = callSiteModRefInfo.end();
336 O << " ----Mod/Ref information for call site\n" << CI->first;
338 O << " --Objects modified at call site:\n";
339 DPH.printValuesInBitVec(O, CI->second->getModSet());
341 O << " --Objects referenced at call site:\n";
342 DPH.printValuesInBitVec(O, CI->second->getRefSet());
344 O << " --Mod and Ref vectors for the nodes listed above:\n";
345 CI->second->print(O, "\t");
353 void FunctionModRefInfo::dump() const
359 //----------------------------------------------------------------------------
360 // class IPModRef: An interprocedural pass that computes IP Mod/Ref info.
361 //----------------------------------------------------------------------------
363 // Free the FunctionModRefInfo objects cached in funcToModRefInfoMap.
365 void IPModRef::releaseMemory()
367 for(std::map<const Function*, FunctionModRefInfo*>::iterator
368 I=funcToModRefInfoMap.begin(), E=funcToModRefInfoMap.end(); I != E; ++I)
371 // Clear map so memory is not re-released if we are called again
372 funcToModRefInfoMap.clear();
375 // Run the "interprocedural" pass on each function. This needs to do
376 // NO real interprocedural work because all that has been done the
377 // data structure analysis.
379 bool IPModRef::run(Module &theModule)
383 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
384 if (! FI->isExternal())
385 getFuncInfo(*FI, /*computeIfMissing*/ true);
390 FunctionModRefInfo& IPModRef::getFuncInfo(const Function& func,
391 bool computeIfMissing)
393 FunctionModRefInfo*& funcInfo = funcToModRefInfoMap[&func];
394 assert (funcInfo != NULL || computeIfMissing);
395 if (funcInfo == NULL)
396 { // Create a new FunctionModRefInfo object.
397 // Clone the top-down graph and remove any dead nodes first, because
398 // otherwise original and merged graphs will not match.
399 // The memory for this graph clone will be freed by FunctionModRefInfo.
400 DSGraph* funcTDGraph =
401 new DSGraph(getAnalysis<TDDataStructures>().getDSGraph(func));
402 funcTDGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
404 funcInfo = new FunctionModRefInfo(func, *this, funcTDGraph); //auto-insert
405 funcInfo->computeModRef(func); // computes the mod/ref info
410 /// getBUDSGraph - This method returns the BU data structure graph for F through
411 /// the use of the BUDataStructures object.
413 const DSGraph &IPModRef::getBUDSGraph(const Function &F) {
414 return getAnalysis<BUDataStructures>().getDSGraph(F);
418 // getAnalysisUsage - This pass requires top-down data structure graphs.
419 // It modifies nothing.
421 void IPModRef::getAnalysisUsage(AnalysisUsage &AU) const {
422 AU.setPreservesAll();
423 AU.addRequired<LocalDataStructures>();
424 AU.addRequired<BUDataStructures>();
425 AU.addRequired<TDDataStructures>();
429 void IPModRef::print(std::ostream &O) const
431 O << "\nRESULTS OF INTERPROCEDURAL MOD/REF ANALYSIS:\n\n";
433 for (std::map<const Function*, FunctionModRefInfo*>::const_iterator
434 mapI = funcToModRefInfoMap.begin(), mapE = funcToModRefInfoMap.end();
435 mapI != mapE; ++mapI)
436 mapI->second->print(O);
442 void IPModRef::dump() const
447 } // End llvm namespace