a185c891197c4db846c07470400824fb82aeaf26
[oota-llvm.git] / lib / Analysis / IPA / MemoryDepAnalysis.cpp
1 //===- 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"
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/TarjanSCCIterator.h"
22 #include "Support/Statistic.h"
23 #include "Support/STLExtras.h"
24 #include "Support/hash_map"
25 #include "Support/hash_set"
26
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
44 struct ModRefTable
45 {
46   typedef hash_map<Instruction*, ModRefInfo> ModRefMap;
47   typedef ModRefMap::const_iterator                 const_map_iterator;
48   typedef ModRefMap::      iterator                        map_iterator;
49   typedef std::vector<Instruction*>::const_iterator const_ref_iterator;
50   typedef std::vector<Instruction*>::      iterator       ref_iterator;
51
52   ModRefMap                 modRefMap;
53   std::vector<Instruction*> definers;
54   std::vector<Instruction*> users;
55   std::vector<unsigned>     numUsersBeforeDef;
56
57   // Iterators to enumerate all the defining instructions
58   const_ref_iterator defsBegin()  const {  return definers.begin(); }
59         ref_iterator defsBegin()        {  return definers.begin(); }
60   const_ref_iterator defsEnd()    const {  return definers.end(); }
61         ref_iterator defsEnd()          {  return definers.end(); }
62
63   // Iterators to enumerate all the user instructions
64   const_ref_iterator usersBegin() const {  return users.begin(); }
65         ref_iterator usersBegin()       {  return users.begin(); }
66   const_ref_iterator usersEnd()   const {  return users.end(); }
67         ref_iterator usersEnd()         {  return users.end(); }
68
69   // Iterator identifying the last user that was seen *before* a
70   // specified def.  In particular, all users in the half-closed range
71   //    [ usersBegin(), usersBeforeDef_End(defPtr) )
72   // were seen *before* the specified def.  All users in the half-closed range
73   //    [ usersBeforeDef_End(defPtr), usersEnd() )
74   // were seen *after* the specified def.
75   // 
76   ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) {
77     unsigned defIndex = (unsigned) (defPtr - defsBegin());
78     assert(defIndex < numUsersBeforeDef.size());
79     assert(usersBegin() + numUsersBeforeDef[defIndex] <= usersEnd()); 
80     return usersBegin() + numUsersBeforeDef[defIndex]; 
81   }
82   const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
83     return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
84   }
85
86   // 
87   // Modifier methods
88   // 
89   void AddDef(Instruction* D) {
90     definers.push_back(D);
91     numUsersBeforeDef.push_back(users.size());
92   }
93   void AddUse(Instruction* U) {
94     users.push_back(U);
95   }
96   void Insert(const ModRefTable& fromTable) {
97     modRefMap.insert(fromTable.modRefMap.begin(), fromTable.modRefMap.end());
98     definers.insert(definers.end(),
99                     fromTable.definers.begin(), fromTable.definers.end());
100     users.insert(users.end(),
101                  fromTable.users.begin(), fromTable.users.end());
102     numUsersBeforeDef.clear(); /* fromTable.numUsersBeforeDef is ignored */
103   }
104 };
105
106
107 ///--------------------------------------------------------------------------
108 /// class ModRefInfoBuilder:
109 /// 
110 /// A simple InstVisitor<> class that retrieves the Mod/Ref info for
111 /// Load/Store/Call instructions and inserts this information in
112 /// a ModRefTable.  It also records all instructions that Mod any node
113 /// and all that use any node.
114 ///--------------------------------------------------------------------------
115
116 class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
117   const DSGraph&            funcGraph;
118   const FunctionModRefInfo& funcModRef;
119   ModRefTable&              modRefTable;
120
121   ModRefInfoBuilder();                         // DO NOT IMPLEMENT
122   ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
123   void operator=(const ModRefInfoBuilder&);    // DO NOT IMPLEMENT
124
125 public:
126   /*ctor*/      ModRefInfoBuilder(const DSGraph&  _funcGraph,
127                                   const FunctionModRefInfo& _funcModRef,
128                                   ModRefTable&    _modRefTable)
129     : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
130   {
131   }
132
133   // At a call instruction, retrieve the ModRefInfo using IPModRef results.
134   // Add the call to the defs list if it modifies any nodes and to the uses
135   // list if it refs any nodes.
136   // 
137   void          visitCallInst   (CallInst& callInst) {
138     ModRefInfo safeModRef(funcGraph.getGraphSize());
139     const ModRefInfo* callModRef = funcModRef.getModRefInfo(callInst);
140     if (callModRef == NULL)
141       { // call to external/unknown function: mark all nodes as Mod and Ref
142         safeModRef.getModSet().set();
143         safeModRef.getRefSet().set();
144         callModRef = &safeModRef;
145       }
146
147     modRefTable.modRefMap.insert(std::make_pair(&callInst,
148                                                 ModRefInfo(*callModRef)));
149     if (callModRef->getModSet().any())
150       modRefTable.AddDef(&callInst);
151     if (callModRef->getRefSet().any())
152       modRefTable.AddUse(&callInst);
153   }
154
155   // At a store instruction, add to the mod set the single node pointed to
156   // by the pointer argument of the store.  Interestingly, if there is no
157   // such node, that would be a null pointer reference!
158   void          visitStoreInst  (StoreInst& storeInst) {
159     const DSNodeHandle& ptrNode =
160       funcGraph.getNodeForValue(storeInst.getPointerOperand());
161     if (const DSNode* target = ptrNode.getNode())
162       {
163         unsigned nodeId = funcModRef.getNodeId(target);
164         ModRefInfo& minfo =
165           modRefTable.modRefMap.insert(
166             std::make_pair(&storeInst,
167                            ModRefInfo(funcGraph.getGraphSize()))).first->second;
168         minfo.setNodeIsMod(nodeId);
169         modRefTable.AddDef(&storeInst);
170       }
171     else
172       std::cerr << "Warning: Uninitialized pointer reference!\n";
173   }
174
175   // At a load instruction, add to the ref set the single node pointed to
176   // by the pointer argument of the load.  Interestingly, if there is no
177   // such node, that would be a null pointer reference!
178   void          visitLoadInst  (LoadInst& loadInst) {
179     const DSNodeHandle& ptrNode =
180       funcGraph.getNodeForValue(loadInst.getPointerOperand());
181     if (const DSNode* target = ptrNode.getNode())
182       {
183         unsigned nodeId = funcModRef.getNodeId(target);
184         ModRefInfo& minfo =
185           modRefTable.modRefMap.insert(
186             std::make_pair(&loadInst,
187                            ModRefInfo(funcGraph.getGraphSize()))).first->second;
188         minfo.setNodeIsRef(nodeId);
189         modRefTable.AddUse(&loadInst);
190       }
191     else
192       std::cerr << "Warning: Uninitialized pointer reference!\n";
193   }
194 };
195
196
197 //----------------------------------------------------------------------------
198 // class MemoryDepAnalysis: A dep. graph for load/store/call instructions
199 //----------------------------------------------------------------------------
200
201 /// Basic dependence gathering algorithm, using TarjanSCCIterator on CFG:
202 /// 
203 /// for every SCC S in the CFG in PostOrder on the SCC DAG
204 ///     {
205 ///       for every basic block BB in S in *postorder*
206 ///         for every instruction I in BB in reverse
207 ///           Add (I, ModRef[I]) to ModRefCurrent
208 ///           if (Mod[I] != NULL)
209 ///               Add I to DefSetCurrent:  { I \in S : Mod[I] != NULL }
210 ///           if (Ref[I] != NULL)
211 ///               Add I to UseSetCurrent:  { I       : Ref[I] != NULL }
212 /// 
213 ///       for every def D in DefSetCurrent
214 /// 
215 ///           // NOTE: D comes after itself iff S contains a loop
216 ///           if (HasLoop(S) && D & D)
217 ///               Add output-dep: D -> D2
218 /// 
219 ///           for every def D2 *after* D in DefSetCurrent
220 ///               // NOTE: D2 comes before D in execution order
221 ///               if (D & D2)
222 ///                   Add output-dep: D2 -> D
223 ///                   if (HasLoop(S))
224 ///                       Add output-dep: D -> D2
225 /// 
226 ///           for every use U in UseSetCurrent that was seen *before* D
227 ///               // NOTE: U comes after D in execution order
228 ///               if (U & D)
229 ///                   if (U != D || HasLoop(S))
230 ///                       Add true-dep: D -> U
231 ///                   if (HasLoop(S))
232 ///                       Add anti-dep: U -> D
233 /// 
234 ///           for every use U in UseSetCurrent that was seen *after* D
235 ///               // NOTE: U comes before D in execution order
236 ///               if (U & D)
237 ///                   if (U != D || HasLoop(S))
238 ///                       Add anti-dep: U -> D
239 ///                   if (HasLoop(S))
240 ///                       Add true-dep: D -> U
241 /// 
242 ///           for every def Dnext in DefSetAfter
243 ///               // NOTE: Dnext comes after D in execution order
244 ///               if (Dnext & D)
245 ///                   Add output-dep: D -> Dnext
246 /// 
247 ///           for every use Unext in UseSetAfter
248 ///               // NOTE: Unext comes after D in execution order
249 ///               if (Unext & D)
250 ///                   Add true-dep: D -> Unext
251 /// 
252 ///       for every use U in UseSetCurrent
253 ///           for every def Dnext in DefSetAfter
254 ///               // NOTE: Dnext comes after U in execution order
255 ///               if (Dnext & D)
256 ///                   Add anti-dep: U -> Dnext
257 /// 
258 ///       Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
259 ///       Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
260 ///       Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
261 ///     }
262 ///         
263 ///
264 void MemoryDepAnalysis::ProcessSCC(SCC<Function*>& S,
265                                    ModRefTable& ModRefAfter) {
266   ModRefTable ModRefCurrent;
267   ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
268   ModRefTable::ModRefMap& mapAfter   = ModRefAfter.modRefMap;
269
270   bool hasLoop = S.HasLoop();
271
272   // Builder class fills out a ModRefTable one instruction at a time.
273   // To use it, we just invoke it's visit function for each basic block:
274   // 
275   //   for each basic block BB in the SCC in *postorder*
276   //       for each instruction  I in BB in *reverse*
277   //           ModRefInfoBuilder::visit(I)
278   //           : Add (I, ModRef[I]) to ModRefCurrent.modRefMap
279   //           : Add I  to ModRefCurrent.definers if it defines any node
280   //           : Add I  to ModRefCurrent.users    if it uses any node
281   // 
282   ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
283   for (SCC<Function*>::iterator BI=S.begin(), BE=S.end(); BI != BE; ++BI)
284     // Note: BBs in the SCC<> created by TarjanSCCIterator are in postorder.
285     for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
286          II != IE; ++II)
287       builder.visit(*II);
288
289   ///       for every def D in DefSetCurrent
290   /// 
291   for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
292          IE=ModRefCurrent.defsEnd(); II != IE; ++II)
293     {
294       ///           // NOTE: D comes after itself iff S contains a loop
295       ///           if (HasLoop(S))
296       ///               Add output-dep: D -> D2
297       if (hasLoop)
298         funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
299
300       ///           for every def D2 *after* D in DefSetCurrent
301       ///               // NOTE: D2 comes before D in execution order
302       ///               if (D2 & D)
303       ///                   Add output-dep: D2 -> D
304       ///                   if (HasLoop(S))
305       ///                       Add output-dep: D -> D2
306       for (ModRefTable::ref_iterator JI=II+1; JI != IE; ++JI)
307         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
308                       mapCurrent.find(*JI)->second.getModSet()))
309           {
310             funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
311             if (hasLoop)
312               funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
313           }
314   
315       ///           for every use U in UseSetCurrent that was seen *before* D
316       ///               // NOTE: U comes after D in execution order
317       ///               if (U & D)
318       ///                   if (U != D || HasLoop(S))
319       ///                       Add true-dep: U -> D
320       ///                   if (HasLoop(S))
321       ///                       Add anti-dep: D -> U
322       ModRefTable::ref_iterator JI=ModRefCurrent.usersBegin();
323       ModRefTable::ref_iterator JE = ModRefCurrent.usersBeforeDef_End(II);
324       for ( ; JI != JE; ++JI)
325         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
326                       mapCurrent.find(*JI)->second.getRefSet()))
327           {
328             if (*II != *JI || hasLoop)
329               funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
330             if (hasLoop)
331               funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
332           }
333
334       ///           for every use U in UseSetCurrent that was seen *after* D
335       ///               // NOTE: U comes before D in execution order
336       ///               if (U & D)
337       ///                   if (U != D || HasLoop(S))
338       ///                       Add anti-dep: U -> D
339       ///                   if (HasLoop(S))
340       ///                       Add true-dep: D -> U
341       for (/*continue JI*/ JE = ModRefCurrent.usersEnd(); JI != JE; ++JI)
342         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
343                       mapCurrent.find(*JI)->second.getRefSet()))
344           {
345             if (*II != *JI || hasLoop)
346               funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
347             if (hasLoop)
348               funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
349           }
350
351       ///           for every def Dnext in DefSetPrev
352       ///               // NOTE: Dnext comes after D in execution order
353       ///               if (Dnext & D)
354       ///                   Add output-dep: D -> Dnext
355       for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
356              JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
357         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
358                       mapAfter.find(*JI)->second.getModSet()))
359           funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
360
361       ///           for every use Unext in UseSetAfter
362       ///               // NOTE: Unext comes after D in execution order
363       ///               if (Unext & D)
364       ///                   Add true-dep: D -> Unext
365       for (ModRefTable::ref_iterator JI=ModRefAfter.usersBegin(),
366              JE=ModRefAfter.usersEnd(); JI != JE; ++JI)
367         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
368                       mapAfter.find(*JI)->second.getRefSet()))
369           funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
370     }
371
372   /// 
373   ///       for every use U in UseSetCurrent
374   ///           for every def Dnext in DefSetAfter
375   ///               // NOTE: Dnext comes after U in execution order
376   ///               if (Dnext & D)
377   ///                   Add anti-dep: U -> Dnext
378   for (ModRefTable::ref_iterator II=ModRefCurrent.usersBegin(),
379          IE=ModRefCurrent.usersEnd(); II != IE; ++II)
380     for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
381            JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
382       if (!Disjoint(mapCurrent.find(*II)->second.getRefSet(),
383                     mapAfter.find(*JI)->second.getModSet()))
384         funcDepGraph->AddSimpleDependence(**II, **JI, AntiDependence);
385     
386   ///       Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
387   ///       Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
388   ///       Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
389   ModRefAfter.Insert(ModRefCurrent);
390 }
391
392
393 /// Debugging support methods
394 /// 
395 void MemoryDepAnalysis::print(std::ostream &O) const
396 {
397   // TEMPORARY LOOP
398   for (hash_map<Function*, DependenceGraph*>::const_iterator
399          I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
400     {
401       Function* func = I->first;
402       DependenceGraph* depGraph = I->second;
403
404   O << "\n================================================================\n";
405   O << "DEPENDENCE GRAPH FOR MEMORY OPERATIONS IN FUNCTION " << func->getName();
406   O << "\n================================================================\n\n";
407   depGraph->print(*func, O);
408
409     }
410 }
411
412
413 /// 
414 /// Run the pass on a function
415 /// 
416 bool MemoryDepAnalysis::runOnFunction(Function &F) {
417   assert(!F.isExternal());
418
419   // Get the FunctionModRefInfo holding IPModRef results for this function.
420   // Use the TD graph recorded within the FunctionModRefInfo object, which
421   // may not be the same as the original TD graph computed by DS analysis.
422   // 
423   funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
424   funcGraph  = &funcModRef->getFuncGraph();
425
426   // TEMPORARY: ptr to depGraph (later just becomes "this").
427   assert(!funcMap.count(&F) && "Analyzing function twice?");
428   funcDepGraph = funcMap[&F] = new DependenceGraph();
429
430   ModRefTable ModRefAfter;
431
432   SCC<Function*>* nextSCC;
433   for (TarjanSCC_iterator<Function*> I = tarj_begin(&F), E = tarj_end(&F);
434        I != E; ++I)
435     ProcessSCC(**I, ModRefAfter);
436
437   return true;
438 }
439
440
441 //-------------------------------------------------------------------------
442 // TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
443 // These functions will go away once this class becomes a FunctionPass.
444 // 
445
446 // Driver function to compute dependence graphs for every function.
447 // This is temporary and will go away once this is a FunctionPass.
448 // 
449 bool MemoryDepAnalysis::run(Module& M)
450 {
451   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
452     if (! FI->isExternal())
453       runOnFunction(*FI); // automatically inserts each depGraph into funcMap
454   return true;
455 }
456   
457 // Release all the dependence graphs in the map.
458 void MemoryDepAnalysis::releaseMemory()
459 {
460   for (hash_map<Function*, DependenceGraph*>::const_iterator
461          I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
462     delete I->second;
463   funcMap.clear();
464
465   // Clear pointers because the pass constructor will not be invoked again.
466   funcDepGraph = NULL;
467   funcGraph = NULL;
468   funcModRef = NULL;
469 }
470
471 MemoryDepAnalysis::~MemoryDepAnalysis()
472 {
473   releaseMemory();
474 }
475
476 //----END TEMPORARY FUNCTIONS----------------------------------------------
477
478
479 void MemoryDepAnalysis::dump() const
480 {
481   this->print(std::cerr);
482 }
483
484 static RegisterAnalysis<MemoryDepAnalysis>
485 Z("memdep", "Memory Dependence Analysis");
486