blob: 84cb3e9da97ccff26a33e07a0af9c2b733f23ee6 [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>
13#include "llvm/Analysis/DataStructure.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000014
Chris Lattnere2219762002-07-18 18:22:40 +000015using std::vector;
16
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000017//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000018// DSNode Implementation
19//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000020
Chris Lattnerc68c31b2002-07-10 22:38:08 +000021DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
22 // If this node has any fields, allocate them now, but leave them null.
23 switch (T->getPrimitiveID()) {
24 case Type::PointerTyID: Links.resize(1); break;
25 case Type::ArrayTyID: Links.resize(1); break;
26 case Type::StructTyID:
27 Links.resize(cast<StructType>(T)->getNumContainedTypes());
28 break;
29 default: break;
30 }
31}
32
Chris Lattner0d9bab82002-07-18 00:12:30 +000033// DSNode copy constructor... do not copy over the referrers list!
34DSNode::DSNode(const DSNode &N)
35 : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
36}
37
Chris Lattnerc68c31b2002-07-10 22:38:08 +000038void DSNode::removeReferrer(DSNodeHandle *H) {
39 // Search backwards, because we depopulate the list from the back for
40 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000041 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000042 std::find(Referrers.rbegin(), Referrers.rend(), H);
43 assert(I != Referrers.rend() && "Referrer not pointing to node!");
44 Referrers.erase(I.base()-1);
45}
46
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000047// addGlobal - Add an entry for a global value to the Globals list. This also
48// marks the node with the 'G' flag if it does not already have it.
49//
50void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000051 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000052 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000053 std::lower_bound(Globals.begin(), Globals.end(), GV);
54
55 if (I == Globals.end() || *I != GV) {
56 assert(GV->getType()->getElementType() == Ty);
57 Globals.insert(I, GV);
58 NodeType |= GlobalNode;
59 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000060}
61
62
Chris Lattnerc68c31b2002-07-10 22:38:08 +000063// addEdgeTo - Add an edge from the current node to the specified node. This
64// can cause merging of nodes in the graph.
65//
66void DSNode::addEdgeTo(unsigned LinkNo, DSNode *N) {
67 assert(LinkNo < Links.size() && "LinkNo out of range!");
68 if (N == 0 || Links[LinkNo] == N) return; // Nothing to do
69 if (Links[LinkNo] == 0) { // No merging to perform
70 Links[LinkNo] = N;
71 return;
72 }
73
74 // Merge the two nodes...
75 Links[LinkNo]->mergeWith(N);
76}
77
78
79// mergeWith - Merge this node into the specified node, moving all links to and
80// from the argument node into the current node. The specified node may be a
81// null pointer (in which case, nothing happens).
82//
83void DSNode::mergeWith(DSNode *N) {
84 if (N == 0 || N == this) return; // Noop
85 assert(N->Ty == Ty && N->Links.size() == Links.size() &&
86 "Cannot merge nodes of two different types!");
87
88 // Remove all edges pointing at N, causing them to point to 'this' instead.
89 while (!N->Referrers.empty())
90 *N->Referrers.back() = this;
91
92 // Make all of the outgoing links of N now be outgoing links of this. This
93 // can cause recursive merging!
94 //
95 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
96 addEdgeTo(i, N->Links[i]);
97 N->Links[i] = 0; // Reduce unneccesary edges in graph. N is dead
98 }
99
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000100 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000101 NodeType |= N->NodeType;
102 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000103
104 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000105 if (!N->Globals.empty()) {
106 // Save the current globals off to the side...
Chris Lattnere2219762002-07-18 18:22:40 +0000107 vector<GlobalValue*> OldGlobals(Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000108
109 // Resize the globals vector to be big enough to hold both of them...
110 Globals.resize(Globals.size()+N->Globals.size());
111
112 // Merge the two sorted globals lists together...
113 std::merge(OldGlobals.begin(), OldGlobals.end(),
114 N->Globals.begin(), N->Globals.end(), Globals.begin());
115
116 // Erase duplicate entries from the globals list...
117 Globals.erase(std::unique(Globals.begin(), Globals.end()), Globals.end());
118
119 // Delete the globals from the old node...
120 N->Globals.clear();
121 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000122}
123
124//===----------------------------------------------------------------------===//
125// DSGraph Implementation
126//===----------------------------------------------------------------------===//
127
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000128DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(G.GlobalsGraph){
129 GlobalsGraph->addReference(this);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000130 std::map<const DSNode*, DSNode*> NodeMap; // ignored
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000131 RetNode = cloneInto(G, ValueMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000132}
133
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000134DSGraph::~DSGraph() {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000135 GlobalsGraph->removeReference(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000136 FunctionCalls.clear();
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000137 OrigFunctionCalls.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000138 ValueMap.clear();
139 RetNode = 0;
140
141#ifndef NDEBUG
142 // Drop all intra-node references, so that assertions don't fail...
143 std::for_each(Nodes.begin(), Nodes.end(),
144 std::mem_fun(&DSNode::dropAllReferences));
145#endif
146
147 // Delete all of the nodes themselves...
148 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
149}
150
Chris Lattner0d9bab82002-07-18 00:12:30 +0000151// dump - Allow inspection of graph in a debugger.
152void DSGraph::dump() const { print(std::cerr); }
153
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000154
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000155// Helper function used to clone a function list.
156// Each call really shd have an explicit representation as a separate class.
157void
158CopyFunctionCallsList(const std::vector<std::vector<DSNodeHandle> >& fromCalls,
159 std::vector<std::vector<DSNodeHandle> >& toCalls,
160 std::map<const DSNode*, DSNode*>& NodeMap) {
161
162 unsigned FC = toCalls.size(); // FirstCall
163 toCalls.reserve(FC+fromCalls.size());
164 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i) {
165 toCalls.push_back(std::vector<DSNodeHandle>());
166 toCalls[FC+i].reserve(fromCalls[i].size());
167 for (unsigned j = 0, ej = fromCalls[i].size(); j != ej; ++j)
168 toCalls[FC+i].push_back(NodeMap[fromCalls[i][j]]);
169 }
170}
171
172
Chris Lattner0d9bab82002-07-18 00:12:30 +0000173// cloneInto - Clone the specified DSGraph into the current graph, returning the
174// Return node of the graph. The translated ValueMap for the old function is
175// filled into the OldValMap member. If StripLocals is set to true, Scalar and
176// Alloca markers are removed from the graph, as the graph is being cloned into
177// a calling function's graph.
178//
179DSNode *DSGraph::cloneInto(const DSGraph &G,
180 std::map<Value*, DSNodeHandle> &OldValMap,
Chris Lattnere2219762002-07-18 18:22:40 +0000181 std::map<const DSNode*, DSNode*> &OldNodeMap,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000182 bool StripScalars, bool StripAllocas,
183 bool CopyCallers, bool CopyOrigCalls) {
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000184
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000185 assert(OldNodeMap.size()==0 && "Return arg. OldNodeMap shd be empty");
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000186
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000187 OldNodeMap[0] = 0; // Null pointer maps to null
Chris Lattner0d9bab82002-07-18 00:12:30 +0000188
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000189 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000190
191 // Duplicate all of the nodes, populating the node map...
192 Nodes.reserve(FN+G.Nodes.size());
193 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
194 DSNode *Old = G.Nodes[i], *New = new DSNode(*Old);
195 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000196 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000197 }
198
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000199 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000200 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
201 for (unsigned j = 0, e = Nodes[i]->getNumLinks(); j != e; ++j)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000202 Nodes[i]->setLink(j, OldNodeMap.find(Nodes[i]->getLink(j))->second);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000203
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000204 // Remove local markers as specified
205 if (StripScalars || StripAllocas) {
206 char keepBits = ~((StripScalars? DSNode::ScalarNode : 0) |
207 (StripAllocas? DSNode::AllocaNode : 0));
Chris Lattner0d9bab82002-07-18 00:12:30 +0000208 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000209 Nodes[i]->NodeType &= keepBits;
210 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000211
212 // Copy the value map...
213 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
214 E = G.ValueMap.end(); I != E; ++I)
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000215 OldValMap[I->first] = OldNodeMap[I->second];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000216
Chris Lattnere2219762002-07-18 18:22:40 +0000217 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000218 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
219 if (CopyOrigCalls)
220 CopyFunctionCallsList(G.OrigFunctionCalls, OrigFunctionCalls, OldNodeMap);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000221
222 // Copy the list of unresolved callers
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000223 if (CopyCallers)
224 PendingCallers.insert(G.PendingCallers.begin(), G.PendingCallers.end());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000225
226 // Return the returned node pointer...
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000227 return OldNodeMap[G.RetNode];
Chris Lattner0d9bab82002-07-18 00:12:30 +0000228}
229
230
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000231// cloneGlobalInto - Clone the given global node and all its target links
232// (and all their llinks, recursively).
233//
234DSNode* DSGraph::cloneGlobalInto(const DSNode* GNode) {
235 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
236
237 // If a clone has already been created for GNode, return it.
238 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
239 if (ValMapEntry != 0)
240 return ValMapEntry;
241
242 // Clone the node and update the ValMap.
243 DSNode* NewNode = new DSNode(*GNode);
244 ValMapEntry = NewNode; // j=0 case of loop below!
245 Nodes.push_back(NewNode);
246 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
247 ValueMap[NewNode->getGlobals()[j]] = NewNode;
248
249 // Rewrite the links in the new node to point into the current graph.
250 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
251 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
252
253 return NewNode;
254}
255
256
Chris Lattner0d9bab82002-07-18 00:12:30 +0000257// markIncompleteNodes - Mark the specified node as having contents that are not
258// known with the current analysis we have performed. Because a node makes all
259// of the nodes it can reach imcomplete if the node itself is incomplete, we
260// must recursively traverse the data structure graph, marking all reachable
261// nodes as incomplete.
262//
263static void markIncompleteNode(DSNode *N) {
264 // Stop recursion if no node, or if node already marked...
265 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
266
267 // Actually mark the node
268 N->NodeType |= DSNode::Incomplete;
269
270 // Recusively process children...
271 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
272 markIncompleteNode(N->getLink(i));
273}
274
275
276// markIncompleteNodes - Traverse the graph, identifying nodes that may be
277// modified by other functions that have not been resolved yet. This marks
278// nodes that are reachable through three sources of "unknownness":
279//
280// Global Variables, Function Calls, and Incoming Arguments
281//
282// For any node that may have unknown components (because something outside the
283// scope of current analysis may have modified it), the 'Incomplete' flag is
284// added to the NodeType.
285//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000286void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000287 // Mark any incoming arguments as incomplete...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000288 if (markFormalArgs)
289 for (Function::aiterator I = Func.abegin(), E = Func.aend(); I != E; ++I)
290 if (isa<PointerType>(I->getType()))
291 markIncompleteNode(ValueMap[I]->getLink(0));
Chris Lattner0d9bab82002-07-18 00:12:30 +0000292
293 // Mark stuff passed into functions calls as being incomplete...
294 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattnere2219762002-07-18 18:22:40 +0000295 vector<DSNodeHandle> &Args = FunctionCalls[i];
296 // Then the return value is certainly incomplete!
297 markIncompleteNode(Args[0]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000298
299 // The call does not make the function argument incomplete...
300
301 // All arguments to the function call are incomplete though!
302 for (unsigned i = 2, e = Args.size(); i != e; ++i)
303 markIncompleteNode(Args[i]);
304 }
305
Chris Lattner055dc2c2002-07-18 15:54:42 +0000306 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000307 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattner055dc2c2002-07-18 15:54:42 +0000308 if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000309 DSNode *N = Nodes[i];
310 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
311 markIncompleteNode(N->getLink(i));
312 }
313}
314
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000315// removeRefsToGlobal - Helper function that removes globals from the
316// ValueMap so that the referrer count will go down to zero.
317static void
318removeRefsToGlobal(DSNode* N, std::map<Value*, DSNodeHandle>& ValueMap) {
319 while (!N->getGlobals().empty()) {
320 GlobalValue *GV = N->getGlobals().back();
321 N->getGlobals().pop_back();
322 ValueMap.erase(GV);
323 }
324}
325
326
Chris Lattner0d9bab82002-07-18 00:12:30 +0000327// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
328// checks to see if there are simple transformations that it can do to make it
329// dead.
330//
331bool DSGraph::isNodeDead(DSNode *N) {
332 // Is it a trivially dead shadow node...
333 if (N->getReferrers().empty() && N->NodeType == 0)
334 return true;
335
336 // Is it a function node or some other trivially unused global?
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000337 if (N->NodeType != 0 &&
338 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000339 N->getNumLinks() == 0 &&
340 N->getReferrers().size() == N->getGlobals().size()) {
341
342 // Remove the globals from the valuemap, so that the referrer count will go
343 // down to zero.
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000344 removeRefsToGlobal(N, ValueMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000345 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
346 return true;
347 }
348
349 return false;
350}
351
Chris Lattner7541b892002-07-31 19:32:12 +0000352static void removeIdenticalCalls(std::vector<std::vector<DSNodeHandle> > &Calls,
353 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000354 // Remove trivially identical function calls
355 unsigned NumFns = Calls.size();
356 std::sort(Calls.begin(), Calls.end());
357 Calls.erase(std::unique(Calls.begin(), Calls.end()),
358 Calls.end());
359
360 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000361 std::cerr << "Merged " << (NumFns-Calls.size())
362 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000363}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000364
Chris Lattnere2219762002-07-18 18:22:40 +0000365// removeTriviallyDeadNodes - After the graph has been constructed, this method
366// removes all unreachable nodes that are created because they got merged with
367// other nodes in the graph. These nodes will all be trivially unreachable, so
368// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000369//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000370void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000371 for (unsigned i = 0; i != Nodes.size(); ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000372 if (! KeepAllGlobals || ! (Nodes[i]->NodeType & DSNode::GlobalNode))
373 if (isNodeDead(Nodes[i])) { // This node is dead!
374 delete Nodes[i]; // Free memory...
375 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
376 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000377
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000378 removeIdenticalCalls(FunctionCalls, Func.getName());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000379}
380
381
Chris Lattnere2219762002-07-18 18:22:40 +0000382// markAlive - Simple graph traverser that recursively walks the graph marking
383// stuff to be alive.
384//
385static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000386 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000387
388 Alive.insert(N);
389 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000390 if (N->getLink(i) && !Alive.count(N->getLink(i)))
391 markAlive(N->getLink(i), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000392}
393
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000394static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
395 std::set<DSNode*> &Visiting) {
396 if (N == 0) return false;
397
398 if (Visiting.count(N) > 0) return false; // terminate recursion on a cycle
399 Visiting.insert(N);
400
401 // If any immediate successor is alive, N is alive
402 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
403 if (N->getLink(i) && Alive.count(N->getLink(i)))
404 { Visiting.erase(N); return true; }
405
406 // Else if any successor reaches a live node, N is alive
407 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
408 if (N->getLink(i) && checkGlobalAlive(N->getLink(i), Alive, Visiting))
409 { Visiting.erase(N); return true; }
410
411 Visiting.erase(N);
412 return false;
413}
414
415
416// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
417// This would be unnecessary if function calls were real nodes! In that case,
418// the simple iterative loop in the first few lines below suffice.
419//
420static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
421 std::vector<std::vector<DSNodeHandle> > &Calls,
422 std::set<DSNode*> &Alive,
423 bool FilterCalls) {
424
425 // Iterate, marking globals or cast nodes alive until no new live nodes
426 // are added to Alive
427 std::set<DSNode*> Visiting; // Used to identify cycles
428 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
429 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
430 liveCount = Alive.size();
431 for ( ; I != E; ++I)
432 if (Alive.count(*I) == 0) {
433 Visiting.clear();
434 if (checkGlobalAlive(*I, Alive, Visiting))
435 markAlive(*I, Alive);
436 }
437 }
438
439 // Find function calls with some dead and some live nodes.
440 // Since all call nodes must be live if any one is live, we have to mark
441 // all nodes of the call as live and continue the iteration (via recursion).
442 if (FilterCalls) {
443 bool recurse = false;
444 for (int i = 0, ei = Calls.size(); i < ei; ++i) {
445 bool CallIsDead = true, CallHasDeadArg = false;
446 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j) {
447 bool argIsDead = Calls[i][j] == 0 || Alive.count(Calls[i][j]) == 0;
448 CallHasDeadArg = CallHasDeadArg || (Calls[i][j] != 0 && argIsDead);
449 CallIsDead = CallIsDead && argIsDead;
450 }
451 if (!CallIsDead && CallHasDeadArg) {
452 // Some node in this call is live and another is dead.
453 // Mark all nodes of call as live and iterate once more.
454 recurse = true;
455 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j)
456 markAlive(Calls[i][j], Alive);
457 }
458 }
459 if (recurse)
460 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
461 }
462}
463
464
465// markGlobalsAlive - Mark global nodes and cast nodes alive if they
466// can reach any other live node. Since this can produce new live nodes,
467// we use a simple iterative algorithm.
468//
469static void markGlobalsAlive(DSGraph& G, std::set<DSNode*> &Alive,
470 bool FilterCalls) {
471 // Add global and cast nodes to a set so we don't walk all nodes every time
472 std::set<DSNode*> GlobalNodes;
473 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
474 if (G.getNodes()[i]->NodeType & (DSNode::CastNode | DSNode::GlobalNode))
475 GlobalNodes.insert(G.getNodes()[i]);
476
477 // Add all call nodes to the same set
478 std::vector<std::vector<DSNodeHandle> > &Calls = G.getFunctionCalls();
479 if (FilterCalls) {
480 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
481 for (unsigned j = 0, e = Calls[i].size(); j != e; ++j)
482 if (Calls[i][j])
483 GlobalNodes.insert(Calls[i][j]);
484 }
485
486 // Iterate and recurse until no new live node are discovered.
487 // This would be a simple iterative loop if function calls were real nodes!
488 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
489
490 // Free up references to dead globals from the ValueMap
491 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
492 for( ; I != E; ++I)
493 if (Alive.count(*I) == 0)
494 removeRefsToGlobal(*I, G.getValueMap());
495
496 // Delete dead function calls
497 if (FilterCalls)
498 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
499 bool CallIsDead = true;
500 for (unsigned j = 0, ej= Calls[i].size(); CallIsDead && j != ej; ++j)
501 CallIsDead = (Alive.count(Calls[i][j]) == 0);
502 if (CallIsDead)
503 Calls.erase(Calls.begin() + i); // remove the call entirely
504 }
505}
Chris Lattnere2219762002-07-18 18:22:40 +0000506
507// removeDeadNodes - Use a more powerful reachability analysis to eliminate
508// subgraphs that are unreachable. This often occurs because the data
509// structure doesn't "escape" into it's caller, and thus should be eliminated
510// from the caller's graph entirely. This is only appropriate to use when
511// inlining graphs.
512//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000513void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
514 assert((!KeepAllGlobals || KeepCalls) &&
515 "KeepAllGlobals without KeepCalls is meaningless");
516
Chris Lattnere2219762002-07-18 18:22:40 +0000517 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000518 removeTriviallyDeadNodes(KeepAllGlobals);
519
Chris Lattnere2219762002-07-18 18:22:40 +0000520 // FIXME: Merge nontrivially identical call nodes...
521
522 // Alive - a set that holds all nodes found to be reachable/alive.
523 std::set<DSNode*> Alive;
524
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000525 // If KeepCalls, mark all nodes reachable by call nodes as alive...
526 if (KeepCalls)
527 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
528 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
529 markAlive(FunctionCalls[i][j], Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000530
531 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
532 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
533 markAlive(OrigFunctionCalls[i][j], Alive);
534
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000535 // Mark all nodes reachable by scalar nodes (and global nodes, if
536 // keeping them was specified) as alive...
537 char keepBits = DSNode::ScalarNode | (KeepAllGlobals? DSNode::GlobalNode : 0);
Chris Lattnere2219762002-07-18 18:22:40 +0000538 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000539 if (Nodes[i]->NodeType & keepBits)
Chris Lattnere2219762002-07-18 18:22:40 +0000540 markAlive(Nodes[i], Alive);
541
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000542 // The return value is alive as well...
543 markAlive(RetNode, Alive);
544
545 // Mark all globals or cast nodes that can reach a live node as alive.
546 // This also marks all nodes reachable from such nodes as alive.
547 // Of course, if KeepAllGlobals is specified, they would be live already.
548 if (! KeepAllGlobals)
549 markGlobalsAlive(*this, Alive, ! KeepCalls);
550
Chris Lattnere2219762002-07-18 18:22:40 +0000551 // Loop over all unreachable nodes, dropping their references...
552 std::vector<DSNode*> DeadNodes;
553 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
554 for (unsigned i = 0; i != Nodes.size(); ++i)
555 if (!Alive.count(Nodes[i])) {
556 DSNode *N = Nodes[i];
557 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
558 DeadNodes.push_back(N); // Add node to our list of dead nodes
559 N->dropAllReferences(); // Drop all outgoing edges
560 }
561
Chris Lattnere2219762002-07-18 18:22:40 +0000562 // Delete all dead nodes...
563 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
564}
565
566
567
Chris Lattner0d9bab82002-07-18 00:12:30 +0000568// maskNodeTypes - Apply a mask to all of the node types in the graph. This
569// is useful for clearing out markers like Scalar or Incomplete.
570//
571void DSGraph::maskNodeTypes(unsigned char Mask) {
572 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
573 Nodes[i]->NodeType &= Mask;
574}
575
576
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000577//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000578// GlobalDSGraph Implementation
579//===----------------------------------------------------------------------===//
580
581GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
582}
583
584GlobalDSGraph::~GlobalDSGraph() {
585 assert(Referrers.size() == 0 &&
586 "Deleting global graph while references from other graphs exist");
587}
588
589void GlobalDSGraph::addReference(const DSGraph* referrer) {
590 if (referrer != this)
591 Referrers.insert(referrer);
592}
593
594void GlobalDSGraph::removeReference(const DSGraph* referrer) {
595 if (referrer != this) {
596 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
597 Referrers.erase(referrer);
598 if (Referrers.size() == 0)
599 delete this;
600 }
601}
602
603// Bits used in the next function
604static const char ExternalTypeBits = (DSNode::GlobalNode | DSNode::NewNode |
605 DSNode::SubElement | DSNode::CastNode);
606
607
608// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
609// visible target links (and recursively their such links) into this graph.
610// NodeCache maps the node being cloned to its clone in the Globals graph,
611// in order to track cycles.
612// GlobalsAreFinal is a flag that says whether it is safe to assume that
613// an existing global node is complete. This is important to avoid
614// reinserting all globals when inserting Calls to functions.
615// This is a helper function for cloneGlobals and cloneCalls.
616//
617DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
618 std::map<const DSNode*, DSNode*> &NodeCache,
619 bool GlobalsAreFinal) {
620 if (OldNode == 0) return 0;
621
622 // The caller should check this is an external node. Just more efficient...
623 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
624
625 // If a clone has already been created for OldNode, return it.
626 DSNode*& CacheEntry = NodeCache[OldNode];
627 if (CacheEntry != 0)
628 return CacheEntry;
629
630 // The result value...
631 DSNode* NewNode = 0;
632
633 // If nodes already exist for any of the globals of OldNode,
634 // merge all such nodes together since they are merged in OldNode.
635 // If ValueCacheIsFinal==true, look for an existing node that has
636 // an identical list of globals and return it if it exists.
637 //
638 for (unsigned j = 0, N = OldNode->getGlobals().size(); j < N; ++j)
639 if (DSNode* PrevNode = ValueMap[OldNode->getGlobals()[j]]) {
640 if (NewNode == 0) {
641 NewNode = PrevNode; // first existing node found
642 if (GlobalsAreFinal && j == 0)
643 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
644 CacheEntry = NewNode;
645 return NewNode;
646 }
647 }
648 else if (NewNode != PrevNode) { // found another, different from prev
649 // update ValMap *before* merging PrevNode into NewNode
650 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
651 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
652 NewNode->mergeWith(PrevNode);
653 }
654 } else if (NewNode != 0) {
655 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
656 }
657
658 // If no existing node was found, clone the node and update the ValMap.
659 if (NewNode == 0) {
660 NewNode = new DSNode(*OldNode);
661 Nodes.push_back(NewNode);
662 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
663 NewNode->setLink(j, 0);
664 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
665 ValueMap[NewNode->getGlobals()[j]] = NewNode;
666 }
667 else
668 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
669
670 // Add the entry to NodeCache
671 CacheEntry = NewNode;
672
673 // Rewrite the links in the new node to point into the current graph,
674 // but only for links to external nodes. Set other links to NULL.
675 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
676 DSNode* OldTarget = OldNode->getLink(j);
677 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
678 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
679 if (NewNode->getLink(j))
680 NewNode->getLink(j)->mergeWith(NewLink);
681 else
682 NewNode->setLink(j, NewLink);
683 }
684 }
685
686 // Remove all local markers
687 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
688
689 return NewNode;
690}
691
692
693// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
694// visible target links (and recursively their such links) into this graph.
695//
696void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
697 std::map<const DSNode*, DSNode*> NodeCache;
698 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
699 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
700 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
701
702 if (CloneCalls)
703 GlobalsGraph->cloneCalls(Graph);
704
705 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
706}
707
708
709// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
710// links (and recursively their such links) into this graph.
711//
712void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
713 std::map<const DSNode*, DSNode*> NodeCache;
714 std::vector<std::vector<DSNodeHandle> >& FromCalls =Graph.FunctionCalls;
715
716 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
717
718 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
719 FunctionCalls.push_back(std::vector<DSNodeHandle>());
720 FunctionCalls.back().reserve(FromCalls[i].size());
721 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
722 FunctionCalls.back().push_back
723 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
724 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
725 : 0);
726 }
727
728 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +0000729 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000730}
731
732
733//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000734// LocalDataStructures Implementation
735//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000736
737// releaseMemory - If the pass pipeline is done with this pass, we can release
738// our memory... here...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000739//
740void LocalDataStructures::releaseMemory() {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000741 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000742 E = DSInfo.end(); I != E; ++I)
743 delete I->second;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000744
745 // Empty map so next time memory is released, data structures are not
746 // re-deleted.
747 DSInfo.clear();
748}
749
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000750bool LocalDataStructures::run(Module &M) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000751 // Create a globals graph for the module. Deleted when all graphs go away.
752 GlobalDSGraph* GG = new GlobalDSGraph;
753
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000754 // Calculate all of the graphs...
755 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000756 if (!I->isExternal())
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000757 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I, GG)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000758
759 return false;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000760}
Chris Lattner7541b892002-07-31 19:32:12 +0000761