blob: 2aadc000f6c8bfb2e68c5a6bd1cc142cbc26cfe5 [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);
84 MergeMap[0] = -1;
85
86 // If we have links, merge all of our outgoing links together...
87 if (!Links.empty()) {
88 MergeMap[0] = 0; // We now contain an outgoing edge...
89 for (unsigned i = 1, e = Links.size(); i != e; ++i)
90 Links[0].mergeWith(Links[i]);
91 Links.resize(1);
92 }
93}
94
95/// isNodeCompletelyFolded - Return true if this node has been completely
96/// folded down to something that can never be expanded, effectively losing
97/// all of the field sensitivity that may be present in the node.
98///
99bool DSNode::isNodeCompletelyFolded() const {
100 return getSize() == 1 && TypeEntries.size() == 1 &&
101 TypeEntries[0].Ty == Type::VoidTy;
102}
103
104
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000105
Chris Lattner7b7200c2002-10-02 04:57:39 +0000106/// setLink - Set the link at the specified offset to the specified
107/// NodeHandle, replacing what was there. It is uncommon to use this method,
108/// instead one of the higher level methods should be used, below.
109///
110void DSNode::setLink(unsigned i, const DSNodeHandle &NH) {
111 // Create a new entry in the Links vector to hold a new element for offset.
112 if (!hasLink(i)) {
113 signed char NewIdx = Links.size();
114 // Check to see if we allocate more than 128 distinct links for this node.
115 // If so, just merge with the last one. This really shouldn't ever happen,
116 // but it should work regardless of whether it does or not.
117 //
118 if (NewIdx >= 0) {
119 Links.push_back(NH); // Allocate space: common case
120 } else { // Wrap around? Too many links?
121 NewIdx--; // Merge with whatever happened last
122 assert(NewIdx > 0 && "Should wrap back around");
123 std::cerr << "\n*** DSNode found that requires more than 128 "
124 << "active links at once!\n\n";
125 }
126
127 signed char OldIdx = MergeMap[i];
128 assert (OldIdx < 0 && "Shouldn't contain link!");
129
130 // Make sure that anything aliasing this field gets updated to point to the
131 // new link field.
132 rewriteMergeMap(OldIdx, NewIdx);
133 assert(MergeMap[i] == NewIdx && "Field not replaced!");
134 } else {
135 Links[MergeMap[i]] = NH;
136 }
137}
138
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000139// addEdgeTo - Add an edge from the current node to the specified node. This
140// can cause merging of nodes in the graph.
141//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000142void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000143 assert(Offset < getSize() && "Offset out of range!");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000144 if (NH.getNode() == 0) return; // Nothing to do
145
Chris Lattner7b7200c2002-10-02 04:57:39 +0000146 if (DSNodeHandle *ExistingNH = getLink(Offset)) {
147 // Merge the two nodes...
148 ExistingNH->mergeWith(NH);
149 } else { // No merging to perform...
150 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000151 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000152}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000153
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000154/// getTypeRec - This method returns the specified type record if it exists.
155/// If it does not yet exist, the method checks to see whether or not the
156/// request would result in an untrackable state. If adding it would cause
157/// untrackable state, we foldNodeCompletely the node and return the void
158/// record, otherwise we add an new TypeEntry and return it.
159///
160DSTypeRec &DSNode::getTypeRec(const Type *Ty, unsigned Offset) {
161 // If the node is already collapsed, we can't do anything... bail out early
162 if (isNodeCompletelyFolded()) {
163 assert(TypeEntries.size() == 1 && "Node folded and Entries.size() != 1?");
164 return TypeEntries[0];
165 }
166
167 // First search to see if we already have a record for this...
168 DSTypeRec SearchFor(Ty, Offset);
169
170 std::vector<DSTypeRec>::iterator I;
171 if (TypeEntries.size() < 5) { // Linear search if we have few entries.
172 I = TypeEntries.begin();
173 while (I != TypeEntries.end() && *I < SearchFor)
174 ++I;
175 } else {
176 I = std::lower_bound(TypeEntries.begin(), TypeEntries.end(), SearchFor);
177 }
178
179 // At this point, I either points to the right entry or it points to the entry
180 // we are to insert the new entry in front of...
181 //
182 if (I != TypeEntries.end() && *I == SearchFor)
183 return *I;
184
185 // ASSUME that it's okay to add this type entry.
186 // FIXME: This should check to make sure it's ok.
187
188 // If the data size is different then our current size, try to resize the node
189 unsigned ReqSize = Ty->isSized() ? TD.getTypeSize(Ty) : 0;
190 if (getSize() < ReqSize) {
191 // If we are trying to make it bigger, and we can grow the node, do so.
192 if (growNode(ReqSize)) {
193 assert(isNodeCompletelyFolded() && "Node isn't folded?");
194 return TypeEntries[0];
195 }
196
197 } else if (getSize() > ReqSize) {
198 // If we are trying to make the node smaller, we don't have to do anything.
199
200 }
201
202 return *TypeEntries.insert(I, SearchFor);
203}
204
205/// growNode - Attempt to grow the node to the specified size. This may do one
206/// of three things:
207/// 1. Grow the node, return false
208/// 2. Refuse to grow the node, but maintain a trackable situation, return
209/// false.
210/// 3. Be unable to track if node was that size, so collapse the node and
211/// return true.
212///
213bool DSNode::growNode(unsigned ReqSize) {
214 unsigned OldSize = getSize();
215
216 if (0) {
217 // FIXME: DSNode::growNode() doesn't perform correct safety checks yet!
218
219 foldNodeCompletely();
220 return true;
221 }
222
223 assert(ReqSize > OldSize && "Not growing node!");
224
225 // Resize the merge map to have enough space...
226 MergeMap.resize(ReqSize);
227
228 // Assign unique values to all of the elements of MergeMap
229 if (ReqSize < 128) {
230 // Handle the common case of reasonable size structures...
231 for (unsigned i = OldSize; i != ReqSize; ++i)
232 MergeMap[i] = -1-i; // Assign -1, -2, -3, ...
233 } else {
234 // It's possible that we have something really big here. In this case,
235 // divide the object into chunks until it will fit into 128 elements.
236 unsigned Multiple = ReqSize/128;
237
238 // It's probably an array, and probably some power of two in size.
239 // Because of this, find the biggest power of two that is bigger than
240 // multiple to use as our real Multiple.
241 unsigned RealMultiple = 2;
242 while (RealMultiple <= Multiple) RealMultiple <<= 1;
243
244 unsigned RealBound = ReqSize/RealMultiple;
245 assert(RealBound <= 128 && "Math didn't work out right");
246
247 // Now go through and assign indexes that are between -1 and -128
248 // inclusive
249 //
250 for (unsigned i = OldSize; i != ReqSize; ++i)
251 MergeMap[i] = -1-(i % RealBound); // Assign -1, -2, -3...
252 }
253 return false;
254}
255
Chris Lattner7b7200c2002-10-02 04:57:39 +0000256/// mergeMappedValues - This is the higher level form of rewriteMergeMap. It is
257/// fully capable of merging links together if neccesary as well as simply
258/// rewriting the map entries.
259///
260void DSNode::mergeMappedValues(signed char V1, signed char V2) {
261 assert(V1 != V2 && "Cannot merge two identical mapped values!");
262
263 if (V1 < 0) { // If there is no outgoing link from V1, merge it with V2
264 if (V2 < 0 && V1 > V2)
265 // If both are not linked, merge to the field closer to 0
266 rewriteMergeMap(V2, V1);
267 else
268 rewriteMergeMap(V1, V2);
269 } else if (V2 < 0) { // Is V2 < 0 && V1 >= 0?
270 rewriteMergeMap(V2, V1); // Merge into the one with the link...
271 } else { // Otherwise, links exist at both locations
272 // Merge Links[V1] with Links[V2] so they point to the same place now...
273 Links[V1].mergeWith(Links[V2]);
274
275 // Merge the V2 link into V1 so that we reduce the overall value of the
276 // links are reduced...
277 //
278 if (V2 < V1) std::swap(V1, V2); // Ensure V1 < V2
279 rewriteMergeMap(V2, V1); // After this, V2 is "dead"
280
281 // Change the user of the last link to use V2 instead
282 if ((unsigned)V2 != Links.size()-1) {
283 rewriteMergeMap(Links.size()-1, V2); // Point to V2 instead of last el...
284 // Make sure V2 points the right DSNode
285 Links[V2] = Links.back();
286 }
287
288 // Reduce the number of distinct outgoing links...
289 Links.pop_back();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000290 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000291}
292
293
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000294// MergeSortedVectors - Efficiently merge a vector into another vector where
295// duplicates are not allowed and both are sorted. This assumes that 'T's are
296// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000297//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000298template<typename T>
299void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
300 // By far, the most common cases will be the simple ones. In these cases,
301 // avoid having to allocate a temporary vector...
302 //
303 if (Src.empty()) { // Nothing to merge in...
304 return;
305 } else if (Dest.empty()) { // Just copy the result in...
306 Dest = Src;
307 } else if (Src.size() == 1) { // Insert a single element...
308 const T &V = Src[0];
309 typename vector<T>::iterator I =
310 std::lower_bound(Dest.begin(), Dest.end(), V);
311 if (I == Dest.end() || *I != Src[0]) // If not already contained...
312 Dest.insert(I, Src[0]);
313 } else if (Dest.size() == 1) {
314 T Tmp = Dest[0]; // Save value in temporary...
315 Dest = Src; // Copy over list...
316 typename vector<T>::iterator I =
317 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
318 if (I == Dest.end() || *I != Src[0]) // If not already contained...
319 Dest.insert(I, Src[0]);
320
321 } else {
322 // Make a copy to the side of Dest...
323 vector<T> Old(Dest);
324
325 // Make space for all of the type entries now...
326 Dest.resize(Dest.size()+Src.size());
327
328 // Merge the two sorted ranges together... into Dest.
329 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
330
331 // Now erase any duplicate entries that may have accumulated into the
332 // vectors (because they were in both of the input sets)
333 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
334 }
335}
336
337
338// mergeWith - Merge this node and the specified node, moving all links to and
339// from the argument node into the current node, deleting the node argument.
340// Offset indicates what offset the specified node is to be merged into the
341// current node.
342//
343// The specified node may be a null pointer (in which case, nothing happens).
344//
345void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
346 DSNode *N = NH.getNode();
347 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000348 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000349
350 assert(NH.getNode() != this &&
351 "Cannot merge two portions of the same node yet!");
352
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000353 // If we are merging a node with a completely folded node, then both nodes are
354 // now completely folded.
355 //
356 if (isNodeCompletelyFolded()) {
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000357 N->foldNodeCompletely();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000358 } else if (NH.getNode()->isNodeCompletelyFolded()) {
359 foldNodeCompletely();
360 Offset = 0;
361 }
362
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000363 // If both nodes are not at offset 0, make sure that we are merging the node
364 // at an later offset into the node with the zero offset.
365 //
366 if (Offset > NH.getOffset()) {
367 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
368 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000369 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
370 // If the offsets are the same, merge the smaller node into the bigger node
371 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
372 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000373 }
374
375#if 0
376 std::cerr << "\n\nMerging:\n";
377 N->print(std::cerr, 0);
378 std::cerr << " and:\n";
379 print(std::cerr, 0);
380#endif
381
382 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
383 // respect to NH.Offset) is now zero.
384 //
385 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000386
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000387 // If our destination node is too small... try to grow it.
388 if (N->getSize()+NOffset > getSize() &&
389 growNode(N->getSize()+NOffset)) {
390 // Catastrophic failure occured and we had to collapse the node. In this
391 // case, collapse the other node as well.
392 N->foldNodeCompletely();
393 NOffset = 0;
394 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000395 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000396
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000397 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000398 // Make sure to adjust their offset, not just the node pointer.
399 //
400 while (!N->Referrers.empty()) {
401 DSNodeHandle &Ref = *N->Referrers.back();
402 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
403 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000404
Chris Lattner7b7200c2002-10-02 04:57:39 +0000405 // We must merge fields in this node due to nodes merged in the source node.
406 // In order to handle this we build a map that converts from the source node's
407 // MergeMap values to our MergeMap values. This map is indexed by the
408 // expression: MergeMap[SMM+SourceNodeSize] so we need to allocate at least
409 // 2*SourceNodeSize elements of space for the mapping. We can do this because
410 // we know that there are at most SourceNodeSize outgoing links in the node
411 // (thus that many positive values) and at most SourceNodeSize distinct fields
412 // (thus that many negative values).
413 //
414 std::vector<signed char> MergeMapMap(NSize*2, 127);
415
416 // Loop through the structures, merging them together...
417 for (unsigned i = 0, e = NSize; i != e; ++i) {
418 // Get what this byte of N maps to...
419 signed char NElement = N->MergeMap[i];
420
421 // Get what we map this byte to...
422 signed char Element = MergeMap[i+NOffset];
423 // We use 127 as a sentinal and don't check for it's existence yet...
424 assert(Element != 127 && "MergeMapMap doesn't permit 127 values yet!");
425
426 signed char CurMappedVal = MergeMapMap[NElement+NSize];
427 if (CurMappedVal == 127) { // Haven't seen this NElement yet?
428 MergeMapMap[NElement+NSize] = Element; // Map the two together...
429 } else if (CurMappedVal != Element) {
430 // If we are mapping two different fields together this means that we need
431 // to merge fields in the current node due to merging in the source node.
432 //
433 mergeMappedValues(CurMappedVal, Element);
434 MergeMapMap[NElement+NSize] = MergeMap[i+NOffset];
435 }
436 }
437
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000438 // Make all of the outgoing links of N now be outgoing links of this. This
439 // can cause recursive merging!
440 //
Chris Lattner7b7200c2002-10-02 04:57:39 +0000441 for (unsigned i = 0, e = NSize; i != e; ++i)
442 if (DSNodeHandle *Link = N->getLink(i)) {
443 addEdgeTo(i+NOffset, *Link);
444 N->MergeMap[i] = -1; // Kill outgoing edge
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000445 }
446
447 // Now that there are no outgoing edges, all of the Links are dead.
448 N->Links.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000449
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000450 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000451 NodeType |= N->NodeType;
452 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000453
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000454 // Adjust all of the type entries we are merging in by the offset...
455 //
456 if (NOffset != 0) { // This case is common enough to optimize for
457 // Offset all of the TypeEntries in N with their new offset
458 for (unsigned i = 0, e = N->TypeEntries.size(); i != e; ++i)
459 N->TypeEntries[i].Offset += NOffset;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000460 }
461
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000462 // ... now add them to the TypeEntries list.
463 MergeSortedVectors(TypeEntries, N->TypeEntries);
464 N->TypeEntries.clear(); // N is dead, no type-entries need exist
465
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000466 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000467 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000468 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000469
470 // Delete the globals from the old node...
471 N->Globals.clear();
472 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000473}
474
Chris Lattner9de906c2002-10-20 22:11:44 +0000475//===----------------------------------------------------------------------===//
476// DSCallSite Implementation
477//===----------------------------------------------------------------------===//
478
Vikram S. Adve26b98262002-10-20 21:41:02 +0000479// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000480Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000481 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000482}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000483
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000484
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000485//===----------------------------------------------------------------------===//
486// DSGraph Implementation
487//===----------------------------------------------------------------------===//
488
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000489DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
490 std::map<const DSNode*, DSNode*> NodeMap;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000491 RetNode = cloneInto(G, ValueMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000492}
493
Chris Lattnereff0da92002-10-21 15:32:34 +0000494DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
495 : Func(G.Func) {
496 RetNode = cloneInto(G, ValueMap, NodeMap);
497}
498
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000499DSGraph::~DSGraph() {
500 FunctionCalls.clear();
501 ValueMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000502 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000503
504#ifndef NDEBUG
505 // Drop all intra-node references, so that assertions don't fail...
506 std::for_each(Nodes.begin(), Nodes.end(),
507 std::mem_fun(&DSNode::dropAllReferences));
508#endif
509
510 // Delete all of the nodes themselves...
511 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
512}
513
Chris Lattner0d9bab82002-07-18 00:12:30 +0000514// dump - Allow inspection of graph in a debugger.
515void DSGraph::dump() const { print(std::cerr); }
516
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000517
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000518// Helper function used to clone a function list.
519//
520static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
521 vector<DSCallSite> &toCalls,
522 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000523 unsigned FC = toCalls.size(); // FirstCall
524 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000525 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000526 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000527}
528
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000529/// remapLinks - Change all of the Links in the current node according to the
530/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000531///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000532void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
533 for (unsigned i = 0, e = Links.size(); i != e; ++i)
534 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
535}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000536
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000537
Chris Lattner0d9bab82002-07-18 00:12:30 +0000538// cloneInto - Clone the specified DSGraph into the current graph, returning the
539// Return node of the graph. The translated ValueMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000540// filled into the OldValMap member. If StripAllocas is set to true, Alloca
541// markers are removed from the graph, as the graph is being cloned into a
542// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000543//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000544DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
545 std::map<Value*, DSNodeHandle> &OldValMap,
546 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner92673292002-11-02 00:13:20 +0000547 bool StripScalars, // FIXME: Kill StripScalars
548 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 Lattner92673292002-11-02 00:13:20 +0000567 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000568 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000569 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000570 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000571
Chris Lattnercf15db32002-10-17 20:09:52 +0000572 // Copy the value map... and merge all of the global nodes...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000573 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
Chris Lattnercf15db32002-10-17 20:09:52 +0000574 E = G.ValueMap.end(); I != E; ++I) {
575 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000576 H.setNode(OldNodeMap[I->second.getNode()]);
577 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000578
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)
Chris Lattner92673292002-11-02 00:13:20 +0000658 if (isPointerType(I->getType()) && ValueMap.find(I) != ValueMap.end())
659 markIncompleteNode(ValueMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000660
661 // Mark stuff passed into functions calls as being incomplete...
662 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000663 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000664 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000665 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000666
Chris Lattner92673292002-11-02 00:13:20 +0000667 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000668 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000669 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000670 }
671
Chris Lattner92673292002-11-02 00:13:20 +0000672 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000673 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000674 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000675 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000676 // FIXME: Make more efficient by looking over Links directly
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000677 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
678 if (DSNodeHandle *DSNH = N->getLink(i))
679 markIncompleteNode(DSNH->getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000680 }
681}
682
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000683// removeRefsToGlobal - Helper function that removes globals from the
684// ValueMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000685static void removeRefsToGlobal(DSNode* N,
686 std::map<Value*, DSNodeHandle> &ValueMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000687 while (!N->getGlobals().empty()) {
688 GlobalValue *GV = N->getGlobals().back();
689 N->getGlobals().pop_back();
690 ValueMap.erase(GV);
691 }
692}
693
694
Chris Lattner0d9bab82002-07-18 00:12:30 +0000695// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
696// checks to see if there are simple transformations that it can do to make it
697// dead.
698//
699bool DSGraph::isNodeDead(DSNode *N) {
700 // Is it a trivially dead shadow node...
701 if (N->getReferrers().empty() && N->NodeType == 0)
702 return true;
703
704 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000705 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000706 N->getReferrers().size() == N->getGlobals().size()) {
707
Chris Lattnera00397e2002-10-03 21:55:28 +0000708 // Remove the globals from the ValueMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000709 // down to zero.
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000710 removeRefsToGlobal(N, ValueMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000711 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
712 return true;
713 }
714
715 return false;
716}
717
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000718static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000719 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000720 // Remove trivially identical function calls
721 unsigned NumFns = Calls.size();
722 std::sort(Calls.begin(), Calls.end());
723 Calls.erase(std::unique(Calls.begin(), Calls.end()),
724 Calls.end());
725
726 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000727 std::cerr << "Merged " << (NumFns-Calls.size())
728 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000729}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000730
Chris Lattnere2219762002-07-18 18:22:40 +0000731// removeTriviallyDeadNodes - After the graph has been constructed, this method
732// removes all unreachable nodes that are created because they got merged with
733// other nodes in the graph. These nodes will all be trivially unreachable, so
734// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000735//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000736void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000737 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000738 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000739 if (isNodeDead(Nodes[i])) { // This node is dead!
740 delete Nodes[i]; // Free memory...
741 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
742 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000743
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000744 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000745}
746
747
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000748// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000749// stuff to be alive.
750//
751static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000752 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000753
754 Alive.insert(N);
Chris Lattner92673292002-11-02 00:13:20 +0000755 // FIXME: Make more efficient by looking over Links directly
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000756 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
757 if (DSNodeHandle *DSNH = N->getLink(i))
758 if (!Alive.count(DSNH->getNode()))
759 markAlive(DSNH->getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000760}
761
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000762static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
763 std::set<DSNode*> &Visiting) {
764 if (N == 0) return false;
765
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000766 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000767 Visiting.insert(N);
768
769 // If any immediate successor is alive, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000770 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
771 if (DSNodeHandle *DSNH = N->getLink(i))
772 if (Alive.count(DSNH->getNode())) {
773 Visiting.erase(N);
774 return true;
775 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000776
777 // Else if any successor reaches a live node, N is alive
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000778 for (unsigned i = 0, e = N->getSize(); i != e; ++i)
779 if (DSNodeHandle *DSNH = N->getLink(i))
780 if (checkGlobalAlive(DSNH->getNode(), Alive, Visiting)) {
781 Visiting.erase(N); return true;
782 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000783
784 Visiting.erase(N);
785 return false;
786}
787
788
789// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
790// This would be unnecessary if function calls were real nodes! In that case,
791// the simple iterative loop in the first few lines below suffice.
792//
793static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000794 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000795 std::set<DSNode*> &Alive,
796 bool FilterCalls) {
797
798 // Iterate, marking globals or cast nodes alive until no new live nodes
799 // are added to Alive
800 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000801 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000802 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
803 liveCount = Alive.size();
804 for ( ; I != E; ++I)
805 if (Alive.count(*I) == 0) {
806 Visiting.clear();
807 if (checkGlobalAlive(*I, Alive, Visiting))
808 markAlive(*I, Alive);
809 }
810 }
811
812 // Find function calls with some dead and some live nodes.
813 // Since all call nodes must be live if any one is live, we have to mark
814 // all nodes of the call as live and continue the iteration (via recursion).
815 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000816 bool Recurse = false;
817 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000818 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000819 DSCallSite &CS = Calls[i];
820 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
821 if (DSNode *N = CS.getPtrArg(j).getNode()) {
822 bool ArgIsDead = !Alive.count(N);
823 CallHasDeadArg |= ArgIsDead;
824 CallIsDead &= ArgIsDead;
825 }
826
827 if (DSNode *N = CS.getRetVal().getNode()) {
828 bool RetIsDead = !Alive.count(N);
829 CallHasDeadArg |= RetIsDead;
830 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000831 }
Chris Lattner0969c502002-10-21 02:08:03 +0000832
833 DSNode *N = CS.getCallee().getNode();
834 bool FnIsDead = !Alive.count(N);
835 CallHasDeadArg |= FnIsDead;
836 CallIsDead &= FnIsDead;
837
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000838 if (!CallIsDead && CallHasDeadArg) {
839 // Some node in this call is live and another is dead.
840 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000841 Recurse = true;
842 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
843 markAlive(CS.getPtrArg(j).getNode(), Alive);
844 markAlive(CS.getRetVal().getNode(), Alive);
845 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000846 }
847 }
Chris Lattner0969c502002-10-21 02:08:03 +0000848 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000849 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
850 }
851}
852
853
854// markGlobalsAlive - Mark global nodes and cast nodes alive if they
855// can reach any other live node. Since this can produce new live nodes,
856// we use a simple iterative algorithm.
857//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000858static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000859 bool FilterCalls) {
860 // Add global and cast nodes to a set so we don't walk all nodes every time
861 std::set<DSNode*> GlobalNodes;
862 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000863 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000864 GlobalNodes.insert(G.getNodes()[i]);
865
866 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000867 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000868 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000869 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
870 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
871 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
872 GlobalNodes.insert(N);
873 if (DSNode *N = Calls[i].getRetVal().getNode())
874 GlobalNodes.insert(N);
875 if (DSNode *N = Calls[i].getCallee().getNode())
876 GlobalNodes.insert(N);
877 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000878 }
879
880 // Iterate and recurse until no new live node are discovered.
881 // This would be a simple iterative loop if function calls were real nodes!
882 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
883
884 // Free up references to dead globals from the ValueMap
Chris Lattner92673292002-11-02 00:13:20 +0000885 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000886 for( ; I != E; ++I)
887 if (Alive.count(*I) == 0)
888 removeRefsToGlobal(*I, G.getValueMap());
889
890 // Delete dead function calls
891 if (FilterCalls)
892 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
893 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000894 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
895 CallIsDead && j != ej; ++j)
896 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000897 if (CallIsDead)
898 Calls.erase(Calls.begin() + i); // remove the call entirely
899 }
900}
Chris Lattnere2219762002-07-18 18:22:40 +0000901
902// removeDeadNodes - Use a more powerful reachability analysis to eliminate
903// subgraphs that are unreachable. This often occurs because the data
904// structure doesn't "escape" into it's caller, and thus should be eliminated
905// from the caller's graph entirely. This is only appropriate to use when
906// inlining graphs.
907//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000908void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
909 assert((!KeepAllGlobals || KeepCalls) &&
910 "KeepAllGlobals without KeepCalls is meaningless");
911
Chris Lattnere2219762002-07-18 18:22:40 +0000912 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000913 removeTriviallyDeadNodes(KeepAllGlobals);
914
Chris Lattnere2219762002-07-18 18:22:40 +0000915 // FIXME: Merge nontrivially identical call nodes...
916
917 // Alive - a set that holds all nodes found to be reachable/alive.
918 std::set<DSNode*> Alive;
919
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000920 // If KeepCalls, mark all nodes reachable by call nodes as alive...
921 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000922 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
923 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
924 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
925 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
926 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
927 }
Chris Lattnere2219762002-07-18 18:22:40 +0000928
Chris Lattner92673292002-11-02 00:13:20 +0000929 // Mark all nodes reachable by scalar nodes as alive...
930 for (std::map<Value*, DSNodeHandle>::iterator I = ValueMap.begin(),
931 E = ValueMap.end(); I != E; ++I)
932 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000933
Chris Lattner92673292002-11-02 00:13:20 +0000934#if 0
935 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
936 // the ValueMap?
937 //
938 if (KeepAllGlobals)
939 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
940 if (Nodes[i]->NodeType & DSNode::GlobalNode)
941 markAlive(Nodes[i], Alive);
942#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000943
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000944 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000945 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000946
947 // Mark all globals or cast nodes that can reach a live node as alive.
948 // This also marks all nodes reachable from such nodes as alive.
949 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000950 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000951 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000952
Chris Lattnere2219762002-07-18 18:22:40 +0000953 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000954 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000955 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
956 for (unsigned i = 0; i != Nodes.size(); ++i)
957 if (!Alive.count(Nodes[i])) {
958 DSNode *N = Nodes[i];
959 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
960 DeadNodes.push_back(N); // Add node to our list of dead nodes
961 N->dropAllReferences(); // Drop all outgoing edges
962 }
963
Chris Lattnere2219762002-07-18 18:22:40 +0000964 // Delete all dead nodes...
965 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
966}
967
968
969
Chris Lattner0d9bab82002-07-18 00:12:30 +0000970// maskNodeTypes - Apply a mask to all of the node types in the graph. This
971// is useful for clearing out markers like Scalar or Incomplete.
972//
973void DSGraph::maskNodeTypes(unsigned char Mask) {
974 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
975 Nodes[i]->NodeType &= Mask;
976}
977
978
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000979#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000980//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000981// GlobalDSGraph Implementation
982//===----------------------------------------------------------------------===//
983
984GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
985}
986
987GlobalDSGraph::~GlobalDSGraph() {
988 assert(Referrers.size() == 0 &&
989 "Deleting global graph while references from other graphs exist");
990}
991
992void GlobalDSGraph::addReference(const DSGraph* referrer) {
993 if (referrer != this)
994 Referrers.insert(referrer);
995}
996
997void GlobalDSGraph::removeReference(const DSGraph* referrer) {
998 if (referrer != this) {
999 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1000 Referrers.erase(referrer);
1001 if (Referrers.size() == 0)
1002 delete this;
1003 }
1004}
1005
1006// Bits used in the next function
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001007static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001008
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001009#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001010// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1011// visible target links (and recursively their such links) into this graph.
1012// NodeCache maps the node being cloned to its clone in the Globals graph,
1013// in order to track cycles.
1014// GlobalsAreFinal is a flag that says whether it is safe to assume that
1015// an existing global node is complete. This is important to avoid
1016// reinserting all globals when inserting Calls to functions.
1017// This is a helper function for cloneGlobals and cloneCalls.
1018//
1019DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1020 std::map<const DSNode*, DSNode*> &NodeCache,
1021 bool GlobalsAreFinal) {
1022 if (OldNode == 0) return 0;
1023
1024 // The caller should check this is an external node. Just more efficient...
1025 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1026
1027 // If a clone has already been created for OldNode, return it.
1028 DSNode*& CacheEntry = NodeCache[OldNode];
1029 if (CacheEntry != 0)
1030 return CacheEntry;
1031
1032 // The result value...
1033 DSNode* NewNode = 0;
1034
1035 // If nodes already exist for any of the globals of OldNode,
1036 // merge all such nodes together since they are merged in OldNode.
1037 // If ValueCacheIsFinal==true, look for an existing node that has
1038 // an identical list of globals and return it if it exists.
1039 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001040 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
1041 if (DSNode *PrevNode = ValueMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001042 if (NewNode == 0) {
1043 NewNode = PrevNode; // first existing node found
1044 if (GlobalsAreFinal && j == 0)
1045 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1046 CacheEntry = NewNode;
1047 return NewNode;
1048 }
1049 }
1050 else if (NewNode != PrevNode) { // found another, different from prev
1051 // update ValMap *before* merging PrevNode into NewNode
1052 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
1053 ValueMap[PrevNode->getGlobals()[k]] = NewNode;
1054 NewNode->mergeWith(PrevNode);
1055 }
1056 } else if (NewNode != 0) {
1057 ValueMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
1058 }
1059
1060 // If no existing node was found, clone the node and update the ValMap.
1061 if (NewNode == 0) {
1062 NewNode = new DSNode(*OldNode);
1063 Nodes.push_back(NewNode);
1064 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1065 NewNode->setLink(j, 0);
1066 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
1067 ValueMap[NewNode->getGlobals()[j]] = NewNode;
1068 }
1069 else
1070 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1071
1072 // Add the entry to NodeCache
1073 CacheEntry = NewNode;
1074
1075 // Rewrite the links in the new node to point into the current graph,
1076 // but only for links to external nodes. Set other links to NULL.
1077 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1078 DSNode* OldTarget = OldNode->getLink(j);
1079 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1080 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1081 if (NewNode->getLink(j))
1082 NewNode->getLink(j)->mergeWith(NewLink);
1083 else
1084 NewNode->setLink(j, NewLink);
1085 }
1086 }
1087
1088 // Remove all local markers
1089 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1090
1091 return NewNode;
1092}
1093
1094
1095// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1096// visible target links (and recursively their such links) into this graph.
1097//
1098void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1099 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001100#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001101 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1102 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1103 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001104 if (CloneCalls)
1105 GlobalsGraph->cloneCalls(Graph);
1106
1107 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001108#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001109}
1110
1111
1112// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1113// links (and recursively their such links) into this graph.
1114//
1115void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1116 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001117 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001118
1119 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1120
1121 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001122 DSCallSite& callCopy = FunctionCalls.back();
1123 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001124 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001125 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001126 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1127 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1128 : 0);
1129 }
1130
1131 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001132 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001133}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001134#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001135
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001136#endif