blob: ff2a4b8e0a3ddfe89e415981e1fe3d7b4c81c7ab [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 {
20 Statistic<> NumFolds("dsnode", "Number of nodes completely folded");
21};
22
Chris Lattnerb1060432002-11-07 05:20:53 +000023namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000024 extern TargetData TD;
25}
Chris Lattnerb1060432002-11-07 05:20:53 +000026using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000027
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 Lattner08db7192002-11-06 06:20:27 +000032DSNode::DSNode(enum NodeTy NT, const Type *T)
33 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000034 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000035 if (T) mergeTypeInfo(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000036}
37
Chris Lattner0d9bab82002-07-18 00:12:30 +000038// DSNode copy constructor... do not copy over the referrers list!
39DSNode::DSNode(const DSNode &N)
Chris Lattner08db7192002-11-06 06:20:27 +000040 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
41 NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000042}
43
Chris Lattnerc68c31b2002-07-10 22:38:08 +000044void DSNode::removeReferrer(DSNodeHandle *H) {
45 // Search backwards, because we depopulate the list from the back for
46 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000047 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000048 std::find(Referrers.rbegin(), Referrers.rend(), H);
49 assert(I != Referrers.rend() && "Referrer not pointing to node!");
50 Referrers.erase(I.base()-1);
51}
52
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000053// addGlobal - Add an entry for a global value to the Globals list. This also
54// marks the node with the 'G' flag if it does not already have it.
55//
56void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000057 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000058 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000059 std::lower_bound(Globals.begin(), Globals.end(), GV);
60
61 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000062 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000063 Globals.insert(I, GV);
64 NodeType |= GlobalNode;
65 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000066}
67
Chris Lattner8f0a16e2002-10-31 05:45:02 +000068/// foldNodeCompletely - If we determine that this node has some funny
69/// behavior happening to it that we cannot represent, we fold it down to a
70/// single, completely pessimistic, node. This node is represented as a
71/// single byte with a single TypeEntry of "void".
72///
73void DSNode::foldNodeCompletely() {
Chris Lattner08db7192002-11-06 06:20:27 +000074 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000075
Chris Lattner08db7192002-11-06 06:20:27 +000076 ++NumFolds;
77
78 // We are no longer typed at all...
79 Ty = DSTypeRec(Type::VoidTy, true);
80 Size = 1;
81
82 // Loop over all of our referrers, making them point to our zero bytes of
83 // space.
Chris Lattner8f0a16e2002-10-31 05:45:02 +000084 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
85 I != E; ++I)
86 (*I)->setOffset(0);
87
Chris Lattner8f0a16e2002-10-31 05:45:02 +000088 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000089 for (unsigned i = 1, e = Links.size(); i < e; ++i)
90 Links[0].mergeWith(Links[i]);
91 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000092}
Chris Lattner8f0a16e2002-10-31 05:45:02 +000093/// isNodeCompletelyFolded - Return true if this node has been completely
94/// folded down to something that can never be expanded, effectively losing
95/// all of the field sensitivity that may be present in the node.
96///
97bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner08db7192002-11-06 06:20:27 +000098 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000099}
100
101
Chris Lattner08db7192002-11-06 06:20:27 +0000102/// mergeTypeInfo - This method merges the specified type into the current node
103/// at the specified offset. This may update the current node's type record if
104/// this gives more information to the node, it may do nothing to the node if
105/// this information is already known, or it may merge the node completely (and
106/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000107///
Chris Lattner08db7192002-11-06 06:20:27 +0000108/// This method returns true if the node is completely folded, otherwise false.
109///
110bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
111 // Check to make sure the Size member is up-to-date. Size can be one of the
112 // following:
113 // Size = 0, Ty = Void: Nothing is known about this node.
114 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
115 // Size = 1, Ty = Void, Array = 1: The node is collapsed
116 // Otherwise, sizeof(Ty) = Size
117 //
118 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
119 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
120 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
121 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
122 (TD.getTypeSize(Ty.Ty) == Size)) &&
123 "Size member of DSNode doesn't match the type structure!");
124 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000125
Chris Lattner08db7192002-11-06 06:20:27 +0000126 if (Offset == 0 && NewTy == Ty.Ty)
127 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000128
Chris Lattner08db7192002-11-06 06:20:27 +0000129 // Return true immediately if the node is completely folded.
130 if (isNodeCompletelyFolded()) return true;
131
132 // Figure out how big the new type we're merging in is...
133 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
134
135 // Otherwise check to see if we can fold this type into the current node. If
136 // we can't, we fold the node completely, if we can, we potentially update our
137 // internal state.
138 //
139 if (Ty.Ty == Type::VoidTy) {
140 // If this is the first type that this node has seen, just accept it without
141 // question....
142 assert(Offset == 0 && "Cannot have an offset into a void node!");
143 assert(Ty.isArray == false && "This shouldn't happen!");
144 Ty.Ty = NewTy;
145 Size = NewTySize;
146
147 // Calculate the number of outgoing links from this node.
148 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
149 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000150 }
Chris Lattner08db7192002-11-06 06:20:27 +0000151
152 // Handle node expansion case here...
153 if (Offset+NewTySize > Size) {
154 // It is illegal to grow this node if we have treated it as an array of
155 // objects...
156 if (Ty.isArray) {
157 foldNodeCompletely();
158 return true;
159 }
160
161 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000162 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
163 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000164 foldNodeCompletely();
165 return true;
166 }
167
168 // Okay, the situation is nice and simple, we are trying to merge a type in
169 // at offset 0 that is bigger than our current type. Implement this by
170 // switching to the new type and then merge in the smaller one, which should
171 // hit the other code path here. If the other code path decides it's not
172 // ok, it will collapse the node as appropriate.
173 //
174 const Type *OldTy = Ty.Ty;
175 Ty.Ty = NewTy;
176 Size = NewTySize;
177
178 // Must grow links to be the appropriate size...
179 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
180
181 // Merge in the old type now... which is guaranteed to be smaller than the
182 // "current" type.
183 return mergeTypeInfo(OldTy, 0);
184 }
185
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000186 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000187 "Cannot merge something into a part of our type that doesn't exist!");
188
189 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
190 // type that starts at offset Offset.
191 //
192 unsigned O = 0;
193 const Type *SubType = Ty.Ty;
194 while (O < Offset) {
195 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
196
197 switch (SubType->getPrimitiveID()) {
198 case Type::StructTyID: {
199 const StructType *STy = cast<StructType>(SubType);
200 const StructLayout &SL = *TD.getStructLayout(STy);
201
202 unsigned i = 0, e = SL.MemberOffsets.size();
203 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
204 /* empty */;
205
206 // The offset we are looking for must be in the i'th element...
207 SubType = STy->getElementTypes()[i];
208 O += SL.MemberOffsets[i];
209 break;
210 }
211 case Type::ArrayTyID: {
212 SubType = cast<ArrayType>(SubType)->getElementType();
213 unsigned ElSize = TD.getTypeSize(SubType);
214 unsigned Remainder = (Offset-O) % ElSize;
215 O = Offset-Remainder;
216 break;
217 }
218 default:
219 assert(0 && "Unknown type!");
220 }
221 }
222
223 assert(O == Offset && "Could not achieve the correct offset!");
224
225 // If we found our type exactly, early exit
226 if (SubType == NewTy) return false;
227
228 // Okay, so we found the leader type at the offset requested. Search the list
229 // of types that starts at this offset. If SubType is currently an array or
230 // structure, the type desired may actually be the first element of the
231 // composite type...
232 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000233 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000234 while (SubType != NewTy) {
235 const Type *NextSubType = 0;
236 unsigned NextSubTypeSize;
237 switch (SubType->getPrimitiveID()) {
238 case Type::StructTyID:
239 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
240 NextSubTypeSize = TD.getTypeSize(SubType);
241 break;
242 case Type::ArrayTyID:
243 NextSubType = cast<ArrayType>(SubType)->getElementType();
244 NextSubTypeSize = TD.getTypeSize(SubType);
245 break;
246 default: ;
247 // fall out
248 }
249
250 if (NextSubType == 0)
251 break; // In the default case, break out of the loop
252
253 if (NextSubTypeSize < NewTySize)
254 break; // Don't allow shrinking to a smaller type than NewTySize
255 SubType = NextSubType;
256 SubTypeSize = NextSubTypeSize;
257 }
258
259 // If we found the type exactly, return it...
260 if (SubType == NewTy)
261 return false;
262
263 // Check to see if we have a compatible, but different type...
264 if (NewTySize == SubTypeSize) {
265 // Check to see if this type is obviously convertable... int -> uint f.e.
266 if (NewTy->isLosslesslyConvertableTo(SubType))
267 return false;
268
269 // Check to see if we have a pointer & integer mismatch going on here,
270 // loading a pointer as a long, for example.
271 //
272 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
273 NewTy->isInteger() && isa<PointerType>(SubType))
274 return false;
275
276 }
277
278
Chris Lattner3c87b292002-11-07 01:54:56 +0000279 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
280 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
281 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000282
283 foldNodeCompletely();
284 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000285}
286
Chris Lattner08db7192002-11-06 06:20:27 +0000287
288
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000289// addEdgeTo - Add an edge from the current node to the specified node. This
290// can cause merging of nodes in the graph.
291//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000292void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000293 if (NH.getNode() == 0) return; // Nothing to do
294
Chris Lattner08db7192002-11-06 06:20:27 +0000295 DSNodeHandle &ExistingEdge = getLink(Offset);
296 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000297 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000298 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000299 } else { // No merging to perform...
300 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000301 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000302}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000303
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000304
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000305// MergeSortedVectors - Efficiently merge a vector into another vector where
306// duplicates are not allowed and both are sorted. This assumes that 'T's are
307// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000308//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000309template<typename T>
310void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
311 // By far, the most common cases will be the simple ones. In these cases,
312 // avoid having to allocate a temporary vector...
313 //
314 if (Src.empty()) { // Nothing to merge in...
315 return;
316 } else if (Dest.empty()) { // Just copy the result in...
317 Dest = Src;
318 } else if (Src.size() == 1) { // Insert a single element...
319 const T &V = Src[0];
320 typename vector<T>::iterator I =
321 std::lower_bound(Dest.begin(), Dest.end(), V);
322 if (I == Dest.end() || *I != Src[0]) // If not already contained...
323 Dest.insert(I, Src[0]);
324 } else if (Dest.size() == 1) {
325 T Tmp = Dest[0]; // Save value in temporary...
326 Dest = Src; // Copy over list...
327 typename vector<T>::iterator I =
328 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
329 if (I == Dest.end() || *I != Src[0]) // If not already contained...
330 Dest.insert(I, Src[0]);
331
332 } else {
333 // Make a copy to the side of Dest...
334 vector<T> Old(Dest);
335
336 // Make space for all of the type entries now...
337 Dest.resize(Dest.size()+Src.size());
338
339 // Merge the two sorted ranges together... into Dest.
340 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
341
342 // Now erase any duplicate entries that may have accumulated into the
343 // vectors (because they were in both of the input sets)
344 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
345 }
346}
347
348
349// mergeWith - Merge this node and the specified node, moving all links to and
350// from the argument node into the current node, deleting the node argument.
351// Offset indicates what offset the specified node is to be merged into the
352// current node.
353//
354// The specified node may be a null pointer (in which case, nothing happens).
355//
356void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
357 DSNode *N = NH.getNode();
358 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000359 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000360
Chris Lattner02606632002-11-04 06:48:26 +0000361 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000362 // We cannot merge two pieces of the same node together, collapse the node
363 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000364 DEBUG(std::cerr << "Attempting to merge two chunks of"
365 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000366 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000367 return;
368 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000369
Chris Lattner08db7192002-11-06 06:20:27 +0000370 // Merge the type entries of the two nodes together...
371 if (N->Ty.Ty != Type::VoidTy)
372 mergeTypeInfo(N->Ty.Ty, Offset);
373
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000374 // If we are merging a node with a completely folded node, then both nodes are
375 // now completely folded.
376 //
377 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000378 if (!N->isNodeCompletelyFolded())
379 N->foldNodeCompletely();
380 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000381 foldNodeCompletely();
382 Offset = 0;
383 }
Chris Lattner02606632002-11-04 06:48:26 +0000384 N = NH.getNode();
385
Chris Lattner2c0bd012002-11-06 18:01:39 +0000386 if (this == N || N == 0) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000387
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000388 // If both nodes are not at offset 0, make sure that we are merging the node
389 // at an later offset into the node with the zero offset.
390 //
391 if (Offset > NH.getOffset()) {
392 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
393 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000394 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
395 // If the offsets are the same, merge the smaller node into the bigger node
396 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
397 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000398 }
399
400#if 0
401 std::cerr << "\n\nMerging:\n";
402 N->print(std::cerr, 0);
403 std::cerr << " and:\n";
404 print(std::cerr, 0);
405#endif
406
407 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
408 // respect to NH.Offset) is now zero.
409 //
410 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000411 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000412
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000413 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000414 // Make sure to adjust their offset, not just the node pointer.
415 //
416 while (!N->Referrers.empty()) {
417 DSNodeHandle &Ref = *N->Referrers.back();
418 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
419 }
Chris Lattner59535132002-11-05 00:01:58 +0000420
421 // Make all of the outgoing links of N now be outgoing links of this. This
422 // can cause recursive merging!
423 //
Chris Lattner08db7192002-11-06 06:20:27 +0000424 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
425 DSNodeHandle &Link = N->getLink(i);
426 if (Link.getNode()) {
427 addEdgeTo((i+NOffset) % getSize(), Link);
Chris Lattner59535132002-11-05 00:01:58 +0000428
Chris Lattner08db7192002-11-06 06:20:27 +0000429 // It's possible that after adding the new edge that some recursive
430 // merging just occured, causing THIS node to get merged into oblivion.
431 // If that happens, we must not try to merge any more edges into it!
Chris Lattner7b7200c2002-10-02 04:57:39 +0000432 //
Chris Lattner08db7192002-11-06 06:20:27 +0000433 if (Size == 0) return;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000434 }
435 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000436
437 // Now that there are no outgoing edges, all of the Links are dead.
438 N->Links.clear();
Chris Lattner08db7192002-11-06 06:20:27 +0000439 N->Size = 0;
440 N->Ty.Ty = Type::VoidTy;
441 N->Ty.isArray = false;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000442
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000443 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000444 NodeType |= N->NodeType;
445 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000446
447 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000448 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000449 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000450
451 // Delete the globals from the old node...
452 N->Globals.clear();
453 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000454}
455
Chris Lattner9de906c2002-10-20 22:11:44 +0000456//===----------------------------------------------------------------------===//
457// DSCallSite Implementation
458//===----------------------------------------------------------------------===//
459
Vikram S. Adve26b98262002-10-20 21:41:02 +0000460// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000461Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000462 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000463}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000464
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000465
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000466//===----------------------------------------------------------------------===//
467// DSGraph Implementation
468//===----------------------------------------------------------------------===//
469
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000470DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
471 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000472 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000473}
474
Chris Lattnereff0da92002-10-21 15:32:34 +0000475DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
476 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000477 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000478}
479
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000480DSGraph::~DSGraph() {
481 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000482 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000483 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000484
485#ifndef NDEBUG
486 // Drop all intra-node references, so that assertions don't fail...
487 std::for_each(Nodes.begin(), Nodes.end(),
488 std::mem_fun(&DSNode::dropAllReferences));
489#endif
490
491 // Delete all of the nodes themselves...
492 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
493}
494
Chris Lattner0d9bab82002-07-18 00:12:30 +0000495// dump - Allow inspection of graph in a debugger.
496void DSGraph::dump() const { print(std::cerr); }
497
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000498
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000499// Helper function used to clone a function list.
500//
501static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
502 vector<DSCallSite> &toCalls,
503 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000504 unsigned FC = toCalls.size(); // FirstCall
505 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000506 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000507 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000508}
509
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000510/// remapLinks - Change all of the Links in the current node according to the
511/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000512///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000513void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
514 for (unsigned i = 0, e = Links.size(); i != e; ++i)
515 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
516}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000517
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000518
Chris Lattner0d9bab82002-07-18 00:12:30 +0000519// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000520// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000521// filled into the OldValMap member. If StripAllocas is set to true, Alloca
522// markers are removed from the graph, as the graph is being cloned into a
523// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000524//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000525DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
526 std::map<Value*, DSNodeHandle> &OldValMap,
527 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner92673292002-11-02 00:13:20 +0000528 bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000529 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000530
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000531 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000532
533 // Duplicate all of the nodes, populating the node map...
534 Nodes.reserve(FN+G.Nodes.size());
535 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000536 DSNode *Old = G.Nodes[i];
537 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000538 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000539 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000540 }
541
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000542 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000543 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000544 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000545
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000546 // Remove local markers as specified
Chris Lattner92673292002-11-02 00:13:20 +0000547 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000548 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000549 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000550 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000551
Chris Lattnercf15db32002-10-17 20:09:52 +0000552 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000553 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
554 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000555 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000556 H.setNode(OldNodeMap[I->second.getNode()]);
557 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000558
559 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000560 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
561 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000562 GVI->second.mergeWith(H);
563 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000564 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000565 }
566 }
567 }
Chris Lattnere2219762002-07-18 18:22:40 +0000568 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000569 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000570
Chris Lattnercf15db32002-10-17 20:09:52 +0000571
Chris Lattner0d9bab82002-07-18 00:12:30 +0000572 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000574}
575
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000576#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000577// cloneGlobalInto - Clone the given global node and all its target links
578// (and all their llinks, recursively).
579//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000580DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000581 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
582
583 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000584 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000585 if (ValMapEntry != 0)
586 return ValMapEntry;
587
588 // Clone the node and update the ValMap.
589 DSNode* NewNode = new DSNode(*GNode);
590 ValMapEntry = NewNode; // j=0 case of loop below!
591 Nodes.push_back(NewNode);
592 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000593 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000594
595 // Rewrite the links in the new node to point into the current graph.
596 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
597 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
598
599 return NewNode;
600}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000601#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000602
603
Chris Lattner0d9bab82002-07-18 00:12:30 +0000604// markIncompleteNodes - Mark the specified node as having contents that are not
605// known with the current analysis we have performed. Because a node makes all
606// of the nodes it can reach imcomplete if the node itself is incomplete, we
607// must recursively traverse the data structure graph, marking all reachable
608// nodes as incomplete.
609//
610static void markIncompleteNode(DSNode *N) {
611 // Stop recursion if no node, or if node already marked...
612 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
613
614 // Actually mark the node
615 N->NodeType |= DSNode::Incomplete;
616
617 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000618 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
619 if (DSNode *DSN = N->getLink(i).getNode())
620 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000621}
622
623
624// markIncompleteNodes - Traverse the graph, identifying nodes that may be
625// modified by other functions that have not been resolved yet. This marks
626// nodes that are reachable through three sources of "unknownness":
627//
628// Global Variables, Function Calls, and Incoming Arguments
629//
630// For any node that may have unknown components (because something outside the
631// scope of current analysis may have modified it), the 'Incomplete' flag is
632// added to the NodeType.
633//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000634void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000635 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000636 if (markFormalArgs && Func)
637 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000638 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
639 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000640
641 // Mark stuff passed into functions calls as being incomplete...
642 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000643 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000644 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000645 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000646
Chris Lattner92673292002-11-02 00:13:20 +0000647 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000648 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000649 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000650 }
651
Chris Lattner92673292002-11-02 00:13:20 +0000652 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000653 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000654 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000655 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000656 // FIXME: Make more efficient by looking over Links directly
Chris Lattner08db7192002-11-06 06:20:27 +0000657 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
658 if (DSNode *DSN = N->getLink(i).getNode())
659 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000660 }
661}
662
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000663// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000664// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000665static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000666 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000667 while (!N->getGlobals().empty()) {
668 GlobalValue *GV = N->getGlobals().back();
669 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000670 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000671 }
672}
673
674
Chris Lattner0d9bab82002-07-18 00:12:30 +0000675// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
676// checks to see if there are simple transformations that it can do to make it
677// dead.
678//
679bool DSGraph::isNodeDead(DSNode *N) {
680 // Is it a trivially dead shadow node...
681 if (N->getReferrers().empty() && N->NodeType == 0)
682 return true;
683
684 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000685 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000686 N->getReferrers().size() == N->getGlobals().size()) {
687
Chris Lattnerc875f022002-11-03 21:27:48 +0000688 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000689 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000690 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000691 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
692 return true;
693 }
694
695 return false;
696}
697
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000698static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000699 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000700 // Remove trivially identical function calls
701 unsigned NumFns = Calls.size();
702 std::sort(Calls.begin(), Calls.end());
703 Calls.erase(std::unique(Calls.begin(), Calls.end()),
704 Calls.end());
705
706 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000707 std::cerr << "Merged " << (NumFns-Calls.size())
708 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000709}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000710
Chris Lattnere2219762002-07-18 18:22:40 +0000711// removeTriviallyDeadNodes - After the graph has been constructed, this method
712// removes all unreachable nodes that are created because they got merged with
713// other nodes in the graph. These nodes will all be trivially unreachable, so
714// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000715//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000716void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000717 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000718 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000719 if (isNodeDead(Nodes[i])) { // This node is dead!
720 delete Nodes[i]; // Free memory...
721 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
722 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000723
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000724 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000725}
726
727
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000728// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000729// stuff to be alive.
730//
731static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000732 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000733
734 Alive.insert(N);
Chris Lattner08db7192002-11-06 06:20:27 +0000735 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
736 if (DSNode *DSN = N->getLink(i).getNode())
737 if (!Alive.count(DSN))
738 markAlive(DSN, Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000739}
740
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000741static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
742 std::set<DSNode*> &Visiting) {
743 if (N == 0) return false;
744
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000745 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000746 Visiting.insert(N);
747
748 // If any immediate successor is alive, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000749 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
750 if (DSNode *DSN = N->getLink(i).getNode())
751 if (Alive.count(DSN)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000752 Visiting.erase(N);
753 return true;
754 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000755
756 // Else if any successor reaches a live node, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000757 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
758 if (DSNode *DSN = N->getLink(i).getNode())
759 if (checkGlobalAlive(DSN, Alive, Visiting)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000760 Visiting.erase(N); return true;
761 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000762
763 Visiting.erase(N);
764 return false;
765}
766
767
768// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
769// This would be unnecessary if function calls were real nodes! In that case,
770// the simple iterative loop in the first few lines below suffice.
771//
772static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000773 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000774 std::set<DSNode*> &Alive,
775 bool FilterCalls) {
776
777 // Iterate, marking globals or cast nodes alive until no new live nodes
778 // are added to Alive
779 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000780 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000781 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
782 liveCount = Alive.size();
783 for ( ; I != E; ++I)
784 if (Alive.count(*I) == 0) {
785 Visiting.clear();
786 if (checkGlobalAlive(*I, Alive, Visiting))
787 markAlive(*I, Alive);
788 }
789 }
790
791 // Find function calls with some dead and some live nodes.
792 // Since all call nodes must be live if any one is live, we have to mark
793 // all nodes of the call as live and continue the iteration (via recursion).
794 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000795 bool Recurse = false;
796 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000797 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000798 DSCallSite &CS = Calls[i];
799 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
800 if (DSNode *N = CS.getPtrArg(j).getNode()) {
801 bool ArgIsDead = !Alive.count(N);
802 CallHasDeadArg |= ArgIsDead;
803 CallIsDead &= ArgIsDead;
804 }
805
806 if (DSNode *N = CS.getRetVal().getNode()) {
807 bool RetIsDead = !Alive.count(N);
808 CallHasDeadArg |= RetIsDead;
809 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000810 }
Chris Lattner0969c502002-10-21 02:08:03 +0000811
812 DSNode *N = CS.getCallee().getNode();
813 bool FnIsDead = !Alive.count(N);
814 CallHasDeadArg |= FnIsDead;
815 CallIsDead &= FnIsDead;
816
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000817 if (!CallIsDead && CallHasDeadArg) {
818 // Some node in this call is live and another is dead.
819 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000820 Recurse = true;
821 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
822 markAlive(CS.getPtrArg(j).getNode(), Alive);
823 markAlive(CS.getRetVal().getNode(), Alive);
824 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000825 }
826 }
Chris Lattner0969c502002-10-21 02:08:03 +0000827 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000828 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
829 }
830}
831
832
833// markGlobalsAlive - Mark global nodes and cast nodes alive if they
834// can reach any other live node. Since this can produce new live nodes,
835// we use a simple iterative algorithm.
836//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000837static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000838 bool FilterCalls) {
839 // Add global and cast nodes to a set so we don't walk all nodes every time
840 std::set<DSNode*> GlobalNodes;
841 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000842 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000843 GlobalNodes.insert(G.getNodes()[i]);
844
845 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000846 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000847 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000848 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
849 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
850 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
851 GlobalNodes.insert(N);
852 if (DSNode *N = Calls[i].getRetVal().getNode())
853 GlobalNodes.insert(N);
854 if (DSNode *N = Calls[i].getCallee().getNode())
855 GlobalNodes.insert(N);
856 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000857 }
858
859 // Iterate and recurse until no new live node are discovered.
860 // This would be a simple iterative loop if function calls were real nodes!
861 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
862
Chris Lattnerc875f022002-11-03 21:27:48 +0000863 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000864 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000865 for( ; I != E; ++I)
866 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000867 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000868
869 // Delete dead function calls
870 if (FilterCalls)
871 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
872 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000873 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
874 CallIsDead && j != ej; ++j)
875 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000876 if (CallIsDead)
877 Calls.erase(Calls.begin() + i); // remove the call entirely
878 }
879}
Chris Lattnere2219762002-07-18 18:22:40 +0000880
881// removeDeadNodes - Use a more powerful reachability analysis to eliminate
882// subgraphs that are unreachable. This often occurs because the data
883// structure doesn't "escape" into it's caller, and thus should be eliminated
884// from the caller's graph entirely. This is only appropriate to use when
885// inlining graphs.
886//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000887void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
888 assert((!KeepAllGlobals || KeepCalls) &&
889 "KeepAllGlobals without KeepCalls is meaningless");
890
Chris Lattnere2219762002-07-18 18:22:40 +0000891 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000892 removeTriviallyDeadNodes(KeepAllGlobals);
893
Chris Lattnere2219762002-07-18 18:22:40 +0000894 // FIXME: Merge nontrivially identical call nodes...
895
896 // Alive - a set that holds all nodes found to be reachable/alive.
897 std::set<DSNode*> Alive;
898
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000899 // If KeepCalls, mark all nodes reachable by call nodes as alive...
900 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000901 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
902 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
903 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
904 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
905 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
906 }
Chris Lattnere2219762002-07-18 18:22:40 +0000907
Chris Lattner92673292002-11-02 00:13:20 +0000908 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000909 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
910 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000911 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000912
Chris Lattner92673292002-11-02 00:13:20 +0000913#if 0
914 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
Chris Lattnerc875f022002-11-03 21:27:48 +0000915 // the ScalarMap?
Chris Lattner92673292002-11-02 00:13:20 +0000916 //
917 if (KeepAllGlobals)
918 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
919 if (Nodes[i]->NodeType & DSNode::GlobalNode)
920 markAlive(Nodes[i], Alive);
921#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000922
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000923 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000924 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000925
926 // Mark all globals or cast nodes that can reach a live node as alive.
927 // This also marks all nodes reachable from such nodes as alive.
928 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000929 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000930 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000931
Chris Lattnere2219762002-07-18 18:22:40 +0000932 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000933 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000934 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
935 for (unsigned i = 0; i != Nodes.size(); ++i)
936 if (!Alive.count(Nodes[i])) {
937 DSNode *N = Nodes[i];
938 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
939 DeadNodes.push_back(N); // Add node to our list of dead nodes
940 N->dropAllReferences(); // Drop all outgoing edges
941 }
942
Chris Lattnere2219762002-07-18 18:22:40 +0000943 // Delete all dead nodes...
944 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
945}
946
947
948
Chris Lattner0d9bab82002-07-18 00:12:30 +0000949// maskNodeTypes - Apply a mask to all of the node types in the graph. This
950// is useful for clearing out markers like Scalar or Incomplete.
951//
952void DSGraph::maskNodeTypes(unsigned char Mask) {
953 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
954 Nodes[i]->NodeType &= Mask;
955}
956
957
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000958#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000959//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000960// GlobalDSGraph Implementation
961//===----------------------------------------------------------------------===//
962
963GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
964}
965
966GlobalDSGraph::~GlobalDSGraph() {
967 assert(Referrers.size() == 0 &&
968 "Deleting global graph while references from other graphs exist");
969}
970
971void GlobalDSGraph::addReference(const DSGraph* referrer) {
972 if (referrer != this)
973 Referrers.insert(referrer);
974}
975
976void GlobalDSGraph::removeReference(const DSGraph* referrer) {
977 if (referrer != this) {
978 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
979 Referrers.erase(referrer);
980 if (Referrers.size() == 0)
981 delete this;
982 }
983}
984
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000985#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +0000986// Bits used in the next function
987static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
988
989
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000990// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
991// visible target links (and recursively their such links) into this graph.
992// NodeCache maps the node being cloned to its clone in the Globals graph,
993// in order to track cycles.
994// GlobalsAreFinal is a flag that says whether it is safe to assume that
995// an existing global node is complete. This is important to avoid
996// reinserting all globals when inserting Calls to functions.
997// This is a helper function for cloneGlobals and cloneCalls.
998//
999DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1000 std::map<const DSNode*, DSNode*> &NodeCache,
1001 bool GlobalsAreFinal) {
1002 if (OldNode == 0) return 0;
1003
1004 // The caller should check this is an external node. Just more efficient...
1005 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1006
1007 // If a clone has already been created for OldNode, return it.
1008 DSNode*& CacheEntry = NodeCache[OldNode];
1009 if (CacheEntry != 0)
1010 return CacheEntry;
1011
1012 // The result value...
1013 DSNode* NewNode = 0;
1014
1015 // If nodes already exist for any of the globals of OldNode,
1016 // merge all such nodes together since they are merged in OldNode.
1017 // If ValueCacheIsFinal==true, look for an existing node that has
1018 // an identical list of globals and return it if it exists.
1019 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001020 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001021 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001022 if (NewNode == 0) {
1023 NewNode = PrevNode; // first existing node found
1024 if (GlobalsAreFinal && j == 0)
1025 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1026 CacheEntry = NewNode;
1027 return NewNode;
1028 }
1029 }
1030 else if (NewNode != PrevNode) { // found another, different from prev
1031 // update ValMap *before* merging PrevNode into NewNode
1032 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001033 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001034 NewNode->mergeWith(PrevNode);
1035 }
1036 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001037 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001038 }
1039
1040 // If no existing node was found, clone the node and update the ValMap.
1041 if (NewNode == 0) {
1042 NewNode = new DSNode(*OldNode);
1043 Nodes.push_back(NewNode);
1044 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1045 NewNode->setLink(j, 0);
1046 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001047 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001048 }
1049 else
1050 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1051
1052 // Add the entry to NodeCache
1053 CacheEntry = NewNode;
1054
1055 // Rewrite the links in the new node to point into the current graph,
1056 // but only for links to external nodes. Set other links to NULL.
1057 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1058 DSNode* OldTarget = OldNode->getLink(j);
1059 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1060 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1061 if (NewNode->getLink(j))
1062 NewNode->getLink(j)->mergeWith(NewLink);
1063 else
1064 NewNode->setLink(j, NewLink);
1065 }
1066 }
1067
1068 // Remove all local markers
1069 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1070
1071 return NewNode;
1072}
1073
1074
1075// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1076// visible target links (and recursively their such links) into this graph.
1077//
1078void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1079 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001080#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001081 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1082 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1083 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001084 if (CloneCalls)
1085 GlobalsGraph->cloneCalls(Graph);
1086
1087 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001088#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001089}
1090
1091
1092// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1093// links (and recursively their such links) into this graph.
1094//
1095void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1096 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001097 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001098
1099 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1100
1101 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001102 DSCallSite& callCopy = FunctionCalls.back();
1103 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001104 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001105 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001106 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1107 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1108 : 0);
1109 }
1110
1111 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001112 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001113}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001114#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001115
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001116#endif