1 //===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops --*-C++-*--===//
3 // This file implements a pass (MemoryDepAnalysis) that computes memory-based
4 // data dependences between instructions for each function in a module.
5 // Memory-based dependences occur due to load and store operations, but
6 // also the side-effects of call instructions.
8 // The result of this pass is a DependenceGraph for each function
9 // representing the memory-based data dependences between instructions.
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Analysis/MemoryDepAnalysis.h"
13 #include "llvm/Analysis/IPModRef.h"
14 #include "llvm/Analysis/DataStructure.h"
15 #include "llvm/Analysis/DSGraph.h"
16 #include "llvm/Module.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/iOther.h"
19 #include "llvm/Support/InstVisitor.h"
20 #include "llvm/Support/CFG.h"
21 #include "Support/SCCIterator.h"
22 #include "Support/Statistic.h"
23 #include "Support/STLExtras.h"
24 #include "Support/hash_map"
25 #include "Support/hash_set"
28 ///--------------------------------------------------------------------------
29 /// struct ModRefTable:
31 /// A data structure that tracks ModRefInfo for instructions:
32 /// -- modRefMap is a map of Instruction* -> ModRefInfo for the instr.
33 /// -- definers is a vector of instructions that define any node
34 /// -- users is a vector of instructions that reference any node
35 /// -- numUsersBeforeDef is a vector indicating that the number of users
36 /// seen before definers[i] is numUsersBeforeDef[i].
38 /// numUsersBeforeDef[] effectively tells us the exact interleaving of
39 /// definers and users within the ModRefTable.
40 /// This is only maintained when constructing the table for one SCC, and
41 /// not copied over from one table to another since it is no longer useful.
42 ///--------------------------------------------------------------------------
45 typedef hash_map<Instruction*, ModRefInfo> ModRefMap;
46 typedef ModRefMap::const_iterator const_map_iterator;
47 typedef ModRefMap:: iterator map_iterator;
48 typedef std::vector<Instruction*>::const_iterator const_ref_iterator;
49 typedef std::vector<Instruction*>:: iterator ref_iterator;
52 std::vector<Instruction*> definers;
53 std::vector<Instruction*> users;
54 std::vector<unsigned> numUsersBeforeDef;
56 // Iterators to enumerate all the defining instructions
57 const_ref_iterator defsBegin() const { return definers.begin(); }
58 ref_iterator defsBegin() { return definers.begin(); }
59 const_ref_iterator defsEnd() const { return definers.end(); }
60 ref_iterator defsEnd() { return definers.end(); }
62 // Iterators to enumerate all the user instructions
63 const_ref_iterator usersBegin() const { return users.begin(); }
64 ref_iterator usersBegin() { return users.begin(); }
65 const_ref_iterator usersEnd() const { return users.end(); }
66 ref_iterator usersEnd() { return users.end(); }
68 // Iterator identifying the last user that was seen *before* a
69 // specified def. In particular, all users in the half-closed range
70 // [ usersBegin(), usersBeforeDef_End(defPtr) )
71 // were seen *before* the specified def. All users in the half-closed range
72 // [ usersBeforeDef_End(defPtr), usersEnd() )
73 // were seen *after* the specified def.
75 ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) {
76 unsigned defIndex = (unsigned) (defPtr - defsBegin());
77 assert(defIndex < numUsersBeforeDef.size());
78 assert(usersBegin() + numUsersBeforeDef[defIndex] <= usersEnd());
79 return usersBegin() + numUsersBeforeDef[defIndex];
81 const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
82 return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
88 void AddDef(Instruction* D) {
89 definers.push_back(D);
90 numUsersBeforeDef.push_back(users.size());
92 void AddUse(Instruction* U) {
95 void Insert(const ModRefTable& fromTable) {
96 modRefMap.insert(fromTable.modRefMap.begin(), fromTable.modRefMap.end());
97 definers.insert(definers.end(),
98 fromTable.definers.begin(), fromTable.definers.end());
99 users.insert(users.end(),
100 fromTable.users.begin(), fromTable.users.end());
101 numUsersBeforeDef.clear(); /* fromTable.numUsersBeforeDef is ignored */
106 ///--------------------------------------------------------------------------
107 /// class ModRefInfoBuilder:
109 /// A simple InstVisitor<> class that retrieves the Mod/Ref info for
110 /// Load/Store/Call instructions and inserts this information in
111 /// a ModRefTable. It also records all instructions that Mod any node
112 /// and all that use any node.
113 ///--------------------------------------------------------------------------
115 class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
116 const DSGraph& funcGraph;
117 const FunctionModRefInfo& funcModRef;
118 ModRefTable& modRefTable;
120 ModRefInfoBuilder(); // DO NOT IMPLEMENT
121 ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
122 void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
125 /*ctor*/ ModRefInfoBuilder(const DSGraph& _funcGraph,
126 const FunctionModRefInfo& _funcModRef,
127 ModRefTable& _modRefTable)
128 : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
132 // At a call instruction, retrieve the ModRefInfo using IPModRef results.
133 // Add the call to the defs list if it modifies any nodes and to the uses
134 // list if it refs any nodes.
136 void visitCallInst (CallInst& callInst) {
137 ModRefInfo safeModRef(funcGraph.getGraphSize());
138 const ModRefInfo* callModRef = funcModRef.getModRefInfo(callInst);
139 if (callModRef == NULL)
140 { // call to external/unknown function: mark all nodes as Mod and Ref
141 safeModRef.getModSet().set();
142 safeModRef.getRefSet().set();
143 callModRef = &safeModRef;
146 modRefTable.modRefMap.insert(std::make_pair(&callInst,
147 ModRefInfo(*callModRef)));
148 if (callModRef->getModSet().any())
149 modRefTable.AddDef(&callInst);
150 if (callModRef->getRefSet().any())
151 modRefTable.AddUse(&callInst);
154 // At a store instruction, add to the mod set the single node pointed to
155 // by the pointer argument of the store. Interestingly, if there is no
156 // such node, that would be a null pointer reference!
157 void visitStoreInst (StoreInst& storeInst) {
158 const DSNodeHandle& ptrNode =
159 funcGraph.getNodeForValue(storeInst.getPointerOperand());
160 if (const DSNode* target = ptrNode.getNode())
162 unsigned nodeId = funcModRef.getNodeId(target);
164 modRefTable.modRefMap.insert(
165 std::make_pair(&storeInst,
166 ModRefInfo(funcGraph.getGraphSize()))).first->second;
167 minfo.setNodeIsMod(nodeId);
168 modRefTable.AddDef(&storeInst);
171 std::cerr << "Warning: Uninitialized pointer reference!\n";
174 // At a load instruction, add to the ref set the single node pointed to
175 // by the pointer argument of the load. Interestingly, if there is no
176 // such node, that would be a null pointer reference!
177 void visitLoadInst (LoadInst& loadInst) {
178 const DSNodeHandle& ptrNode =
179 funcGraph.getNodeForValue(loadInst.getPointerOperand());
180 if (const DSNode* target = ptrNode.getNode())
182 unsigned nodeId = funcModRef.getNodeId(target);
184 modRefTable.modRefMap.insert(
185 std::make_pair(&loadInst,
186 ModRefInfo(funcGraph.getGraphSize()))).first->second;
187 minfo.setNodeIsRef(nodeId);
188 modRefTable.AddUse(&loadInst);
191 std::cerr << "Warning: Uninitialized pointer reference!\n";
196 //----------------------------------------------------------------------------
197 // class MemoryDepAnalysis: A dep. graph for load/store/call instructions
198 //----------------------------------------------------------------------------
201 /// getAnalysisUsage - This does not modify anything. It uses the Top-Down DS
202 /// Graph and IPModRef.
204 void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
205 AU.setPreservesAll();
206 AU.addRequired<TDDataStructures>();
207 AU.addRequired<IPModRef>();
211 /// Basic dependence gathering algorithm, using scc_iterator on CFG:
213 /// for every SCC S in the CFG in PostOrder on the SCC DAG
215 /// for every basic block BB in S in *postorder*
216 /// for every instruction I in BB in reverse
217 /// Add (I, ModRef[I]) to ModRefCurrent
218 /// if (Mod[I] != NULL)
219 /// Add I to DefSetCurrent: { I \in S : Mod[I] != NULL }
220 /// if (Ref[I] != NULL)
221 /// Add I to UseSetCurrent: { I : Ref[I] != NULL }
223 /// for every def D in DefSetCurrent
225 /// // NOTE: D comes after itself iff S contains a loop
226 /// if (HasLoop(S) && D & D)
227 /// Add output-dep: D -> D2
229 /// for every def D2 *after* D in DefSetCurrent
230 /// // NOTE: D2 comes before D in execution order
232 /// Add output-dep: D2 -> D
234 /// Add output-dep: D -> D2
236 /// for every use U in UseSetCurrent that was seen *before* D
237 /// // NOTE: U comes after D in execution order
239 /// if (U != D || HasLoop(S))
240 /// Add true-dep: D -> U
242 /// Add anti-dep: U -> D
244 /// for every use U in UseSetCurrent that was seen *after* D
245 /// // NOTE: U comes before D in execution order
247 /// if (U != D || HasLoop(S))
248 /// Add anti-dep: U -> D
250 /// Add true-dep: D -> U
252 /// for every def Dnext in DefSetAfter
253 /// // NOTE: Dnext comes after D in execution order
255 /// Add output-dep: D -> Dnext
257 /// for every use Unext in UseSetAfter
258 /// // NOTE: Unext comes after D in execution order
260 /// Add true-dep: D -> Unext
262 /// for every use U in UseSetCurrent
263 /// for every def Dnext in DefSetAfter
264 /// // NOTE: Dnext comes after U in execution order
266 /// Add anti-dep: U -> Dnext
268 /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
269 /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
270 /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
274 void MemoryDepAnalysis::ProcessSCC(std::vector<BasicBlock*> &S,
275 ModRefTable& ModRefAfter, bool hasLoop) {
276 ModRefTable ModRefCurrent;
277 ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
278 ModRefTable::ModRefMap& mapAfter = ModRefAfter.modRefMap;
280 // Builder class fills out a ModRefTable one instruction at a time.
281 // To use it, we just invoke it's visit function for each basic block:
283 // for each basic block BB in the SCC in *postorder*
284 // for each instruction I in BB in *reverse*
285 // ModRefInfoBuilder::visit(I)
286 // : Add (I, ModRef[I]) to ModRefCurrent.modRefMap
287 // : Add I to ModRefCurrent.definers if it defines any node
288 // : Add I to ModRefCurrent.users if it uses any node
290 ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
291 for (std::vector<BasicBlock*>::iterator BI = S.begin(), BE = S.end();
293 // Note: BBs in the SCC<> created by scc_iterator are in postorder.
294 for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
298 /// for every def D in DefSetCurrent
300 for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
301 IE=ModRefCurrent.defsEnd(); II != IE; ++II)
303 /// // NOTE: D comes after itself iff S contains a loop
305 /// Add output-dep: D -> D2
307 funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
309 /// for every def D2 *after* D in DefSetCurrent
310 /// // NOTE: D2 comes before D in execution order
312 /// Add output-dep: D2 -> D
314 /// Add output-dep: D -> D2
315 for (ModRefTable::ref_iterator JI=II+1; JI != IE; ++JI)
316 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
317 mapCurrent.find(*JI)->second.getModSet()))
319 funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
321 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
324 /// for every use U in UseSetCurrent that was seen *before* D
325 /// // NOTE: U comes after D in execution order
327 /// if (U != D || HasLoop(S))
328 /// Add true-dep: U -> D
330 /// Add anti-dep: D -> U
331 ModRefTable::ref_iterator JI=ModRefCurrent.usersBegin();
332 ModRefTable::ref_iterator JE = ModRefCurrent.usersBeforeDef_End(II);
333 for ( ; JI != JE; ++JI)
334 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
335 mapCurrent.find(*JI)->second.getRefSet()))
337 if (*II != *JI || hasLoop)
338 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
340 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
343 /// for every use U in UseSetCurrent that was seen *after* D
344 /// // NOTE: U comes before D in execution order
346 /// if (U != D || HasLoop(S))
347 /// Add anti-dep: U -> D
349 /// Add true-dep: D -> U
350 for (/*continue JI*/ JE = ModRefCurrent.usersEnd(); JI != JE; ++JI)
351 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
352 mapCurrent.find(*JI)->second.getRefSet()))
354 if (*II != *JI || hasLoop)
355 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
357 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
360 /// for every def Dnext in DefSetPrev
361 /// // NOTE: Dnext comes after D in execution order
363 /// Add output-dep: D -> Dnext
364 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
365 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
366 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
367 mapAfter.find(*JI)->second.getModSet()))
368 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
370 /// for every use Unext in UseSetAfter
371 /// // NOTE: Unext comes after D in execution order
373 /// Add true-dep: D -> Unext
374 for (ModRefTable::ref_iterator JI=ModRefAfter.usersBegin(),
375 JE=ModRefAfter.usersEnd(); JI != JE; ++JI)
376 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
377 mapAfter.find(*JI)->second.getRefSet()))
378 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
382 /// for every use U in UseSetCurrent
383 /// for every def Dnext in DefSetAfter
384 /// // NOTE: Dnext comes after U in execution order
386 /// Add anti-dep: U -> Dnext
387 for (ModRefTable::ref_iterator II=ModRefCurrent.usersBegin(),
388 IE=ModRefCurrent.usersEnd(); II != IE; ++II)
389 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
390 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
391 if (!Disjoint(mapCurrent.find(*II)->second.getRefSet(),
392 mapAfter.find(*JI)->second.getModSet()))
393 funcDepGraph->AddSimpleDependence(**II, **JI, AntiDependence);
395 /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
396 /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
397 /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
398 ModRefAfter.Insert(ModRefCurrent);
402 /// Debugging support methods
404 void MemoryDepAnalysis::print(std::ostream &O) const
407 for (hash_map<Function*, DependenceGraph*>::const_iterator
408 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
410 Function* func = I->first;
411 DependenceGraph* depGraph = I->second;
413 O << "\n================================================================\n";
414 O << "DEPENDENCE GRAPH FOR MEMORY OPERATIONS IN FUNCTION " << func->getName();
415 O << "\n================================================================\n\n";
416 depGraph->print(*func, O);
423 /// Run the pass on a function
425 bool MemoryDepAnalysis::runOnFunction(Function &F) {
426 assert(!F.isExternal());
428 // Get the FunctionModRefInfo holding IPModRef results for this function.
429 // Use the TD graph recorded within the FunctionModRefInfo object, which
430 // may not be the same as the original TD graph computed by DS analysis.
432 funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
433 funcGraph = &funcModRef->getFuncGraph();
435 // TEMPORARY: ptr to depGraph (later just becomes "this").
436 assert(!funcMap.count(&F) && "Analyzing function twice?");
437 funcDepGraph = funcMap[&F] = new DependenceGraph();
439 ModRefTable ModRefAfter;
441 for (scc_iterator<Function*> I = scc_begin(&F), E = scc_end(&F); I != E; ++I)
442 ProcessSCC(*I, ModRefAfter, I.hasLoop());
448 //-------------------------------------------------------------------------
449 // TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
450 // These functions will go away once this class becomes a FunctionPass.
453 // Driver function to compute dependence graphs for every function.
454 // This is temporary and will go away once this is a FunctionPass.
456 bool MemoryDepAnalysis::run(Module& M)
458 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
459 if (! FI->isExternal())
460 runOnFunction(*FI); // automatically inserts each depGraph into funcMap
464 // Release all the dependence graphs in the map.
465 void MemoryDepAnalysis::releaseMemory()
467 for (hash_map<Function*, DependenceGraph*>::const_iterator
468 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
472 // Clear pointers because the pass constructor will not be invoked again.
478 MemoryDepAnalysis::~MemoryDepAnalysis()
483 //----END TEMPORARY FUNCTIONS----------------------------------------------
486 void MemoryDepAnalysis::dump() const
488 this->print(std::cerr);
491 static RegisterAnalysis<MemoryDepAnalysis>
492 Z("memdep", "Memory Dependence Analysis");