blob: 7ef79211ac339096c3c432f30ab4f57272505670 [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
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000352static void
353removeIdenticalCalls(std::vector<std::vector<DSNodeHandle> >& Calls,
354 const string& where) {
355 // Remove trivially identical function calls
356 unsigned NumFns = Calls.size();
357 std::sort(Calls.begin(), Calls.end());
358 Calls.erase(std::unique(Calls.begin(), Calls.end()),
359 Calls.end());
360
361 DEBUG(if (NumFns != Calls.size())
362 std::cerr << "Merged " << (NumFns-Calls.size())
363 << " call nodes in " << where << "\n";);
364}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000365
Chris Lattnere2219762002-07-18 18:22:40 +0000366// removeTriviallyDeadNodes - After the graph has been constructed, this method
367// removes all unreachable nodes that are created because they got merged with
368// other nodes in the graph. These nodes will all be trivially unreachable, so
369// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000370//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000371void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000372 for (unsigned i = 0; i != Nodes.size(); ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000373 if (! KeepAllGlobals || ! (Nodes[i]->NodeType & DSNode::GlobalNode))
374 if (isNodeDead(Nodes[i])) { // This node is dead!
375 delete Nodes[i]; // Free memory...
376 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
377 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000378
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000379 removeIdenticalCalls(FunctionCalls, Func.getName());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000380}
381
382
Chris Lattnere2219762002-07-18 18:22:40 +0000383// markAlive - Simple graph traverser that recursively walks the graph marking
384// stuff to be alive.
385//
386static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000387 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000388
389 Alive.insert(N);
390 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000391 if (N->getLink(i) && !Alive.count(N->getLink(i)))
392 markAlive(N->getLink(i), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000393}
394
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000395static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
396 std::set<DSNode*> &Visiting) {
397 if (N == 0) return false;
398
399 if (Visiting.count(N) > 0) return false; // terminate recursion on a cycle
400 Visiting.insert(N);
401
402 // If any immediate successor is alive, N is alive
403 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
404 if (N->getLink(i) && Alive.count(N->getLink(i)))
405 { Visiting.erase(N); return true; }
406
407 // Else if any successor reaches a live node, N is alive
408 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
409 if (N->getLink(i) && checkGlobalAlive(N->getLink(i), Alive, Visiting))
410 { Visiting.erase(N); return true; }
411
412 Visiting.erase(N);
413 return false;
414}
415
416
417// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
418// This would be unnecessary if function calls were real nodes! In that case,
419// the simple iterative loop in the first few lines below suffice.
420//
421static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
422 std::vector<std::vector<DSNodeHandle> > &Calls,
423 std::set<DSNode*> &Alive,
424 bool FilterCalls) {
425
426 // Iterate, marking globals or cast nodes alive until no new live nodes
427 // are added to Alive
428 std::set<DSNode*> Visiting; // Used to identify cycles
429 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
430 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
431 liveCount = Alive.size();
432 for ( ; I != E; ++I)
433 if (Alive.count(*I) == 0) {
434 Visiting.clear();
435 if (checkGlobalAlive(*I, Alive, Visiting))
436 markAlive(*I, Alive);
437 }
438 }
439
440 // Find function calls with some dead and some live nodes.
441 // Since all call nodes must be live if any one is live, we have to mark
442 // all nodes of the call as live and continue the iteration (via recursion).
443 if (FilterCalls) {
444 bool recurse = false;
445 for (int i = 0, ei = Calls.size(); i < ei; ++i) {
446 bool CallIsDead = true, CallHasDeadArg = false;
447 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j) {
448 bool argIsDead = Calls[i][j] == 0 || Alive.count(Calls[i][j]) == 0;
449 CallHasDeadArg = CallHasDeadArg || (Calls[i][j] != 0 && argIsDead);
450 CallIsDead = CallIsDead && argIsDead;
451 }
452 if (!CallIsDead && CallHasDeadArg) {
453 // Some node in this call is live and another is dead.
454 // Mark all nodes of call as live and iterate once more.
455 recurse = true;
456 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j)
457 markAlive(Calls[i][j], Alive);
458 }
459 }
460 if (recurse)
461 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
462 }
463}
464
465
466// markGlobalsAlive - Mark global nodes and cast nodes alive if they
467// can reach any other live node. Since this can produce new live nodes,
468// we use a simple iterative algorithm.
469//
470static void markGlobalsAlive(DSGraph& G, std::set<DSNode*> &Alive,
471 bool FilterCalls) {
472 // Add global and cast nodes to a set so we don't walk all nodes every time
473 std::set<DSNode*> GlobalNodes;
474 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
475 if (G.getNodes()[i]->NodeType & (DSNode::CastNode | DSNode::GlobalNode))
476 GlobalNodes.insert(G.getNodes()[i]);
477
478 // Add all call nodes to the same set
479 std::vector<std::vector<DSNodeHandle> > &Calls = G.getFunctionCalls();
480 if (FilterCalls) {
481 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
482 for (unsigned j = 0, e = Calls[i].size(); j != e; ++j)
483 if (Calls[i][j])
484 GlobalNodes.insert(Calls[i][j]);
485 }
486
487 // Iterate and recurse until no new live node are discovered.
488 // This would be a simple iterative loop if function calls were real nodes!
489 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
490
491 // Free up references to dead globals from the ValueMap
492 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
493 for( ; I != E; ++I)
494 if (Alive.count(*I) == 0)
495 removeRefsToGlobal(*I, G.getValueMap());
496
497 // Delete dead function calls
498 if (FilterCalls)
499 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
500 bool CallIsDead = true;
501 for (unsigned j = 0, ej= Calls[i].size(); CallIsDead && j != ej; ++j)
502 CallIsDead = (Alive.count(Calls[i][j]) == 0);
503 if (CallIsDead)
504 Calls.erase(Calls.begin() + i); // remove the call entirely
505 }
506}
Chris Lattnere2219762002-07-18 18:22:40 +0000507
508// removeDeadNodes - Use a more powerful reachability analysis to eliminate
509// subgraphs that are unreachable. This often occurs because the data
510// structure doesn't "escape" into it's caller, and thus should be eliminated
511// from the caller's graph entirely. This is only appropriate to use when
512// inlining graphs.
513//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000514void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
515 assert((!KeepAllGlobals || KeepCalls) &&
516 "KeepAllGlobals without KeepCalls is meaningless");
517
Chris Lattnere2219762002-07-18 18:22:40 +0000518 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000519 removeTriviallyDeadNodes(KeepAllGlobals);
520
Chris Lattnere2219762002-07-18 18:22:40 +0000521 // FIXME: Merge nontrivially identical call nodes...
522
523 // Alive - a set that holds all nodes found to be reachable/alive.
524 std::set<DSNode*> Alive;
525
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000526 // If KeepCalls, mark all nodes reachable by call nodes as alive...
527 if (KeepCalls)
528 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
529 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
530 markAlive(FunctionCalls[i][j], Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000531
532 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
533 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
534 markAlive(OrigFunctionCalls[i][j], Alive);
535
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000536 // Mark all nodes reachable by scalar nodes (and global nodes, if
537 // keeping them was specified) as alive...
538 char keepBits = DSNode::ScalarNode | (KeepAllGlobals? DSNode::GlobalNode : 0);
Chris Lattnere2219762002-07-18 18:22:40 +0000539 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000540 if (Nodes[i]->NodeType & keepBits)
Chris Lattnere2219762002-07-18 18:22:40 +0000541 markAlive(Nodes[i], Alive);
542
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000543 // The return value is alive as well...
544 markAlive(RetNode, Alive);
545
546 // Mark all globals or cast nodes that can reach a live node as alive.
547 // This also marks all nodes reachable from such nodes as alive.
548 // Of course, if KeepAllGlobals is specified, they would be live already.
549 if (! KeepAllGlobals)
550 markGlobalsAlive(*this, Alive, ! KeepCalls);
551
Chris Lattnere2219762002-07-18 18:22:40 +0000552 // Loop over all unreachable nodes, dropping their references...
553 std::vector<DSNode*> DeadNodes;
554 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
555 for (unsigned i = 0; i != Nodes.size(); ++i)
556 if (!Alive.count(Nodes[i])) {
557 DSNode *N = Nodes[i];
558 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
559 DeadNodes.push_back(N); // Add node to our list of dead nodes
560 N->dropAllReferences(); // Drop all outgoing edges
561 }
562
Chris Lattnere2219762002-07-18 18:22:40 +0000563 // Delete all dead nodes...
564 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
565}
566
567
568
Chris Lattner0d9bab82002-07-18 00:12:30 +0000569// maskNodeTypes - Apply a mask to all of the node types in the graph. This
570// is useful for clearing out markers like Scalar or Incomplete.
571//
572void DSGraph::maskNodeTypes(unsigned char Mask) {
573 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
574 Nodes[i]->NodeType &= Mask;
575}
576
577
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000578//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000579// GlobalDSGraph Implementation
580//===----------------------------------------------------------------------===//
581
582GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
583}
584
585GlobalDSGraph::~GlobalDSGraph() {
586 assert(Referrers.size() == 0 &&
587 "Deleting global graph while references from other graphs exist");
588}
589
590void GlobalDSGraph::addReference(const DSGraph* referrer) {
591 if (referrer != this)
592 Referrers.insert(referrer);
593}
594
595void GlobalDSGraph::removeReference(const DSGraph* referrer) {
596 if (referrer != this) {
597 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
598 Referrers.erase(referrer);
599 if (Referrers.size() == 0)
600 delete this;
601 }
602}
603
604// Bits used in the next function
605static const char ExternalTypeBits = (DSNode::GlobalNode | DSNode::NewNode |
606 DSNode::SubElement | DSNode::CastNode);
607
608
609// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
610// visible target links (and recursively their such links) into this graph.
611// NodeCache maps the node being cloned to its clone in the Globals graph,
612// in order to track cycles.
613// GlobalsAreFinal is a flag that says whether it is safe to assume that
614// an existing global node is complete. This is important to avoid
615// reinserting all globals when inserting Calls to functions.
616// This is a helper function for cloneGlobals and cloneCalls.
617//
618DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
619 std::map<const DSNode*, DSNode*> &NodeCache,
620 bool GlobalsAreFinal) {
621 if (OldNode == 0) return 0;
622
623 // The caller should check this is an external node. Just more efficient...
624 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
625
626 // If a clone has already been created for OldNode, return it.
627 DSNode*& CacheEntry = NodeCache[OldNode];
628 if (CacheEntry != 0)
629 return CacheEntry;
630
631 // The result value...
632 DSNode* NewNode = 0;
633
634 // If nodes already exist for any of the globals of OldNode,
635 // merge all such nodes together since they are merged in OldNode.
636 // If ValueCacheIsFinal==true, look for an existing node that has
637 // an identical list of globals and return it if it exists.
638 //
639 for (unsigned j = 0, N = OldNode->getGlobals().size(); j < N; ++j)
640 if (DSNode* PrevNode = ValueMap[OldNode->getGlobals()[j]]) {
641 if (NewNode == 0) {
642 NewNode = PrevNode; // first existing node found
643 if (GlobalsAreFinal && j == 0)
644 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
645 CacheEntry = NewNode;
646 return NewNode;
647 }
648 }
649 else if (NewNode != PrevNode) { // found another, different from prev
650 // update ValMap *before* merging PrevNode into NewNode
651 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
652 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
653 NewNode->mergeWith(PrevNode);
654 }
655 } else if (NewNode != 0) {
656 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
657 }
658
659 // If no existing node was found, clone the node and update the ValMap.
660 if (NewNode == 0) {
661 NewNode = new DSNode(*OldNode);
662 Nodes.push_back(NewNode);
663 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
664 NewNode->setLink(j, 0);
665 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
666 ValueMap[NewNode->getGlobals()[j]] = NewNode;
667 }
668 else
669 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
670
671 // Add the entry to NodeCache
672 CacheEntry = NewNode;
673
674 // Rewrite the links in the new node to point into the current graph,
675 // but only for links to external nodes. Set other links to NULL.
676 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
677 DSNode* OldTarget = OldNode->getLink(j);
678 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
679 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
680 if (NewNode->getLink(j))
681 NewNode->getLink(j)->mergeWith(NewLink);
682 else
683 NewNode->setLink(j, NewLink);
684 }
685 }
686
687 // Remove all local markers
688 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
689
690 return NewNode;
691}
692
693
694// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
695// visible target links (and recursively their such links) into this graph.
696//
697void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
698 std::map<const DSNode*, DSNode*> NodeCache;
699 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
700 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
701 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
702
703 if (CloneCalls)
704 GlobalsGraph->cloneCalls(Graph);
705
706 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
707}
708
709
710// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
711// links (and recursively their such links) into this graph.
712//
713void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
714 std::map<const DSNode*, DSNode*> NodeCache;
715 std::vector<std::vector<DSNodeHandle> >& FromCalls =Graph.FunctionCalls;
716
717 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
718
719 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
720 FunctionCalls.push_back(std::vector<DSNodeHandle>());
721 FunctionCalls.back().reserve(FromCalls[i].size());
722 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
723 FunctionCalls.back().push_back
724 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
725 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
726 : 0);
727 }
728
729 // remove trivially identical function calls
730 removeIdenticalCalls(FunctionCalls, string("Globals Graph"));
731}
732
733
734//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000735// LocalDataStructures Implementation
736//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000737
738// releaseMemory - If the pass pipeline is done with this pass, we can release
739// our memory... here...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000740//
741void LocalDataStructures::releaseMemory() {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000742 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000743 E = DSInfo.end(); I != E; ++I)
744 delete I->second;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000745
746 // Empty map so next time memory is released, data structures are not
747 // re-deleted.
748 DSInfo.clear();
749}
750
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000751bool LocalDataStructures::run(Module &M) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000752 // Create a globals graph for the module. Deleted when all graphs go away.
753 GlobalDSGraph* GG = new GlobalDSGraph;
754
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000755 // Calculate all of the graphs...
756 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000757 if (!I->isExternal())
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000758 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I, GG)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000759
760 return false;
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000761}