blob: 41cd7185ec99faa3d75f4f6fd5653745c1695503 [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 Lattner076c1f92002-11-07 06:31:54 +000093
Chris Lattner8f0a16e2002-10-31 05:45:02 +000094/// isNodeCompletelyFolded - Return true if this node has been completely
95/// folded down to something that can never be expanded, effectively losing
96/// all of the field sensitivity that may be present in the node.
97///
98bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner08db7192002-11-06 06:20:27 +000099 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000100}
101
102
Chris Lattner08db7192002-11-06 06:20:27 +0000103/// mergeTypeInfo - This method merges the specified type into the current node
104/// at the specified offset. This may update the current node's type record if
105/// this gives more information to the node, it may do nothing to the node if
106/// this information is already known, or it may merge the node completely (and
107/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000108///
Chris Lattner08db7192002-11-06 06:20:27 +0000109/// This method returns true if the node is completely folded, otherwise false.
110///
111bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
112 // Check to make sure the Size member is up-to-date. Size can be one of the
113 // following:
114 // Size = 0, Ty = Void: Nothing is known about this node.
115 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
116 // Size = 1, Ty = Void, Array = 1: The node is collapsed
117 // Otherwise, sizeof(Ty) = Size
118 //
119 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
120 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
121 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
122 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
123 (TD.getTypeSize(Ty.Ty) == Size)) &&
124 "Size member of DSNode doesn't match the type structure!");
125 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000126
Chris Lattner08db7192002-11-06 06:20:27 +0000127 if (Offset == 0 && NewTy == Ty.Ty)
128 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000129
Chris Lattner08db7192002-11-06 06:20:27 +0000130 // Return true immediately if the node is completely folded.
131 if (isNodeCompletelyFolded()) return true;
132
133 // Figure out how big the new type we're merging in is...
134 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
135
136 // Otherwise check to see if we can fold this type into the current node. If
137 // we can't, we fold the node completely, if we can, we potentially update our
138 // internal state.
139 //
140 if (Ty.Ty == Type::VoidTy) {
141 // If this is the first type that this node has seen, just accept it without
142 // question....
143 assert(Offset == 0 && "Cannot have an offset into a void node!");
144 assert(Ty.isArray == false && "This shouldn't happen!");
145 Ty.Ty = NewTy;
146 Size = NewTySize;
147
148 // Calculate the number of outgoing links from this node.
149 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
150 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000151 }
Chris Lattner08db7192002-11-06 06:20:27 +0000152
153 // Handle node expansion case here...
154 if (Offset+NewTySize > Size) {
155 // It is illegal to grow this node if we have treated it as an array of
156 // objects...
157 if (Ty.isArray) {
158 foldNodeCompletely();
159 return true;
160 }
161
162 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000163 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
164 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000165 foldNodeCompletely();
166 return true;
167 }
168
169 // Okay, the situation is nice and simple, we are trying to merge a type in
170 // at offset 0 that is bigger than our current type. Implement this by
171 // switching to the new type and then merge in the smaller one, which should
172 // hit the other code path here. If the other code path decides it's not
173 // ok, it will collapse the node as appropriate.
174 //
175 const Type *OldTy = Ty.Ty;
176 Ty.Ty = NewTy;
177 Size = NewTySize;
178
179 // Must grow links to be the appropriate size...
180 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
181
182 // Merge in the old type now... which is guaranteed to be smaller than the
183 // "current" type.
184 return mergeTypeInfo(OldTy, 0);
185 }
186
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000187 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000188 "Cannot merge something into a part of our type that doesn't exist!");
189
190 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
191 // type that starts at offset Offset.
192 //
193 unsigned O = 0;
194 const Type *SubType = Ty.Ty;
195 while (O < Offset) {
196 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
197
198 switch (SubType->getPrimitiveID()) {
199 case Type::StructTyID: {
200 const StructType *STy = cast<StructType>(SubType);
201 const StructLayout &SL = *TD.getStructLayout(STy);
202
203 unsigned i = 0, e = SL.MemberOffsets.size();
204 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
205 /* empty */;
206
207 // The offset we are looking for must be in the i'th element...
208 SubType = STy->getElementTypes()[i];
209 O += SL.MemberOffsets[i];
210 break;
211 }
212 case Type::ArrayTyID: {
213 SubType = cast<ArrayType>(SubType)->getElementType();
214 unsigned ElSize = TD.getTypeSize(SubType);
215 unsigned Remainder = (Offset-O) % ElSize;
216 O = Offset-Remainder;
217 break;
218 }
219 default:
220 assert(0 && "Unknown type!");
221 }
222 }
223
224 assert(O == Offset && "Could not achieve the correct offset!");
225
226 // If we found our type exactly, early exit
227 if (SubType == NewTy) return false;
228
229 // Okay, so we found the leader type at the offset requested. Search the list
230 // of types that starts at this offset. If SubType is currently an array or
231 // structure, the type desired may actually be the first element of the
232 // composite type...
233 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000234 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000235 while (SubType != NewTy) {
236 const Type *NextSubType = 0;
237 unsigned NextSubTypeSize;
238 switch (SubType->getPrimitiveID()) {
239 case Type::StructTyID:
240 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
241 NextSubTypeSize = TD.getTypeSize(SubType);
242 break;
243 case Type::ArrayTyID:
244 NextSubType = cast<ArrayType>(SubType)->getElementType();
245 NextSubTypeSize = TD.getTypeSize(SubType);
246 break;
247 default: ;
248 // fall out
249 }
250
251 if (NextSubType == 0)
252 break; // In the default case, break out of the loop
253
254 if (NextSubTypeSize < NewTySize)
255 break; // Don't allow shrinking to a smaller type than NewTySize
256 SubType = NextSubType;
257 SubTypeSize = NextSubTypeSize;
258 }
259
260 // If we found the type exactly, return it...
261 if (SubType == NewTy)
262 return false;
263
264 // Check to see if we have a compatible, but different type...
265 if (NewTySize == SubTypeSize) {
266 // Check to see if this type is obviously convertable... int -> uint f.e.
267 if (NewTy->isLosslesslyConvertableTo(SubType))
268 return false;
269
270 // Check to see if we have a pointer & integer mismatch going on here,
271 // loading a pointer as a long, for example.
272 //
273 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
274 NewTy->isInteger() && isa<PointerType>(SubType))
275 return false;
276
277 }
278
279
Chris Lattner3c87b292002-11-07 01:54:56 +0000280 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
281 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
282 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000283
284 foldNodeCompletely();
285 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000286}
287
Chris Lattner08db7192002-11-06 06:20:27 +0000288
289
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000290// addEdgeTo - Add an edge from the current node to the specified node. This
291// can cause merging of nodes in the graph.
292//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000293void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000294 if (NH.getNode() == 0) return; // Nothing to do
295
Chris Lattner08db7192002-11-06 06:20:27 +0000296 DSNodeHandle &ExistingEdge = getLink(Offset);
297 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000298 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000299 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000300 } else { // No merging to perform...
301 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000302 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000303}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000304
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000305
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000306// MergeSortedVectors - Efficiently merge a vector into another vector where
307// duplicates are not allowed and both are sorted. This assumes that 'T's are
308// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000309//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000310template<typename T>
311void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
312 // By far, the most common cases will be the simple ones. In these cases,
313 // avoid having to allocate a temporary vector...
314 //
315 if (Src.empty()) { // Nothing to merge in...
316 return;
317 } else if (Dest.empty()) { // Just copy the result in...
318 Dest = Src;
319 } else if (Src.size() == 1) { // Insert a single element...
320 const T &V = Src[0];
321 typename vector<T>::iterator I =
322 std::lower_bound(Dest.begin(), Dest.end(), V);
323 if (I == Dest.end() || *I != Src[0]) // If not already contained...
324 Dest.insert(I, Src[0]);
325 } else if (Dest.size() == 1) {
326 T Tmp = Dest[0]; // Save value in temporary...
327 Dest = Src; // Copy over list...
328 typename vector<T>::iterator I =
329 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
330 if (I == Dest.end() || *I != Src[0]) // If not already contained...
331 Dest.insert(I, Src[0]);
332
333 } else {
334 // Make a copy to the side of Dest...
335 vector<T> Old(Dest);
336
337 // Make space for all of the type entries now...
338 Dest.resize(Dest.size()+Src.size());
339
340 // Merge the two sorted ranges together... into Dest.
341 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
342
343 // Now erase any duplicate entries that may have accumulated into the
344 // vectors (because they were in both of the input sets)
345 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
346 }
347}
348
349
350// mergeWith - Merge this node and the specified node, moving all links to and
351// from the argument node into the current node, deleting the node argument.
352// Offset indicates what offset the specified node is to be merged into the
353// current node.
354//
355// The specified node may be a null pointer (in which case, nothing happens).
356//
357void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
358 DSNode *N = NH.getNode();
359 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000360 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000361
Chris Lattner02606632002-11-04 06:48:26 +0000362 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000363 // We cannot merge two pieces of the same node together, collapse the node
364 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000365 DEBUG(std::cerr << "Attempting to merge two chunks of"
366 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000367 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000368 return;
369 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000370
Chris Lattner08db7192002-11-06 06:20:27 +0000371 // Merge the type entries of the two nodes together...
372 if (N->Ty.Ty != Type::VoidTy)
373 mergeTypeInfo(N->Ty.Ty, Offset);
374
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000375 // If we are merging a node with a completely folded node, then both nodes are
376 // now completely folded.
377 //
378 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000379 if (!N->isNodeCompletelyFolded())
380 N->foldNodeCompletely();
381 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000382 foldNodeCompletely();
383 Offset = 0;
384 }
Chris Lattner02606632002-11-04 06:48:26 +0000385 N = NH.getNode();
386
Chris Lattner2c0bd012002-11-06 18:01:39 +0000387 if (this == N || N == 0) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000388
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000389 // If both nodes are not at offset 0, make sure that we are merging the node
390 // at an later offset into the node with the zero offset.
391 //
392 if (Offset > NH.getOffset()) {
393 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
394 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000395 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
396 // If the offsets are the same, merge the smaller node into the bigger node
397 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
398 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000399 }
400
401#if 0
402 std::cerr << "\n\nMerging:\n";
403 N->print(std::cerr, 0);
404 std::cerr << " and:\n";
405 print(std::cerr, 0);
406#endif
407
408 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
409 // respect to NH.Offset) is now zero.
410 //
411 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000412 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000413
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000414 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000415 // Make sure to adjust their offset, not just the node pointer.
416 //
417 while (!N->Referrers.empty()) {
418 DSNodeHandle &Ref = *N->Referrers.back();
419 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
420 }
Chris Lattner59535132002-11-05 00:01:58 +0000421
422 // Make all of the outgoing links of N now be outgoing links of this. This
423 // can cause recursive merging!
424 //
Chris Lattner08db7192002-11-06 06:20:27 +0000425 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
426 DSNodeHandle &Link = N->getLink(i);
427 if (Link.getNode()) {
428 addEdgeTo((i+NOffset) % getSize(), Link);
Chris Lattner59535132002-11-05 00:01:58 +0000429
Chris Lattner08db7192002-11-06 06:20:27 +0000430 // It's possible that after adding the new edge that some recursive
431 // merging just occured, causing THIS node to get merged into oblivion.
432 // If that happens, we must not try to merge any more edges into it!
Chris Lattner7b7200c2002-10-02 04:57:39 +0000433 //
Chris Lattner08db7192002-11-06 06:20:27 +0000434 if (Size == 0) return;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000435 }
436 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000437
438 // Now that there are no outgoing edges, all of the Links are dead.
439 N->Links.clear();
Chris Lattner08db7192002-11-06 06:20:27 +0000440 N->Size = 0;
441 N->Ty.Ty = Type::VoidTy;
442 N->Ty.isArray = false;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000443
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000444 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000445 NodeType |= N->NodeType;
446 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000447
448 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000449 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000450 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000451
452 // Delete the globals from the old node...
453 N->Globals.clear();
454 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000455}
456
Chris Lattner9de906c2002-10-20 22:11:44 +0000457//===----------------------------------------------------------------------===//
458// DSCallSite Implementation
459//===----------------------------------------------------------------------===//
460
Vikram S. Adve26b98262002-10-20 21:41:02 +0000461// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000462Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000463 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000464}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000465
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000466
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000467//===----------------------------------------------------------------------===//
468// DSGraph Implementation
469//===----------------------------------------------------------------------===//
470
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000471DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
472 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000473 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000474}
475
Chris Lattnereff0da92002-10-21 15:32:34 +0000476DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
477 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000478 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000479}
480
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000481DSGraph::~DSGraph() {
482 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000483 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000484 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000485
486#ifndef NDEBUG
487 // Drop all intra-node references, so that assertions don't fail...
488 std::for_each(Nodes.begin(), Nodes.end(),
489 std::mem_fun(&DSNode::dropAllReferences));
490#endif
491
492 // Delete all of the nodes themselves...
493 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
494}
495
Chris Lattner0d9bab82002-07-18 00:12:30 +0000496// dump - Allow inspection of graph in a debugger.
497void DSGraph::dump() const { print(std::cerr); }
498
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000499
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000500// Helper function used to clone a function list.
501//
502static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
503 vector<DSCallSite> &toCalls,
504 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000505 unsigned FC = toCalls.size(); // FirstCall
506 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000507 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000508 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000509}
510
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000511/// remapLinks - Change all of the Links in the current node according to the
512/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000513///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000514void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
515 for (unsigned i = 0, e = Links.size(); i != e; ++i)
516 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
517}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000518
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000519
Chris Lattner0d9bab82002-07-18 00:12:30 +0000520// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000521// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000522// filled into the OldValMap member. If StripAllocas is set to true, Alloca
523// markers are removed from the graph, as the graph is being cloned into a
524// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000525//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000526DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
527 std::map<Value*, DSNodeHandle> &OldValMap,
528 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner92673292002-11-02 00:13:20 +0000529 bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000530 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000531
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000532 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000533
534 // Duplicate all of the nodes, populating the node map...
535 Nodes.reserve(FN+G.Nodes.size());
536 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000537 DSNode *Old = G.Nodes[i];
538 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000539 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000540 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000541 }
542
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000543 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000544 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000545 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000546
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000547 // Remove local markers as specified
Chris Lattner92673292002-11-02 00:13:20 +0000548 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000549 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000550 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000551 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000552
Chris Lattnercf15db32002-10-17 20:09:52 +0000553 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000554 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
555 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000556 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000557 H.setNode(OldNodeMap[I->second.getNode()]);
558 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000559
560 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000561 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
562 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000563 GVI->second.mergeWith(H);
564 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000565 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000566 }
567 }
568 }
Chris Lattnere2219762002-07-18 18:22:40 +0000569 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000570 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571
Chris Lattnercf15db32002-10-17 20:09:52 +0000572
Chris Lattner0d9bab82002-07-18 00:12:30 +0000573 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000574 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000575}
576
Chris Lattner076c1f92002-11-07 06:31:54 +0000577/// mergeInGraph - The method is used for merging graphs together. If the
578/// argument graph is not *this, it makes a clone of the specified graph, then
579/// merges the nodes specified in the call site with the formal arguments in the
580/// graph.
581///
582void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
583 bool StripAllocas) {
584 std::map<Value*, DSNodeHandle> OldValMap;
585 DSNodeHandle RetVal;
586 std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
587
588 // If this is not a recursive call, clone the graph into this graph...
589 if (&Graph != this) {
590 // Clone the callee's graph into the current graph, keeping
591 // track of where scalars in the old graph _used_ to point,
592 // and of the new nodes matching nodes of the old graph.
593 std::map<const DSNode*, DSNode*> OldNodeMap;
594
595 // The clone call may invalidate any of the vectors in the data
596 // structure graph. Strip locals and don't copy the list of callers
597 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, StripAllocas);
598 ScalarMap = &OldValMap;
599 } else {
600 RetVal = getRetNode();
601 ScalarMap = &getScalarMap();
602 }
603
604 // Merge the return value with the return value of the context...
605 RetVal.mergeWith(CS.getRetVal());
606
607 // Resolve all of the function arguments...
608 Function &F = Graph.getFunction();
609 Function::aiterator AI = F.abegin();
610 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
611 // Advance the argument iterator to the first pointer argument...
612 while (!isPointerType(AI->getType())) {
613 ++AI;
614#ifndef NDEBUG
615 if (AI == F.aend())
616 std::cerr << "Bad call to Function: " << F.getName() << "\n";
617#endif
618 assert(AI != F.aend() && "# Args provided is not # Args required!");
619 }
620
621 // Add the link from the argument scalar to the provided value
622 DSNodeHandle &NH = (*ScalarMap)[AI];
623 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
624 NH.mergeWith(CS.getPtrArg(i));
625 }
626}
627
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000628#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000629// cloneGlobalInto - Clone the given global node and all its target links
630// (and all their llinks, recursively).
631//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000632DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000633 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
634
635 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000636 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000637 if (ValMapEntry != 0)
638 return ValMapEntry;
639
640 // Clone the node and update the ValMap.
641 DSNode* NewNode = new DSNode(*GNode);
642 ValMapEntry = NewNode; // j=0 case of loop below!
643 Nodes.push_back(NewNode);
644 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000645 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000646
647 // Rewrite the links in the new node to point into the current graph.
648 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
649 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
650
651 return NewNode;
652}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000653#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000654
655
Chris Lattner0d9bab82002-07-18 00:12:30 +0000656// markIncompleteNodes - Mark the specified node as having contents that are not
657// known with the current analysis we have performed. Because a node makes all
658// of the nodes it can reach imcomplete if the node itself is incomplete, we
659// must recursively traverse the data structure graph, marking all reachable
660// nodes as incomplete.
661//
662static void markIncompleteNode(DSNode *N) {
663 // Stop recursion if no node, or if node already marked...
664 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
665
666 // Actually mark the node
667 N->NodeType |= DSNode::Incomplete;
668
669 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000670 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
671 if (DSNode *DSN = N->getLink(i).getNode())
672 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000673}
674
675
676// markIncompleteNodes - Traverse the graph, identifying nodes that may be
677// modified by other functions that have not been resolved yet. This marks
678// nodes that are reachable through three sources of "unknownness":
679//
680// Global Variables, Function Calls, and Incoming Arguments
681//
682// For any node that may have unknown components (because something outside the
683// scope of current analysis may have modified it), the 'Incomplete' flag is
684// added to the NodeType.
685//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000686void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000687 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000688 if (markFormalArgs && Func)
689 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000690 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
691 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000692
693 // Mark stuff passed into functions calls as being incomplete...
694 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000695 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000696 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000697 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000698
Chris Lattner92673292002-11-02 00:13:20 +0000699 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000700 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000701 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000702 }
703
Chris Lattner92673292002-11-02 00:13:20 +0000704 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000705 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000706 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000707 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000708 // FIXME: Make more efficient by looking over Links directly
Chris Lattner08db7192002-11-06 06:20:27 +0000709 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
710 if (DSNode *DSN = N->getLink(i).getNode())
711 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000712 }
713}
714
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000715// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000716// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000717static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000718 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000719 while (!N->getGlobals().empty()) {
720 GlobalValue *GV = N->getGlobals().back();
721 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000722 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000723 }
724}
725
726
Chris Lattner0d9bab82002-07-18 00:12:30 +0000727// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
728// checks to see if there are simple transformations that it can do to make it
729// dead.
730//
731bool DSGraph::isNodeDead(DSNode *N) {
732 // Is it a trivially dead shadow node...
733 if (N->getReferrers().empty() && N->NodeType == 0)
734 return true;
735
736 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000737 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000738 N->getReferrers().size() == N->getGlobals().size()) {
739
Chris Lattnerc875f022002-11-03 21:27:48 +0000740 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000741 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000742 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000743 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
744 return true;
745 }
746
747 return false;
748}
749
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000750static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000751 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000752 // Remove trivially identical function calls
753 unsigned NumFns = Calls.size();
754 std::sort(Calls.begin(), Calls.end());
755 Calls.erase(std::unique(Calls.begin(), Calls.end()),
756 Calls.end());
757
758 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000759 std::cerr << "Merged " << (NumFns-Calls.size())
760 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000761}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000762
Chris Lattnere2219762002-07-18 18:22:40 +0000763// removeTriviallyDeadNodes - After the graph has been constructed, this method
764// removes all unreachable nodes that are created because they got merged with
765// other nodes in the graph. These nodes will all be trivially unreachable, so
766// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000767//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000768void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000769 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000770 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000771 if (isNodeDead(Nodes[i])) { // This node is dead!
772 delete Nodes[i]; // Free memory...
773 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
774 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000775
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000776 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000777}
778
779
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000780// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000781// stuff to be alive.
782//
783static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000784 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000785
786 Alive.insert(N);
Chris Lattner08db7192002-11-06 06:20:27 +0000787 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
788 if (DSNode *DSN = N->getLink(i).getNode())
789 if (!Alive.count(DSN))
790 markAlive(DSN, Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000791}
792
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000793static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
794 std::set<DSNode*> &Visiting) {
795 if (N == 0) return false;
796
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000797 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000798 Visiting.insert(N);
799
800 // If any immediate successor is alive, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000801 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
802 if (DSNode *DSN = N->getLink(i).getNode())
803 if (Alive.count(DSN)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000804 Visiting.erase(N);
805 return true;
806 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000807
808 // Else if any successor reaches a live node, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000809 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
810 if (DSNode *DSN = N->getLink(i).getNode())
811 if (checkGlobalAlive(DSN, Alive, Visiting)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000812 Visiting.erase(N); return true;
813 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000814
815 Visiting.erase(N);
816 return false;
817}
818
819
820// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
821// This would be unnecessary if function calls were real nodes! In that case,
822// the simple iterative loop in the first few lines below suffice.
823//
824static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000825 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000826 std::set<DSNode*> &Alive,
827 bool FilterCalls) {
828
829 // Iterate, marking globals or cast nodes alive until no new live nodes
830 // are added to Alive
831 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000832 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000833 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
834 liveCount = Alive.size();
835 for ( ; I != E; ++I)
836 if (Alive.count(*I) == 0) {
837 Visiting.clear();
838 if (checkGlobalAlive(*I, Alive, Visiting))
839 markAlive(*I, Alive);
840 }
841 }
842
843 // Find function calls with some dead and some live nodes.
844 // Since all call nodes must be live if any one is live, we have to mark
845 // all nodes of the call as live and continue the iteration (via recursion).
846 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000847 bool Recurse = false;
848 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000849 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000850 DSCallSite &CS = Calls[i];
851 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
852 if (DSNode *N = CS.getPtrArg(j).getNode()) {
853 bool ArgIsDead = !Alive.count(N);
854 CallHasDeadArg |= ArgIsDead;
855 CallIsDead &= ArgIsDead;
856 }
857
858 if (DSNode *N = CS.getRetVal().getNode()) {
859 bool RetIsDead = !Alive.count(N);
860 CallHasDeadArg |= RetIsDead;
861 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000862 }
Chris Lattner0969c502002-10-21 02:08:03 +0000863
864 DSNode *N = CS.getCallee().getNode();
865 bool FnIsDead = !Alive.count(N);
866 CallHasDeadArg |= FnIsDead;
867 CallIsDead &= FnIsDead;
868
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000869 if (!CallIsDead && CallHasDeadArg) {
870 // Some node in this call is live and another is dead.
871 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000872 Recurse = true;
873 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
874 markAlive(CS.getPtrArg(j).getNode(), Alive);
875 markAlive(CS.getRetVal().getNode(), Alive);
876 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000877 }
878 }
Chris Lattner0969c502002-10-21 02:08:03 +0000879 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000880 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
881 }
882}
883
884
885// markGlobalsAlive - Mark global nodes and cast nodes alive if they
886// can reach any other live node. Since this can produce new live nodes,
887// we use a simple iterative algorithm.
888//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000889static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000890 bool FilterCalls) {
891 // Add global and cast nodes to a set so we don't walk all nodes every time
892 std::set<DSNode*> GlobalNodes;
893 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000894 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000895 GlobalNodes.insert(G.getNodes()[i]);
896
897 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000898 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000899 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000900 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
901 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
902 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
903 GlobalNodes.insert(N);
904 if (DSNode *N = Calls[i].getRetVal().getNode())
905 GlobalNodes.insert(N);
906 if (DSNode *N = Calls[i].getCallee().getNode())
907 GlobalNodes.insert(N);
908 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000909 }
910
911 // Iterate and recurse until no new live node are discovered.
912 // This would be a simple iterative loop if function calls were real nodes!
913 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
914
Chris Lattnerc875f022002-11-03 21:27:48 +0000915 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000916 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000917 for( ; I != E; ++I)
918 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000919 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000920
921 // Delete dead function calls
922 if (FilterCalls)
923 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
924 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000925 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
926 CallIsDead && j != ej; ++j)
927 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000928 if (CallIsDead)
929 Calls.erase(Calls.begin() + i); // remove the call entirely
930 }
931}
Chris Lattnere2219762002-07-18 18:22:40 +0000932
933// removeDeadNodes - Use a more powerful reachability analysis to eliminate
934// subgraphs that are unreachable. This often occurs because the data
935// structure doesn't "escape" into it's caller, and thus should be eliminated
936// from the caller's graph entirely. This is only appropriate to use when
937// inlining graphs.
938//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000939void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
940 assert((!KeepAllGlobals || KeepCalls) &&
941 "KeepAllGlobals without KeepCalls is meaningless");
942
Chris Lattnere2219762002-07-18 18:22:40 +0000943 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000944 removeTriviallyDeadNodes(KeepAllGlobals);
945
Chris Lattnere2219762002-07-18 18:22:40 +0000946 // FIXME: Merge nontrivially identical call nodes...
947
948 // Alive - a set that holds all nodes found to be reachable/alive.
949 std::set<DSNode*> Alive;
950
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000951 // If KeepCalls, mark all nodes reachable by call nodes as alive...
952 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000953 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
954 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
955 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
956 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
957 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
958 }
Chris Lattnere2219762002-07-18 18:22:40 +0000959
Chris Lattner92673292002-11-02 00:13:20 +0000960 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000961 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
962 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000963 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000964
Chris Lattner92673292002-11-02 00:13:20 +0000965#if 0
966 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
Chris Lattnerc875f022002-11-03 21:27:48 +0000967 // the ScalarMap?
Chris Lattner92673292002-11-02 00:13:20 +0000968 //
969 if (KeepAllGlobals)
970 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
971 if (Nodes[i]->NodeType & DSNode::GlobalNode)
972 markAlive(Nodes[i], Alive);
973#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000974
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000975 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000976 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000977
978 // Mark all globals or cast nodes that can reach a live node as alive.
979 // This also marks all nodes reachable from such nodes as alive.
980 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000981 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000982 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000983
Chris Lattnere2219762002-07-18 18:22:40 +0000984 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000985 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000986 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
987 for (unsigned i = 0; i != Nodes.size(); ++i)
988 if (!Alive.count(Nodes[i])) {
989 DSNode *N = Nodes[i];
990 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
991 DeadNodes.push_back(N); // Add node to our list of dead nodes
992 N->dropAllReferences(); // Drop all outgoing edges
993 }
994
Chris Lattnere2219762002-07-18 18:22:40 +0000995 // Delete all dead nodes...
996 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
997}
998
999
1000
Chris Lattner0d9bab82002-07-18 00:12:30 +00001001// maskNodeTypes - Apply a mask to all of the node types in the graph. This
1002// is useful for clearing out markers like Scalar or Incomplete.
1003//
1004void DSGraph::maskNodeTypes(unsigned char Mask) {
1005 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1006 Nodes[i]->NodeType &= Mask;
1007}
1008
1009
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001010#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001011//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001012// GlobalDSGraph Implementation
1013//===----------------------------------------------------------------------===//
1014
1015GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
1016}
1017
1018GlobalDSGraph::~GlobalDSGraph() {
1019 assert(Referrers.size() == 0 &&
1020 "Deleting global graph while references from other graphs exist");
1021}
1022
1023void GlobalDSGraph::addReference(const DSGraph* referrer) {
1024 if (referrer != this)
1025 Referrers.insert(referrer);
1026}
1027
1028void GlobalDSGraph::removeReference(const DSGraph* referrer) {
1029 if (referrer != this) {
1030 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
1031 Referrers.erase(referrer);
1032 if (Referrers.size() == 0)
1033 delete this;
1034 }
1035}
1036
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001037#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001038// Bits used in the next function
1039static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1040
1041
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001042// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1043// visible target links (and recursively their such links) into this graph.
1044// NodeCache maps the node being cloned to its clone in the Globals graph,
1045// in order to track cycles.
1046// GlobalsAreFinal is a flag that says whether it is safe to assume that
1047// an existing global node is complete. This is important to avoid
1048// reinserting all globals when inserting Calls to functions.
1049// This is a helper function for cloneGlobals and cloneCalls.
1050//
1051DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1052 std::map<const DSNode*, DSNode*> &NodeCache,
1053 bool GlobalsAreFinal) {
1054 if (OldNode == 0) return 0;
1055
1056 // The caller should check this is an external node. Just more efficient...
1057 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1058
1059 // If a clone has already been created for OldNode, return it.
1060 DSNode*& CacheEntry = NodeCache[OldNode];
1061 if (CacheEntry != 0)
1062 return CacheEntry;
1063
1064 // The result value...
1065 DSNode* NewNode = 0;
1066
1067 // If nodes already exist for any of the globals of OldNode,
1068 // merge all such nodes together since they are merged in OldNode.
1069 // If ValueCacheIsFinal==true, look for an existing node that has
1070 // an identical list of globals and return it if it exists.
1071 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001072 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001073 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001074 if (NewNode == 0) {
1075 NewNode = PrevNode; // first existing node found
1076 if (GlobalsAreFinal && j == 0)
1077 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1078 CacheEntry = NewNode;
1079 return NewNode;
1080 }
1081 }
1082 else if (NewNode != PrevNode) { // found another, different from prev
1083 // update ValMap *before* merging PrevNode into NewNode
1084 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001085 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001086 NewNode->mergeWith(PrevNode);
1087 }
1088 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001089 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001090 }
1091
1092 // If no existing node was found, clone the node and update the ValMap.
1093 if (NewNode == 0) {
1094 NewNode = new DSNode(*OldNode);
1095 Nodes.push_back(NewNode);
1096 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1097 NewNode->setLink(j, 0);
1098 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001099 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001100 }
1101 else
1102 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1103
1104 // Add the entry to NodeCache
1105 CacheEntry = NewNode;
1106
1107 // Rewrite the links in the new node to point into the current graph,
1108 // but only for links to external nodes. Set other links to NULL.
1109 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1110 DSNode* OldTarget = OldNode->getLink(j);
1111 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1112 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1113 if (NewNode->getLink(j))
1114 NewNode->getLink(j)->mergeWith(NewLink);
1115 else
1116 NewNode->setLink(j, NewLink);
1117 }
1118 }
1119
1120 // Remove all local markers
1121 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1122
1123 return NewNode;
1124}
1125
1126
1127// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1128// visible target links (and recursively their such links) into this graph.
1129//
1130void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1131 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001132#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001133 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1134 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1135 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001136 if (CloneCalls)
1137 GlobalsGraph->cloneCalls(Graph);
1138
1139 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001140#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001141}
1142
1143
1144// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1145// links (and recursively their such links) into this graph.
1146//
1147void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1148 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001149 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001150
1151 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1152
1153 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001154 DSCallSite& callCopy = FunctionCalls.back();
1155 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001156 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001157 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001158 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1159 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1160 : 0);
1161 }
1162
1163 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001164 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001165}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001166#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001167
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001168#endif