blob: befbd55040c300ddcfcf8ce0fe443077497660c9 [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"
Chris Lattnere2219762002-07-18 18:22:40 +000011#include "Support/STLExtras.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000012#include <algorithm>
Chris Lattnere2219762002-07-18 18:22:40 +000013#include <set>
Chris Lattner0d9bab82002-07-18 00:12:30 +000014#include "llvm/Analysis/DataStructure.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000015
Chris Lattnere2219762002-07-18 18:22:40 +000016using std::vector;
17
Chris Lattnerc68c31b2002-07-10 22:38:08 +000018AnalysisID LocalDataStructures::ID(AnalysisID::create<LocalDataStructures>());
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000019
20//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000021// DSNode Implementation
22//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000023
Chris Lattnerc68c31b2002-07-10 22:38:08 +000024DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
25 // If this node has any fields, allocate them now, but leave them null.
26 switch (T->getPrimitiveID()) {
27 case Type::PointerTyID: Links.resize(1); break;
28 case Type::ArrayTyID: Links.resize(1); break;
29 case Type::StructTyID:
30 Links.resize(cast<StructType>(T)->getNumContainedTypes());
31 break;
32 default: break;
33 }
34}
35
Chris Lattner0d9bab82002-07-18 00:12:30 +000036// DSNode copy constructor... do not copy over the referrers list!
37DSNode::DSNode(const DSNode &N)
38 : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
39}
40
Chris Lattnerc68c31b2002-07-10 22:38:08 +000041void DSNode::removeReferrer(DSNodeHandle *H) {
42 // Search backwards, because we depopulate the list from the back for
43 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000044 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000045 std::find(Referrers.rbegin(), Referrers.rend(), H);
46 assert(I != Referrers.rend() && "Referrer not pointing to node!");
47 Referrers.erase(I.base()-1);
48}
49
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000050// addGlobal - Add an entry for a global value to the Globals list. This also
51// marks the node with the 'G' flag if it does not already have it.
52//
53void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000054 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000055 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000056 std::lower_bound(Globals.begin(), Globals.end(), GV);
57
58 if (I == Globals.end() || *I != GV) {
59 assert(GV->getType()->getElementType() == Ty);
60 Globals.insert(I, GV);
61 NodeType |= GlobalNode;
62 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000063}
64
65
Chris Lattnerc68c31b2002-07-10 22:38:08 +000066// addEdgeTo - Add an edge from the current node to the specified node. This
67// can cause merging of nodes in the graph.
68//
69void DSNode::addEdgeTo(unsigned LinkNo, DSNode *N) {
70 assert(LinkNo < Links.size() && "LinkNo out of range!");
71 if (N == 0 || Links[LinkNo] == N) return; // Nothing to do
72 if (Links[LinkNo] == 0) { // No merging to perform
73 Links[LinkNo] = N;
74 return;
75 }
76
77 // Merge the two nodes...
78 Links[LinkNo]->mergeWith(N);
79}
80
81
82// mergeWith - Merge this node into the specified node, moving all links to and
83// from the argument node into the current node. The specified node may be a
84// null pointer (in which case, nothing happens).
85//
86void DSNode::mergeWith(DSNode *N) {
87 if (N == 0 || N == this) return; // Noop
88 assert(N->Ty == Ty && N->Links.size() == Links.size() &&
89 "Cannot merge nodes of two different types!");
90
91 // Remove all edges pointing at N, causing them to point to 'this' instead.
92 while (!N->Referrers.empty())
93 *N->Referrers.back() = this;
94
95 // Make all of the outgoing links of N now be outgoing links of this. This
96 // can cause recursive merging!
97 //
98 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
99 addEdgeTo(i, N->Links[i]);
100 N->Links[i] = 0; // Reduce unneccesary edges in graph. N is dead
101 }
102
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000103 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000104 NodeType |= N->NodeType;
105 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000106
107 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000108 if (!N->Globals.empty()) {
109 // Save the current globals off to the side...
Chris Lattnere2219762002-07-18 18:22:40 +0000110 vector<GlobalValue*> OldGlobals(Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000111
112 // Resize the globals vector to be big enough to hold both of them...
113 Globals.resize(Globals.size()+N->Globals.size());
114
115 // Merge the two sorted globals lists together...
116 std::merge(OldGlobals.begin(), OldGlobals.end(),
117 N->Globals.begin(), N->Globals.end(), Globals.begin());
118
119 // Erase duplicate entries from the globals list...
120 Globals.erase(std::unique(Globals.begin(), Globals.end()), Globals.end());
121
122 // Delete the globals from the old node...
123 N->Globals.clear();
124 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000125}
126
127//===----------------------------------------------------------------------===//
128// DSGraph Implementation
129//===----------------------------------------------------------------------===//
130
Chris Lattner0d9bab82002-07-18 00:12:30 +0000131DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000132 std::map<const DSNode*, DSNode*> NodeMap; // ignored
133 RetNode = cloneInto(G, ValueMap, NodeMap, false);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000134}
135
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000136DSGraph::~DSGraph() {
137 FunctionCalls.clear();
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000138 OrigFunctionCalls.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000139 ValueMap.clear();
140 RetNode = 0;
141
142#ifndef NDEBUG
143 // Drop all intra-node references, so that assertions don't fail...
144 std::for_each(Nodes.begin(), Nodes.end(),
145 std::mem_fun(&DSNode::dropAllReferences));
146#endif
147
148 // Delete all of the nodes themselves...
149 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
150}
151
Chris Lattner0d9bab82002-07-18 00:12:30 +0000152// dump - Allow inspection of graph in a debugger.
153void DSGraph::dump() const { print(std::cerr); }
154
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000155
Chris Lattner0d9bab82002-07-18 00:12:30 +0000156// cloneInto - Clone the specified DSGraph into the current graph, returning the
157// Return node of the graph. The translated ValueMap for the old function is
158// filled into the OldValMap member. If StripLocals is set to true, Scalar and
159// Alloca markers are removed from the graph, as the graph is being cloned into
160// a calling function's graph.
161//
162DSNode *DSGraph::cloneInto(const DSGraph &G,
163 std::map<Value*, DSNodeHandle> &OldValMap,
Chris Lattnere2219762002-07-18 18:22:40 +0000164 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner0d9bab82002-07-18 00:12:30 +0000165 bool StripLocals) {
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000166
167 assert(OldNodeMap.size()==0 && "Return argument OldNodeMap should be empty");
168
169 OldNodeMap[0] = 0; // Null pointer maps to null
Chris Lattner0d9bab82002-07-18 00:12:30 +0000170
171 unsigned FN = Nodes.size(); // FirstNode...
172
173 // Duplicate all of the nodes, populating the node map...
174 Nodes.reserve(FN+G.Nodes.size());
175 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
176 DSNode *Old = G.Nodes[i], *New = new DSNode(*Old);
177 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000178 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000179 }
180
181 // Rewrite the links in the nodes to point into the current graph now.
182 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
183 for (unsigned j = 0, e = Nodes[i]->getNumLinks(); j != e; ++j)
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000184 Nodes[i]->setLink(j, OldNodeMap[Nodes[i]->getLink(j)]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000185
186 // If we are inlining this graph into the called function graph, remove local
187 // markers.
188 if (StripLocals)
189 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
190 Nodes[i]->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
191
192 // Copy the value map...
193 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
194 E = G.ValueMap.end(); I != E; ++I)
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000195 OldValMap[I->first] = OldNodeMap[I->second];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000196
Chris Lattnere2219762002-07-18 18:22:40 +0000197 // Copy the function calls list...
198 unsigned FC = FunctionCalls.size(); // FirstCall
199 FunctionCalls.reserve(FC+G.FunctionCalls.size());
200 for (unsigned i = 0, e = G.FunctionCalls.size(); i != e; ++i) {
201 FunctionCalls.push_back(std::vector<DSNodeHandle>());
202 FunctionCalls[FC+i].reserve(G.FunctionCalls[i].size());
203 for (unsigned j = 0, e = G.FunctionCalls[i].size(); j != e; ++j)
204 FunctionCalls[FC+i].push_back(OldNodeMap[G.FunctionCalls[i][j]]);
205 }
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000206
207 // Copy the list of unresolved callers
208 PendingCallers.insert(PendingCallers.end(),
209 G.PendingCallers.begin(), G.PendingCallers.end());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000210
211 // Return the returned node pointer...
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000212 return OldNodeMap[G.RetNode];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000213}
214
215
216// markIncompleteNodes - Mark the specified node as having contents that are not
217// known with the current analysis we have performed. Because a node makes all
218// of the nodes it can reach imcomplete if the node itself is incomplete, we
219// must recursively traverse the data structure graph, marking all reachable
220// nodes as incomplete.
221//
222static void markIncompleteNode(DSNode *N) {
223 // Stop recursion if no node, or if node already marked...
224 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
225
226 // Actually mark the node
227 N->NodeType |= DSNode::Incomplete;
228
229 // Recusively process children...
230 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
231 markIncompleteNode(N->getLink(i));
232}
233
234
235// markIncompleteNodes - Traverse the graph, identifying nodes that may be
236// modified by other functions that have not been resolved yet. This marks
237// nodes that are reachable through three sources of "unknownness":
238//
239// Global Variables, Function Calls, and Incoming Arguments
240//
241// For any node that may have unknown components (because something outside the
242// scope of current analysis may have modified it), the 'Incomplete' flag is
243// added to the NodeType.
244//
245void DSGraph::markIncompleteNodes() {
246 // Mark any incoming arguments as incomplete...
247 for (Function::aiterator I = Func.abegin(), E = Func.aend(); I != E; ++I)
248 if (isa<PointerType>(I->getType()))
249 markIncompleteNode(ValueMap[I]->getLink(0));
250
251 // Mark stuff passed into functions calls as being incomplete...
252 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattnere2219762002-07-18 18:22:40 +0000253 vector<DSNodeHandle> &Args = FunctionCalls[i];
254 // Then the return value is certainly incomplete!
255 markIncompleteNode(Args[0]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000256
257 // The call does not make the function argument incomplete...
258
259 // All arguments to the function call are incomplete though!
260 for (unsigned i = 2, e = Args.size(); i != e; ++i)
261 markIncompleteNode(Args[i]);
262 }
263
Chris Lattner055dc2c2002-07-18 15:54:42 +0000264 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000265 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner055dc2c2002-07-18 15:54:42 +0000266 if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000267 DSNode *N = Nodes[i];
268 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
269 markIncompleteNode(N->getLink(i));
270 }
271}
272
273// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
274// checks to see if there are simple transformations that it can do to make it
275// dead.
276//
277bool DSGraph::isNodeDead(DSNode *N) {
278 // Is it a trivially dead shadow node...
279 if (N->getReferrers().empty() && N->NodeType == 0)
280 return true;
281
282 // Is it a function node or some other trivially unused global?
283 if ((N->NodeType & ~DSNode::GlobalNode) == 0 &&
284 N->getNumLinks() == 0 &&
285 N->getReferrers().size() == N->getGlobals().size()) {
286
287 // Remove the globals from the valuemap, so that the referrer count will go
288 // down to zero.
289 while (!N->getGlobals().empty()) {
290 GlobalValue *GV = N->getGlobals().back();
291 N->getGlobals().pop_back();
292 ValueMap.erase(GV);
293 }
294 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
295 return true;
296 }
297
298 return false;
299}
300
301
Chris Lattnere2219762002-07-18 18:22:40 +0000302// removeTriviallyDeadNodes - After the graph has been constructed, this method
303// removes all unreachable nodes that are created because they got merged with
304// other nodes in the graph. These nodes will all be trivially unreachable, so
305// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000306//
Chris Lattnere2219762002-07-18 18:22:40 +0000307void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000308 for (unsigned i = 0; i != Nodes.size(); ++i)
309 if (isNodeDead(Nodes[i])) { // This node is dead!
310 delete Nodes[i]; // Free memory...
311 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
312 }
313
Chris Lattnere2219762002-07-18 18:22:40 +0000314 // Remove trivially identical function calls
Chris Lattner0d9bab82002-07-18 00:12:30 +0000315 unsigned NumFns = FunctionCalls.size();
316 std::sort(FunctionCalls.begin(), FunctionCalls.end());
317 FunctionCalls.erase(std::unique(FunctionCalls.begin(), FunctionCalls.end()),
318 FunctionCalls.end());
319
320 DEBUG(if (NumFns != FunctionCalls.size())
321 std::cerr << "Merged " << (NumFns-FunctionCalls.size())
322 << " call nodes in " << Func.getName() << "\n";);
323}
324
325
Chris Lattnere2219762002-07-18 18:22:40 +0000326// markAlive - Simple graph traverser that recursively walks the graph marking
327// stuff to be alive.
328//
329static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
330 if (N == 0 || Alive.count(N)) return;
331
332 Alive.insert(N);
333 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
334 markAlive(N->getLink(i), Alive);
335}
336
337
338// removeDeadNodes - Use a more powerful reachability analysis to eliminate
339// subgraphs that are unreachable. This often occurs because the data
340// structure doesn't "escape" into it's caller, and thus should be eliminated
341// from the caller's graph entirely. This is only appropriate to use when
342// inlining graphs.
343//
344void DSGraph::removeDeadNodes() {
345 // Reduce the amount of work we have to do...
346 removeTriviallyDeadNodes();
347
348 // FIXME: Merge nontrivially identical call nodes...
349
350 // Alive - a set that holds all nodes found to be reachable/alive.
351 std::set<DSNode*> Alive;
352
353 // Mark all nodes reachable by call nodes as alive...
354 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
355 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
356 markAlive(FunctionCalls[i][j], Alive);
357
358 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
359 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
360 markAlive(OrigFunctionCalls[i][j], Alive);
361
362 // Mark all nodes reachable by scalar, global, or incomplete nodes as
363 // reachable...
364 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
365 if (Nodes[i]->NodeType & (DSNode::ScalarNode | DSNode::GlobalNode))
366 markAlive(Nodes[i], Alive);
367
368 // Loop over all unreachable nodes, dropping their references...
369 std::vector<DSNode*> DeadNodes;
370 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
371 for (unsigned i = 0; i != Nodes.size(); ++i)
372 if (!Alive.count(Nodes[i])) {
373 DSNode *N = Nodes[i];
374 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
375 DeadNodes.push_back(N); // Add node to our list of dead nodes
376 N->dropAllReferences(); // Drop all outgoing edges
377 }
378
379 // The return value is alive as well...
380 markAlive(RetNode, Alive);
381
382 // Delete all dead nodes...
383 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
384}
385
386
387
Chris Lattner0d9bab82002-07-18 00:12:30 +0000388// maskNodeTypes - Apply a mask to all of the node types in the graph. This
389// is useful for clearing out markers like Scalar or Incomplete.
390//
391void DSGraph::maskNodeTypes(unsigned char Mask) {
392 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
393 Nodes[i]->NodeType &= Mask;
394}
395
396
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000397//===----------------------------------------------------------------------===//
398// LocalDataStructures Implementation
399//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000400
401// releaseMemory - If the pass pipeline is done with this pass, we can release
402// our memory... here...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000403//
404void LocalDataStructures::releaseMemory() {
405 for (std::map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
406 E = DSInfo.end(); I != E; ++I)
407 delete I->second;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000408
409 // Empty map so next time memory is released, data structures are not
410 // re-deleted.
411 DSInfo.clear();
412}
413
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000414bool LocalDataStructures::run(Module &M) {
415 // Calculate all of the graphs...
416 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000417 if (!I->isExternal())
418 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000419
420 return false;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000421}