blob: 685b2eeed768380f31a4b0b3a96b4cfcb7e44d97 [file] [log] [blame]
Vikram S. Adve96b21c12002-12-08 13:26:29 +00001//===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops --*-C++-*--===//
2//
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.
7//
8// The result of this pass is a DependenceGraph for each function
9// representing the memory-based data dependences between instructions.
10//===----------------------------------------------------------------------===//
11
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"
Vikram S. Adve96b21c12002-12-08 13:26:29 +000017#include "llvm/iMemory.h"
18#include "llvm/iOther.h"
19#include "llvm/Support/InstVisitor.h"
20#include "llvm/Support/CFG.h"
21#include "Support/TarjanSCCIterator.h"
22#include "Support/Statistic.h"
Vikram S. Adve96b21c12002-12-08 13:26:29 +000023#include "Support/STLExtras.h"
24#include "Support/hash_map"
25#include "Support/hash_set"
Vikram S. Adve96b21c12002-12-08 13:26:29 +000026
27
28///--------------------------------------------------------------------------
29/// struct ModRefTable:
30///
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].
37///
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///--------------------------------------------------------------------------
43
Chris Lattner95008bc2003-08-31 19:40:57 +000044struct ModRefTable {
Vikram S. Adve96b21c12002-12-08 13:26:29 +000045 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;
50
51 ModRefMap modRefMap;
52 std::vector<Instruction*> definers;
53 std::vector<Instruction*> users;
54 std::vector<unsigned> numUsersBeforeDef;
55
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(); }
61
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(); }
67
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.
74 //
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];
80 }
81 const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
82 return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
83 }
84
85 //
86 // Modifier methods
87 //
88 void AddDef(Instruction* D) {
89 definers.push_back(D);
90 numUsersBeforeDef.push_back(users.size());
91 }
92 void AddUse(Instruction* U) {
93 users.push_back(U);
94 }
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 */
102 }
103};
104
105
106///--------------------------------------------------------------------------
107/// class ModRefInfoBuilder:
108///
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///--------------------------------------------------------------------------
114
Chris Lattner80431272003-08-06 17:16:24 +0000115class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000116 const DSGraph& funcGraph;
117 const FunctionModRefInfo& funcModRef;
118 ModRefTable& modRefTable;
119
Chris Lattner80431272003-08-06 17:16:24 +0000120 ModRefInfoBuilder(); // DO NOT IMPLEMENT
121 ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
122 void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000123
124public:
125 /*ctor*/ ModRefInfoBuilder(const DSGraph& _funcGraph,
126 const FunctionModRefInfo& _funcModRef,
127 ModRefTable& _modRefTable)
128 : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
129 {
130 }
131
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.
135 //
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;
144 }
145
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);
152 }
153
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())
161 {
162 unsigned nodeId = funcModRef.getNodeId(target);
163 ModRefInfo& minfo =
164 modRefTable.modRefMap.insert(
165 std::make_pair(&storeInst,
166 ModRefInfo(funcGraph.getGraphSize()))).first->second;
167 minfo.setNodeIsMod(nodeId);
168 modRefTable.AddDef(&storeInst);
169 }
170 else
171 std::cerr << "Warning: Uninitialized pointer reference!\n";
172 }
173
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())
181 {
182 unsigned nodeId = funcModRef.getNodeId(target);
183 ModRefInfo& minfo =
184 modRefTable.modRefMap.insert(
185 std::make_pair(&loadInst,
186 ModRefInfo(funcGraph.getGraphSize()))).first->second;
187 minfo.setNodeIsRef(nodeId);
188 modRefTable.AddUse(&loadInst);
189 }
190 else
191 std::cerr << "Warning: Uninitialized pointer reference!\n";
192 }
193};
194
195
196//----------------------------------------------------------------------------
197// class MemoryDepAnalysis: A dep. graph for load/store/call instructions
198//----------------------------------------------------------------------------
199
Chris Lattner95008bc2003-08-31 19:40:57 +0000200
201/// getAnalysisUsage - This does not modify anything. It uses the Top-Down DS
202/// Graph and IPModRef.
203///
204void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
205 AU.setPreservesAll();
206 AU.addRequired<TDDataStructures>();
207 AU.addRequired<IPModRef>();
208}
209
210
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000211/// Basic dependence gathering algorithm, using TarjanSCCIterator on CFG:
212///
213/// for every SCC S in the CFG in PostOrder on the SCC DAG
214/// {
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 }
222///
223/// for every def D in DefSetCurrent
224///
225/// // NOTE: D comes after itself iff S contains a loop
226/// if (HasLoop(S) && D & D)
227/// Add output-dep: D -> D2
228///
229/// for every def D2 *after* D in DefSetCurrent
230/// // NOTE: D2 comes before D in execution order
231/// if (D & D2)
232/// Add output-dep: D2 -> D
233/// if (HasLoop(S))
234/// Add output-dep: D -> D2
235///
236/// for every use U in UseSetCurrent that was seen *before* D
237/// // NOTE: U comes after D in execution order
238/// if (U & D)
239/// if (U != D || HasLoop(S))
240/// Add true-dep: D -> U
241/// if (HasLoop(S))
242/// Add anti-dep: U -> D
243///
244/// for every use U in UseSetCurrent that was seen *after* D
245/// // NOTE: U comes before D in execution order
246/// if (U & D)
247/// if (U != D || HasLoop(S))
248/// Add anti-dep: U -> D
249/// if (HasLoop(S))
250/// Add true-dep: D -> U
251///
252/// for every def Dnext in DefSetAfter
253/// // NOTE: Dnext comes after D in execution order
254/// if (Dnext & D)
255/// Add output-dep: D -> Dnext
256///
257/// for every use Unext in UseSetAfter
258/// // NOTE: Unext comes after D in execution order
259/// if (Unext & D)
260/// Add true-dep: D -> Unext
261///
262/// for every use U in UseSetCurrent
263/// for every def Dnext in DefSetAfter
264/// // NOTE: Dnext comes after U in execution order
265/// if (Dnext & D)
266/// Add anti-dep: U -> Dnext
267///
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 }
271/// }
272///
273///
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000274void MemoryDepAnalysis::ProcessSCC(SCC<Function*>& S,
Chris Lattner0c0023b2003-08-31 19:29:52 +0000275 ModRefTable& ModRefAfter) {
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000276 ModRefTable ModRefCurrent;
277 ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
278 ModRefTable::ModRefMap& mapAfter = ModRefAfter.modRefMap;
279
280 bool hasLoop = S.HasLoop();
281
282 // Builder class fills out a ModRefTable one instruction at a time.
283 // To use it, we just invoke it's visit function for each basic block:
284 //
285 // for each basic block BB in the SCC in *postorder*
286 // for each instruction I in BB in *reverse*
287 // ModRefInfoBuilder::visit(I)
288 // : Add (I, ModRef[I]) to ModRefCurrent.modRefMap
289 // : Add I to ModRefCurrent.definers if it defines any node
290 // : Add I to ModRefCurrent.users if it uses any node
291 //
292 ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
293 for (SCC<Function*>::iterator BI=S.begin(), BE=S.end(); BI != BE; ++BI)
294 // Note: BBs in the SCC<> created by TarjanSCCIterator are in postorder.
295 for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
296 II != IE; ++II)
297 builder.visit(*II);
298
299 /// for every def D in DefSetCurrent
300 ///
301 for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
302 IE=ModRefCurrent.defsEnd(); II != IE; ++II)
303 {
304 /// // NOTE: D comes after itself iff S contains a loop
305 /// if (HasLoop(S))
306 /// Add output-dep: D -> D2
307 if (hasLoop)
308 funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
309
310 /// for every def D2 *after* D in DefSetCurrent
311 /// // NOTE: D2 comes before D in execution order
312 /// if (D2 & D)
313 /// Add output-dep: D2 -> D
314 /// if (HasLoop(S))
315 /// Add output-dep: D -> D2
316 for (ModRefTable::ref_iterator JI=II+1; JI != IE; ++JI)
317 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
318 mapCurrent.find(*JI)->second.getModSet()))
319 {
320 funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
321 if (hasLoop)
322 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
323 }
324
325 /// for every use U in UseSetCurrent that was seen *before* D
326 /// // NOTE: U comes after D in execution order
327 /// if (U & D)
328 /// if (U != D || HasLoop(S))
329 /// Add true-dep: U -> D
330 /// if (HasLoop(S))
331 /// Add anti-dep: D -> U
332 ModRefTable::ref_iterator JI=ModRefCurrent.usersBegin();
333 ModRefTable::ref_iterator JE = ModRefCurrent.usersBeforeDef_End(II);
334 for ( ; JI != JE; ++JI)
335 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
336 mapCurrent.find(*JI)->second.getRefSet()))
337 {
338 if (*II != *JI || hasLoop)
339 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
340 if (hasLoop)
341 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
342 }
343
344 /// for every use U in UseSetCurrent that was seen *after* D
345 /// // NOTE: U comes before D in execution order
346 /// if (U & D)
347 /// if (U != D || HasLoop(S))
348 /// Add anti-dep: U -> D
349 /// if (HasLoop(S))
350 /// Add true-dep: D -> U
351 for (/*continue JI*/ JE = ModRefCurrent.usersEnd(); JI != JE; ++JI)
352 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
353 mapCurrent.find(*JI)->second.getRefSet()))
354 {
355 if (*II != *JI || hasLoop)
356 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
357 if (hasLoop)
358 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
359 }
360
361 /// for every def Dnext in DefSetPrev
362 /// // NOTE: Dnext comes after D in execution order
363 /// if (Dnext & D)
364 /// Add output-dep: D -> Dnext
365 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
366 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
367 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
368 mapAfter.find(*JI)->second.getModSet()))
369 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
370
371 /// for every use Unext in UseSetAfter
372 /// // NOTE: Unext comes after D in execution order
373 /// if (Unext & D)
374 /// Add true-dep: D -> Unext
375 for (ModRefTable::ref_iterator JI=ModRefAfter.usersBegin(),
376 JE=ModRefAfter.usersEnd(); JI != JE; ++JI)
377 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
378 mapAfter.find(*JI)->second.getRefSet()))
379 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
380 }
381
382 ///
383 /// for every use U in UseSetCurrent
384 /// for every def Dnext in DefSetAfter
385 /// // NOTE: Dnext comes after U in execution order
386 /// if (Dnext & D)
387 /// Add anti-dep: U -> Dnext
388 for (ModRefTable::ref_iterator II=ModRefCurrent.usersBegin(),
389 IE=ModRefCurrent.usersEnd(); II != IE; ++II)
390 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
391 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
392 if (!Disjoint(mapCurrent.find(*II)->second.getRefSet(),
393 mapAfter.find(*JI)->second.getModSet()))
394 funcDepGraph->AddSimpleDependence(**II, **JI, AntiDependence);
395
396 /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
397 /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
398 /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
399 ModRefAfter.Insert(ModRefCurrent);
400}
401
402
403/// Debugging support methods
404///
405void MemoryDepAnalysis::print(std::ostream &O) const
406{
407 // TEMPORARY LOOP
408 for (hash_map<Function*, DependenceGraph*>::const_iterator
409 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
410 {
411 Function* func = I->first;
412 DependenceGraph* depGraph = I->second;
413
414 O << "\n================================================================\n";
415 O << "DEPENDENCE GRAPH FOR MEMORY OPERATIONS IN FUNCTION " << func->getName();
416 O << "\n================================================================\n\n";
417 depGraph->print(*func, O);
418
419 }
420}
421
422
423///
424/// Run the pass on a function
425///
Chris Lattner0c0023b2003-08-31 19:29:52 +0000426bool MemoryDepAnalysis::runOnFunction(Function &F) {
427 assert(!F.isExternal());
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000428
429 // Get the FunctionModRefInfo holding IPModRef results for this function.
430 // Use the TD graph recorded within the FunctionModRefInfo object, which
431 // may not be the same as the original TD graph computed by DS analysis.
432 //
Chris Lattner0c0023b2003-08-31 19:29:52 +0000433 funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000434 funcGraph = &funcModRef->getFuncGraph();
435
436 // TEMPORARY: ptr to depGraph (later just becomes "this").
Chris Lattner0c0023b2003-08-31 19:29:52 +0000437 assert(!funcMap.count(&F) && "Analyzing function twice?");
438 funcDepGraph = funcMap[&F] = new DependenceGraph();
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000439
440 ModRefTable ModRefAfter;
441
442 SCC<Function*>* nextSCC;
Chris Lattner0c0023b2003-08-31 19:29:52 +0000443 for (TarjanSCC_iterator<Function*> I = tarj_begin(&F), E = tarj_end(&F);
444 I != E; ++I)
Chris Lattner6c5fd8e2003-08-31 19:35:16 +0000445 ProcessSCC(*I, ModRefAfter);
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000446
447 return true;
448}
449
450
451//-------------------------------------------------------------------------
452// TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
453// These functions will go away once this class becomes a FunctionPass.
454//
455
456// Driver function to compute dependence graphs for every function.
457// This is temporary and will go away once this is a FunctionPass.
458//
459bool MemoryDepAnalysis::run(Module& M)
460{
461 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
462 if (! FI->isExternal())
463 runOnFunction(*FI); // automatically inserts each depGraph into funcMap
464 return true;
465}
466
467// Release all the dependence graphs in the map.
468void MemoryDepAnalysis::releaseMemory()
469{
470 for (hash_map<Function*, DependenceGraph*>::const_iterator
471 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
472 delete I->second;
473 funcMap.clear();
474
475 // Clear pointers because the pass constructor will not be invoked again.
476 funcDepGraph = NULL;
477 funcGraph = NULL;
478 funcModRef = NULL;
479}
480
481MemoryDepAnalysis::~MemoryDepAnalysis()
482{
483 releaseMemory();
484}
485
486//----END TEMPORARY FUNCTIONS----------------------------------------------
487
488
489void MemoryDepAnalysis::dump() const
490{
491 this->print(std::cerr);
492}
493
494static RegisterAnalysis<MemoryDepAnalysis>
495Z("memdep", "Memory Dependence Analysis");
496