blob: 44ecd01ab7e6bae6c078bd8a67d89cfcbd61d181 [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()) {
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000358 N->foldNodeCompletely();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000359 } 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;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000370 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
371 // If the offsets are the same, merge the smaller node into the bigger node
372 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
373 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000374 }
375
376#if 0
377 std::cerr << "\n\nMerging:\n";
378 N->print(std::cerr, 0);
379 std::cerr << " and:\n";
380 print(std::cerr, 0);
381#endif
382
383 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
384 // respect to NH.Offset) is now zero.
385 //
386 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000387
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000388 // If our destination node is too small... try to grow it.
389 if (N->getSize()+NOffset > getSize() &&
390 growNode(N->getSize()+NOffset)) {
391 // Catastrophic failure occured and we had to collapse the node. In this
392 // case, collapse the other node as well.
393 N->foldNodeCompletely();
394 NOffset = 0;
395 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000396 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000397
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000398 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000399 // Make sure to adjust their offset, not just the node pointer.
400 //
401 while (!N->Referrers.empty()) {
402 DSNodeHandle &Ref = *N->Referrers.back();
403 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
404 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000405
Chris Lattner7b7200c2002-10-02 04:57:39 +0000406 // We must merge fields in this node due to nodes merged in the source node.
407 // In order to handle this we build a map that converts from the source node's
408 // MergeMap values to our MergeMap values. This map is indexed by the
409 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
410 // 2*SourceNodeSize elements of space for the mapping. We can do this because
411 // we know that there are at most SourceNodeSize outgoing links in the node
412 // (thus that many positive values) and at most SourceNodeSize distinct fields
413 // (thus that many negative values).
414 //
415 std::vector<signed char> MergeMapMap(NSize*2, 127);
416
417 // Loop through the structures, merging them together...
418 for (unsigned i = 0, e = NSize; i != e; ++i) {
419 // Get what this byte of N maps to...
420 signed char NElement = N->MergeMap[i];
421
422 // Get what we map this byte to...
423 signed char Element = MergeMap[i+NOffset];
424 // We use 127 as a sentinal and don't check for it's existence yet...
425 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
426
427 signed char CurMappedVal = MergeMapMap[NElement+NSize];
428 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
429 MergeMapMap[NElement+NSize] = Element; // Map the two together...
430 } else if (CurMappedVal != Element) {
431 // If we are mapping two different fields together this means that we need
432 // to merge fields in the current node due to merging in the source node.
433 //
434 mergeMappedValues(CurMappedVal, Element);
435 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
436 }
437 }
438
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000439 // Make all of the outgoing links of N now be outgoing links of this. This
440 // can cause recursive merging!
441 //
Chris Lattner7b7200c2002-10-02 04:57:39 +0000442 for (unsigned i = 0, e = NSize; i != e; ++i)
443 if (DSNodeHandle *Link = N->getLink(i)) {
444 addEdgeTo(i+NOffset, *Link);
445 N->MergeMap[i] = -1; // Kill outgoing edge
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000446 }
447
448 // Now that there are no outgoing edges, all of the Links are dead.
449 N->Links.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000450
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000451 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000452 NodeType |= N->NodeType;
453 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000454
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000455 // Adjust all of the type entries we are merging in by the offset...
456 //
457 if (NOffset != 0) { // This case is common enough to optimize for
458 // Offset all of the TypeEntries in N with their new offset
459 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
460 N->TypeEntries[i].Offset += NOffset;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000461 }
462
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000463 // ... now add them to the TypeEntries list.
464 MergeSortedVectors(TypeEntries, N->TypeEntries);
465 N->TypeEntries.clear(); // N is dead, no type-entries need exist
466
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000467 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000468 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000469 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000470
471 // Delete the globals from the old node...
472 N->Globals.clear();
473 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000474}
475
Chris Lattner9de906c2002-10-20 22:11:44 +0000476//===----------------------------------------------------------------------===//
477// DSCallSite Implementation
478//===----------------------------------------------------------------------===//
479
Vikram S. Adve26b98262002-10-20 21:41:02 +0000480// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000481Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000482 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000483}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000484
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000485
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000486//===----------------------------------------------------------------------===//
487// DSGraph Implementation
488//===----------------------------------------------------------------------===//
489
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000490DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
491 std::map<const DSNode*, DSNode*> NodeMap;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000492 RetNode = cloneInto(G, ValueMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000493}
494
Chris Lattnereff0da92002-10-21 15:32:34 +0000495DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
496 : Func(G.Func) {
497 RetNode = cloneInto(G, ValueMap, NodeMap);
498}
499
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000500DSGraph::~DSGraph() {
501 FunctionCalls.clear();
502 ValueMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000503 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000504
505#ifndef NDEBUG
506 // Drop all intra-node references, so that assertions don't fail...
507 std::for_each(Nodes.begin(), Nodes.end(),
508 std::mem_fun(&DSNode::dropAllReferences));
509#endif
510
511 // Delete all of the nodes themselves...
512 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
513}
514
Chris Lattner0d9bab82002-07-18 00:12:30 +0000515// dump - Allow inspection of graph in a debugger.
516void DSGraph::dump() const { print(std::cerr); }
517
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000518
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000519// Helper function used to clone a function list.
520//
521static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
522 vector<DSCallSite> &toCalls,
523 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000524 unsigned FC = toCalls.size(); // FirstCall
525 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000526 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000527 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000528}
529
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000530/// remapLinks - Change all of the Links in the current node according to the
531/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000532///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000533void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
534 for (unsigned i = 0, e = Links.size(); i != e; ++i)
535 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
536}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000537
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000538
Chris Lattner0d9bab82002-07-18 00:12:30 +0000539// cloneInto - Clone the specified DSGraph into the current graph, returning the
540// Return node of the graph. The translated ValueMap for the old function is
541// filled into the OldValMap member. If StripLocals is set to true, Scalar and
542// Alloca markers are removed from the graph, as the graph is being cloned into
543// a calling function's graph.
544//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000545DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
546 std::map<Value*, DSNodeHandle> &OldValMap,
547 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattnere4ae3042002-10-21 19:50:29 +0000548 bool StripScalars, bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000549 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000550
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000551 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000552
553 // Duplicate all of the nodes, populating the node map...
554 Nodes.reserve(FN+G.Nodes.size());
555 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000556 DSNode *Old = G.Nodes[i];
557 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000558 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000559 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000560 }
561
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000562 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000563 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000564 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000565
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000566 // Remove local markers as specified
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000567 unsigned char StripBits = (StripScalars ? DSNode::ScalarNode : 0) |
568 (StripAllocas ? DSNode::AllocaNode : 0);
569 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000570 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000572
Chris Lattnercf15db32002-10-17 20:09:52 +0000573 // Copy the value map... and merge all of the global nodes...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000574 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
Chris Lattnercf15db32002-10-17 20:09:52 +0000575 E = G.ValueMap.end(); I != E; ++I) {
576 DSNodeHandle &H = OldValMap[I->first];
577 H = DSNodeHandle(OldNodeMap[I->second.getNode()], I->second.getOffset());
578
579 if (isa<GlobalValue>(I->first)) { // Is this a global?
580 std::map<Value*, DSNodeHandle>::iterator GVI = ValueMap.find(I->first);
581 if (GVI != ValueMap.end()) { // Is the global value in this fun already?
582 GVI->second.mergeWith(H);
583 } else {
584 ValueMap[I->first] = H; // Add global pointer to this graph
585 }
586 }
587 }
Chris Lattnere2219762002-07-18 18:22:40 +0000588 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000589 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000590
Chris Lattnercf15db32002-10-17 20:09:52 +0000591
Chris Lattner0d9bab82002-07-18 00:12:30 +0000592 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000593 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000594}
595
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000596#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000597// cloneGlobalInto - Clone the given global node and all its target links
598// (and all their llinks, recursively).
599//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000600DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000601 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
602
603 // If a clone has already been created for GNode, return it.
604 DSNodeHandle& ValMapEntry = ValueMap[GNode->getGlobals()[0]];
605 if (ValMapEntry != 0)
606 return ValMapEntry;
607
608 // Clone the node and update the ValMap.
609 DSNode* NewNode = new DSNode(*GNode);
610 ValMapEntry = NewNode; // j=0 case of loop below!
611 Nodes.push_back(NewNode);
612 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
613 ValueMap[NewNode->getGlobals()[j]] = NewNode;
614
615 // Rewrite the links in the new node to point into the current graph.
616 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
617 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
618
619 return NewNode;
620}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000621#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000622
623
Chris Lattner0d9bab82002-07-18 00:12:30 +0000624// markIncompleteNodes - Mark the specified node as having contents that are not
625// known with the current analysis we have performed. Because a node makes all
626// of the nodes it can reach imcomplete if the node itself is incomplete, we
627// must recursively traverse the data structure graph, marking all reachable
628// nodes as incomplete.
629//
630static void markIncompleteNode(DSNode *N) {
631 // Stop recursion if no node, or if node already marked...
632 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
633
634 // Actually mark the node
635 N->NodeType |= DSNode::Incomplete;
636
637 // Recusively process children...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000638 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
639 if (DSNodeHandle *DSNH = N->getLink(i))
640 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000641}
642
643
644// markIncompleteNodes - Traverse the graph, identifying nodes that may be
645// modified by other functions that have not been resolved yet. This marks
646// nodes that are reachable through three sources of "unknownness":
647//
648// Global Variables, Function Calls, and Incoming Arguments
649//
650// For any node that may have unknown components (because something outside the
651// scope of current analysis may have modified it), the 'Incomplete' flag is
652// added to the NodeType.
653//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000654void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000655 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000656 if (markFormalArgs && Func)
657 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
658 if (isPointerType(I->getType()) && ValueMap.find(I) != ValueMap.end()) {
659 DSNodeHandle &INH = ValueMap[I];
660 if (INH.getNode() && INH.hasLink(0))
661 markIncompleteNode(ValueMap[I].getLink(0)->getNode());
662 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000663
664 // Mark stuff passed into functions calls as being incomplete...
665 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000666 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000667 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000668 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000669
670 // The call does not make the function argument incomplete...
671
672 // All arguments to the function call are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000673 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000674 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000675 }
676
Chris Lattner055dc2c2002-07-18 15:54:42 +0000677 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000678 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000679 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000680 DSNode *N = Nodes[i];
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000681 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
682 if (DSNodeHandle *DSNH = N->getLink(i))
683 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000684 }
685}
686
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000687// removeRefsToGlobal - Helper function that removes globals from the
688// ValueMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000689static void removeRefsToGlobal(DSNode* N,
690 std::map<Value*, DSNodeHandle> &ValueMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000691 while (!N->getGlobals().empty()) {
692 GlobalValue *GV = N->getGlobals().back();
693 N->getGlobals().pop_back();
694 ValueMap.erase(GV);
695 }
696}
697
698
Chris Lattner0d9bab82002-07-18 00:12:30 +0000699// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
700// checks to see if there are simple transformations that it can do to make it
701// dead.
702//
703bool DSGraph::isNodeDead(DSNode *N) {
704 // Is it a trivially dead shadow node...
705 if (N->getReferrers().empty() && N->NodeType == 0)
706 return true;
707
708 // Is it a function node or some other trivially unused global?
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000709 if (N->NodeType != 0 &&
710 (N->NodeType & ~DSNode::GlobalNode) == 0 &&
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000711 N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000712 N->getReferrers().size() == N->getGlobals().size()) {
713
Chris Lattnera00397e2002-10-03 21:55:28 +0000714 // Remove the globals from the ValueMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000715 // down to zero.
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000716 removeRefsToGlobal(N, ValueMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000717 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
718 return true;
719 }
720
721 return false;
722}
723
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000724static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000725 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000726 // Remove trivially identical function calls
727 unsigned NumFns = Calls.size();
728 std::sort(Calls.begin(), Calls.end());
729 Calls.erase(std::unique(Calls.begin(), Calls.end()),
730 Calls.end());
731
732 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000733 std::cerr << "Merged " << (NumFns-Calls.size())
734 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000735}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000736
Chris Lattnere2219762002-07-18 18:22:40 +0000737// removeTriviallyDeadNodes - After the graph has been constructed, this method
738// removes all unreachable nodes that are created because they got merged with
739// other nodes in the graph. These nodes will all be trivially unreachable, so
740// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000741//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000742void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000743 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000744 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000745 if (isNodeDead(Nodes[i])) { // This node is dead!
746 delete Nodes[i]; // Free memory...
747 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
748 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000749
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000750 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000751}
752
753
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000754// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000755// stuff to be alive.
756//
757static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000758 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000759
760 Alive.insert(N);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000761 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
762 if (DSNodeHandle *DSNH = N->getLink(i))
763 if (!Alive.count(DSNH->getNode()))
764 markAlive(DSNH->getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000765}
766
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000767static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
768 std::set<DSNode*> &Visiting) {
769 if (N == 0) return false;
770
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000771 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000772 Visiting.insert(N);
773
774 // If any immediate successor is alive, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000775 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
776 if (DSNodeHandle *DSNH = N->getLink(i))
777 if (Alive.count(DSNH->getNode())) {
778 Visiting.erase(N);
779 return true;
780 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000781
782 // Else if any successor reaches a live node, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000783 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
784 if (DSNodeHandle *DSNH = N->getLink(i))
785 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
786 Visiting.erase(N); return true;
787 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000788
789 Visiting.erase(N);
790 return false;
791}
792
793
794// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
795// This would be unnecessary if function calls were real nodes! In that case,
796// the simple iterative loop in the first few lines below suffice.
797//
798static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000799 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000800 std::set<DSNode*> &Alive,
801 bool FilterCalls) {
802
803 // Iterate, marking globals or cast nodes alive until no new live nodes
804 // are added to Alive
805 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000806 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000807 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
808 liveCount = Alive.size();
809 for ( ; I != E; ++I)
810 if (Alive.count(*I) == 0) {
811 Visiting.clear();
812 if (checkGlobalAlive(*I, Alive, Visiting))
813 markAlive(*I, Alive);
814 }
815 }
816
817 // Find function calls with some dead and some live nodes.
818 // Since all call nodes must be live if any one is live, we have to mark
819 // all nodes of the call as live and continue the iteration (via recursion).
820 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000821 bool Recurse = false;
822 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000823 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000824 DSCallSite &CS = Calls[i];
825 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
826 if (DSNode *N = CS.getPtrArg(j).getNode()) {
827 bool ArgIsDead = !Alive.count(N);
828 CallHasDeadArg |= ArgIsDead;
829 CallIsDead &= ArgIsDead;
830 }
831
832 if (DSNode *N = CS.getRetVal().getNode()) {
833 bool RetIsDead = !Alive.count(N);
834 CallHasDeadArg |= RetIsDead;
835 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000836 }
Chris Lattner0969c502002-10-21 02:08:03 +0000837
838 DSNode *N = CS.getCallee().getNode();
839 bool FnIsDead = !Alive.count(N);
840 CallHasDeadArg |= FnIsDead;
841 CallIsDead &= FnIsDead;
842
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000843 if (!CallIsDead && CallHasDeadArg) {
844 // Some node in this call is live and another is dead.
845 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000846 Recurse = true;
847 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
848 markAlive(CS.getPtrArg(j).getNode(), Alive);
849 markAlive(CS.getRetVal().getNode(), Alive);
850 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000851 }
852 }
Chris Lattner0969c502002-10-21 02:08:03 +0000853 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000854 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
855 }
856}
857
858
859// markGlobalsAlive - Mark global nodes and cast nodes alive if they
860// can reach any other live node. Since this can produce new live nodes,
861// we use a simple iterative algorithm.
862//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000863static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000864 bool FilterCalls) {
865 // Add global and cast nodes to a set so we don't walk all nodes every time
866 std::set<DSNode*> GlobalNodes;
867 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000868 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000869 GlobalNodes.insert(G.getNodes()[i]);
870
871 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000872 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000873 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000874 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
875 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
876 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
877 GlobalNodes.insert(N);
878 if (DSNode *N = Calls[i].getRetVal().getNode())
879 GlobalNodes.insert(N);
880 if (DSNode *N = Calls[i].getCallee().getNode())
881 GlobalNodes.insert(N);
882 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000883 }
884
885 // Iterate and recurse until no new live node are discovered.
886 // This would be a simple iterative loop if function calls were real nodes!
887 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
888
889 // Free up references to dead globals from the ValueMap
890 std::set<DSNode*>::iterator I=GlobalNodes.begin(), E=GlobalNodes.end();
891 for( ; I != E; ++I)
892 if (Alive.count(*I) == 0)
893 removeRefsToGlobal(*I, G.getValueMap());
894
895 // Delete dead function calls
896 if (FilterCalls)
897 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
898 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000899 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
900 CallIsDead && j != ej; ++j)
901 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000902 if (CallIsDead)
903 Calls.erase(Calls.begin() + i); // remove the call entirely
904 }
905}
Chris Lattnere2219762002-07-18 18:22:40 +0000906
907// removeDeadNodes - Use a more powerful reachability analysis to eliminate
908// subgraphs that are unreachable. This often occurs because the data
909// structure doesn't "escape" into it's caller, and thus should be eliminated
910// from the caller's graph entirely. This is only appropriate to use when
911// inlining graphs.
912//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000913void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
914 assert((!KeepAllGlobals || KeepCalls) &&
915 "KeepAllGlobals without KeepCalls is meaningless");
916
Chris Lattnere2219762002-07-18 18:22:40 +0000917 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000918 removeTriviallyDeadNodes(KeepAllGlobals);
919
Chris Lattnere2219762002-07-18 18:22:40 +0000920 // FIXME: Merge nontrivially identical call nodes...
921
922 // Alive - a set that holds all nodes found to be reachable/alive.
923 std::set<DSNode*> Alive;
924
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000925 // If KeepCalls, mark all nodes reachable by call nodes as alive...
926 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000927 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
928 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
929 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
930 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
931 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
932 }
Chris Lattnere2219762002-07-18 18:22:40 +0000933
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000934#if 0
Chris Lattnere2219762002-07-18 18:22:40 +0000935 for (unsigned i = 0, e = OrigFunctionCalls.size(); i != e; ++i)
936 for (unsigned j = 0, e = OrigFunctionCalls[i].size(); j != e; ++j)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000937 markAlive(OrigFunctionCalls[i][j].getNode(), Alive);
938#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000939
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000940 // Mark all nodes reachable by scalar nodes (and global nodes, if
941 // keeping them was specified) as alive...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000942 unsigned char keepBits = DSNode::ScalarNode |
943 (KeepAllGlobals ? DSNode::GlobalNode : 0);
Chris Lattnere2219762002-07-18 18:22:40 +0000944 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000945 if (Nodes[i]->NodeType & keepBits)
Chris Lattnere2219762002-07-18 18:22:40 +0000946 markAlive(Nodes[i], Alive);
947
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000948 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000949 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000950
951 // Mark all globals or cast nodes that can reach a live node as alive.
952 // This also marks all nodes reachable from such nodes as alive.
953 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000954 if (!KeepAllGlobals)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000955 markGlobalsAlive(*this, Alive, ! KeepCalls);
956
Chris Lattnere2219762002-07-18 18:22:40 +0000957 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000958 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000959 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
960 for (unsigned i = 0; i != Nodes.size(); ++i)
961 if (!Alive.count(Nodes[i])) {
962 DSNode *N = Nodes[i];
963 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
964 DeadNodes.push_back(N); // Add node to our list of dead nodes
965 N->dropAllReferences(); // Drop all outgoing edges
966 }
967
Chris Lattnere2219762002-07-18 18:22:40 +0000968 // Delete all dead nodes...
969 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
970}
971
972
973
Chris Lattner0d9bab82002-07-18 00:12:30 +0000974// maskNodeTypes - Apply a mask to all of the node types in the graph. This
975// is useful for clearing out markers like Scalar or Incomplete.
976//
977void DSGraph::maskNodeTypes(unsigned char Mask) {
978 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
979 Nodes[i]->NodeType &= Mask;
980}
981
982
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000983#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000984//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000985// GlobalDSGraph Implementation
986//===----------------------------------------------------------------------===//
987
988GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
989}
990
991GlobalDSGraph::~GlobalDSGraph() {
992 assert(Referrers.size() == 0 &&
993 "Deleting global graph while references from other graphs exist");
994}
995
996void GlobalDSGraph::addReference(const DSGraph* referrer) {
997 if (referrer != this)
998 Referrers.insert(referrer);
999}
1000
1001void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1002 if (referrer != this) {
1003 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1004 Referrers.erase(referrer);
1005 if (Referrers.size() == 0)
1006 delete this;
1007 }
1008}
1009
1010// Bits used in the next function
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001011static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001012
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001013#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001014// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1015// visible target links (and recursively their such links) into this graph.
1016// NodeCache maps the node being cloned to its clone in the Globals graph,
1017// in order to track cycles.
1018// GlobalsAreFinal is a flag that says whether it is safe to assume that
1019// an existing global node is complete. This is important to avoid
1020// reinserting all globals when inserting Calls to functions.
1021// This is a helper function for cloneGlobals and cloneCalls.
1022//
1023DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1024 std::map<const DSNode*, DSNode*> &NodeCache,
1025 bool GlobalsAreFinal) {
1026 if (OldNode == 0) return 0;
1027
1028 // The caller should check this is an external node. Just more efficient...
1029 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1030
1031 // If a clone has already been created for OldNode, return it.
1032 DSNode*& CacheEntry = NodeCache[OldNode];
1033 if (CacheEntry != 0)
1034 return CacheEntry;
1035
1036 // The result value...
1037 DSNode* NewNode = 0;
1038
1039 // If nodes already exist for any of the globals of OldNode,
1040 // merge all such nodes together since they are merged in OldNode.
1041 // If ValueCacheIsFinal==true, look for an existing node that has
1042 // an identical list of globals and return it if it exists.
1043 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001044 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1045 if (DSNode *PrevNode = ValueMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001046 if (NewNode == 0) {
1047 NewNode = PrevNode; // first existing node found
1048 if (GlobalsAreFinal && j == 0)
1049 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1050 CacheEntry = NewNode;
1051 return NewNode;
1052 }
1053 }
1054 else if (NewNode != PrevNode) { // found another, different from prev
1055 // update ValMap *before* merging PrevNode into NewNode
1056 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1057 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
1058 NewNode->mergeWith(PrevNode);
1059 }
1060 } else if (NewNode != 0) {
1061 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1062 }
1063
1064 // If no existing node was found, clone the node and update the ValMap.
1065 if (NewNode == 0) {
1066 NewNode = new DSNode(*OldNode);
1067 Nodes.push_back(NewNode);
1068 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1069 NewNode->setLink(j, 0);
1070 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1071 ValueMap[NewNode->getGlobals()[j]] = NewNode;
1072 }
1073 else
1074 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1075
1076 // Add the entry to NodeCache
1077 CacheEntry = NewNode;
1078
1079 // Rewrite the links in the new node to point into the current graph,
1080 // but only for links to external nodes. Set other links to NULL.
1081 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1082 DSNode* OldTarget = OldNode->getLink(j);
1083 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1084 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1085 if (NewNode->getLink(j))
1086 NewNode->getLink(j)->mergeWith(NewLink);
1087 else
1088 NewNode->setLink(j, NewLink);
1089 }
1090 }
1091
1092 // Remove all local markers
1093 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1094
1095 return NewNode;
1096}
1097
1098
1099// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1100// visible target links (and recursively their such links) into this graph.
1101//
1102void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1103 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001104#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001105 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1106 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1107 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001108 if (CloneCalls)
1109 GlobalsGraph->cloneCalls(Graph);
1110
1111 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001112#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001113}
1114
1115
1116// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1117// links (and recursively their such links) into this graph.
1118//
1119void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1120 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001121 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001122
1123 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1124
1125 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001126 DSCallSite& callCopy = FunctionCalls.back();
1127 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001128 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001129 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001130 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1131 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1132 : 0);
1133 }
1134
1135 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001136 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001137}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001138#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001139
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001140#endif