blob: 89904c1019ea1fb891bcd6e701a6aab8b177ffa6 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00002//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00003// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00004//
5//===----------------------------------------------------------------------===//
6
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00007#include "llvm/Module.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +00008#include "llvm/DerivedTypes.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +00009#include "Support/STLExtras.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000010#include "Support/StatisticReporter.h"
11#include <algorithm>
12#include "llvm/Analysis/DataStructure.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000013
14AnalysisID LocalDataStructures::ID(AnalysisID::create<LocalDataStructures>());
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000015
16//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017// DSNode Implementation
18//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000019
Chris Lattnerc68c31b2002-07-10 22:38:08 +000020DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
21 // If this node has any fields, allocate them now, but leave them null.
22 switch (T->getPrimitiveID()) {
23 case Type::PointerTyID: Links.resize(1); break;
24 case Type::ArrayTyID: Links.resize(1); break;
25 case Type::StructTyID:
26 Links.resize(cast<StructType>(T)->getNumContainedTypes());
27 break;
28 default: break;
29 }
30}
31
Chris Lattner0d9bab82002-07-18 00:12:30 +000032// DSNode copy constructor... do not copy over the referrers list!
33DSNode::DSNode(const DSNode &N)
34 : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
35}
36
Chris Lattnerc68c31b2002-07-10 22:38:08 +000037void DSNode::removeReferrer(DSNodeHandle *H) {
38 // Search backwards, because we depopulate the list from the back for
39 // efficiency (because it's a vector).
40 std::vector<DSNodeHandle*>::reverse_iterator I =
41 std::find(Referrers.rbegin(), Referrers.rend(), H);
42 assert(I != Referrers.rend() && "Referrer not pointing to node!");
43 Referrers.erase(I.base()-1);
44}
45
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000046// addGlobal - Add an entry for a global value to the Globals list. This also
47// marks the node with the 'G' flag if it does not already have it.
48//
49void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000050 // Keep the list sorted.
51 std::vector<GlobalValue*>::iterator I =
52 std::lower_bound(Globals.begin(), Globals.end(), GV);
53
54 if (I == Globals.end() || *I != GV) {
55 assert(GV->getType()->getElementType() == Ty);
56 Globals.insert(I, GV);
57 NodeType |= GlobalNode;
58 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000059}
60
61
Chris Lattnerc68c31b2002-07-10 22:38:08 +000062// addEdgeTo - Add an edge from the current node to the specified node. This
63// can cause merging of nodes in the graph.
64//
65void DSNode::addEdgeTo(unsigned LinkNo, DSNode *N) {
66 assert(LinkNo < Links.size() && "LinkNo out of range!");
67 if (N == 0 || Links[LinkNo] == N) return; // Nothing to do
68 if (Links[LinkNo] == 0) { // No merging to perform
69 Links[LinkNo] = N;
70 return;
71 }
72
73 // Merge the two nodes...
74 Links[LinkNo]->mergeWith(N);
75}
76
77
78// mergeWith - Merge this node into the specified node, moving all links to and
79// from the argument node into the current node. The specified node may be a
80// null pointer (in which case, nothing happens).
81//
82void DSNode::mergeWith(DSNode *N) {
83 if (N == 0 || N == this) return; // Noop
84 assert(N->Ty == Ty && N->Links.size() == Links.size() &&
85 "Cannot merge nodes of two different types!");
86
87 // Remove all edges pointing at N, causing them to point to 'this' instead.
88 while (!N->Referrers.empty())
89 *N->Referrers.back() = this;
90
91 // Make all of the outgoing links of N now be outgoing links of this. This
92 // can cause recursive merging!
93 //
94 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
95 addEdgeTo(i, N->Links[i]);
96 N->Links[i] = 0; // Reduce unneccesary edges in graph. N is dead
97 }
98
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000099 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000100 NodeType |= N->NodeType;
101 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000102
103 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000104 if (!N->Globals.empty()) {
105 // Save the current globals off to the side...
106 std::vector<GlobalValue*> OldGlobals(Globals);
107
108 // Resize the globals vector to be big enough to hold both of them...
109 Globals.resize(Globals.size()+N->Globals.size());
110
111 // Merge the two sorted globals lists together...
112 std::merge(OldGlobals.begin(), OldGlobals.end(),
113 N->Globals.begin(), N->Globals.end(), Globals.begin());
114
115 // Erase duplicate entries from the globals list...
116 Globals.erase(std::unique(Globals.begin(), Globals.end()), Globals.end());
117
118 // Delete the globals from the old node...
119 N->Globals.clear();
120 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000121}
122
123//===----------------------------------------------------------------------===//
124// DSGraph Implementation
125//===----------------------------------------------------------------------===//
126
Chris Lattner0d9bab82002-07-18 00:12:30 +0000127DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000128 std::map<const DSNode*, DSNode*> NodeMap; // ignored
129 RetNode = cloneInto(G, ValueMap, NodeMap, false);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000130}
131
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000132DSGraph::~DSGraph() {
133 FunctionCalls.clear();
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000134 OrigFunctionCalls.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000135 ValueMap.clear();
136 RetNode = 0;
137
138#ifndef NDEBUG
139 // Drop all intra-node references, so that assertions don't fail...
140 std::for_each(Nodes.begin(), Nodes.end(),
141 std::mem_fun(&DSNode::dropAllReferences));
142#endif
143
144 // Delete all of the nodes themselves...
145 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
146}
147
Chris Lattner0d9bab82002-07-18 00:12:30 +0000148// dump - Allow inspection of graph in a debugger.
149void DSGraph::dump() const { print(std::cerr); }
150
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000151
152// Helper function used to clone a function list.
153// Each call really shd have an explicit representation as a separate class.
154void
155CopyFunctionCallsList(const std::vector<std::vector<DSNodeHandle> >& fromCalls,
156 std::vector<std::vector<DSNodeHandle> >& toCalls,
157 std::map<const DSNode*, DSNode*>& NodeMap) {
158
159 unsigned FC = toCalls.size(); // FirstCall
160 toCalls.reserve(FC+fromCalls.size());
161 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i) {
162 toCalls.push_back(std::vector<DSNodeHandle>());
163 toCalls[FC+i].reserve(fromCalls[i].size());
164 for (unsigned j = 0, ej = fromCalls[i].size(); j != ej; ++j)
165 toCalls[FC+i].push_back(NodeMap[fromCalls[i][j]]);
166 }
167}
168
169
Chris Lattner0d9bab82002-07-18 00:12:30 +0000170// cloneInto - Clone the specified DSGraph into the current graph, returning the
171// Return node of the graph. The translated ValueMap for the old function is
172// filled into the OldValMap member. If StripLocals is set to true, Scalar and
173// Alloca markers are removed from the graph, as the graph is being cloned into
174// a calling function's graph.
175//
176DSNode *DSGraph::cloneInto(const DSGraph &G,
177 std::map<Value*, DSNodeHandle> &OldValMap,
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000178 std::map<const DSNode*, DSNode*>& OldNodeMap,
Chris Lattner0d9bab82002-07-18 00:12:30 +0000179 bool StripLocals) {
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000180
181 assert(OldNodeMap.size()==0 && "Return argument OldNodeMap should be empty");
182
183 OldNodeMap[0] = 0; // Null pointer maps to null
Chris Lattner0d9bab82002-07-18 00:12:30 +0000184
185 unsigned FN = Nodes.size(); // FirstNode...
186
187 // Duplicate all of the nodes, populating the node map...
188 Nodes.reserve(FN+G.Nodes.size());
189 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
190 DSNode *Old = G.Nodes[i], *New = new DSNode(*Old);
191 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000192 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000193 }
194
195 // Rewrite the links in the nodes to point into the current graph now.
196 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
197 for (unsigned j = 0, e = Nodes[i]->getNumLinks(); j != e; ++j)
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000198 Nodes[i]->setLink(j, OldNodeMap[Nodes[i]->getLink(j)]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000199
200 // If we are inlining this graph into the called function graph, remove local
201 // markers.
202 if (StripLocals)
203 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
204 Nodes[i]->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
205
206 // Copy the value map...
207 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
208 E = G.ValueMap.end(); I != E; ++I)
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000209 OldValMap[I->first] = OldNodeMap[I->second];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000210
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000211 // Copy the current function calls list and the orig function calls list ...
212 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
213 CopyFunctionCallsList(G.OrigFunctionCalls, OrigFunctionCalls, OldNodeMap);
214
215 // Copy the list of unresolved callers
216 PendingCallers.insert(PendingCallers.end(),
217 G.PendingCallers.begin(), G.PendingCallers.end());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000218
219 // Return the returned node pointer...
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000220 return OldNodeMap[G.RetNode];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000221}
222
223
224// markIncompleteNodes - Mark the specified node as having contents that are not
225// known with the current analysis we have performed. Because a node makes all
226// of the nodes it can reach imcomplete if the node itself is incomplete, we
227// must recursively traverse the data structure graph, marking all reachable
228// nodes as incomplete.
229//
230static void markIncompleteNode(DSNode *N) {
231 // Stop recursion if no node, or if node already marked...
232 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
233
234 // Actually mark the node
235 N->NodeType |= DSNode::Incomplete;
236
237 // Recusively process children...
238 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
239 markIncompleteNode(N->getLink(i));
240}
241
242
243// markIncompleteNodes - Traverse the graph, identifying nodes that may be
244// modified by other functions that have not been resolved yet. This marks
245// nodes that are reachable through three sources of "unknownness":
246//
247// Global Variables, Function Calls, and Incoming Arguments
248//
249// For any node that may have unknown components (because something outside the
250// scope of current analysis may have modified it), the 'Incomplete' flag is
251// added to the NodeType.
252//
253void DSGraph::markIncompleteNodes() {
254 // Mark any incoming arguments as incomplete...
255 for (Function::aiterator I = Func.abegin(), E = Func.aend(); I != E; ++I)
256 if (isa<PointerType>(I->getType()))
257 markIncompleteNode(ValueMap[I]->getLink(0));
258
259 // Mark stuff passed into functions calls as being incomplete...
260 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
261 std::vector<DSNodeHandle> &Args = FunctionCalls[i];
262 if (Args[0]) // If the call returns a pointer...
263 // Then the return value is certainly incomplete!
264 markIncompleteNode(Args[0]);
265
266 // The call does not make the function argument incomplete...
267
268 // All arguments to the function call are incomplete though!
269 for (unsigned i = 2, e = Args.size(); i != e; ++i)
270 markIncompleteNode(Args[i]);
271 }
272
Chris Lattner055dc2c2002-07-18 15:54:42 +0000273 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000274 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner055dc2c2002-07-18 15:54:42 +0000275 if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000276 DSNode *N = Nodes[i];
277 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
278 markIncompleteNode(N->getLink(i));
279 }
280}
281
282// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
283// checks to see if there are simple transformations that it can do to make it
284// dead.
285//
286bool DSGraph::isNodeDead(DSNode *N) {
287 // Is it a trivially dead shadow node...
288 if (N->getReferrers().empty() && N->NodeType == 0)
289 return true;
290
291 // Is it a function node or some other trivially unused global?
292 if ((N->NodeType & ~DSNode::GlobalNode) == 0 &&
293 N->getNumLinks() == 0 &&
294 N->getReferrers().size() == N->getGlobals().size()) {
295
296 // Remove the globals from the valuemap, so that the referrer count will go
297 // down to zero.
298 while (!N->getGlobals().empty()) {
299 GlobalValue *GV = N->getGlobals().back();
300 N->getGlobals().pop_back();
301 ValueMap.erase(GV);
302 }
303 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
304 return true;
305 }
306
307 return false;
308}
309
310
311// removeDeadNodes - After the graph has been constructed, this method removes
312// all unreachable nodes that are created because they got merged with other
313// nodes in the graph. These nodes will all be trivially unreachable, so we
314// don't have to perform any non-trivial analysis here.
315//
316void DSGraph::removeDeadNodes() {
317 for (unsigned i = 0; i != Nodes.size(); ++i)
318 if (isNodeDead(Nodes[i])) { // This node is dead!
319 delete Nodes[i]; // Free memory...
320 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
321 }
322
323 // Remove identical function calls
324 unsigned NumFns = FunctionCalls.size();
325 std::sort(FunctionCalls.begin(), FunctionCalls.end());
326 FunctionCalls.erase(std::unique(FunctionCalls.begin(), FunctionCalls.end()),
327 FunctionCalls.end());
328
329 DEBUG(if (NumFns != FunctionCalls.size())
330 std::cerr << "Merged " << (NumFns-FunctionCalls.size())
331 << " call nodes in " << Func.getName() << "\n";);
332}
333
334
335// maskNodeTypes - Apply a mask to all of the node types in the graph. This
336// is useful for clearing out markers like Scalar or Incomplete.
337//
338void DSGraph::maskNodeTypes(unsigned char Mask) {
339 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
340 Nodes[i]->NodeType &= Mask;
341}
342
343
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000344//===----------------------------------------------------------------------===//
345// LocalDataStructures Implementation
346//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000347
348// releaseMemory - If the pass pipeline is done with this pass, we can release
349// our memory... here...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000350//
351void LocalDataStructures::releaseMemory() {
352 for (std::map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
353 E = DSInfo.end(); I != E; ++I)
354 delete I->second;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000355
356 // Empty map so next time memory is released, data structures are not
357 // re-deleted.
358 DSInfo.clear();
359}
360
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000361bool LocalDataStructures::run(Module &M) {
362 // Calculate all of the graphs...
363 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000364 if (!I->isExternal())
365 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000366
367 return false;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000368}