blob: 57f677cd67e3f1a658f18b549ab6d2e65c20f2c1 [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 Lattner92673292002-11-02 00:13:20 +000019namespace DataStructureAnalysis { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000020 // 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) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000033 // Add the type entry if it is specified...
34 if (T) getTypeRec(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000035}
36
Chris Lattner0d9bab82002-07-18 00:12:30 +000037// DSNode copy constructor... do not copy over the referrers list!
38DSNode::DSNode(const DSNode &N)
Chris Lattner7b7200c2002-10-02 04:57:39 +000039 : Links(N.Links), MergeMap(N.MergeMap),
Chris Lattnerfccd06f2002-10-01 22:33:50 +000040 TypeEntries(N.TypeEntries), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000041}
42
Chris Lattnerc68c31b2002-07-10 22:38:08 +000043void DSNode::removeReferrer(DSNodeHandle *H) {
44 // Search backwards, because we depopulate the list from the back for
45 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000046 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000047 std::find(Referrers.rbegin(), Referrers.rend(), H);
48 assert(I != Referrers.rend() && "Referrer not pointing to node!");
49 Referrers.erase(I.base()-1);
50}
51
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000052// addGlobal - Add an entry for a global value to the Globals list. This also
53// marks the node with the 'G' flag if it does not already have it.
54//
55void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000056 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000057 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000058 std::lower_bound(Globals.begin(), Globals.end(), GV);
59
60 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000061 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000062 Globals.insert(I, GV);
63 NodeType |= GlobalNode;
64 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000065}
66
Chris Lattner8f0a16e2002-10-31 05:45:02 +000067/// foldNodeCompletely - If we determine that this node has some funny
68/// behavior happening to it that we cannot represent, we fold it down to a
69/// single, completely pessimistic, node. This node is represented as a
70/// single byte with a single TypeEntry of "void".
71///
72void DSNode::foldNodeCompletely() {
73 // We are no longer typed at all...
74 TypeEntries.clear();
75 TypeEntries.push_back(DSTypeRec(Type::VoidTy, 0));
76
77 // Loop over all of our referrers, making them point to our one byte of space.
78 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
79 I != E; ++I)
80 (*I)->setOffset(0);
81
82 // Fold the MergeMap down to a single byte of space...
83 MergeMap.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000084
85 // If we have links, merge all of our outgoing links together...
86 if (!Links.empty()) {
87 MergeMap[0] = 0; // We now contain an outgoing edge...
88 for (unsigned i = 1, e = Links.size(); i != e; ++i)
89 Links[0].mergeWith(Links[i]);
90 Links.resize(1);
Chris Lattner59535132002-11-05 00:01:58 +000091 } else {
92 MergeMap[0] = -1;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000093 }
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 {
Chris Lattner59535132002-11-05 00:01:58 +0000136 assert(MergeMap[i] < (int)Links.size() && "MergeMap index out of range!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000137 Links[MergeMap[i]] = NH;
138 }
139}
140
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000141// addEdgeTo - Add an edge from the current node to the specified node. This
142// can cause merging of nodes in the graph.
143//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000144void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000145 assert(Offset < getSize() && "Offset out of range!");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000146 if (NH.getNode() == 0) return; // Nothing to do
147
Chris Lattner7b7200c2002-10-02 04:57:39 +0000148 if (DSNodeHandle *ExistingNH = getLink(Offset)) {
149 // Merge the two nodes...
150 ExistingNH->mergeWith(NH);
151 } else { // No merging to perform...
152 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000153 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000154}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000155
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000156/// getTypeRec - This method returns the specified type record if it exists.
157/// If it does not yet exist, the method checks to see whether or not the
158/// request would result in an untrackable state. If adding it would cause
159/// untrackable state, we foldNodeCompletely the node and return the void
160/// record, otherwise we add an new TypeEntry and return it.
161///
162DSTypeRec &DSNode::getTypeRec(const Type *Ty, unsigned Offset) {
163 // If the node is already collapsed, we can't do anything... bail out early
164 if (isNodeCompletelyFolded()) {
165 assert(TypeEntries.size() == 1 && "Node folded and Entries.size() != 1?");
166 return TypeEntries[0];
167 }
168
169 // First search to see if we already have a record for this...
170 DSTypeRec SearchFor(Ty, Offset);
171
172 std::vector<DSTypeRec>::iterator I;
173 if (TypeEntries.size() < 5) { // Linear search if we have few entries.
174 I = TypeEntries.begin();
175 while (I != TypeEntries.end() && *I < SearchFor)
176 ++I;
177 } else {
178 I = std::lower_bound(TypeEntries.begin(), TypeEntries.end(), SearchFor);
179 }
180
181 // At this point, I either points to the right entry or it points to the entry
182 // we are to insert the new entry in front of...
183 //
184 if (I != TypeEntries.end() && *I == SearchFor)
185 return *I;
186
187 // ASSUME that it's okay to add this type entry.
188 // FIXME: This should check to make sure it's ok.
189
190 // If the data size is different then our current size, try to resize the node
191 unsigned ReqSize = Ty->isSized() ? TD.getTypeSize(Ty) : 0;
192 if (getSize() < ReqSize) {
193 // If we are trying to make it bigger, and we can grow the node, do so.
194 if (growNode(ReqSize)) {
195 assert(isNodeCompletelyFolded() && "Node isn't folded?");
196 return TypeEntries[0];
197 }
198
199 } else if (getSize() > ReqSize) {
200 // If we are trying to make the node smaller, we don't have to do anything.
201
202 }
203
204 return *TypeEntries.insert(I, SearchFor);
205}
206
207/// growNode - Attempt to grow the node to the specified size. This may do one
208/// of three things:
209/// 1. Grow the node, return false
210/// 2. Refuse to grow the node, but maintain a trackable situation, return
211/// false.
212/// 3. Be unable to track if node was that size, so collapse the node and
213/// return true.
214///
215bool DSNode::growNode(unsigned ReqSize) {
216 unsigned OldSize = getSize();
217
218 if (0) {
219 // FIXME: DSNode::growNode() doesn't perform correct safety checks yet!
220
221 foldNodeCompletely();
222 return true;
223 }
224
225 assert(ReqSize > OldSize && "Not growing node!");
226
227 // Resize the merge map to have enough space...
228 MergeMap.resize(ReqSize);
229
230 // Assign unique values to all of the elements of MergeMap
231 if (ReqSize < 128) {
232 // Handle the common case of reasonable size structures...
233 for (unsigned i = OldSize; i != ReqSize; ++i)
234 MergeMap[i] = -1-i; // Assign -1, -2, -3, ...
235 } else {
236 // It's possible that we have something really big here. In this case,
237 // divide the object into chunks until it will fit into 128 elements.
238 unsigned Multiple = ReqSize/128;
239
240 // It's probably an array, and probably some power of two in size.
241 // Because of this, find the biggest power of two that is bigger than
242 // multiple to use as our real Multiple.
243 unsigned RealMultiple = 2;
244 while (RealMultiple <= Multiple) RealMultiple <<= 1;
245
246 unsigned RealBound = ReqSize/RealMultiple;
247 assert(RealBound <= 128 && "Math didn't work out right");
248
249 // Now go through and assign indexes that are between -1 and -128
250 // inclusive
251 //
252 for (unsigned i = OldSize; i != ReqSize; ++i)
253 MergeMap[i] = -1-(i % RealBound); // Assign -1, -2, -3...
254 }
255 return false;
256}
257
Chris Lattner7b7200c2002-10-02 04:57:39 +0000258/// mergeMappedValues - This is the higher level form of rewriteMergeMap. It is
259/// fully capable of merging links together if neccesary as well as simply
260/// rewriting the map entries.
261///
262void DSNode::mergeMappedValues(signed char V1, signed char V2) {
263 assert(V1 != V2 && "Cannot merge two identical mapped values!");
Chris Lattner59535132002-11-05 00:01:58 +0000264 assert(V2 < (int)Links.size() &&
265 "Attempting to rewrite to invalid link number!");
266 assert(V1 < (int)Links.size() &&
267 "Attempting to rewrite to invalid link number!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000268
269 if (V1 < 0) { // If there is no outgoing link from V1, merge it with V2
270 if (V2 < 0 && V1 > V2)
271 // If both are not linked, merge to the field closer to 0
272 rewriteMergeMap(V2, V1);
273 else
274 rewriteMergeMap(V1, V2);
275 } else if (V2 < 0) { // Is V2 < 0 && V1 >= 0?
276 rewriteMergeMap(V2, V1); // Merge into the one with the link...
277 } else { // Otherwise, links exist at both locations
Chris Lattner7b7200c2002-10-02 04:57:39 +0000278 // Merge the V2 link into V1 so that we reduce the overall value of the
Chris Lattner59535132002-11-05 00:01:58 +0000279 // links are reduced...
Chris Lattner7b7200c2002-10-02 04:57:39 +0000280 //
281 if (V2 < V1) std::swap(V1, V2); // Ensure V1 < V2
282 rewriteMergeMap(V2, V1); // After this, V2 is "dead"
283
Chris Lattner59535132002-11-05 00:01:58 +0000284 // Merge Links[V1] with Links[V2] so they point to the same place now...
285 Links[V1].mergeWith(Links[V2]); // BROKEN, this can invalidate V2!!
286
Chris Lattner7b7200c2002-10-02 04:57:39 +0000287 // Change the user of the last link to use V2 instead
288 if ((unsigned)V2 != Links.size()-1) {
289 rewriteMergeMap(Links.size()-1, V2); // Point to V2 instead of last el...
290 // Make sure V2 points the right DSNode
291 Links[V2] = Links.back();
292 }
293
294 // Reduce the number of distinct outgoing links...
295 Links.pop_back();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000296 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000297}
298
299
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000300// MergeSortedVectors - Efficiently merge a vector into another vector where
301// duplicates are not allowed and both are sorted. This assumes that 'T's are
302// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000303//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000304template<typename T>
305void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
306 // By far, the most common cases will be the simple ones. In these cases,
307 // avoid having to allocate a temporary vector...
308 //
309 if (Src.empty()) { // Nothing to merge in...
310 return;
311 } else if (Dest.empty()) { // Just copy the result in...
312 Dest = Src;
313 } else if (Src.size() == 1) { // Insert a single element...
314 const T &V = Src[0];
315 typename vector<T>::iterator I =
316 std::lower_bound(Dest.begin(), Dest.end(), V);
317 if (I == Dest.end() || *I != Src[0]) // If not already contained...
318 Dest.insert(I, Src[0]);
319 } else if (Dest.size() == 1) {
320 T Tmp = Dest[0]; // Save value in temporary...
321 Dest = Src; // Copy over list...
322 typename vector<T>::iterator I =
323 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
324 if (I == Dest.end() || *I != Src[0]) // If not already contained...
325 Dest.insert(I, Src[0]);
326
327 } else {
328 // Make a copy to the side of Dest...
329 vector<T> Old(Dest);
330
331 // Make space for all of the type entries now...
332 Dest.resize(Dest.size()+Src.size());
333
334 // Merge the two sorted ranges together... into Dest.
335 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
336
337 // Now erase any duplicate entries that may have accumulated into the
338 // vectors (because they were in both of the input sets)
339 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
340 }
341}
342
343
344// mergeWith - Merge this node and the specified node, moving all links to and
345// from the argument node into the current node, deleting the node argument.
346// Offset indicates what offset the specified node is to be merged into the
347// current node.
348//
349// The specified node may be a null pointer (in which case, nothing happens).
350//
351void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
352 DSNode *N = NH.getNode();
353 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000354 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000355
Chris Lattner02606632002-11-04 06:48:26 +0000356 if (N == this) {
357 std::cerr << "WARNING: Cannot merge two portions of the same node yet, so we collapse instead!\n";
358 N->foldNodeCompletely();
359 return;
360 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000361
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000362 // If we are merging a node with a completely folded node, then both nodes are
363 // now completely folded.
364 //
365 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000366 if (!N->isNodeCompletelyFolded())
367 N->foldNodeCompletely();
368 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000369 foldNodeCompletely();
370 Offset = 0;
371 }
Chris Lattner02606632002-11-04 06:48:26 +0000372 N = NH.getNode();
373
374 if (this == N) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000375
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000376 // If both nodes are not at offset 0, make sure that we are merging the node
377 // at an later offset into the node with the zero offset.
378 //
379 if (Offset > NH.getOffset()) {
380 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
381 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000382 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
383 // If the offsets are the same, merge the smaller node into the bigger node
384 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
385 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000386 }
387
388#if 0
389 std::cerr << "\n\nMerging:\n";
390 N->print(std::cerr, 0);
391 std::cerr << " and:\n";
392 print(std::cerr, 0);
393#endif
394
395 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
396 // respect to NH.Offset) is now zero.
397 //
398 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000399
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000400 // If our destination node is too small... try to grow it.
401 if (N->getSize()+NOffset > getSize() &&
402 growNode(N->getSize()+NOffset)) {
403 // Catastrophic failure occured and we had to collapse the node. In this
404 // case, collapse the other node as well.
405 N->foldNodeCompletely();
406 NOffset = 0;
407 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000408 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000409
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000410 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000411 // Make sure to adjust their offset, not just the node pointer.
412 //
413 while (!N->Referrers.empty()) {
414 DSNodeHandle &Ref = *N->Referrers.back();
415 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
416 }
Chris Lattner59535132002-11-05 00:01:58 +0000417
418 // Make all of the outgoing links of N now be outgoing links of this. This
419 // can cause recursive merging!
420 //
421 for (unsigned i = 0, e = NSize; i != e; ++i)
422 if (DSNodeHandle *Link = N->getLink(i)) {
423 addEdgeTo((i+NOffset) % getSize(), *Link);
424 N->MergeMap[i] = -1; // Kill outgoing edge
425 }
426
427#if 0
Chris Lattner7b7200c2002-10-02 04:57:39 +0000428 // We must merge fields in this node due to nodes merged in the source node.
429 // In order to handle this we build a map that converts from the source node's
430 // MergeMap values to our MergeMap values. This map is indexed by the
431 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
432 // 2*SourceNodeSize elements of space for the mapping. We can do this because
433 // we know that there are at most SourceNodeSize outgoing links in the node
434 // (thus that many positive values) and at most SourceNodeSize distinct fields
435 // (thus that many negative values).
436 //
437 std::vector<signed char> MergeMapMap(NSize*2, 127);
438
439 // Loop through the structures, merging them together...
440 for (unsigned i = 0, e = NSize; i != e; ++i) {
441 // Get what this byte of N maps to...
442 signed char NElement = N->MergeMap[i];
443
444 // Get what we map this byte to...
445 signed char Element = MergeMap[i+NOffset];
Chris Lattner59535132002-11-05 00:01:58 +0000446 assert(Element < (int)Links.size() && "Element in merge map out of range!");
447
Chris Lattner7b7200c2002-10-02 04:57:39 +0000448 // We use 127 as a sentinal and don't check for it's existence yet...
449 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
450
451 signed char CurMappedVal = MergeMapMap[NElement+NSize];
452 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
453 MergeMapMap[NElement+NSize] = Element; // Map the two together...
454 } else if (CurMappedVal != Element) {
455 // If we are mapping two different fields together this means that we need
456 // to merge fields in the current node due to merging in the source node.
457 //
458 mergeMappedValues(CurMappedVal, Element);
459 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
Chris Lattner59535132002-11-05 00:01:58 +0000460 assert(MergeMap[i+NOffset] < (int)Links.size()
461 && "Element in merge map out of range!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000462 }
463 }
Chris Lattner59535132002-11-05 00:01:58 +0000464#endif
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000465
466 // Now that there are no outgoing edges, all of the Links are dead.
467 N->Links.clear();
Chris Lattner59535132002-11-05 00:01:58 +0000468 N->MergeMap.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000469
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000470 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000471 NodeType |= N->NodeType;
472 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000473
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000474 // Adjust all of the type entries we are merging in by the offset...
475 //
476 if (NOffset != 0) { // This case is common enough to optimize for
477 // Offset all of the TypeEntries in N with their new offset
478 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
479 N->TypeEntries[i].Offset += NOffset;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000480 }
481
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000482 // ... now add them to the TypeEntries list.
483 MergeSortedVectors(TypeEntries, N->TypeEntries);
484 N->TypeEntries.clear(); // N is dead, no type-entries need exist
485
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000486 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000487 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000488 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000489
490 // Delete the globals from the old node...
491 N->Globals.clear();
492 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000493}
494
Chris Lattner9de906c2002-10-20 22:11:44 +0000495//===----------------------------------------------------------------------===//
496// DSCallSite Implementation
497//===----------------------------------------------------------------------===//
498
Vikram S. Adve26b98262002-10-20 21:41:02 +0000499// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000500Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000501 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000502}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000503
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000504
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000505//===----------------------------------------------------------------------===//
506// DSGraph Implementation
507//===----------------------------------------------------------------------===//
508
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000509DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
510 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000511 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000512}
513
Chris Lattnereff0da92002-10-21 15:32:34 +0000514DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
515 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000516 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000517}
518
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000519DSGraph::~DSGraph() {
520 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000521 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000522 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000523
524#ifndef NDEBUG
525 // Drop all intra-node references, so that assertions don't fail...
526 std::for_each(Nodes.begin(), Nodes.end(),
527 std::mem_fun(&DSNode::dropAllReferences));
528#endif
529
530 // Delete all of the nodes themselves...
531 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
532}
533
Chris Lattner0d9bab82002-07-18 00:12:30 +0000534// dump - Allow inspection of graph in a debugger.
535void DSGraph::dump() const { print(std::cerr); }
536
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000537
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000538// Helper function used to clone a function list.
539//
540static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
541 vector<DSCallSite> &toCalls,
542 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000543 unsigned FC = toCalls.size(); // FirstCall
544 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000545 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000546 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000547}
548
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000549/// remapLinks - Change all of the Links in the current node according to the
550/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000551///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000552void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
553 for (unsigned i = 0, e = Links.size(); i != e; ++i)
554 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
555}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000556
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000557
Chris Lattner0d9bab82002-07-18 00:12:30 +0000558// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000559// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000560// filled into the OldValMap member. If StripAllocas is set to true, Alloca
561// markers are removed from the graph, as the graph is being cloned into a
562// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000563//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000564DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
565 std::map<Value*, DSNodeHandle> &OldValMap,
566 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner92673292002-11-02 00:13:20 +0000567 bool StripScalars, // FIXME: Kill StripScalars
568 bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000569 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000570
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000571 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000572
573 // Duplicate all of the nodes, populating the node map...
574 Nodes.reserve(FN+G.Nodes.size());
575 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000576 DSNode *Old = G.Nodes[i];
577 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000578 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000579 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000580 }
581
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000582 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000583 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000584 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000585
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000586 // Remove local markers as specified
Chris Lattner92673292002-11-02 00:13:20 +0000587 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000588 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000589 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000590 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000591
Chris Lattnercf15db32002-10-17 20:09:52 +0000592 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000593 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
594 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000595 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000596 H.setNode(OldNodeMap[I->second.getNode()]);
597 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000598
599 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000600 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
601 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000602 GVI->second.mergeWith(H);
603 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000604 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000605 }
606 }
607 }
Chris Lattnere2219762002-07-18 18:22:40 +0000608 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000609 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000610
Chris Lattnercf15db32002-10-17 20:09:52 +0000611
Chris Lattner0d9bab82002-07-18 00:12:30 +0000612 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000613 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000614}
615
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000616#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000617// cloneGlobalInto - Clone the given global node and all its target links
618// (and all their llinks, recursively).
619//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000620DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000621 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
622
623 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000624 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000625 if (ValMapEntry != 0)
626 return ValMapEntry;
627
628 // Clone the node and update the ValMap.
629 DSNode* NewNode = new DSNode(*GNode);
630 ValMapEntry = NewNode; // j=0 case of loop below!
631 Nodes.push_back(NewNode);
632 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000633 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000634
635 // Rewrite the links in the new node to point into the current graph.
636 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
637 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
638
639 return NewNode;
640}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000641#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000642
643
Chris Lattner0d9bab82002-07-18 00:12:30 +0000644// markIncompleteNodes - Mark the specified node as having contents that are not
645// known with the current analysis we have performed. Because a node makes all
646// of the nodes it can reach imcomplete if the node itself is incomplete, we
647// must recursively traverse the data structure graph, marking all reachable
648// nodes as incomplete.
649//
650static void markIncompleteNode(DSNode *N) {
651 // Stop recursion if no node, or if node already marked...
652 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
653
654 // Actually mark the node
655 N->NodeType |= DSNode::Incomplete;
656
657 // Recusively process children...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000658 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
659 if (DSNodeHandle *DSNH = N->getLink(i))
660 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000661}
662
663
664// markIncompleteNodes - Traverse the graph, identifying nodes that may be
665// modified by other functions that have not been resolved yet. This marks
666// nodes that are reachable through three sources of "unknownness":
667//
668// Global Variables, Function Calls, and Incoming Arguments
669//
670// For any node that may have unknown components (because something outside the
671// scope of current analysis may have modified it), the 'Incomplete' flag is
672// added to the NodeType.
673//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000674void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000675 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000676 if (markFormalArgs && Func)
677 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000678 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
679 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000680
681 // Mark stuff passed into functions calls as being incomplete...
682 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000683 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000684 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000685 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000686
Chris Lattner92673292002-11-02 00:13:20 +0000687 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000688 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000689 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000690 }
691
Chris Lattner92673292002-11-02 00:13:20 +0000692 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000693 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000694 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000695 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000696 // FIXME: Make more efficient by looking over Links directly
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000697 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
698 if (DSNodeHandle *DSNH = N->getLink(i))
699 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000700 }
701}
702
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000703// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000704// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000705static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000706 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000707 while (!N->getGlobals().empty()) {
708 GlobalValue *GV = N->getGlobals().back();
709 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000710 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000711 }
712}
713
714
Chris Lattner0d9bab82002-07-18 00:12:30 +0000715// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
716// checks to see if there are simple transformations that it can do to make it
717// dead.
718//
719bool DSGraph::isNodeDead(DSNode *N) {
720 // Is it a trivially dead shadow node...
721 if (N->getReferrers().empty() && N->NodeType == 0)
722 return true;
723
724 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000725 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000726 N->getReferrers().size() == N->getGlobals().size()) {
727
Chris Lattnerc875f022002-11-03 21:27:48 +0000728 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000729 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000730 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000731 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
732 return true;
733 }
734
735 return false;
736}
737
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000738static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000739 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000740 // Remove trivially identical function calls
741 unsigned NumFns = Calls.size();
742 std::sort(Calls.begin(), Calls.end());
743 Calls.erase(std::unique(Calls.begin(), Calls.end()),
744 Calls.end());
745
746 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000747 std::cerr << "Merged " << (NumFns-Calls.size())
748 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000749}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000750
Chris Lattnere2219762002-07-18 18:22:40 +0000751// removeTriviallyDeadNodes - After the graph has been constructed, this method
752// removes all unreachable nodes that are created because they got merged with
753// other nodes in the graph. These nodes will all be trivially unreachable, so
754// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000755//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000756void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000757 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000758 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000759 if (isNodeDead(Nodes[i])) { // This node is dead!
760 delete Nodes[i]; // Free memory...
761 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
762 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000763
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000764 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000765}
766
767
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000768// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000769// stuff to be alive.
770//
771static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000772 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000773
774 Alive.insert(N);
Chris Lattner92673292002-11-02 00:13:20 +0000775 // FIXME: Make more efficient by looking over Links directly
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000776 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
777 if (DSNodeHandle *DSNH = N->getLink(i))
778 if (!Alive.count(DSNH->getNode()))
779 markAlive(DSNH->getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000780}
781
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000782static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
783 std::set<DSNode*> &Visiting) {
784 if (N == 0) return false;
785
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000786 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000787 Visiting.insert(N);
788
789 // If any immediate successor is alive, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000790 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
791 if (DSNodeHandle *DSNH = N->getLink(i))
792 if (Alive.count(DSNH->getNode())) {
793 Visiting.erase(N);
794 return true;
795 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000796
797 // Else if any successor reaches a live node, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000798 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
799 if (DSNodeHandle *DSNH = N->getLink(i))
800 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
801 Visiting.erase(N); return true;
802 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000803
804 Visiting.erase(N);
805 return false;
806}
807
808
809// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
810// This would be unnecessary if function calls were real nodes! In that case,
811// the simple iterative loop in the first few lines below suffice.
812//
813static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000814 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000815 std::set<DSNode*> &Alive,
816 bool FilterCalls) {
817
818 // Iterate, marking globals or cast nodes alive until no new live nodes
819 // are added to Alive
820 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000821 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000822 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
823 liveCount = Alive.size();
824 for ( ; I != E; ++I)
825 if (Alive.count(*I) == 0) {
826 Visiting.clear();
827 if (checkGlobalAlive(*I, Alive, Visiting))
828 markAlive(*I, Alive);
829 }
830 }
831
832 // Find function calls with some dead and some live nodes.
833 // Since all call nodes must be live if any one is live, we have to mark
834 // all nodes of the call as live and continue the iteration (via recursion).
835 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000836 bool Recurse = false;
837 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000838 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000839 DSCallSite &CS = Calls[i];
840 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
841 if (DSNode *N = CS.getPtrArg(j).getNode()) {
842 bool ArgIsDead = !Alive.count(N);
843 CallHasDeadArg |= ArgIsDead;
844 CallIsDead &= ArgIsDead;
845 }
846
847 if (DSNode *N = CS.getRetVal().getNode()) {
848 bool RetIsDead = !Alive.count(N);
849 CallHasDeadArg |= RetIsDead;
850 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000851 }
Chris Lattner0969c502002-10-21 02:08:03 +0000852
853 DSNode *N = CS.getCallee().getNode();
854 bool FnIsDead = !Alive.count(N);
855 CallHasDeadArg |= FnIsDead;
856 CallIsDead &= FnIsDead;
857
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000858 if (!CallIsDead && CallHasDeadArg) {
859 // Some node in this call is live and another is dead.
860 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000861 Recurse = true;
862 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
863 markAlive(CS.getPtrArg(j).getNode(), Alive);
864 markAlive(CS.getRetVal().getNode(), Alive);
865 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000866 }
867 }
Chris Lattner0969c502002-10-21 02:08:03 +0000868 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000869 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
870 }
871}
872
873
874// markGlobalsAlive - Mark global nodes and cast nodes alive if they
875// can reach any other live node. Since this can produce new live nodes,
876// we use a simple iterative algorithm.
877//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000878static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000879 bool FilterCalls) {
880 // Add global and cast nodes to a set so we don't walk all nodes every time
881 std::set<DSNode*> GlobalNodes;
882 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000883 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000884 GlobalNodes.insert(G.getNodes()[i]);
885
886 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000887 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000888 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000889 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
890 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
891 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
892 GlobalNodes.insert(N);
893 if (DSNode *N = Calls[i].getRetVal().getNode())
894 GlobalNodes.insert(N);
895 if (DSNode *N = Calls[i].getCallee().getNode())
896 GlobalNodes.insert(N);
897 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000898 }
899
900 // Iterate and recurse until no new live node are discovered.
901 // This would be a simple iterative loop if function calls were real nodes!
902 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
903
Chris Lattnerc875f022002-11-03 21:27:48 +0000904 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000905 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000906 for( ; I != E; ++I)
907 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000908 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000909
910 // Delete dead function calls
911 if (FilterCalls)
912 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
913 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000914 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
915 CallIsDead && j != ej; ++j)
916 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000917 if (CallIsDead)
918 Calls.erase(Calls.begin() + i); // remove the call entirely
919 }
920}
Chris Lattnere2219762002-07-18 18:22:40 +0000921
922// removeDeadNodes - Use a more powerful reachability analysis to eliminate
923// subgraphs that are unreachable. This often occurs because the data
924// structure doesn't "escape" into it's caller, and thus should be eliminated
925// from the caller's graph entirely. This is only appropriate to use when
926// inlining graphs.
927//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000928void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
929 assert((!KeepAllGlobals || KeepCalls) &&
930 "KeepAllGlobals without KeepCalls is meaningless");
931
Chris Lattnere2219762002-07-18 18:22:40 +0000932 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000933 removeTriviallyDeadNodes(KeepAllGlobals);
934
Chris Lattnere2219762002-07-18 18:22:40 +0000935 // FIXME: Merge nontrivially identical call nodes...
936
937 // Alive - a set that holds all nodes found to be reachable/alive.
938 std::set<DSNode*> Alive;
939
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000940 // If KeepCalls, mark all nodes reachable by call nodes as alive...
941 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000942 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
943 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
944 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
945 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
946 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
947 }
Chris Lattnere2219762002-07-18 18:22:40 +0000948
Chris Lattner92673292002-11-02 00:13:20 +0000949 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000950 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
951 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000952 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000953
Chris Lattner92673292002-11-02 00:13:20 +0000954#if 0
955 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
Chris Lattnerc875f022002-11-03 21:27:48 +0000956 // the ScalarMap?
Chris Lattner92673292002-11-02 00:13:20 +0000957 //
958 if (KeepAllGlobals)
959 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
960 if (Nodes[i]->NodeType & DSNode::GlobalNode)
961 markAlive(Nodes[i], Alive);
962#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000963
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000964 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000965 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000966
967 // Mark all globals or cast nodes that can reach a live node as alive.
968 // This also marks all nodes reachable from such nodes as alive.
969 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000970 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000971 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000972
Chris Lattnere2219762002-07-18 18:22:40 +0000973 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000974 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000975 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
976 for (unsigned i = 0; i != Nodes.size(); ++i)
977 if (!Alive.count(Nodes[i])) {
978 DSNode *N = Nodes[i];
979 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
980 DeadNodes.push_back(N); // Add node to our list of dead nodes
981 N->dropAllReferences(); // Drop all outgoing edges
982 }
983
Chris Lattnere2219762002-07-18 18:22:40 +0000984 // Delete all dead nodes...
985 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
986}
987
988
989
Chris Lattner0d9bab82002-07-18 00:12:30 +0000990// maskNodeTypes - Apply a mask to all of the node types in the graph. This
991// is useful for clearing out markers like Scalar or Incomplete.
992//
993void DSGraph::maskNodeTypes(unsigned char Mask) {
994 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
995 Nodes[i]->NodeType &= Mask;
996}
997
998
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000999#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001000//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001001// GlobalDSGraph Implementation
1002//===----------------------------------------------------------------------===//
1003
1004GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1005}
1006
1007GlobalDSGraph::~GlobalDSGraph() {
1008 assert(Referrers.size() == 0 &&
1009 "Deleting global graph while references from other graphs exist");
1010}
1011
1012void GlobalDSGraph::addReference(const DSGraph* referrer) {
1013 if (referrer != this)
1014 Referrers.insert(referrer);
1015}
1016
1017void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1018 if (referrer != this) {
1019 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1020 Referrers.erase(referrer);
1021 if (Referrers.size() == 0)
1022 delete this;
1023 }
1024}
1025
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001026#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001027// Bits used in the next function
1028static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1029
1030
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001031// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1032// visible target links (and recursively their such links) into this graph.
1033// NodeCache maps the node being cloned to its clone in the Globals graph,
1034// in order to track cycles.
1035// GlobalsAreFinal is a flag that says whether it is safe to assume that
1036// an existing global node is complete. This is important to avoid
1037// reinserting all globals when inserting Calls to functions.
1038// This is a helper function for cloneGlobals and cloneCalls.
1039//
1040DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1041 std::map<const DSNode*, DSNode*> &NodeCache,
1042 bool GlobalsAreFinal) {
1043 if (OldNode == 0) return 0;
1044
1045 // The caller should check this is an external node. Just more efficient...
1046 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1047
1048 // If a clone has already been created for OldNode, return it.
1049 DSNode*& CacheEntry = NodeCache[OldNode];
1050 if (CacheEntry != 0)
1051 return CacheEntry;
1052
1053 // The result value...
1054 DSNode* NewNode = 0;
1055
1056 // If nodes already exist for any of the globals of OldNode,
1057 // merge all such nodes together since they are merged in OldNode.
1058 // If ValueCacheIsFinal==true, look for an existing node that has
1059 // an identical list of globals and return it if it exists.
1060 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001061 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001062 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001063 if (NewNode == 0) {
1064 NewNode = PrevNode; // first existing node found
1065 if (GlobalsAreFinal && j == 0)
1066 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1067 CacheEntry = NewNode;
1068 return NewNode;
1069 }
1070 }
1071 else if (NewNode != PrevNode) { // found another, different from prev
1072 // update ValMap *before* merging PrevNode into NewNode
1073 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001074 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001075 NewNode->mergeWith(PrevNode);
1076 }
1077 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001078 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001079 }
1080
1081 // If no existing node was found, clone the node and update the ValMap.
1082 if (NewNode == 0) {
1083 NewNode = new DSNode(*OldNode);
1084 Nodes.push_back(NewNode);
1085 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1086 NewNode->setLink(j, 0);
1087 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001088 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001089 }
1090 else
1091 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1092
1093 // Add the entry to NodeCache
1094 CacheEntry = NewNode;
1095
1096 // Rewrite the links in the new node to point into the current graph,
1097 // but only for links to external nodes. Set other links to NULL.
1098 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1099 DSNode* OldTarget = OldNode->getLink(j);
1100 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1101 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1102 if (NewNode->getLink(j))
1103 NewNode->getLink(j)->mergeWith(NewLink);
1104 else
1105 NewNode->setLink(j, NewLink);
1106 }
1107 }
1108
1109 // Remove all local markers
1110 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1111
1112 return NewNode;
1113}
1114
1115
1116// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1117// visible target links (and recursively their such links) into this graph.
1118//
1119void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1120 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001121#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001122 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1123 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1124 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001125 if (CloneCalls)
1126 GlobalsGraph->cloneCalls(Graph);
1127
1128 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001129#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001130}
1131
1132
1133// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1134// links (and recursively their such links) into this graph.
1135//
1136void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1137 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001138 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001139
1140 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1141
1142 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001143 DSCallSite& callCopy = FunctionCalls.back();
1144 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001145 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001146 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001147 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1148 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1149 : 0);
1150 }
1151
1152 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001153 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001154}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001155#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001156
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001157#endif