Fix bug
[oota-llvm.git] / lib / Analysis / DataStructure / IPModRef.cpp
1 //===- IPModRef.cpp - Compute IP Mod/Ref information ------------*- C++ -*-===//
2 //
3 // See high-level comments in include/llvm/Analysis/IPModRef.h
4 // 
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Analysis/IPModRef.h"
8 #include "llvm/Analysis/DataStructure.h"
9 #include "llvm/Analysis/DSGraph.h"
10 #include "llvm/Module.h"
11 #include "llvm/iOther.h"
12 #include "Support/Statistic.h"
13 #include "Support/STLExtras.h"
14 #include "Support/StringExtras.h"
15
16 //----------------------------------------------------------------------------
17 // Private constants and data
18 //----------------------------------------------------------------------------
19
20 static RegisterAnalysis<IPModRef>
21 Z("ipmodref", "Interprocedural mod/ref analysis");
22
23
24 //----------------------------------------------------------------------------
25 // class ModRefInfo
26 //----------------------------------------------------------------------------
27
28 void ModRefInfo::print(std::ostream &O) const
29 {
30   O << std::endl << "Modified   nodes = " << modNodeSet;
31   O              << "Referenced nodes = " << refNodeSet << std::endl;
32 }
33
34 void ModRefInfo::dump() const
35 {
36   print(std::cerr);
37 }
38
39 //----------------------------------------------------------------------------
40 // class FunctionModRefInfo
41 //----------------------------------------------------------------------------
42
43
44 // This constructor computes a node numbering for the TD graph.
45 // 
46 FunctionModRefInfo::FunctionModRefInfo(const Function& func,
47                                        IPModRef& ipmro,
48                                        const DSGraph& tdg,
49                                        const DSGraph& ldg)
50   : F(func), IPModRefObj(ipmro), 
51     funcTDGraph(tdg),
52     funcLocalGraph(ldg),
53     funcModRefInfo(tdg.getGraphSize())
54 {
55   for (unsigned i=0, N = funcTDGraph.getGraphSize(); i < N; ++i)
56     NodeIds[funcTDGraph.getNodes()[i]] = i;
57 }
58
59
60 FunctionModRefInfo::~FunctionModRefInfo()
61 {
62   for(std::map<const CallInst*, ModRefInfo*>::iterator
63         I=callSiteModRefInfo.begin(), E=callSiteModRefInfo.end(); I != E; ++I)
64     delete(I->second);
65
66   // Empty map just to make problems easier to track down
67   callSiteModRefInfo.clear();
68 }
69
70 unsigned FunctionModRefInfo::getNodeId(const Value* value) const {
71   return getNodeId(funcTDGraph.getNodeForValue(const_cast<Value*>(value))
72                    .getNode());
73 }
74
75
76
77 // Compute Mod/Ref bit vectors for the entire function.
78 // These are simply copies of the Read/Write flags from the nodes of
79 // the top-down DS graph.
80 // 
81 void FunctionModRefInfo::computeModRef(const Function &func)
82 {
83   // Mark all nodes in the graph that are marked MOD as being mod
84   // and all those marked REF as being ref.
85   for (unsigned i = 0, N = funcTDGraph.getGraphSize(); i < N; ++i)
86     {
87       if (funcTDGraph.getNodes()[i]->isModified())
88         funcModRefInfo.setNodeIsMod(i);
89       if (funcTDGraph.getNodes()[i]->isRead())
90         funcModRefInfo.setNodeIsRef(i);
91     }
92
93   // Compute the Mod/Ref info for all call sites within the function
94   // Use the Local DSgraph, which includes all the call sites in the
95   // original program.
96   const std::vector<DSCallSite>& callSites = funcLocalGraph.getFunctionCalls();
97   for (unsigned i = 0, N = callSites.size(); i < N; ++i)
98     computeModRef(callSites[i].getCallInst());
99 }
100
101 // ResolveCallSiteModRefInfo - This method performs the following actions:
102 //
103 //  1. It clones the top-down graph for the current function
104 //  2. It clears all of the mod/ref bits in the cloned graph
105 //  3. It then merges the bottom-up graph(s) for the specified call-site into
106 //     the clone (bringing new mod/ref bits).
107 //  4. It returns the clone, and a mapping of nodes from the original TDGraph to
108 //     the cloned graph with Mod/Ref info for the callsite.
109 //
110 // NOTE: Because this clones a dsgraph and returns it, the caller is responsible
111 //       for deleting the returned graph!
112 // NOTE: This method may return a null pointer if it is unable to determine the
113 //       requested information (because the call site calls an external
114 //       function or we cannot determine the complete set of functions invoked).
115 //
116 DSGraph *FunctionModRefInfo::ResolveCallSiteModRefInfo(CallInst &CI,
117                                std::map<const DSNode*, DSNodeHandle> &NodeMap) {
118
119   // Step #1: Clone the top-down graph...
120   DSGraph *Result = new DSGraph(funcTDGraph, NodeMap);
121
122   // Step #2: Clear Mod/Ref information...
123   Result->maskNodeTypes(~(DSNode::Modified | DSNode::Read));
124
125   // Step #3: clone the bottom up graphs for the callees into the caller graph
126   if (const Function *F = CI.getCalledFunction()) {
127     if (F->isExternal()) {
128       delete Result;
129       return 0;   // We cannot compute Mod/Ref info for this callsite...
130     }
131
132     // Build up a DSCallSite for our invocation point here...
133
134     // If the call returns a value, make sure to merge the nodes...
135     DSNodeHandle RetVal;
136     if (DS::isPointerType(CI.getType()))
137       RetVal = Result->getNodeForValue(&CI);
138
139     // Populate the arguments list...
140     std::vector<DSNodeHandle> Args;
141     for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
142       if (DS::isPointerType(CI.getOperand(i)->getType()))
143         Args.push_back(Result->getNodeForValue(CI.getOperand(i)));
144
145     // Build the call site...
146     DSCallSite CS(CI, RetVal, 0, Args);
147
148     // Perform the merging now of the graph for the callee, which will come with
149     // mod/ref bits set...
150     Result->mergeInGraph(CS, IPModRefObj.getBUDSGraph(*F),
151                          DSGraph::StripAllocaBit | DSGraph::DontCloneCallNodes |
152                          DSGraph::DontCloneAuxCallNodes);
153
154   } else {
155     std::cerr << "IP Mod/Ref indirect call not implemented yet: "
156               << "Being conservative\n";
157     delete Result;
158     return 0;
159   }
160
161   // Remove dead nodes... 
162   Result->removeDeadNodes();
163
164   // Step #4: Return the clone + the mapping (by ref)
165   return Result;
166 }
167
168 // Compute Mod/Ref bit vectors for a single call site.
169 // These are copies of the Read/Write flags from the nodes of
170 // the graph produced by clearing all flags in teh caller's TD graph
171 // and then inlining the callee's BU graph into the caller's TD graph.
172 // 
173 void
174 FunctionModRefInfo::computeModRef(const CallInst& callInst)
175 {
176   // Allocate the mod/ref info for the call site.  Bits automatically cleared.
177   ModRefInfo* callModRefInfo = new ModRefInfo(funcTDGraph.getGraphSize());
178   callSiteModRefInfo[&callInst] = callModRefInfo;
179
180   // Get a copy of the graph for the callee with the callee inlined
181   std::map<const DSNode*, DSNodeHandle> NodeMap;
182   DSGraph* csgp =
183     ResolveCallSiteModRefInfo(const_cast<CallInst&>(callInst), NodeMap);
184
185   assert(csgp && "FIXME: Cannot handle case where call site mod/ref info"
186          " is not available yet!");
187
188   // For all nodes in the graph, extract the mod/ref information
189   const std::vector<DSNode*>& csgNodes = csgp->getNodes();
190   const std::vector<DSNode*>& origNodes = funcTDGraph.getNodes();
191   assert(csgNodes.size() == origNodes.size());
192   for (unsigned i=0, N = csgNodes.size(); i < N; ++i)
193     { 
194       if (csgNodes[i]->isModified())
195         callModRefInfo->setNodeIsMod(getNodeId(origNodes[i]));
196       if (csgNodes[i]->isRead())
197         callModRefInfo->setNodeIsRef(getNodeId(origNodes[i]));
198     }
199
200   // Drop nodemap before we delete the graph...
201   NodeMap.clear();
202   delete csgp;
203 }
204
205
206 // Print the results of the pass.
207 // Currently this just prints bit-vectors and is not very readable.
208 // 
209 void FunctionModRefInfo::print(std::ostream &O) const
210 {
211   O << "---------- Mod/ref information for function "
212     << F.getName() << "---------- \n\n";
213
214   O << "Mod/ref info for function body:\n";
215   funcModRefInfo.print(O);
216
217   for (std::map<const CallInst*, ModRefInfo*>::const_iterator
218          CI = callSiteModRefInfo.begin(), CE = callSiteModRefInfo.end();
219        CI != CE; ++CI)
220     {
221       O << "Mod/ref info for call site " << CI->first << ":\n";
222       CI->second->print(O);
223     }
224
225   O << "\n";
226 }
227
228 void FunctionModRefInfo::dump() const
229 {
230   print(std::cerr);
231 }
232
233
234 //----------------------------------------------------------------------------
235 // class IPModRef: An interprocedural pass that computes IP Mod/Ref info.
236 //----------------------------------------------------------------------------
237
238 // Free the FunctionModRefInfo objects cached in funcToModRefInfoMap.
239 // 
240 void IPModRef::releaseMemory()
241 {
242   for(std::map<const Function*, FunctionModRefInfo*>::iterator
243         I=funcToModRefInfoMap.begin(), E=funcToModRefInfoMap.end(); I != E; ++I)
244     delete(I->second);
245
246   // Clear map so memory is not re-released if we are called again
247   funcToModRefInfoMap.clear();
248 }
249
250 // Run the "interprocedural" pass on each function.  This needs to do
251 // NO real interprocedural work because all that has been done the
252 // data structure analysis.
253 // 
254 bool IPModRef::run(Module &theModule)
255 {
256   M = &theModule;
257
258   for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
259     if (! FI->isExternal())
260       getFuncInfo(*FI, /*computeIfMissing*/ true);
261   return true;
262 }
263
264
265 FunctionModRefInfo& IPModRef::getFuncInfo(const Function& func,
266                                           bool computeIfMissing)
267 {
268   FunctionModRefInfo*& funcInfo = funcToModRefInfoMap[&func];
269   assert (funcInfo != NULL || computeIfMissing);
270   if (funcInfo == NULL)
271     { // Create a new FunctionModRefInfo object
272       funcInfo = new FunctionModRefInfo(func, *this, // inserts into map
273                               getAnalysis<TDDataStructures>().getDSGraph(func),
274                           getAnalysis<LocalDataStructures>().getDSGraph(func));
275       funcInfo->computeModRef(func);            // computes the mod/ref info
276     }
277   return *funcInfo;
278 }
279
280 /// getBUDSGraph - This method returns the BU data structure graph for F through
281 /// the use of the BUDataStructures object.
282 ///
283 const DSGraph &IPModRef::getBUDSGraph(const Function &F) {
284   return getAnalysis<BUDataStructures>().getDSGraph(F);
285 }
286
287
288 // getAnalysisUsage - This pass requires top-down data structure graphs.
289 // It modifies nothing.
290 // 
291 void IPModRef::getAnalysisUsage(AnalysisUsage &AU) const {
292   AU.setPreservesAll();
293   AU.addRequired<LocalDataStructures>();
294   AU.addRequired<BUDataStructures>();
295   AU.addRequired<TDDataStructures>();
296 }
297
298
299 void IPModRef::print(std::ostream &O) const
300 {
301   O << "\n========== Results of Interprocedural Mod/Ref Analysis ==========\n";
302   
303   for (std::map<const Function*, FunctionModRefInfo*>::const_iterator
304          mapI = funcToModRefInfoMap.begin(), mapE = funcToModRefInfoMap.end();
305        mapI != mapE; ++mapI)
306     mapI->second->print(O);
307
308   O << "\n";
309 }
310
311
312 void IPModRef::dump() const
313 {
314   print(std::cerr);
315 }