blob: cd2c898319476babf5976c5499d3b3ca5da16ad3 [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"
Vikram S. Adve26b98262002-10-20 21:41:02 +00009#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000011#include "llvm/Target/TargetData.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000012#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000013#include "Support/Statistic.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000014#include <algorithm>
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include <set>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000016
Chris Lattnere2219762002-07-18 18:22:40 +000017using std::vector;
18
Chris Lattnerfccd06f2002-10-01 22:33:50 +000019// TODO: FIXME
20namespace DataStructureAnalysis {
21 // isPointerType - Return true if this first class type is big enough to hold
22 // a pointer.
23 //
24 bool isPointerType(const Type *Ty);
25 extern TargetData TD;
26}
27using namespace DataStructureAnalysis;
28
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000029//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000030// DSNode Implementation
31//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000032
Chris Lattnerfccd06f2002-10-01 22:33:50 +000033DSNode::DSNode(enum NodeTy NT, const Type *T) : NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000034 // Add the type entry if it is specified...
35 if (T) getTypeRec(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000036}
37
Chris Lattner0d9bab82002-07-18 00:12:30 +000038// DSNode copy constructor... do not copy over the referrers list!
39DSNode::DSNode(const DSNode &N)
Chris Lattner7b7200c2002-10-02 04:57:39 +000040 : Links(N.Links), MergeMap(N.MergeMap),
Chris Lattnerfccd06f2002-10-01 22:33:50 +000041 TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000042}
43
Chris Lattnerc68c31b2002-07-10 22:38:08 +000044void DSNode::removeReferrer(DSNodeHandle *H) {
45 // Search backwards, because we depopulate the list from the back for
46 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000047 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000048 std::find(Referrers.rbegin(), Referrers.rend(), H);
49 assert(I != Referrers.rend() && "Referrer not pointing to node!");
50 Referrers.erase(I.base()-1);
51}
52
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000053// addGlobal - Add an entry for a global value to the Globals list. This also
54// marks the node with the 'G' flag if it does not already have it.
55//
56void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000057 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000058 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000059 std::lower_bound(Globals.begin(), Globals.end(), GV);
60
61 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000062 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000063 Globals.insert(I, GV);
64 NodeType |= GlobalNode;
65 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000066}
67
Chris Lattner8f0a16e2002-10-31 05:45:02 +000068/// foldNodeCompletely - If we determine that this node has some funny
69/// behavior happening to it that we cannot represent, we fold it down to a
70/// single, completely pessimistic, node. This node is represented as a
71/// single byte with a single TypeEntry of "void".
72///
73void DSNode::foldNodeCompletely() {
74 // We are no longer typed at all...
75 TypeEntries.clear();
76 TypeEntries.push_back(DSTypeRec(Type::VoidTy, 0));
77
78 // Loop over all of our referrers, making them point to our one byte of space.
79 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
80 I != E; ++I)
81 (*I)->setOffset(0);
82
83 // Fold the MergeMap down to a single byte of space...
84 MergeMap.resize(1);
85 MergeMap[0] = -1;
86
87 // If we have links, merge all of our outgoing links together...
88 if (!Links.empty()) {
89 MergeMap[0] = 0; // We now contain an outgoing edge...
90 for (unsigned i = 1, e = Links.size(); i != e; ++i)
91 Links[0].mergeWith(Links[i]);
92 Links.resize(1);
93 }
94}
95
96/// isNodeCompletelyFolded - Return true if this node has been completely
97/// folded down to something that can never be expanded, effectively losing
98/// all of the field sensitivity that may be present in the node.
99///
100bool DSNode::isNodeCompletelyFolded() const {
101 return getSize() == 1 && TypeEntries.size() == 1 &&
102 TypeEntries[0].Ty == Type::VoidTy;
103}
104
105
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000106
Chris Lattner7b7200c2002-10-02 04:57:39 +0000107/// setLink - Set the link at the specified offset to the specified
108/// NodeHandle, replacing what was there. It is uncommon to use this method,
109/// instead one of the higher level methods should be used, below.
110///
111void DSNode::setLink(unsigned i, const DSNodeHandle &NH) {
112 // Create a new entry in the Links vector to hold a new element for offset.
113 if (!hasLink(i)) {
114 signed char NewIdx = Links.size();
115 // Check to see if we allocate more than 128 distinct links for this node.
116 // If so, just merge with the last one. This really shouldn't ever happen,
117 // but it should work regardless of whether it does or not.
118 //
119 if (NewIdx >= 0) {
120 Links.push_back(NH); // Allocate space: common case
121 } else { // Wrap around? Too many links?
122 NewIdx--; // Merge with whatever happened last
123 assert(NewIdx > 0 && "Should wrap back around");
124 std::cerr << "\n*** DSNode found that requires more than 128 "
125 << "active links at once!\n\n";
126 }
127
128 signed char OldIdx = MergeMap[i];
129 assert (OldIdx < 0 && "Shouldn't contain link!");
130
131 // Make sure that anything aliasing this field gets updated to point to the
132 // new link field.
133 rewriteMergeMap(OldIdx, NewIdx);
134 assert(MergeMap[i] == NewIdx && "Field not replaced!");
135 } else {
136 Links[MergeMap[i]] = NH;
137 }
138}
139
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000140// addEdgeTo - Add an edge from the current node to the specified node. This
141// can cause merging of nodes in the graph.
142//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000143void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000144 assert(Offset < getSize() && "Offset out of range!");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000145 if (NH.getNode() == 0) return; // Nothing to do
146
Chris Lattner7b7200c2002-10-02 04:57:39 +0000147 if (DSNodeHandle *ExistingNH = getLink(Offset)) {
148 // Merge the two nodes...
149 ExistingNH->mergeWith(NH);
150 } else { // No merging to perform...
151 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000152 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000153}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000154
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000155/// getTypeRec - This method returns the specified type record if it exists.
156/// If it does not yet exist, the method checks to see whether or not the
157/// request would result in an untrackable state. If adding it would cause
158/// untrackable state, we foldNodeCompletely the node and return the void
159/// record, otherwise we add an new TypeEntry and return it.
160///
161DSTypeRec &DSNode::getTypeRec(const Type *Ty, unsigned Offset) {
162 // If the node is already collapsed, we can't do anything... bail out early
163 if (isNodeCompletelyFolded()) {
164 assert(TypeEntries.size() == 1 && "Node folded and Entries.size() != 1?");
165 return TypeEntries[0];
166 }
167
168 // First search to see if we already have a record for this...
169 DSTypeRec SearchFor(Ty, Offset);
170
171 std::vector<DSTypeRec>::iterator I;
172 if (TypeEntries.size() < 5) { // Linear search if we have few entries.
173 I = TypeEntries.begin();
174 while (I != TypeEntries.end() && *I < SearchFor)
175 ++I;
176 } else {
177 I = std::lower_bound(TypeEntries.begin(), TypeEntries.end(), SearchFor);
178 }
179
180 // At this point, I either points to the right entry or it points to the entry
181 // we are to insert the new entry in front of...
182 //
183 if (I != TypeEntries.end() && *I == SearchFor)
184 return *I;
185
186 // ASSUME that it's okay to add this type entry.
187 // FIXME: This should check to make sure it's ok.
188
189 // If the data size is different then our current size, try to resize the node
190 unsigned ReqSize = Ty->isSized() ? TD.getTypeSize(Ty) : 0;
191 if (getSize() < ReqSize) {
192 // If we are trying to make it bigger, and we can grow the node, do so.
193 if (growNode(ReqSize)) {
194 assert(isNodeCompletelyFolded() && "Node isn't folded?");
195 return TypeEntries[0];
196 }
197
198 } else if (getSize() > ReqSize) {
199 // If we are trying to make the node smaller, we don't have to do anything.
200
201 }
202
203 return *TypeEntries.insert(I, SearchFor);
204}
205
206/// growNode - Attempt to grow the node to the specified size. This may do one
207/// of three things:
208/// 1. Grow the node, return false
209/// 2. Refuse to grow the node, but maintain a trackable situation, return
210/// false.
211/// 3. Be unable to track if node was that size, so collapse the node and
212/// return true.
213///
214bool DSNode::growNode(unsigned ReqSize) {
215 unsigned OldSize = getSize();
216
217 if (0) {
218 // FIXME: DSNode::growNode() doesn't perform correct safety checks yet!
219
220 foldNodeCompletely();
221 return true;
222 }
223
224 assert(ReqSize > OldSize && "Not growing node!");
225
226 // Resize the merge map to have enough space...
227 MergeMap.resize(ReqSize);
228
229 // Assign unique values to all of the elements of MergeMap
230 if (ReqSize < 128) {
231 // Handle the common case of reasonable size structures...
232 for (unsigned i = OldSize; i != ReqSize; ++i)
233 MergeMap[i] = -1-i; // Assign -1, -2, -3, ...
234 } else {
235 // It's possible that we have something really big here. In this case,
236 // divide the object into chunks until it will fit into 128 elements.
237 unsigned Multiple = ReqSize/128;
238
239 // It's probably an array, and probably some power of two in size.
240 // Because of this, find the biggest power of two that is bigger than
241 // multiple to use as our real Multiple.
242 unsigned RealMultiple = 2;
243 while (RealMultiple <= Multiple) RealMultiple <<= 1;
244
245 unsigned RealBound = ReqSize/RealMultiple;
246 assert(RealBound <= 128 && "Math didn't work out right");
247
248 // Now go through and assign indexes that are between -1 and -128
249 // inclusive
250 //
251 for (unsigned i = OldSize; i != ReqSize; ++i)
252 MergeMap[i] = -1-(i % RealBound); // Assign -1, -2, -3...
253 }
254 return false;
255}
256
Chris Lattner7b7200c2002-10-02 04:57:39 +0000257/// mergeMappedValues - This is the higher level form of rewriteMergeMap. It is
258/// fully capable of merging links together if neccesary as well as simply
259/// rewriting the map entries.
260///
261void DSNode::mergeMappedValues(signed char V1, signed char V2) {
262 assert(V1 != V2 && "Cannot merge two identical mapped values!");
263
264 if (V1 < 0) { // If there is no outgoing link from V1, merge it with V2
265 if (V2 < 0 && V1 > V2)
266 // If both are not linked, merge to the field closer to 0
267 rewriteMergeMap(V2, V1);
268 else
269 rewriteMergeMap(V1, V2);
270 } else if (V2 < 0) { // Is V2 < 0 && V1 >= 0?
271 rewriteMergeMap(V2, V1); // Merge into the one with the link...
272 } else { // Otherwise, links exist at both locations
273 // Merge Links[V1] with Links[V2] so they point to the same place now...
274 Links[V1].mergeWith(Links[V2]);
275
276 // Merge the V2 link into V1 so that we reduce the overall value of the
277 // links are reduced...
278 //
279 if (V2 < V1) std::swap(V1, V2); // Ensure V1 < V2
280 rewriteMergeMap(V2, V1); // After this, V2 is "dead"
281
282 // Change the user of the last link to use V2 instead
283 if ((unsigned)V2 != Links.size()-1) {
284 rewriteMergeMap(Links.size()-1, V2); // Point to V2 instead of last el...
285 // Make sure V2 points the right DSNode
286 Links[V2] = Links.back();
287 }
288
289 // Reduce the number of distinct outgoing links...
290 Links.pop_back();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000291 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000292}
293
294
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000295// MergeSortedVectors - Efficiently merge a vector into another vector where
296// duplicates are not allowed and both are sorted. This assumes that 'T's are
297// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000298//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000299template<typename T>
300void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
301 // By far, the most common cases will be the simple ones. In these cases,
302 // avoid having to allocate a temporary vector...
303 //
304 if (Src.empty()) { // Nothing to merge in...
305 return;
306 } else if (Dest.empty()) { // Just copy the result in...
307 Dest = Src;
308 } else if (Src.size() == 1) { // Insert a single element...
309 const T &V = Src[0];
310 typename vector<T>::iterator I =
311 std::lower_bound(Dest.begin(), Dest.end(), V);
312 if (I == Dest.end() || *I != Src[0]) // If not already contained...
313 Dest.insert(I, Src[0]);
314 } else if (Dest.size() == 1) {
315 T Tmp = Dest[0]; // Save value in temporary...
316 Dest = Src; // Copy over list...
317 typename vector<T>::iterator I =
318 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
319 if (I == Dest.end() || *I != Src[0]) // If not already contained...
320 Dest.insert(I, Src[0]);
321
322 } else {
323 // Make a copy to the side of Dest...
324 vector<T> Old(Dest);
325
326 // Make space for all of the type entries now...
327 Dest.resize(Dest.size()+Src.size());
328
329 // Merge the two sorted ranges together... into Dest.
330 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
331
332 // Now erase any duplicate entries that may have accumulated into the
333 // vectors (because they were in both of the input sets)
334 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
335 }
336}
337
338
339// mergeWith - Merge this node and the specified node, moving all links to and
340// from the argument node into the current node, deleting the node argument.
341// Offset indicates what offset the specified node is to be merged into the
342// current node.
343//
344// The specified node may be a null pointer (in which case, nothing happens).
345//
346void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
347 DSNode *N = NH.getNode();
348 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000349 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000350
351 assert(NH.getNode() != this &&
352 "Cannot merge two portions of the same node yet!");
353
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000354 // If we are merging a node with a completely folded node, then both nodes are
355 // now completely folded.
356 //
357 if (isNodeCompletelyFolded()) {
358 NH.getNode()->foldNodeCompletely();
359 } else if (NH.getNode()->isNodeCompletelyFolded()) {
360 foldNodeCompletely();
361 Offset = 0;
362 }
363
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000364 // If both nodes are not at offset 0, make sure that we are merging the node
365 // at an later offset into the node with the zero offset.
366 //
367 if (Offset > NH.getOffset()) {
368 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
369 return;
370 }
371
372#if 0
373 std::cerr << "\n\nMerging:\n";
374 N->print(std::cerr, 0);
375 std::cerr << " and:\n";
376 print(std::cerr, 0);
377#endif
378
379 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
380 // respect to NH.Offset) is now zero.
381 //
382 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000383
Chris Lattner7b7200c2002-10-02 04:57:39 +0000384 unsigned NSize = N->getSize();
385 assert(NSize+NOffset <= getSize() &&
386 "Don't know how to merge extend a merged nodes size yet!");
387
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000388 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000389 // Make sure to adjust their offset, not just the node pointer.
390 //
391 while (!N->Referrers.empty()) {
392 DSNodeHandle &Ref = *N->Referrers.back();
393 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
394 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000395
Chris Lattner7b7200c2002-10-02 04:57:39 +0000396 // We must merge fields in this node due to nodes merged in the source node.
397 // In order to handle this we build a map that converts from the source node's
398 // MergeMap values to our MergeMap values. This map is indexed by the
399 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
400 // 2*SourceNodeSize elements of space for the mapping. We can do this because
401 // we know that there are at most SourceNodeSize outgoing links in the node
402 // (thus that many positive values) and at most SourceNodeSize distinct fields
403 // (thus that many negative values).
404 //
405 std::vector<signed char> MergeMapMap(NSize*2, 127);
406
407 // Loop through the structures, merging them together...
408 for (unsigned i = 0, e = NSize; i != e; ++i) {
409 // Get what this byte of N maps to...
410 signed char NElement = N->MergeMap[i];
411
412 // Get what we map this byte to...
413 signed char Element = MergeMap[i+NOffset];
414 // We use 127 as a sentinal and don't check for it's existence yet...
415 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
416
417 signed char CurMappedVal = MergeMapMap[NElement+NSize];
418 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
419 MergeMapMap[NElement+NSize] = Element; // Map the two together...
420 } else if (CurMappedVal != Element) {
421 // If we are mapping two different fields together this means that we need
422 // to merge fields in the current node due to merging in the source node.
423 //
424 mergeMappedValues(CurMappedVal, Element);
425 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
426 }
427 }
428
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000429 // Make all of the outgoing links of N now be outgoing links of this. This
430 // can cause recursive merging!
431 //
Chris Lattner7b7200c2002-10-02 04:57:39 +0000432 for (unsigned i = 0, e = NSize; i != e; ++i)
433 if (DSNodeHandle *Link = N->getLink(i)) {
434 addEdgeTo(i+NOffset, *Link);
435 N->MergeMap[i] = -1; // Kill outgoing edge
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000436 }
437
438 // Now that there are no outgoing edges, all of the Links are dead.
439 N->Links.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000440
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000441 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000442 NodeType |= N->NodeType;
443 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000444
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000445 // Adjust all of the type entries we are merging in by the offset...
446 //
447 if (NOffset != 0) { // This case is common enough to optimize for
448 // Offset all of the TypeEntries in N with their new offset
449 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
450 N->TypeEntries[i].Offset += NOffset;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000451 }
452
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000453 // ... now add them to the TypeEntries list.
454 MergeSortedVectors(TypeEntries, N->TypeEntries);
455 N->TypeEntries.clear(); // N is dead, no type-entries need exist
456
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000457 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000458 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000459 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000460
461 // Delete the globals from the old node...
462 N->Globals.clear();
463 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000464}
465
Chris Lattner9de906c2002-10-20 22:11:44 +0000466//===----------------------------------------------------------------------===//
467// DSCallSite Implementation
468//===----------------------------------------------------------------------===//
469
Vikram S. Adve26b98262002-10-20 21:41:02 +0000470// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000471Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000472 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000473}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000474
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000475
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000476//===----------------------------------------------------------------------===//
477// DSGraph Implementation
478//===----------------------------------------------------------------------===//
479
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000480DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
481 std::map<const DSNode*, DSNode*> NodeMap;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000482 RetNode = cloneInto(G, ValueMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000483}
484
Chris Lattnereff0da92002-10-21 15:32:34 +0000485DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
486 : Func(G.Func) {
487 RetNode = cloneInto(G, ValueMap, NodeMap);
488}
489
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000490DSGraph::~DSGraph() {
491 FunctionCalls.clear();
492 ValueMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000493 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000494
495#ifndef NDEBUG
496 // Drop all intra-node references, so that assertions don't fail...
497 std::for_each(Nodes.begin(), Nodes.end(),
498 std::mem_fun(&DSNode::dropAllReferences));
499#endif
500
501 // Delete all of the nodes themselves...
502 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
503}
504
Chris Lattner0d9bab82002-07-18 00:12:30 +0000505// dump - Allow inspection of graph in a debugger.
506void DSGraph::dump() const { print(std::cerr); }
507
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000508
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000509// Helper function used to clone a function list.
510//
511static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
512 vector<DSCallSite> &toCalls,
513 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000514 unsigned FC = toCalls.size(); // FirstCall
515 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000516 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000517 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000518}
519
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000520/// remapLinks - Change all of the Links in the current node according to the
521/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000522///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000523void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
524 for (unsigned i = 0, e = Links.size(); i != e; ++i)
525 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
526}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000527
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000528
Chris Lattner0d9bab82002-07-18 00:12:30 +0000529// cloneInto - Clone the specified DSGraph into the current graph, returning the
530// Return node of the graph. The translated ValueMap for the old function is
531// filled into the OldValMap member. If StripLocals is set to true, Scalar and
532// Alloca markers are removed from the graph, as the graph is being cloned into
533// a calling function's graph.
534//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000535DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
536 std::map<Value*, DSNodeHandle> &OldValMap,
537 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattnere4ae3042002-10-21 19:50:29 +0000538 bool StripScalars, bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000539 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000540
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000541 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000542
543 // Duplicate all of the nodes, populating the node map...
544 Nodes.reserve(FN+G.Nodes.size());
545 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000546 DSNode *Old = G.Nodes[i];
547 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000548 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000549 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000550 }
551
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000552 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000553 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000554 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000555
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000556 // Remove local markers as specified
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000557 unsigned char StripBits = (StripScalars ? DSNode::ScalarNode : 0) |
558 (StripAllocas ? DSNode::AllocaNode : 0);
559 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000560 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000561 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000562
Chris Lattnercf15db32002-10-17 20:09:52 +0000563 // Copy the value map... and merge all of the global nodes...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000564 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
Chris Lattnercf15db32002-10-17 20:09:52 +0000565 E = G.ValueMap.end(); I != E; ++I) {
566 DSNodeHandle &H = OldValMap[I->first];
567 H = DSNodeHandle(OldNodeMap[I->second.getNode()], I->second.getOffset());
568
569 if (isa<GlobalValue>(I->first)) { // Is this a global?
570 std::map<Value*, DSNodeHandle>::iterator GVI = ValueMap.find(I->first);
571 if (GVI != ValueMap.end()) { // Is the global value in this fun already?
572 GVI->second.mergeWith(H);
573 } else {
574 ValueMap[I->first] = H; // Add global pointer to this graph
575 }
576 }
577 }
Chris Lattnere2219762002-07-18 18:22:40 +0000578 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000579 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000580
Chris Lattnercf15db32002-10-17 20:09:52 +0000581
Chris Lattner0d9bab82002-07-18 00:12:30 +0000582 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000583 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000584}
585
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000586#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000587// cloneGlobalInto - Clone the given global node and all its target links
588// (and all their llinks, recursively).
589//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000590DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000591 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
592
593 // If a clone has already been created for GNode, return it.
594 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
595 if (ValMapEntry != 0)
596 return ValMapEntry;
597
598 // Clone the node and update the ValMap.
599 DSNode* NewNode = new DSNode(*GNode);
600 ValMapEntry = NewNode; // j=0 case of loop below!
601 Nodes.push_back(NewNode);
602 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
603 ValueMap[NewNode->getGlobals()[j]] = NewNode;
604
605 // Rewrite the links in the new node to point into the current graph.
606 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
607 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
608
609 return NewNode;
610}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000611#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000612
613
Chris Lattner0d9bab82002-07-18 00:12:30 +0000614// markIncompleteNodes - Mark the specified node as having contents that are not
615// known with the current analysis we have performed. Because a node makes all
616// of the nodes it can reach imcomplete if the node itself is incomplete, we
617// must recursively traverse the data structure graph, marking all reachable
618// nodes as incomplete.
619//
620static void markIncompleteNode(DSNode *N) {
621 // Stop recursion if no node, or if node already marked...
622 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
623
624 // Actually mark the node
625 N->NodeType |= DSNode::Incomplete;
626
627 // Recusively process children...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000628 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
629 if (DSNodeHandle *DSNH = N->getLink(i))
630 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000631}
632
633
634// markIncompleteNodes - Traverse the graph, identifying nodes that may be
635// modified by other functions that have not been resolved yet. This marks
636// nodes that are reachable through three sources of "unknownness":
637//
638// Global Variables, Function Calls, and Incoming Arguments
639//
640// For any node that may have unknown components (because something outside the
641// scope of current analysis may have modified it), the 'Incomplete' flag is
642// added to the NodeType.
643//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000644void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000645 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000646 if (markFormalArgs && Func)
647 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
648 if (isPointerType(I->getType()) && ValueMap.find(I) != ValueMap.end()) {
649 DSNodeHandle &INH = ValueMap[I];
650 if (INH.getNode() && INH.hasLink(0))
651 markIncompleteNode(ValueMap[I].getLink(0)->getNode());
652 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000653
654 // Mark stuff passed into functions calls as being incomplete...
655 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000656 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000657 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000658 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000659
660 // The call does not make the function argument incomplete...
661
662 // All arguments to the function call are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000663 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000664 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000665 }
666
Chris Lattner055dc2c2002-07-18 15:54:42 +0000667 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000668 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000669 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000670 DSNode *N = Nodes[i];
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000671 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
672 if (DSNodeHandle *DSNH = N->getLink(i))
673 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000674 }
675}
676
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000677// removeRefsToGlobal - Helper function that removes globals from the
678// ValueMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000679static void removeRefsToGlobal(DSNode* N,
680 std::map<Value*, DSNodeHandle> &ValueMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000681 while (!N->getGlobals().empty()) {
682 GlobalValue *GV = N->getGlobals().back();
683 N->getGlobals().pop_back();
684 ValueMap.erase(GV);
685 }
686}
687
688
Chris Lattner0d9bab82002-07-18 00:12:30 +0000689// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
690// checks to see if there are simple transformations that it can do to make it
691// dead.
692//
693bool DSGraph::isNodeDead(DSNode *N) {
694 // Is it a trivially dead shadow node...
695 if (N->getReferrers().empty() && N->NodeType == 0)
696 return true;
697
698 // Is it a function node or some other trivially unused global?
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000699 if (N->NodeType != 0 &&
700 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000701 N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000702 N->getReferrers().size() == N->getGlobals().size()) {
703
Chris Lattnera00397e2002-10-03 21:55:28 +0000704 // Remove the globals from the ValueMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000705 // down to zero.
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000706 removeRefsToGlobal(N, ValueMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000707 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
708 return true;
709 }
710
711 return false;
712}
713
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000714static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000715 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000716 // Remove trivially identical function calls
717 unsigned NumFns = Calls.size();
718 std::sort(Calls.begin(), Calls.end());
719 Calls.erase(std::unique(Calls.begin(), Calls.end()),
720 Calls.end());
721
722 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000723 std::cerr << "Merged " << (NumFns-Calls.size())
724 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000725}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000726
Chris Lattnere2219762002-07-18 18:22:40 +0000727// removeTriviallyDeadNodes - After the graph has been constructed, this method
728// removes all unreachable nodes that are created because they got merged with
729// other nodes in the graph. These nodes will all be trivially unreachable, so
730// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000731//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000732void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000733 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000734 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000735 if (isNodeDead(Nodes[i])) { // This node is dead!
736 delete Nodes[i]; // Free memory...
737 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
738 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000739
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000740 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000741}
742
743
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000744// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000745// stuff to be alive.
746//
747static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000748 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000749
750 Alive.insert(N);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000751 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
752 if (DSNodeHandle *DSNH = N->getLink(i))
753 if (!Alive.count(DSNH->getNode()))
754 markAlive(DSNH->getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000755}
756
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000757static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
758 std::set<DSNode*> &Visiting) {
759 if (N == 0) return false;
760
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000761 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000762 Visiting.insert(N);
763
764 // If any immediate successor is alive, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000765 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
766 if (DSNodeHandle *DSNH = N->getLink(i))
767 if (Alive.count(DSNH->getNode())) {
768 Visiting.erase(N);
769 return true;
770 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000771
772 // Else if any successor reaches a live node, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000773 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
774 if (DSNodeHandle *DSNH = N->getLink(i))
775 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
776 Visiting.erase(N); return true;
777 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000778
779 Visiting.erase(N);
780 return false;
781}
782
783
784// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
785// This would be unnecessary if function calls were real nodes! In that case,
786// the simple iterative loop in the first few lines below suffice.
787//
788static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000789 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000790 std::set<DSNode*> &Alive,
791 bool FilterCalls) {
792
793 // Iterate, marking globals or cast nodes alive until no new live nodes
794 // are added to Alive
795 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000796 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000797 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
798 liveCount = Alive.size();
799 for ( ; I != E; ++I)
800 if (Alive.count(*I) == 0) {
801 Visiting.clear();
802 if (checkGlobalAlive(*I, Alive, Visiting))
803 markAlive(*I, Alive);
804 }
805 }
806
807 // Find function calls with some dead and some live nodes.
808 // Since all call nodes must be live if any one is live, we have to mark
809 // all nodes of the call as live and continue the iteration (via recursion).
810 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000811 bool Recurse = false;
812 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000813 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000814 DSCallSite &CS = Calls[i];
815 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
816 if (DSNode *N = CS.getPtrArg(j).getNode()) {
817 bool ArgIsDead = !Alive.count(N);
818 CallHasDeadArg |= ArgIsDead;
819 CallIsDead &= ArgIsDead;
820 }
821
822 if (DSNode *N = CS.getRetVal().getNode()) {
823 bool RetIsDead = !Alive.count(N);
824 CallHasDeadArg |= RetIsDead;
825 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000826 }
Chris Lattner0969c502002-10-21 02:08:03 +0000827
828 DSNode *N = CS.getCallee().getNode();
829 bool FnIsDead = !Alive.count(N);
830 CallHasDeadArg |= FnIsDead;
831 CallIsDead &= FnIsDead;
832
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000833 if (!CallIsDead && CallHasDeadArg) {
834 // Some node in this call is live and another is dead.
835 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000836 Recurse = true;
837 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
838 markAlive(CS.getPtrArg(j).getNode(), Alive);
839 markAlive(CS.getRetVal().getNode(), Alive);
840 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000841 }
842 }
Chris Lattner0969c502002-10-21 02:08:03 +0000843 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000844 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
845 }
846}
847
848
849// markGlobalsAlive - Mark global nodes and cast nodes alive if they
850// can reach any other live node. Since this can produce new live nodes,
851// we use a simple iterative algorithm.
852//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000853static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000854 bool FilterCalls) {
855 // Add global and cast nodes to a set so we don't walk all nodes every time
856 std::set<DSNode*> GlobalNodes;
857 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000858 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000859 GlobalNodes.insert(G.getNodes()[i]);
860
861 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000862 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000863 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000864 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
865 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
866 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
867 GlobalNodes.insert(N);
868 if (DSNode *N = Calls[i].getRetVal().getNode())
869 GlobalNodes.insert(N);
870 if (DSNode *N = Calls[i].getCallee().getNode())
871 GlobalNodes.insert(N);
872 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000873 }
874
875 // Iterate and recurse until no new live node are discovered.
876 // This would be a simple iterative loop if function calls were real nodes!
877 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
878
879 // Free up references to dead globals from the ValueMap
880 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
881 for( ; I != E; ++I)
882 if (Alive.count(*I) == 0)
883 removeRefsToGlobal(*I, G.getValueMap());
884
885 // Delete dead function calls
886 if (FilterCalls)
887 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
888 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000889 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
890 CallIsDead && j != ej; ++j)
891 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000892 if (CallIsDead)
893 Calls.erase(Calls.begin() + i); // remove the call entirely
894 }
895}
Chris Lattnere2219762002-07-18 18:22:40 +0000896
897// removeDeadNodes - Use a more powerful reachability analysis to eliminate
898// subgraphs that are unreachable. This often occurs because the data
899// structure doesn't "escape" into it's caller, and thus should be eliminated
900// from the caller's graph entirely. This is only appropriate to use when
901// inlining graphs.
902//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000903void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
904 assert((!KeepAllGlobals || KeepCalls) &&
905 "KeepAllGlobals without KeepCalls is meaningless");
906
Chris Lattnere2219762002-07-18 18:22:40 +0000907 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000908 removeTriviallyDeadNodes(KeepAllGlobals);
909
Chris Lattnere2219762002-07-18 18:22:40 +0000910 // FIXME: Merge nontrivially identical call nodes...
911
912 // Alive - a set that holds all nodes found to be reachable/alive.
913 std::set<DSNode*> Alive;
914
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000915 // If KeepCalls, mark all nodes reachable by call nodes as alive...
916 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000917 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
918 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
919 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
920 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
921 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
922 }
Chris Lattnere2219762002-07-18 18:22:40 +0000923
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000924#if 0
Chris Lattnere2219762002-07-18 18:22:40 +0000925 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
926 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000927 markAlive(OrigFunctionCalls[i][j].getNode(), Alive);
928#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000929
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000930 // Mark all nodes reachable by scalar nodes (and global nodes, if
931 // keeping them was specified) as alive...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000932 unsigned char keepBits = DSNode::ScalarNode |
933 (KeepAllGlobals ? DSNode::GlobalNode : 0);
Chris Lattnere2219762002-07-18 18:22:40 +0000934 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000935 if (Nodes[i]->NodeType & keepBits)
Chris Lattnere2219762002-07-18 18:22:40 +0000936 markAlive(Nodes[i], Alive);
937
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000938 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000939 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000940
941 // Mark all globals or cast nodes that can reach a live node as alive.
942 // This also marks all nodes reachable from such nodes as alive.
943 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000944 if (!KeepAllGlobals)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000945 markGlobalsAlive(*this, Alive, ! KeepCalls);
946
Chris Lattnere2219762002-07-18 18:22:40 +0000947 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000948 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000949 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
950 for (unsigned i = 0; i != Nodes.size(); ++i)
951 if (!Alive.count(Nodes[i])) {
952 DSNode *N = Nodes[i];
953 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
954 DeadNodes.push_back(N); // Add node to our list of dead nodes
955 N->dropAllReferences(); // Drop all outgoing edges
956 }
957
Chris Lattnere2219762002-07-18 18:22:40 +0000958 // Delete all dead nodes...
959 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
960}
961
962
963
Chris Lattner0d9bab82002-07-18 00:12:30 +0000964// maskNodeTypes - Apply a mask to all of the node types in the graph. This
965// is useful for clearing out markers like Scalar or Incomplete.
966//
967void DSGraph::maskNodeTypes(unsigned char Mask) {
968 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
969 Nodes[i]->NodeType &= Mask;
970}
971
972
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000973#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000974//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000975// GlobalDSGraph Implementation
976//===----------------------------------------------------------------------===//
977
978GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
979}
980
981GlobalDSGraph::~GlobalDSGraph() {
982 assert(Referrers.size() == 0 &&
983 "Deleting global graph while references from other graphs exist");
984}
985
986void GlobalDSGraph::addReference(const DSGraph* referrer) {
987 if (referrer != this)
988 Referrers.insert(referrer);
989}
990
991void GlobalDSGraph::removeReference(const DSGraph* referrer) {
992 if (referrer != this) {
993 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
994 Referrers.erase(referrer);
995 if (Referrers.size() == 0)
996 delete this;
997 }
998}
999
1000// Bits used in the next function
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001001static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001002
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001003#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001004// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1005// visible target links (and recursively their such links) into this graph.
1006// NodeCache maps the node being cloned to its clone in the Globals graph,
1007// in order to track cycles.
1008// GlobalsAreFinal is a flag that says whether it is safe to assume that
1009// an existing global node is complete. This is important to avoid
1010// reinserting all globals when inserting Calls to functions.
1011// This is a helper function for cloneGlobals and cloneCalls.
1012//
1013DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1014 std::map<const DSNode*, DSNode*> &NodeCache,
1015 bool GlobalsAreFinal) {
1016 if (OldNode == 0) return 0;
1017
1018 // The caller should check this is an external node. Just more efficient...
1019 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1020
1021 // If a clone has already been created for OldNode, return it.
1022 DSNode*& CacheEntry = NodeCache[OldNode];
1023 if (CacheEntry != 0)
1024 return CacheEntry;
1025
1026 // The result value...
1027 DSNode* NewNode = 0;
1028
1029 // If nodes already exist for any of the globals of OldNode,
1030 // merge all such nodes together since they are merged in OldNode.
1031 // If ValueCacheIsFinal==true, look for an existing node that has
1032 // an identical list of globals and return it if it exists.
1033 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001034 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1035 if (DSNode *PrevNode = ValueMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001036 if (NewNode == 0) {
1037 NewNode = PrevNode; // first existing node found
1038 if (GlobalsAreFinal && j == 0)
1039 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1040 CacheEntry = NewNode;
1041 return NewNode;
1042 }
1043 }
1044 else if (NewNode != PrevNode) { // found another, different from prev
1045 // update ValMap *before* merging PrevNode into NewNode
1046 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1047 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
1048 NewNode->mergeWith(PrevNode);
1049 }
1050 } else if (NewNode != 0) {
1051 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1052 }
1053
1054 // If no existing node was found, clone the node and update the ValMap.
1055 if (NewNode == 0) {
1056 NewNode = new DSNode(*OldNode);
1057 Nodes.push_back(NewNode);
1058 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1059 NewNode->setLink(j, 0);
1060 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1061 ValueMap[NewNode->getGlobals()[j]] = NewNode;
1062 }
1063 else
1064 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1065
1066 // Add the entry to NodeCache
1067 CacheEntry = NewNode;
1068
1069 // Rewrite the links in the new node to point into the current graph,
1070 // but only for links to external nodes. Set other links to NULL.
1071 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1072 DSNode* OldTarget = OldNode->getLink(j);
1073 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1074 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1075 if (NewNode->getLink(j))
1076 NewNode->getLink(j)->mergeWith(NewLink);
1077 else
1078 NewNode->setLink(j, NewLink);
1079 }
1080 }
1081
1082 // Remove all local markers
1083 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1084
1085 return NewNode;
1086}
1087
1088
1089// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1090// visible target links (and recursively their such links) into this graph.
1091//
1092void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1093 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001094#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001095 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1096 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1097 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001098 if (CloneCalls)
1099 GlobalsGraph->cloneCalls(Graph);
1100
1101 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001102#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001103}
1104
1105
1106// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1107// links (and recursively their such links) into this graph.
1108//
1109void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1110 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001111 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001112
1113 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1114
1115 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001116 DSCallSite& callCopy = FunctionCalls.back();
1117 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001118 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001119 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001120 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1121 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1122 : 0);
1123 }
1124
1125 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001126 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001127}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001128#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001129
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001130#endif