blob: e7e40108c60e9f4d55acc1645cd99ed350dc7cd0 [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 Lattnerfccd06f2002-10-01 22:33:50 +00007#include "llvm/Analysis/DSGraph.h"
8#include "llvm/Function.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +00009#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000010#include "llvm/Target/TargetData.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000011#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000012#include "Support/Statistic.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000013#include <algorithm>
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include <set>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000015
Chris Lattnere2219762002-07-18 18:22:40 +000016using std::vector;
17
Chris Lattnerfccd06f2002-10-01 22:33:50 +000018// TODO: FIXME
19namespace DataStructureAnalysis {
20 // isPointerType - Return true if this first class type is big enough to hold
21 // a pointer.
22 //
23 bool isPointerType(const Type *Ty);
24 extern TargetData TD;
25}
26using namespace DataStructureAnalysis;
27
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000028//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000029// DSNode Implementation
30//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000031
Chris Lattnerfccd06f2002-10-01 22:33:50 +000032DSNode::DSNode(enum NodeTy NT, const Type *T) : NodeType(NT) {
33 // If this node is big enough to have pointer fields, add space for them now.
Chris Lattner7b7200c2002-10-02 04:57:39 +000034 if (T != Type::VoidTy && !isa<FunctionType>(T)) { // Avoid TargetData assert's
35 MergeMap.resize(TD.getTypeSize(T));
36
37 // Assign unique values to all of the elements of MergeMap
38 if (MergeMap.size() < 128) {
39 // Handle the common case of reasonable size structures...
40 for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
41 MergeMap[i] = -1-i; // Assign -1, -2, -3, ...
42 } else {
43 // It's possible that we have something really big here. In this case,
44 // divide the object into chunks until it will fit into 128 elements.
45 unsigned Multiple = MergeMap.size()/128;
46
47 // It's probably an array, and probably some power of two in size.
48 // Because of this, find the biggest power of two that is bigger than
49 // multiple to use as our real Multiple.
50 unsigned RealMultiple = 2;
Chris Lattner62d928e2002-10-03 21:06:38 +000051 while (RealMultiple <= Multiple) RealMultiple <<= 1;
Chris Lattner7b7200c2002-10-02 04:57:39 +000052
53 unsigned RealBound = MergeMap.size()/RealMultiple;
54 assert(RealBound <= 128 && "Math didn't work out right");
55
56 // Now go through and assign indexes that are between -1 and -128
57 // inclusive
58 //
59 for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
60 MergeMap[i] = -1-(i % RealBound); // Assign -1, -2, -3...
61 }
62 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +000063
Chris Lattnera3f85862002-10-18 18:22:46 +000064 TypeEntries.push_back(TypeRec(T, 0));
Chris Lattnerc68c31b2002-07-10 22:38:08 +000065}
66
Chris Lattner0d9bab82002-07-18 00:12:30 +000067// DSNode copy constructor... do not copy over the referrers list!
68DSNode::DSNode(const DSNode &N)
Chris Lattner7b7200c2002-10-02 04:57:39 +000069 : Links(N.Links), MergeMap(N.MergeMap),
Chris Lattnerfccd06f2002-10-01 22:33:50 +000070 TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000071}
72
Chris Lattnerc68c31b2002-07-10 22:38:08 +000073void DSNode::removeReferrer(DSNodeHandle *H) {
74 // Search backwards, because we depopulate the list from the back for
75 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000076 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000077 std::find(Referrers.rbegin(), Referrers.rend(), H);
78 assert(I != Referrers.rend() && "Referrer not pointing to node!");
79 Referrers.erase(I.base()-1);
80}
81
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000082// addGlobal - Add an entry for a global value to the Globals list. This also
83// marks the node with the 'G' flag if it does not already have it.
84//
85void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000086 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000087 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000088 std::lower_bound(Globals.begin(), Globals.end(), GV);
89
90 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000091 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000092 Globals.insert(I, GV);
93 NodeType |= GlobalNode;
94 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000095}
96
97
Chris Lattner7b7200c2002-10-02 04:57:39 +000098/// setLink - Set the link at the specified offset to the specified
99/// NodeHandle, replacing what was there. It is uncommon to use this method,
100/// instead one of the higher level methods should be used, below.
101///
102void DSNode::setLink(unsigned i, const DSNodeHandle &NH) {
103 // Create a new entry in the Links vector to hold a new element for offset.
104 if (!hasLink(i)) {
105 signed char NewIdx = Links.size();
106 // Check to see if we allocate more than 128 distinct links for this node.
107 // If so, just merge with the last one. This really shouldn't ever happen,
108 // but it should work regardless of whether it does or not.
109 //
110 if (NewIdx >= 0) {
111 Links.push_back(NH); // Allocate space: common case
112 } else { // Wrap around? Too many links?
113 NewIdx--; // Merge with whatever happened last
114 assert(NewIdx > 0 && "Should wrap back around");
115 std::cerr << "\n*** DSNode found that requires more than 128 "
116 << "active links at once!\n\n";
117 }
118
119 signed char OldIdx = MergeMap[i];
120 assert (OldIdx < 0 && "Shouldn't contain link!");
121
122 // Make sure that anything aliasing this field gets updated to point to the
123 // new link field.
124 rewriteMergeMap(OldIdx, NewIdx);
125 assert(MergeMap[i] == NewIdx && "Field not replaced!");
126 } else {
127 Links[MergeMap[i]] = NH;
128 }
129}
130
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000131// addEdgeTo - Add an edge from the current node to the specified node. This
132// can cause merging of nodes in the graph.
133//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000134void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000135 assert(Offset < getSize() && "Offset out of range!");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000136 if (NH.getNode() == 0) return; // Nothing to do
137
Chris Lattner7b7200c2002-10-02 04:57:39 +0000138 if (DSNodeHandle *ExistingNH = getLink(Offset)) {
139 // Merge the two nodes...
140 ExistingNH->mergeWith(NH);
141 } else { // No merging to perform...
142 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000143 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000144}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000145
Chris Lattner7b7200c2002-10-02 04:57:39 +0000146/// mergeMappedValues - This is the higher level form of rewriteMergeMap. It is
147/// fully capable of merging links together if neccesary as well as simply
148/// rewriting the map entries.
149///
150void DSNode::mergeMappedValues(signed char V1, signed char V2) {
151 assert(V1 != V2 && "Cannot merge two identical mapped values!");
152
153 if (V1 < 0) { // If there is no outgoing link from V1, merge it with V2
154 if (V2 < 0 && V1 > V2)
155 // If both are not linked, merge to the field closer to 0
156 rewriteMergeMap(V2, V1);
157 else
158 rewriteMergeMap(V1, V2);
159 } else if (V2 < 0) { // Is V2 < 0 && V1 >= 0?
160 rewriteMergeMap(V2, V1); // Merge into the one with the link...
161 } else { // Otherwise, links exist at both locations
162 // Merge Links[V1] with Links[V2] so they point to the same place now...
163 Links[V1].mergeWith(Links[V2]);
164
165 // Merge the V2 link into V1 so that we reduce the overall value of the
166 // links are reduced...
167 //
168 if (V2 < V1) std::swap(V1, V2); // Ensure V1 < V2
169 rewriteMergeMap(V2, V1); // After this, V2 is "dead"
170
171 // Change the user of the last link to use V2 instead
172 if ((unsigned)V2 != Links.size()-1) {
173 rewriteMergeMap(Links.size()-1, V2); // Point to V2 instead of last el...
174 // Make sure V2 points the right DSNode
175 Links[V2] = Links.back();
176 }
177
178 // Reduce the number of distinct outgoing links...
179 Links.pop_back();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000180 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000181}
182
183
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000184// MergeSortedVectors - Efficiently merge a vector into another vector where
185// duplicates are not allowed and both are sorted. This assumes that 'T's are
186// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000187//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000188template<typename T>
189void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
190 // By far, the most common cases will be the simple ones. In these cases,
191 // avoid having to allocate a temporary vector...
192 //
193 if (Src.empty()) { // Nothing to merge in...
194 return;
195 } else if (Dest.empty()) { // Just copy the result in...
196 Dest = Src;
197 } else if (Src.size() == 1) { // Insert a single element...
198 const T &V = Src[0];
199 typename vector<T>::iterator I =
200 std::lower_bound(Dest.begin(), Dest.end(), V);
201 if (I == Dest.end() || *I != Src[0]) // If not already contained...
202 Dest.insert(I, Src[0]);
203 } else if (Dest.size() == 1) {
204 T Tmp = Dest[0]; // Save value in temporary...
205 Dest = Src; // Copy over list...
206 typename vector<T>::iterator I =
207 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
208 if (I == Dest.end() || *I != Src[0]) // If not already contained...
209 Dest.insert(I, Src[0]);
210
211 } else {
212 // Make a copy to the side of Dest...
213 vector<T> Old(Dest);
214
215 // Make space for all of the type entries now...
216 Dest.resize(Dest.size()+Src.size());
217
218 // Merge the two sorted ranges together... into Dest.
219 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
220
221 // Now erase any duplicate entries that may have accumulated into the
222 // vectors (because they were in both of the input sets)
223 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
224 }
225}
226
227
228// mergeWith - Merge this node and the specified node, moving all links to and
229// from the argument node into the current node, deleting the node argument.
230// Offset indicates what offset the specified node is to be merged into the
231// current node.
232//
233// The specified node may be a null pointer (in which case, nothing happens).
234//
235void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
236 DSNode *N = NH.getNode();
237 if (N == 0 || (N == this && NH.getOffset() == Offset))
238 return; // Noop
239
240 assert(NH.getNode() != this &&
241 "Cannot merge two portions of the same node yet!");
242
243 // If both nodes are not at offset 0, make sure that we are merging the node
244 // at an later offset into the node with the zero offset.
245 //
246 if (Offset > NH.getOffset()) {
247 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
248 return;
249 }
250
251#if 0
252 std::cerr << "\n\nMerging:\n";
253 N->print(std::cerr, 0);
254 std::cerr << " and:\n";
255 print(std::cerr, 0);
256#endif
257
258 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
259 // respect to NH.Offset) is now zero.
260 //
261 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000262
Chris Lattner7b7200c2002-10-02 04:57:39 +0000263 unsigned NSize = N->getSize();
264 assert(NSize+NOffset <= getSize() &&
265 "Don't know how to merge extend a merged nodes size yet!");
266
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000267 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000268 // Make sure to adjust their offset, not just the node pointer.
269 //
270 while (!N->Referrers.empty()) {
271 DSNodeHandle &Ref = *N->Referrers.back();
272 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
273 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000274
Chris Lattner7b7200c2002-10-02 04:57:39 +0000275 // We must merge fields in this node due to nodes merged in the source node.
276 // In order to handle this we build a map that converts from the source node's
277 // MergeMap values to our MergeMap values. This map is indexed by the
278 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
279 // 2*SourceNodeSize elements of space for the mapping. We can do this because
280 // we know that there are at most SourceNodeSize outgoing links in the node
281 // (thus that many positive values) and at most SourceNodeSize distinct fields
282 // (thus that many negative values).
283 //
284 std::vector<signed char> MergeMapMap(NSize*2, 127);
285
286 // Loop through the structures, merging them together...
287 for (unsigned i = 0, e = NSize; i != e; ++i) {
288 // Get what this byte of N maps to...
289 signed char NElement = N->MergeMap[i];
290
291 // Get what we map this byte to...
292 signed char Element = MergeMap[i+NOffset];
293 // We use 127 as a sentinal and don't check for it's existence yet...
294 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
295
296 signed char CurMappedVal = MergeMapMap[NElement+NSize];
297 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
298 MergeMapMap[NElement+NSize] = Element; // Map the two together...
299 } else if (CurMappedVal != Element) {
300 // If we are mapping two different fields together this means that we need
301 // to merge fields in the current node due to merging in the source node.
302 //
303 mergeMappedValues(CurMappedVal, Element);
304 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
305 }
306 }
307
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000308 // Make all of the outgoing links of N now be outgoing links of this. This
309 // can cause recursive merging!
310 //
Chris Lattner7b7200c2002-10-02 04:57:39 +0000311 for (unsigned i = 0, e = NSize; i != e; ++i)
312 if (DSNodeHandle *Link = N->getLink(i)) {
313 addEdgeTo(i+NOffset, *Link);
314 N->MergeMap[i] = -1; // Kill outgoing edge
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000315 }
316
317 // Now that there are no outgoing edges, all of the Links are dead.
318 N->Links.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000319
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000320 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000321 NodeType |= N->NodeType;
322 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000323
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000324 // If this merging into node has more than just void nodes in it, merge!
325 assert(!N->TypeEntries.empty() && "TypeEntries is empty for a node?");
Chris Lattnera3f85862002-10-18 18:22:46 +0000326 if (N->TypeEntries.size() != 1 || N->TypeEntries[0].Ty != Type::VoidTy) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000327 // If the current node just has a Void entry in it, remove it.
Chris Lattnera3f85862002-10-18 18:22:46 +0000328 if (TypeEntries.size() == 1 && TypeEntries[0].Ty == Type::VoidTy)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000329 TypeEntries.clear();
330
331 // Adjust all of the type entries we are merging in by the offset... and add
332 // them to the TypeEntries list.
333 //
334 if (NOffset != 0) { // This case is common enough to optimize for
335 // Offset all of the TypeEntries in N with their new offset
336 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
Chris Lattnera3f85862002-10-18 18:22:46 +0000337 N->TypeEntries[i].Offset += NOffset;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000338 }
339
340 MergeSortedVectors(TypeEntries, N->TypeEntries);
341
342 N->TypeEntries.clear();
343 }
344
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000345 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000346 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000347 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000348
349 // Delete the globals from the old node...
350 N->Globals.clear();
351 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000352}
353
354//===----------------------------------------------------------------------===//
355// DSGraph Implementation
356//===----------------------------------------------------------------------===//
357
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000358DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
359 std::map<const DSNode*, DSNode*> NodeMap;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000360 RetNode = cloneInto(G, ValueMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000361}
362
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000363DSGraph::~DSGraph() {
364 FunctionCalls.clear();
365 ValueMap.clear();
366 RetNode = 0;
367
368#ifndef NDEBUG
369 // Drop all intra-node references, so that assertions don't fail...
370 std::for_each(Nodes.begin(), Nodes.end(),
371 std::mem_fun(&DSNode::dropAllReferences));
372#endif
373
374 // Delete all of the nodes themselves...
375 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
376}
377
Chris Lattner0d9bab82002-07-18 00:12:30 +0000378// dump - Allow inspection of graph in a debugger.
379void DSGraph::dump() const { print(std::cerr); }
380
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000381// Helper function used to clone a function list.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000382//
383static void CopyFunctionCallsList(const vector<vector<DSNodeHandle> >&fromCalls,
384 vector<vector<DSNodeHandle> > &toCalls,
385 std::map<const DSNode*, DSNode*> &NodeMap) {
386
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000387 unsigned FC = toCalls.size(); // FirstCall
388 toCalls.reserve(FC+fromCalls.size());
389 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000390 toCalls.push_back(vector<DSNodeHandle>());
391
392 const vector<DSNodeHandle> &CurCall = fromCalls[i];
393 toCalls.back().reserve(CurCall.size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000394 for (unsigned j = 0, ej = fromCalls[i].size(); j != ej; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000395 toCalls[FC+i].push_back(DSNodeHandle(NodeMap[CurCall[j].getNode()],
396 CurCall[j].getOffset()));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000397 }
398}
399
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000400/// remapLinks - Change all of the Links in the current node according to the
401/// specified mapping.
402void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
403 for (unsigned i = 0, e = Links.size(); i != e; ++i)
404 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
405}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000406
Chris Lattner0d9bab82002-07-18 00:12:30 +0000407// cloneInto - Clone the specified DSGraph into the current graph, returning the
408// Return node of the graph. The translated ValueMap for the old function is
409// filled into the OldValMap member. If StripLocals is set to true, Scalar and
410// Alloca markers are removed from the graph, as the graph is being cloned into
411// a calling function's graph.
412//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000413DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
414 std::map<Value*, DSNodeHandle> &OldValMap,
415 std::map<const DSNode*, DSNode*> &OldNodeMap,
416 bool StripScalars, bool StripAllocas,
417 bool CopyCallers, bool CopyOrigCalls) {
418 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000419
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000420 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000421
422 // Duplicate all of the nodes, populating the node map...
423 Nodes.reserve(FN+G.Nodes.size());
424 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000425 DSNode *Old = G.Nodes[i];
426 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000427 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000428 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000429 }
430
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000431 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000432 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000433 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000434
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000435 // Remove local markers as specified
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000436 unsigned char StripBits = (StripScalars ? DSNode::ScalarNode : 0) |
437 (StripAllocas ? DSNode::AllocaNode : 0);
438 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000439 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000440 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000441
Chris Lattnercf15db32002-10-17 20:09:52 +0000442 // Copy the value map... and merge all of the global nodes...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000443 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
Chris Lattnercf15db32002-10-17 20:09:52 +0000444 E = G.ValueMap.end(); I != E; ++I) {
445 DSNodeHandle &H = OldValMap[I->first];
446 H = DSNodeHandle(OldNodeMap[I->second.getNode()], I->second.getOffset());
447
448 if (isa<GlobalValue>(I->first)) { // Is this a global?
449 std::map<Value*, DSNodeHandle>::iterator GVI = ValueMap.find(I->first);
450 if (GVI != ValueMap.end()) { // Is the global value in this fun already?
451 GVI->second.mergeWith(H);
452 } else {
453 ValueMap[I->first] = H; // Add global pointer to this graph
454 }
455 }
456 }
Chris Lattnere2219762002-07-18 18:22:40 +0000457 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000458 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000459
Chris Lattnercf15db32002-10-17 20:09:52 +0000460
Chris Lattner0d9bab82002-07-18 00:12:30 +0000461 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000462 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000463}
464
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000465#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000466// cloneGlobalInto - Clone the given global node and all its target links
467// (and all their llinks, recursively).
468//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000469DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000470 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
471
472 // If a clone has already been created for GNode, return it.
473 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
474 if (ValMapEntry != 0)
475 return ValMapEntry;
476
477 // Clone the node and update the ValMap.
478 DSNode* NewNode = new DSNode(*GNode);
479 ValMapEntry = NewNode; // j=0 case of loop below!
480 Nodes.push_back(NewNode);
481 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
482 ValueMap[NewNode->getGlobals()[j]] = NewNode;
483
484 // Rewrite the links in the new node to point into the current graph.
485 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
486 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
487
488 return NewNode;
489}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000490#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000491
492
Chris Lattner0d9bab82002-07-18 00:12:30 +0000493// markIncompleteNodes - Mark the specified node as having contents that are not
494// known with the current analysis we have performed. Because a node makes all
495// of the nodes it can reach imcomplete if the node itself is incomplete, we
496// must recursively traverse the data structure graph, marking all reachable
497// nodes as incomplete.
498//
499static void markIncompleteNode(DSNode *N) {
500 // Stop recursion if no node, or if node already marked...
501 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
502
503 // Actually mark the node
504 N->NodeType |= DSNode::Incomplete;
505
506 // Recusively process children...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000507 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
508 if (DSNodeHandle *DSNH = N->getLink(i))
509 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000510}
511
512
513// markIncompleteNodes - Traverse the graph, identifying nodes that may be
514// modified by other functions that have not been resolved yet. This marks
515// nodes that are reachable through three sources of "unknownness":
516//
517// Global Variables, Function Calls, and Incoming Arguments
518//
519// For any node that may have unknown components (because something outside the
520// scope of current analysis may have modified it), the 'Incomplete' flag is
521// added to the NodeType.
522//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000523void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000524 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000525 if (markFormalArgs && Func)
526 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
527 if (isPointerType(I->getType()) && ValueMap.find(I) != ValueMap.end()) {
528 DSNodeHandle &INH = ValueMap[I];
529 if (INH.getNode() && INH.hasLink(0))
530 markIncompleteNode(ValueMap[I].getLink(0)->getNode());
531 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000532
533 // Mark stuff passed into functions calls as being incomplete...
534 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Chris Lattnere2219762002-07-18 18:22:40 +0000535 vector<DSNodeHandle> &Args = FunctionCalls[i];
536 // Then the return value is certainly incomplete!
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000537 markIncompleteNode(Args[0].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000538
539 // The call does not make the function argument incomplete...
540
541 // All arguments to the function call are incomplete though!
542 for (unsigned i = 2, e = Args.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000543 markIncompleteNode(Args[i].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000544 }
545
Chris Lattner055dc2c2002-07-18 15:54:42 +0000546 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000547 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000548 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000549 DSNode *N = Nodes[i];
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000550 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
551 if (DSNodeHandle *DSNH = N->getLink(i))
552 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000553 }
554}
555
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000556// removeRefsToGlobal - Helper function that removes globals from the
557// ValueMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000558static void removeRefsToGlobal(DSNode* N,
559 std::map<Value*, DSNodeHandle> &ValueMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000560 while (!N->getGlobals().empty()) {
561 GlobalValue *GV = N->getGlobals().back();
562 N->getGlobals().pop_back();
563 ValueMap.erase(GV);
564 }
565}
566
567
Chris Lattner0d9bab82002-07-18 00:12:30 +0000568// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
569// checks to see if there are simple transformations that it can do to make it
570// dead.
571//
572bool DSGraph::isNodeDead(DSNode *N) {
573 // Is it a trivially dead shadow node...
574 if (N->getReferrers().empty() && N->NodeType == 0)
575 return true;
576
577 // Is it a function node or some other trivially unused global?
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000578 if (N->NodeType != 0 &&
579 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000580 N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000581 N->getReferrers().size() == N->getGlobals().size()) {
582
Chris Lattnera00397e2002-10-03 21:55:28 +0000583 // Remove the globals from the ValueMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000584 // down to zero.
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000585 removeRefsToGlobal(N, ValueMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000586 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
587 return true;
588 }
589
590 return false;
591}
592
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000593static void removeIdenticalCalls(vector<vector<DSNodeHandle> > &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000594 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000595 // Remove trivially identical function calls
596 unsigned NumFns = Calls.size();
597 std::sort(Calls.begin(), Calls.end());
598 Calls.erase(std::unique(Calls.begin(), Calls.end()),
599 Calls.end());
600
601 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000602 std::cerr << "Merged " << (NumFns-Calls.size())
603 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000604}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000605
Chris Lattnere2219762002-07-18 18:22:40 +0000606// removeTriviallyDeadNodes - After the graph has been constructed, this method
607// removes all unreachable nodes that are created because they got merged with
608// other nodes in the graph. These nodes will all be trivially unreachable, so
609// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000610//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000611void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000612 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000613 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000614 if (isNodeDead(Nodes[i])) { // This node is dead!
615 delete Nodes[i]; // Free memory...
616 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
617 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000618
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000619 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000620}
621
622
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000623// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000624// stuff to be alive.
625//
626static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000627 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000628
629 Alive.insert(N);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000630 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
631 if (DSNodeHandle *DSNH = N->getLink(i))
632 if (!Alive.count(DSNH->getNode()))
633 markAlive(DSNH->getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000634}
635
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000636static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
637 std::set<DSNode*> &Visiting) {
638 if (N == 0) return false;
639
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000640 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000641 Visiting.insert(N);
642
643 // If any immediate successor is alive, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000644 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
645 if (DSNodeHandle *DSNH = N->getLink(i))
646 if (Alive.count(DSNH->getNode())) {
647 Visiting.erase(N);
648 return true;
649 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000650
651 // Else if any successor reaches a live node, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000652 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
653 if (DSNodeHandle *DSNH = N->getLink(i))
654 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
655 Visiting.erase(N); return true;
656 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000657
658 Visiting.erase(N);
659 return false;
660}
661
662
663// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
664// This would be unnecessary if function calls were real nodes! In that case,
665// the simple iterative loop in the first few lines below suffice.
666//
667static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000668 vector<vector<DSNodeHandle> > &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000669 std::set<DSNode*> &Alive,
670 bool FilterCalls) {
671
672 // Iterate, marking globals or cast nodes alive until no new live nodes
673 // are added to Alive
674 std::set<DSNode*> Visiting; // Used to identify cycles
675 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
676 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
677 liveCount = Alive.size();
678 for ( ; I != E; ++I)
679 if (Alive.count(*I) == 0) {
680 Visiting.clear();
681 if (checkGlobalAlive(*I, Alive, Visiting))
682 markAlive(*I, Alive);
683 }
684 }
685
686 // Find function calls with some dead and some live nodes.
687 // Since all call nodes must be live if any one is live, we have to mark
688 // all nodes of the call as live and continue the iteration (via recursion).
689 if (FilterCalls) {
690 bool recurse = false;
691 for (int i = 0, ei = Calls.size(); i < ei; ++i) {
692 bool CallIsDead = true, CallHasDeadArg = false;
693 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000694 bool argIsDead = Calls[i][j].getNode() == 0 ||
695 Alive.count(Calls[i][j].getNode()) == 0;
696 CallHasDeadArg |= (Calls[i][j].getNode() != 0 && argIsDead);
697 CallIsDead &= argIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000698 }
699 if (!CallIsDead && CallHasDeadArg) {
700 // Some node in this call is live and another is dead.
701 // Mark all nodes of call as live and iterate once more.
702 recurse = true;
703 for (unsigned j = 0, ej = Calls[i].size(); j != ej; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000704 markAlive(Calls[i][j].getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000705 }
706 }
707 if (recurse)
708 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
709 }
710}
711
712
713// markGlobalsAlive - Mark global nodes and cast nodes alive if they
714// can reach any other live node. Since this can produce new live nodes,
715// we use a simple iterative algorithm.
716//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000717static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000718 bool FilterCalls) {
719 // Add global and cast nodes to a set so we don't walk all nodes every time
720 std::set<DSNode*> GlobalNodes;
721 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000722 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000723 GlobalNodes.insert(G.getNodes()[i]);
724
725 // Add all call nodes to the same set
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000726 vector<vector<DSNodeHandle> > &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000727 if (FilterCalls) {
728 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
729 for (unsigned j = 0, e = Calls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000730 if (Calls[i][j].getNode())
731 GlobalNodes.insert(Calls[i][j].getNode());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000732 }
733
734 // Iterate and recurse until no new live node are discovered.
735 // This would be a simple iterative loop if function calls were real nodes!
736 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
737
738 // Free up references to dead globals from the ValueMap
739 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
740 for( ; I != E; ++I)
741 if (Alive.count(*I) == 0)
742 removeRefsToGlobal(*I, G.getValueMap());
743
744 // Delete dead function calls
745 if (FilterCalls)
746 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
747 bool CallIsDead = true;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000748 for (unsigned j = 0, ej = Calls[i].size(); CallIsDead && j != ej; ++j)
749 CallIsDead = Alive.count(Calls[i][j].getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000750 if (CallIsDead)
751 Calls.erase(Calls.begin() + i); // remove the call entirely
752 }
753}
Chris Lattnere2219762002-07-18 18:22:40 +0000754
755// removeDeadNodes - Use a more powerful reachability analysis to eliminate
756// subgraphs that are unreachable. This often occurs because the data
757// structure doesn't "escape" into it's caller, and thus should be eliminated
758// from the caller's graph entirely. This is only appropriate to use when
759// inlining graphs.
760//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000761void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
762 assert((!KeepAllGlobals || KeepCalls) &&
763 "KeepAllGlobals without KeepCalls is meaningless");
764
Chris Lattnere2219762002-07-18 18:22:40 +0000765 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000766 removeTriviallyDeadNodes(KeepAllGlobals);
767
Chris Lattnere2219762002-07-18 18:22:40 +0000768 // FIXME: Merge nontrivially identical call nodes...
769
770 // Alive - a set that holds all nodes found to be reachable/alive.
771 std::set<DSNode*> Alive;
772
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000773 // If KeepCalls, mark all nodes reachable by call nodes as alive...
774 if (KeepCalls)
775 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
776 for (unsigned j = 0, e = FunctionCalls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000777 markAlive(FunctionCalls[i][j].getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000778
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000779#if 0
Chris Lattnere2219762002-07-18 18:22:40 +0000780 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
781 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000782 markAlive(OrigFunctionCalls[i][j].getNode(), Alive);
783#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000784
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000785 // Mark all nodes reachable by scalar nodes (and global nodes, if
786 // keeping them was specified) as alive...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000787 unsigned char keepBits = DSNode::ScalarNode |
788 (KeepAllGlobals ? DSNode::GlobalNode : 0);
Chris Lattnere2219762002-07-18 18:22:40 +0000789 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000790 if (Nodes[i]->NodeType & keepBits)
Chris Lattnere2219762002-07-18 18:22:40 +0000791 markAlive(Nodes[i], Alive);
792
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000793 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000794 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000795
796 // Mark all globals or cast nodes that can reach a live node as alive.
797 // This also marks all nodes reachable from such nodes as alive.
798 // Of course, if KeepAllGlobals is specified, they would be live already.
799 if (! KeepAllGlobals)
800 markGlobalsAlive(*this, Alive, ! KeepCalls);
801
Chris Lattnere2219762002-07-18 18:22:40 +0000802 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000803 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000804 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
805 for (unsigned i = 0; i != Nodes.size(); ++i)
806 if (!Alive.count(Nodes[i])) {
807 DSNode *N = Nodes[i];
808 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
809 DeadNodes.push_back(N); // Add node to our list of dead nodes
810 N->dropAllReferences(); // Drop all outgoing edges
811 }
812
Chris Lattnere2219762002-07-18 18:22:40 +0000813 // Delete all dead nodes...
814 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
815}
816
817
818
Chris Lattner0d9bab82002-07-18 00:12:30 +0000819// maskNodeTypes - Apply a mask to all of the node types in the graph. This
820// is useful for clearing out markers like Scalar or Incomplete.
821//
822void DSGraph::maskNodeTypes(unsigned char Mask) {
823 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
824 Nodes[i]->NodeType &= Mask;
825}
826
827
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000828#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000829//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000830// GlobalDSGraph Implementation
831//===----------------------------------------------------------------------===//
832
833GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
834}
835
836GlobalDSGraph::~GlobalDSGraph() {
837 assert(Referrers.size() == 0 &&
838 "Deleting global graph while references from other graphs exist");
839}
840
841void GlobalDSGraph::addReference(const DSGraph* referrer) {
842 if (referrer != this)
843 Referrers.insert(referrer);
844}
845
846void GlobalDSGraph::removeReference(const DSGraph* referrer) {
847 if (referrer != this) {
848 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
849 Referrers.erase(referrer);
850 if (Referrers.size() == 0)
851 delete this;
852 }
853}
854
855// Bits used in the next function
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000856static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000857
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000858#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000859// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
860// visible target links (and recursively their such links) into this graph.
861// NodeCache maps the node being cloned to its clone in the Globals graph,
862// in order to track cycles.
863// GlobalsAreFinal is a flag that says whether it is safe to assume that
864// an existing global node is complete. This is important to avoid
865// reinserting all globals when inserting Calls to functions.
866// This is a helper function for cloneGlobals and cloneCalls.
867//
868DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
869 std::map<const DSNode*, DSNode*> &NodeCache,
870 bool GlobalsAreFinal) {
871 if (OldNode == 0) return 0;
872
873 // The caller should check this is an external node. Just more efficient...
874 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
875
876 // If a clone has already been created for OldNode, return it.
877 DSNode*& CacheEntry = NodeCache[OldNode];
878 if (CacheEntry != 0)
879 return CacheEntry;
880
881 // The result value...
882 DSNode* NewNode = 0;
883
884 // If nodes already exist for any of the globals of OldNode,
885 // merge all such nodes together since they are merged in OldNode.
886 // If ValueCacheIsFinal==true, look for an existing node that has
887 // an identical list of globals and return it if it exists.
888 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000889 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
890 if (DSNode *PrevNode = ValueMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000891 if (NewNode == 0) {
892 NewNode = PrevNode; // first existing node found
893 if (GlobalsAreFinal && j == 0)
894 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
895 CacheEntry = NewNode;
896 return NewNode;
897 }
898 }
899 else if (NewNode != PrevNode) { // found another, different from prev
900 // update ValMap *before* merging PrevNode into NewNode
901 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
902 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
903 NewNode->mergeWith(PrevNode);
904 }
905 } else if (NewNode != 0) {
906 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
907 }
908
909 // If no existing node was found, clone the node and update the ValMap.
910 if (NewNode == 0) {
911 NewNode = new DSNode(*OldNode);
912 Nodes.push_back(NewNode);
913 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
914 NewNode->setLink(j, 0);
915 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
916 ValueMap[NewNode->getGlobals()[j]] = NewNode;
917 }
918 else
919 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
920
921 // Add the entry to NodeCache
922 CacheEntry = NewNode;
923
924 // Rewrite the links in the new node to point into the current graph,
925 // but only for links to external nodes. Set other links to NULL.
926 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
927 DSNode* OldTarget = OldNode->getLink(j);
928 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
929 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
930 if (NewNode->getLink(j))
931 NewNode->getLink(j)->mergeWith(NewLink);
932 else
933 NewNode->setLink(j, NewLink);
934 }
935 }
936
937 // Remove all local markers
938 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
939
940 return NewNode;
941}
942
943
944// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
945// visible target links (and recursively their such links) into this graph.
946//
947void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
948 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000949#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000950 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
951 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
952 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000953 if (CloneCalls)
954 GlobalsGraph->cloneCalls(Graph);
955
956 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000957#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000958}
959
960
961// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
962// links (and recursively their such links) into this graph.
963//
964void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
965 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000966 vector<vector<DSNodeHandle> >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000967
968 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
969
970 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000971 FunctionCalls.push_back(vector<DSNodeHandle>());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000972 FunctionCalls.back().reserve(FromCalls[i].size());
973 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
974 FunctionCalls.back().push_back
975 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
976 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
977 : 0);
978 }
979
980 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +0000981 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000982}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000983#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000984
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000985#endif