blob: 8d798e3dc2844c26257413619e8159a1e7c12902 [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 Lattner08db7192002-11-06 06:20:27 +000019namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000020 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
21 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000022};
23
Chris Lattnerb1060432002-11-07 05:20:53 +000024namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000025 extern TargetData TD;
26}
Chris Lattnerb1060432002-11-07 05:20:53 +000027using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000028
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 Lattner08db7192002-11-06 06:20:27 +000033DSNode::DSNode(enum NodeTy NT, const Type *T)
34 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000035 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000036 if (T) mergeTypeInfo(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000037}
38
Chris Lattner0d9bab82002-07-18 00:12:30 +000039// DSNode copy constructor... do not copy over the referrers list!
40DSNode::DSNode(const DSNode &N)
Chris Lattner08db7192002-11-06 06:20:27 +000041 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
42 NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000043}
44
Chris Lattnerc68c31b2002-07-10 22:38:08 +000045void DSNode::removeReferrer(DSNodeHandle *H) {
46 // Search backwards, because we depopulate the list from the back for
47 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000048 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000049 std::find(Referrers.rbegin(), Referrers.rend(), H);
50 assert(I != Referrers.rend() && "Referrer not pointing to node!");
51 Referrers.erase(I.base()-1);
52}
53
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000054// addGlobal - Add an entry for a global value to the Globals list. This also
55// marks the node with the 'G' flag if it does not already have it.
56//
57void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000058 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000059 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000060 std::lower_bound(Globals.begin(), Globals.end(), GV);
61
62 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000063 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000064 Globals.insert(I, GV);
65 NodeType |= GlobalNode;
66 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000067}
68
Chris Lattner8f0a16e2002-10-31 05:45:02 +000069/// foldNodeCompletely - If we determine that this node has some funny
70/// behavior happening to it that we cannot represent, we fold it down to a
71/// single, completely pessimistic, node. This node is represented as a
72/// single byte with a single TypeEntry of "void".
73///
74void DSNode::foldNodeCompletely() {
Chris Lattner08db7192002-11-06 06:20:27 +000075 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000076
Chris Lattner08db7192002-11-06 06:20:27 +000077 ++NumFolds;
78
79 // We are no longer typed at all...
80 Ty = DSTypeRec(Type::VoidTy, true);
81 Size = 1;
82
83 // Loop over all of our referrers, making them point to our zero bytes of
84 // space.
Chris Lattner8f0a16e2002-10-31 05:45:02 +000085 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
86 I != E; ++I)
87 (*I)->setOffset(0);
88
Chris Lattner8f0a16e2002-10-31 05:45:02 +000089 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000090 for (unsigned i = 1, e = Links.size(); i < e; ++i)
91 Links[0].mergeWith(Links[i]);
92 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000093}
Chris Lattner076c1f92002-11-07 06:31:54 +000094
Chris Lattner8f0a16e2002-10-31 05:45:02 +000095/// 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 {
Chris Lattner08db7192002-11-06 06:20:27 +0000100 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000101}
102
103
Chris Lattner08db7192002-11-06 06:20:27 +0000104/// mergeTypeInfo - This method merges the specified type into the current node
105/// at the specified offset. This may update the current node's type record if
106/// this gives more information to the node, it may do nothing to the node if
107/// this information is already known, or it may merge the node completely (and
108/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000109///
Chris Lattner08db7192002-11-06 06:20:27 +0000110/// This method returns true if the node is completely folded, otherwise false.
111///
112bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
113 // Check to make sure the Size member is up-to-date. Size can be one of the
114 // following:
115 // Size = 0, Ty = Void: Nothing is known about this node.
116 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
117 // Size = 1, Ty = Void, Array = 1: The node is collapsed
118 // Otherwise, sizeof(Ty) = Size
119 //
120 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
121 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
122 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
123 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
124 (TD.getTypeSize(Ty.Ty) == Size)) &&
125 "Size member of DSNode doesn't match the type structure!");
126 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000127
Chris Lattner08db7192002-11-06 06:20:27 +0000128 if (Offset == 0 && NewTy == Ty.Ty)
129 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000130
Chris Lattner08db7192002-11-06 06:20:27 +0000131 // Return true immediately if the node is completely folded.
132 if (isNodeCompletelyFolded()) return true;
133
134 // Figure out how big the new type we're merging in is...
135 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
136
137 // Otherwise check to see if we can fold this type into the current node. If
138 // we can't, we fold the node completely, if we can, we potentially update our
139 // internal state.
140 //
141 if (Ty.Ty == Type::VoidTy) {
142 // If this is the first type that this node has seen, just accept it without
143 // question....
144 assert(Offset == 0 && "Cannot have an offset into a void node!");
145 assert(Ty.isArray == false && "This shouldn't happen!");
146 Ty.Ty = NewTy;
147 Size = NewTySize;
148
149 // Calculate the number of outgoing links from this node.
150 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
151 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000152 }
Chris Lattner08db7192002-11-06 06:20:27 +0000153
154 // Handle node expansion case here...
155 if (Offset+NewTySize > Size) {
156 // It is illegal to grow this node if we have treated it as an array of
157 // objects...
158 if (Ty.isArray) {
159 foldNodeCompletely();
160 return true;
161 }
162
163 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000164 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
165 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000166 foldNodeCompletely();
167 return true;
168 }
169
170 // Okay, the situation is nice and simple, we are trying to merge a type in
171 // at offset 0 that is bigger than our current type. Implement this by
172 // switching to the new type and then merge in the smaller one, which should
173 // hit the other code path here. If the other code path decides it's not
174 // ok, it will collapse the node as appropriate.
175 //
176 const Type *OldTy = Ty.Ty;
177 Ty.Ty = NewTy;
178 Size = NewTySize;
179
180 // Must grow links to be the appropriate size...
181 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
182
183 // Merge in the old type now... which is guaranteed to be smaller than the
184 // "current" type.
185 return mergeTypeInfo(OldTy, 0);
186 }
187
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000188 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000189 "Cannot merge something into a part of our type that doesn't exist!");
190
191 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
192 // type that starts at offset Offset.
193 //
194 unsigned O = 0;
195 const Type *SubType = Ty.Ty;
196 while (O < Offset) {
197 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
198
199 switch (SubType->getPrimitiveID()) {
200 case Type::StructTyID: {
201 const StructType *STy = cast<StructType>(SubType);
202 const StructLayout &SL = *TD.getStructLayout(STy);
203
204 unsigned i = 0, e = SL.MemberOffsets.size();
205 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
206 /* empty */;
207
208 // The offset we are looking for must be in the i'th element...
209 SubType = STy->getElementTypes()[i];
210 O += SL.MemberOffsets[i];
211 break;
212 }
213 case Type::ArrayTyID: {
214 SubType = cast<ArrayType>(SubType)->getElementType();
215 unsigned ElSize = TD.getTypeSize(SubType);
216 unsigned Remainder = (Offset-O) % ElSize;
217 O = Offset-Remainder;
218 break;
219 }
220 default:
221 assert(0 && "Unknown type!");
222 }
223 }
224
225 assert(O == Offset && "Could not achieve the correct offset!");
226
227 // If we found our type exactly, early exit
228 if (SubType == NewTy) return false;
229
230 // Okay, so we found the leader type at the offset requested. Search the list
231 // of types that starts at this offset. If SubType is currently an array or
232 // structure, the type desired may actually be the first element of the
233 // composite type...
234 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000235 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000236 while (SubType != NewTy) {
237 const Type *NextSubType = 0;
238 unsigned NextSubTypeSize;
239 switch (SubType->getPrimitiveID()) {
240 case Type::StructTyID:
241 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
242 NextSubTypeSize = TD.getTypeSize(SubType);
243 break;
244 case Type::ArrayTyID:
245 NextSubType = cast<ArrayType>(SubType)->getElementType();
246 NextSubTypeSize = TD.getTypeSize(SubType);
247 break;
248 default: ;
249 // fall out
250 }
251
252 if (NextSubType == 0)
253 break; // In the default case, break out of the loop
254
255 if (NextSubTypeSize < NewTySize)
256 break; // Don't allow shrinking to a smaller type than NewTySize
257 SubType = NextSubType;
258 SubTypeSize = NextSubTypeSize;
259 }
260
261 // If we found the type exactly, return it...
262 if (SubType == NewTy)
263 return false;
264
265 // Check to see if we have a compatible, but different type...
266 if (NewTySize == SubTypeSize) {
267 // Check to see if this type is obviously convertable... int -> uint f.e.
268 if (NewTy->isLosslesslyConvertableTo(SubType))
269 return false;
270
271 // Check to see if we have a pointer & integer mismatch going on here,
272 // loading a pointer as a long, for example.
273 //
274 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
275 NewTy->isInteger() && isa<PointerType>(SubType))
276 return false;
277
278 }
279
280
Chris Lattner3c87b292002-11-07 01:54:56 +0000281 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
282 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
283 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000284
285 foldNodeCompletely();
286 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000287}
288
Chris Lattner08db7192002-11-06 06:20:27 +0000289
290
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000291// addEdgeTo - Add an edge from the current node to the specified node. This
292// can cause merging of nodes in the graph.
293//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000294void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000295 if (NH.getNode() == 0) return; // Nothing to do
296
Chris Lattner08db7192002-11-06 06:20:27 +0000297 DSNodeHandle &ExistingEdge = getLink(Offset);
298 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000299 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000300 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000301 } else { // No merging to perform...
302 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000303 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000304}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000305
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000306
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000307// MergeSortedVectors - Efficiently merge a vector into another vector where
308// duplicates are not allowed and both are sorted. This assumes that 'T's are
309// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000310//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000311template<typename T>
312void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
313 // By far, the most common cases will be the simple ones. In these cases,
314 // avoid having to allocate a temporary vector...
315 //
316 if (Src.empty()) { // Nothing to merge in...
317 return;
318 } else if (Dest.empty()) { // Just copy the result in...
319 Dest = Src;
320 } else if (Src.size() == 1) { // Insert a single element...
321 const T &V = Src[0];
322 typename vector<T>::iterator I =
323 std::lower_bound(Dest.begin(), Dest.end(), V);
324 if (I == Dest.end() || *I != Src[0]) // If not already contained...
325 Dest.insert(I, Src[0]);
326 } else if (Dest.size() == 1) {
327 T Tmp = Dest[0]; // Save value in temporary...
328 Dest = Src; // Copy over list...
329 typename vector<T>::iterator I =
330 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
331 if (I == Dest.end() || *I != Src[0]) // If not already contained...
332 Dest.insert(I, Src[0]);
333
334 } else {
335 // Make a copy to the side of Dest...
336 vector<T> Old(Dest);
337
338 // Make space for all of the type entries now...
339 Dest.resize(Dest.size()+Src.size());
340
341 // Merge the two sorted ranges together... into Dest.
342 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
343
344 // Now erase any duplicate entries that may have accumulated into the
345 // vectors (because they were in both of the input sets)
346 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
347 }
348}
349
350
351// mergeWith - Merge this node and the specified node, moving all links to and
352// from the argument node into the current node, deleting the node argument.
353// Offset indicates what offset the specified node is to be merged into the
354// current node.
355//
356// The specified node may be a null pointer (in which case, nothing happens).
357//
358void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
359 DSNode *N = NH.getNode();
360 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000361 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000362
Chris Lattner02606632002-11-04 06:48:26 +0000363 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000364 // We cannot merge two pieces of the same node together, collapse the node
365 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000366 DEBUG(std::cerr << "Attempting to merge two chunks of"
367 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000368 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000369 return;
370 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000371
Chris Lattner08db7192002-11-06 06:20:27 +0000372 // Merge the type entries of the two nodes together...
373 if (N->Ty.Ty != Type::VoidTy)
374 mergeTypeInfo(N->Ty.Ty, Offset);
375
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000376 // If we are merging a node with a completely folded node, then both nodes are
377 // now completely folded.
378 //
379 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000380 if (!N->isNodeCompletelyFolded())
381 N->foldNodeCompletely();
382 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000383 foldNodeCompletely();
384 Offset = 0;
385 }
Chris Lattner02606632002-11-04 06:48:26 +0000386 N = NH.getNode();
387
Chris Lattner2c0bd012002-11-06 18:01:39 +0000388 if (this == N || N == 0) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000389
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000390 // If both nodes are not at offset 0, make sure that we are merging the node
391 // at an later offset into the node with the zero offset.
392 //
393 if (Offset > NH.getOffset()) {
394 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
395 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000396 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
397 // If the offsets are the same, merge the smaller node into the bigger node
398 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
399 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000400 }
401
402#if 0
403 std::cerr << "\n\nMerging:\n";
404 N->print(std::cerr, 0);
405 std::cerr << " and:\n";
406 print(std::cerr, 0);
407#endif
408
409 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
410 // respect to NH.Offset) is now zero.
411 //
412 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000413 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000414
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000415 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000416 // Make sure to adjust their offset, not just the node pointer.
417 //
418 while (!N->Referrers.empty()) {
419 DSNodeHandle &Ref = *N->Referrers.back();
420 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
421 }
Chris Lattner59535132002-11-05 00:01:58 +0000422
423 // Make all of the outgoing links of N now be outgoing links of this. This
424 // can cause recursive merging!
425 //
Chris Lattner08db7192002-11-06 06:20:27 +0000426 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
427 DSNodeHandle &Link = N->getLink(i);
428 if (Link.getNode()) {
429 addEdgeTo((i+NOffset) % getSize(), Link);
Chris Lattner59535132002-11-05 00:01:58 +0000430
Chris Lattner08db7192002-11-06 06:20:27 +0000431 // It's possible that after adding the new edge that some recursive
432 // merging just occured, causing THIS node to get merged into oblivion.
433 // If that happens, we must not try to merge any more edges into it!
Chris Lattner7b7200c2002-10-02 04:57:39 +0000434 //
Chris Lattner08db7192002-11-06 06:20:27 +0000435 if (Size == 0) return;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000436 }
437 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000438
439 // Now that there are no outgoing edges, all of the Links are dead.
440 N->Links.clear();
Chris Lattner08db7192002-11-06 06:20:27 +0000441 N->Size = 0;
442 N->Ty.Ty = Type::VoidTy;
443 N->Ty.isArray = false;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000444
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000445 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000446 NodeType |= N->NodeType;
Chris Lattner33312f72002-11-08 01:21:07 +0000447 N->NodeType = DEAD; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000448
449 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000450 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000451 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000452
453 // Delete the globals from the old node...
454 N->Globals.clear();
455 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000456}
457
Chris Lattner9de906c2002-10-20 22:11:44 +0000458//===----------------------------------------------------------------------===//
459// DSCallSite Implementation
460//===----------------------------------------------------------------------===//
461
Vikram S. Adve26b98262002-10-20 21:41:02 +0000462// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000463Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000464 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000465}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000466
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000467
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000468//===----------------------------------------------------------------------===//
469// DSGraph Implementation
470//===----------------------------------------------------------------------===//
471
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000472DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
473 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000474 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000475}
476
Chris Lattnereff0da92002-10-21 15:32:34 +0000477DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
478 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000479 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000480}
481
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000482DSGraph::~DSGraph() {
483 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000484 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000485 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000486
487#ifndef NDEBUG
488 // Drop all intra-node references, so that assertions don't fail...
489 std::for_each(Nodes.begin(), Nodes.end(),
490 std::mem_fun(&DSNode::dropAllReferences));
491#endif
492
493 // Delete all of the nodes themselves...
494 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
495}
496
Chris Lattner0d9bab82002-07-18 00:12:30 +0000497// dump - Allow inspection of graph in a debugger.
498void DSGraph::dump() const { print(std::cerr); }
499
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000500
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000501/// remapLinks - Change all of the Links in the current node according to the
502/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000503///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000504void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
505 for (unsigned i = 0, e = Links.size(); i != e; ++i)
506 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
507}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000508
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000509
Chris Lattner0d9bab82002-07-18 00:12:30 +0000510// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000511// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000512// filled into the OldValMap member. If StripAllocas is set to true, Alloca
513// markers are removed from the graph, as the graph is being cloned into a
514// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000515//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000516DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
517 std::map<Value*, DSNodeHandle> &OldValMap,
518 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner460ea292002-11-07 07:06:20 +0000519 AllocaBit StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000520 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000521 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000522
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000523 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000524
525 // Duplicate all of the nodes, populating the node map...
526 Nodes.reserve(FN+G.Nodes.size());
527 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000528 DSNode *Old = G.Nodes[i];
529 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000530 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000531 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000532 }
533
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000534 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000535 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000536 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000537
Chris Lattner460ea292002-11-07 07:06:20 +0000538 // Remove alloca markers as specified
539 if (StripAllocas == StripAllocaBit)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000540 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattner460ea292002-11-07 07:06:20 +0000541 Nodes[i]->NodeType &= ~DSNode::AllocaNode;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000542
Chris Lattnercf15db32002-10-17 20:09:52 +0000543 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000544 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
545 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000546 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000547 H.setNode(OldNodeMap[I->second.getNode()]);
548 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000549
550 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000551 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
552 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000553 GVI->second.mergeWith(H);
Chris Lattner33312f72002-11-08 01:21:07 +0000554 OldNodeMap[I->second.getNode()] = H.getNode();
Chris Lattnercf15db32002-10-17 20:09:52 +0000555 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000556 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000557 }
558 }
559 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000560
Chris Lattner33312f72002-11-08 01:21:07 +0000561 // Copy the function calls list...
562 unsigned FC = FunctionCalls.size(); // FirstCall
563 FunctionCalls.reserve(FC+G.FunctionCalls.size());
564 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
565 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattnercf15db32002-10-17 20:09:52 +0000566
Chris Lattner0d9bab82002-07-18 00:12:30 +0000567 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000568 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000569}
570
Chris Lattner076c1f92002-11-07 06:31:54 +0000571/// mergeInGraph - The method is used for merging graphs together. If the
572/// argument graph is not *this, it makes a clone of the specified graph, then
573/// merges the nodes specified in the call site with the formal arguments in the
574/// graph.
575///
576void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner460ea292002-11-07 07:06:20 +0000577 AllocaBit StripAllocas) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000578 std::map<Value*, DSNodeHandle> OldValMap;
579 DSNodeHandle RetVal;
580 std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
581
582 // If this is not a recursive call, clone the graph into this graph...
583 if (&Graph != this) {
584 // Clone the callee's graph into the current graph, keeping
585 // track of where scalars in the old graph _used_ to point,
586 // and of the new nodes matching nodes of the old graph.
587 std::map<const DSNode*, DSNode*> OldNodeMap;
588
589 // The clone call may invalidate any of the vectors in the data
590 // structure graph. Strip locals and don't copy the list of callers
591 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, StripAllocas);
592 ScalarMap = &OldValMap;
593 } else {
594 RetVal = getRetNode();
595 ScalarMap = &getScalarMap();
596 }
597
598 // Merge the return value with the return value of the context...
599 RetVal.mergeWith(CS.getRetVal());
600
601 // Resolve all of the function arguments...
602 Function &F = Graph.getFunction();
603 Function::aiterator AI = F.abegin();
604 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
605 // Advance the argument iterator to the first pointer argument...
606 while (!isPointerType(AI->getType())) {
607 ++AI;
608#ifndef NDEBUG
609 if (AI == F.aend())
610 std::cerr << "Bad call to Function: " << F.getName() << "\n";
611#endif
612 assert(AI != F.aend() && "# Args provided is not # Args required!");
613 }
614
615 // Add the link from the argument scalar to the provided value
616 DSNodeHandle &NH = (*ScalarMap)[AI];
617 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
618 NH.mergeWith(CS.getPtrArg(i));
619 }
620}
621
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000622#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000623// cloneGlobalInto - Clone the given global node and all its target links
624// (and all their llinks, recursively).
625//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000626DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000627 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
628
629 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000630 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000631 if (ValMapEntry != 0)
632 return ValMapEntry;
633
634 // Clone the node and update the ValMap.
635 DSNode* NewNode = new DSNode(*GNode);
636 ValMapEntry = NewNode; // j=0 case of loop below!
637 Nodes.push_back(NewNode);
638 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000639 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000640
641 // Rewrite the links in the new node to point into the current graph.
642 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
643 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
644
645 return NewNode;
646}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000647#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000648
649
Chris Lattner0d9bab82002-07-18 00:12:30 +0000650// markIncompleteNodes - Mark the specified node as having contents that are not
651// known with the current analysis we have performed. Because a node makes all
652// of the nodes it can reach imcomplete if the node itself is incomplete, we
653// must recursively traverse the data structure graph, marking all reachable
654// nodes as incomplete.
655//
656static void markIncompleteNode(DSNode *N) {
657 // Stop recursion if no node, or if node already marked...
658 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
659
660 // Actually mark the node
661 N->NodeType |= DSNode::Incomplete;
662
663 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000664 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
665 if (DSNode *DSN = N->getLink(i).getNode())
666 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000667}
668
669
670// markIncompleteNodes - Traverse the graph, identifying nodes that may be
671// modified by other functions that have not been resolved yet. This marks
672// nodes that are reachable through three sources of "unknownness":
673//
674// Global Variables, Function Calls, and Incoming Arguments
675//
676// For any node that may have unknown components (because something outside the
677// scope of current analysis may have modified it), the 'Incomplete' flag is
678// added to the NodeType.
679//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000680void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000681 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000682 if (markFormalArgs && Func)
683 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000684 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
685 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000686
687 // Mark stuff passed into functions calls as being incomplete...
688 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000689 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000690 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000691 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000692
Chris Lattner92673292002-11-02 00:13:20 +0000693 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000694 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000695 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000696 }
697
Chris Lattner92673292002-11-02 00:13:20 +0000698 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000699 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000700 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000701 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000702 // FIXME: Make more efficient by looking over Links directly
Chris Lattner08db7192002-11-06 06:20:27 +0000703 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
704 if (DSNode *DSN = N->getLink(i).getNode())
705 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000706 }
707}
708
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000709// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000710// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000711static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000712 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000713 while (!N->getGlobals().empty()) {
714 GlobalValue *GV = N->getGlobals().back();
715 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000716 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000717 }
718}
719
720
Chris Lattner0d9bab82002-07-18 00:12:30 +0000721// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
722// checks to see if there are simple transformations that it can do to make it
723// dead.
724//
725bool DSGraph::isNodeDead(DSNode *N) {
726 // Is it a trivially dead shadow node...
Chris Lattner33312f72002-11-08 01:21:07 +0000727 if (N->getReferrers().empty() &&
728 (N->NodeType == 0 || N->NodeType == DSNode::DEAD))
Chris Lattner0d9bab82002-07-18 00:12:30 +0000729 return true;
730
731 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000732 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000733 N->getReferrers().size() == N->getGlobals().size()) {
734
Chris Lattnerc875f022002-11-03 21:27:48 +0000735 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000736 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000737 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000738 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
739 return true;
740 }
741
742 return false;
743}
744
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000745static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000746 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000747 // Remove trivially identical function calls
748 unsigned NumFns = Calls.size();
749 std::sort(Calls.begin(), Calls.end());
750 Calls.erase(std::unique(Calls.begin(), Calls.end()),
751 Calls.end());
752
Chris Lattner33312f72002-11-08 01:21:07 +0000753 // Track the number of call nodes merged away...
754 NumCallNodesMerged += NumFns-Calls.size();
755
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000756 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000757 std::cerr << "Merged " << (NumFns-Calls.size())
758 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000759}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000760
Chris Lattnere2219762002-07-18 18:22:40 +0000761// removeTriviallyDeadNodes - After the graph has been constructed, this method
762// removes all unreachable nodes that are created because they got merged with
763// other nodes in the graph. These nodes will all be trivially unreachable, so
764// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000765//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000766void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000767 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000768 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000769 if (isNodeDead(Nodes[i])) { // This node is dead!
770 delete Nodes[i]; // Free memory...
771 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
772 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000773
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000774 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000775}
776
777
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000778// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000779// stuff to be alive.
780//
781static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000782 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000783
784 Alive.insert(N);
Chris Lattner08db7192002-11-06 06:20:27 +0000785 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
786 if (DSNode *DSN = N->getLink(i).getNode())
787 if (!Alive.count(DSN))
788 markAlive(DSN, Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000789}
790
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000791static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
792 std::set<DSNode*> &Visiting) {
793 if (N == 0) return false;
794
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000795 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000796 Visiting.insert(N);
797
798 // If any immediate successor is alive, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000799 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
800 if (DSNode *DSN = N->getLink(i).getNode())
801 if (Alive.count(DSN)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000802 Visiting.erase(N);
803 return true;
804 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000805
806 // Else if any successor reaches a live node, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000807 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
808 if (DSNode *DSN = N->getLink(i).getNode())
809 if (checkGlobalAlive(DSN, Alive, Visiting)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000810 Visiting.erase(N); return true;
811 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000812
813 Visiting.erase(N);
814 return false;
815}
816
817
818// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
819// This would be unnecessary if function calls were real nodes! In that case,
820// the simple iterative loop in the first few lines below suffice.
821//
822static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000823 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000824 std::set<DSNode*> &Alive,
825 bool FilterCalls) {
826
827 // Iterate, marking globals or cast nodes alive until no new live nodes
828 // are added to Alive
829 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000830 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000831 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
832 liveCount = Alive.size();
833 for ( ; I != E; ++I)
834 if (Alive.count(*I) == 0) {
835 Visiting.clear();
836 if (checkGlobalAlive(*I, Alive, Visiting))
837 markAlive(*I, Alive);
838 }
839 }
840
841 // Find function calls with some dead and some live nodes.
842 // Since all call nodes must be live if any one is live, we have to mark
843 // all nodes of the call as live and continue the iteration (via recursion).
844 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000845 bool Recurse = false;
846 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000847 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000848 DSCallSite &CS = Calls[i];
849 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
850 if (DSNode *N = CS.getPtrArg(j).getNode()) {
851 bool ArgIsDead = !Alive.count(N);
852 CallHasDeadArg |= ArgIsDead;
853 CallIsDead &= ArgIsDead;
854 }
855
856 if (DSNode *N = CS.getRetVal().getNode()) {
857 bool RetIsDead = !Alive.count(N);
858 CallHasDeadArg |= RetIsDead;
859 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000860 }
Chris Lattner0969c502002-10-21 02:08:03 +0000861
862 DSNode *N = CS.getCallee().getNode();
863 bool FnIsDead = !Alive.count(N);
864 CallHasDeadArg |= FnIsDead;
865 CallIsDead &= FnIsDead;
866
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000867 if (!CallIsDead && CallHasDeadArg) {
868 // Some node in this call is live and another is dead.
869 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000870 Recurse = true;
871 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
872 markAlive(CS.getPtrArg(j).getNode(), Alive);
873 markAlive(CS.getRetVal().getNode(), Alive);
874 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000875 }
876 }
Chris Lattner0969c502002-10-21 02:08:03 +0000877 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000878 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
879 }
880}
881
882
883// markGlobalsAlive - Mark global nodes and cast nodes alive if they
884// can reach any other live node. Since this can produce new live nodes,
885// we use a simple iterative algorithm.
886//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000887static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000888 bool FilterCalls) {
889 // Add global and cast nodes to a set so we don't walk all nodes every time
890 std::set<DSNode*> GlobalNodes;
891 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000892 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000893 GlobalNodes.insert(G.getNodes()[i]);
894
895 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000896 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000897 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000898 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
899 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
900 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
901 GlobalNodes.insert(N);
902 if (DSNode *N = Calls[i].getRetVal().getNode())
903 GlobalNodes.insert(N);
904 if (DSNode *N = Calls[i].getCallee().getNode())
905 GlobalNodes.insert(N);
906 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000907 }
908
909 // Iterate and recurse until no new live node are discovered.
910 // This would be a simple iterative loop if function calls were real nodes!
911 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
912
Chris Lattnerc875f022002-11-03 21:27:48 +0000913 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000914 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000915 for( ; I != E; ++I)
916 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000917 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000918
919 // Delete dead function calls
920 if (FilterCalls)
921 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
922 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000923 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
924 CallIsDead && j != ej; ++j)
925 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000926 if (CallIsDead)
927 Calls.erase(Calls.begin() + i); // remove the call entirely
928 }
929}
Chris Lattnere2219762002-07-18 18:22:40 +0000930
931// removeDeadNodes - Use a more powerful reachability analysis to eliminate
932// subgraphs that are unreachable. This often occurs because the data
933// structure doesn't "escape" into it's caller, and thus should be eliminated
934// from the caller's graph entirely. This is only appropriate to use when
935// inlining graphs.
936//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000937void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
Chris Lattner33312f72002-11-08 01:21:07 +0000938 assert((!KeepAllGlobals || KeepCalls) && // FIXME: This should be an enum!
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000939 "KeepAllGlobals without KeepCalls is meaningless");
940
Chris Lattnere2219762002-07-18 18:22:40 +0000941 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000942 removeTriviallyDeadNodes(KeepAllGlobals);
943
Chris Lattnere2219762002-07-18 18:22:40 +0000944 // FIXME: Merge nontrivially identical call nodes...
945
946 // Alive - a set that holds all nodes found to be reachable/alive.
947 std::set<DSNode*> Alive;
948
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000949 // If KeepCalls, mark all nodes reachable by call nodes as alive...
950 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000951 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
952 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
953 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
954 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
955 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
956 }
Chris Lattnere2219762002-07-18 18:22:40 +0000957
Chris Lattner92673292002-11-02 00:13:20 +0000958 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000959 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
960 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000961 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000962
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000963 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000964 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000965
966 // Mark all globals or cast nodes that can reach a live node as alive.
967 // This also marks all nodes reachable from such nodes as alive.
968 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner33312f72002-11-08 01:21:07 +0000969
Chris Lattner0969c502002-10-21 02:08:03 +0000970 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000971 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000972
Chris Lattnere2219762002-07-18 18:22:40 +0000973 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000974 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000975 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
976 for (unsigned i = 0; i != Nodes.size(); ++i)
977 if (!Alive.count(Nodes[i])) {
978 DSNode *N = Nodes[i];
979 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
980 DeadNodes.push_back(N); // Add node to our list of dead nodes
981 N->dropAllReferences(); // Drop all outgoing edges
982 }
983
Chris Lattnere2219762002-07-18 18:22:40 +0000984 // Delete all dead nodes...
985 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
986}
987
988
989
Chris Lattner0d9bab82002-07-18 00:12:30 +0000990// maskNodeTypes - Apply a mask to all of the node types in the graph. This
991// is useful for clearing out markers like Scalar or Incomplete.
992//
993void DSGraph::maskNodeTypes(unsigned char Mask) {
994 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
995 Nodes[i]->NodeType &= Mask;
996}
997
998
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000999#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001000//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001001// GlobalDSGraph Implementation
1002//===----------------------------------------------------------------------===//
1003
1004GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1005}
1006
1007GlobalDSGraph::~GlobalDSGraph() {
1008 assert(Referrers.size() == 0 &&
1009 "Deleting global graph while references from other graphs exist");
1010}
1011
1012void GlobalDSGraph::addReference(const DSGraph* referrer) {
1013 if (referrer != this)
1014 Referrers.insert(referrer);
1015}
1016
1017void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1018 if (referrer != this) {
1019 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1020 Referrers.erase(referrer);
1021 if (Referrers.size() == 0)
1022 delete this;
1023 }
1024}
1025
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001026#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001027// Bits used in the next function
1028static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1029
1030
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001031// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1032// visible target links (and recursively their such links) into this graph.
1033// NodeCache maps the node being cloned to its clone in the Globals graph,
1034// in order to track cycles.
1035// GlobalsAreFinal is a flag that says whether it is safe to assume that
1036// an existing global node is complete. This is important to avoid
1037// reinserting all globals when inserting Calls to functions.
1038// This is a helper function for cloneGlobals and cloneCalls.
1039//
1040DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1041 std::map<const DSNode*, DSNode*> &NodeCache,
1042 bool GlobalsAreFinal) {
1043 if (OldNode == 0) return 0;
1044
1045 // The caller should check this is an external node. Just more efficient...
1046 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1047
1048 // If a clone has already been created for OldNode, return it.
1049 DSNode*& CacheEntry = NodeCache[OldNode];
1050 if (CacheEntry != 0)
1051 return CacheEntry;
1052
1053 // The result value...
1054 DSNode* NewNode = 0;
1055
1056 // If nodes already exist for any of the globals of OldNode,
1057 // merge all such nodes together since they are merged in OldNode.
1058 // If ValueCacheIsFinal==true, look for an existing node that has
1059 // an identical list of globals and return it if it exists.
1060 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001061 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001062 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001063 if (NewNode == 0) {
1064 NewNode = PrevNode; // first existing node found
1065 if (GlobalsAreFinal && j == 0)
1066 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1067 CacheEntry = NewNode;
1068 return NewNode;
1069 }
1070 }
1071 else if (NewNode != PrevNode) { // found another, different from prev
1072 // update ValMap *before* merging PrevNode into NewNode
1073 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001074 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001075 NewNode->mergeWith(PrevNode);
1076 }
1077 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001078 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001079 }
1080
1081 // If no existing node was found, clone the node and update the ValMap.
1082 if (NewNode == 0) {
1083 NewNode = new DSNode(*OldNode);
1084 Nodes.push_back(NewNode);
1085 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1086 NewNode->setLink(j, 0);
1087 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001088 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001089 }
1090 else
1091 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1092
1093 // Add the entry to NodeCache
1094 CacheEntry = NewNode;
1095
1096 // Rewrite the links in the new node to point into the current graph,
1097 // but only for links to external nodes. Set other links to NULL.
1098 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1099 DSNode* OldTarget = OldNode->getLink(j);
1100 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1101 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1102 if (NewNode->getLink(j))
1103 NewNode->getLink(j)->mergeWith(NewLink);
1104 else
1105 NewNode->setLink(j, NewLink);
1106 }
1107 }
1108
1109 // Remove all local markers
1110 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1111
1112 return NewNode;
1113}
1114
1115
1116// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1117// visible target links (and recursively their such links) into this graph.
1118//
1119void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1120 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001121#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001122 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1123 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1124 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001125 if (CloneCalls)
1126 GlobalsGraph->cloneCalls(Graph);
1127
1128 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001129#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001130}
1131
1132
1133// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1134// links (and recursively their such links) into this graph.
1135//
1136void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1137 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001138 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001139
1140 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1141
1142 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001143 DSCallSite& callCopy = FunctionCalls.back();
1144 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001145 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001146 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001147 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1148 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1149 : 0);
1150 }
1151
1152 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001153 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001154}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001155#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001156
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001157#endif