blob: 432dbb0d5c970c85d588631aeb29201f9d3fa029 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00002//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00003// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00004//
5//===----------------------------------------------------------------------===//
6
Chris Lattnerfccd06f2002-10-01 22:33:50 +00007#include "llvm/Analysis/DSGraph.h"
8#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +00009#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000011#include "llvm/Target/TargetData.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000012#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000013#include "Support/Statistic.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000014#include <algorithm>
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include <set>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000016
Chris Lattnere2219762002-07-18 18:22:40 +000017using std::vector;
18
Chris Lattner08db7192002-11-06 06:20:27 +000019namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000020 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
21 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000022};
23
Chris Lattnerb1060432002-11-07 05:20:53 +000024namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000025 extern TargetData TD;
26}
Chris Lattnerb1060432002-11-07 05:20:53 +000027using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000028
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000029//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000030// DSNode Implementation
31//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000032
Chris Lattner08db7192002-11-06 06:20:27 +000033DSNode::DSNode(enum NodeTy NT, const Type *T)
34 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000035 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000036 if (T) mergeTypeInfo(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000037}
38
Chris Lattner0d9bab82002-07-18 00:12:30 +000039// DSNode copy constructor... do not copy over the referrers list!
40DSNode::DSNode(const DSNode &N)
Chris Lattner08db7192002-11-06 06:20:27 +000041 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
42 NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000043}
44
Chris Lattnerc68c31b2002-07-10 22:38:08 +000045void DSNode::removeReferrer(DSNodeHandle *H) {
46 // Search backwards, because we depopulate the list from the back for
47 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000048 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000049 std::find(Referrers.rbegin(), Referrers.rend(), H);
50 assert(I != Referrers.rend() && "Referrer not pointing to node!");
51 Referrers.erase(I.base()-1);
52}
53
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000054// addGlobal - Add an entry for a global value to the Globals list. This also
55// marks the node with the 'G' flag if it does not already have it.
56//
57void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000058 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000059 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000060 std::lower_bound(Globals.begin(), Globals.end(), GV);
61
62 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000063 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000064 Globals.insert(I, GV);
65 NodeType |= GlobalNode;
66 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000067}
68
Chris Lattner8f0a16e2002-10-31 05:45:02 +000069/// foldNodeCompletely - If we determine that this node has some funny
70/// behavior happening to it that we cannot represent, we fold it down to a
71/// single, completely pessimistic, node. This node is represented as a
72/// single byte with a single TypeEntry of "void".
73///
74void DSNode::foldNodeCompletely() {
Chris Lattner08db7192002-11-06 06:20:27 +000075 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000076
Chris Lattner08db7192002-11-06 06:20:27 +000077 ++NumFolds;
78
79 // We are no longer typed at all...
80 Ty = DSTypeRec(Type::VoidTy, true);
81 Size = 1;
82
83 // Loop over all of our referrers, making them point to our zero bytes of
84 // space.
Chris Lattner8f0a16e2002-10-31 05:45:02 +000085 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
86 I != E; ++I)
87 (*I)->setOffset(0);
88
Chris Lattner8f0a16e2002-10-31 05:45:02 +000089 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000090 for (unsigned i = 1, e = Links.size(); i < e; ++i)
91 Links[0].mergeWith(Links[i]);
92 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000093}
Chris Lattner076c1f92002-11-07 06:31:54 +000094
Chris Lattner8f0a16e2002-10-31 05:45:02 +000095/// isNodeCompletelyFolded - Return true if this node has been completely
96/// folded down to something that can never be expanded, effectively losing
97/// all of the field sensitivity that may be present in the node.
98///
99bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner08db7192002-11-06 06:20:27 +0000100 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000101}
102
103
Chris Lattner08db7192002-11-06 06:20:27 +0000104/// mergeTypeInfo - This method merges the specified type into the current node
105/// at the specified offset. This may update the current node's type record if
106/// this gives more information to the node, it may do nothing to the node if
107/// this information is already known, or it may merge the node completely (and
108/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000109///
Chris Lattner08db7192002-11-06 06:20:27 +0000110/// This method returns true if the node is completely folded, otherwise false.
111///
112bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
113 // Check to make sure the Size member is up-to-date. Size can be one of the
114 // following:
115 // Size = 0, Ty = Void: Nothing is known about this node.
116 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
117 // Size = 1, Ty = Void, Array = 1: The node is collapsed
118 // Otherwise, sizeof(Ty) = Size
119 //
120 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
121 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
122 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
123 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
124 (TD.getTypeSize(Ty.Ty) == Size)) &&
125 "Size member of DSNode doesn't match the type structure!");
126 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000127
Chris Lattner08db7192002-11-06 06:20:27 +0000128 if (Offset == 0 && NewTy == Ty.Ty)
129 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000130
Chris Lattner08db7192002-11-06 06:20:27 +0000131 // Return true immediately if the node is completely folded.
132 if (isNodeCompletelyFolded()) return true;
133
Chris Lattner23f83dc2002-11-08 22:49:57 +0000134 // If this is an array type, eliminate the outside arrays because they won't
135 // be used anyway. This greatly reduces the size of large static arrays used
136 // as global variables, for example.
137 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000138 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000139 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
140 // FIXME: we might want to keep small arrays, but must be careful about
141 // things like: [2 x [10000 x int*]]
142 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000143 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000144 }
145
Chris Lattner08db7192002-11-06 06:20:27 +0000146 // Figure out how big the new type we're merging in is...
147 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
148
149 // Otherwise check to see if we can fold this type into the current node. If
150 // we can't, we fold the node completely, if we can, we potentially update our
151 // internal state.
152 //
153 if (Ty.Ty == Type::VoidTy) {
154 // If this is the first type that this node has seen, just accept it without
155 // question....
156 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattnerd8888932002-11-09 19:25:27 +0000157 assert(!Ty.isArray && "This shouldn't happen!");
Chris Lattner08db7192002-11-06 06:20:27 +0000158 Ty.Ty = NewTy;
Chris Lattnerd8888932002-11-09 19:25:27 +0000159 Ty.isArray = WillBeArray;
Chris Lattner08db7192002-11-06 06:20:27 +0000160 Size = NewTySize;
161
162 // Calculate the number of outgoing links from this node.
163 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
164 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000165 }
Chris Lattner08db7192002-11-06 06:20:27 +0000166
167 // Handle node expansion case here...
168 if (Offset+NewTySize > Size) {
169 // It is illegal to grow this node if we have treated it as an array of
170 // objects...
171 if (Ty.isArray) {
172 foldNodeCompletely();
173 return true;
174 }
175
176 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000177 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
178 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000179 foldNodeCompletely();
180 return true;
181 }
182
183 // Okay, the situation is nice and simple, we are trying to merge a type in
184 // at offset 0 that is bigger than our current type. Implement this by
185 // switching to the new type and then merge in the smaller one, which should
186 // hit the other code path here. If the other code path decides it's not
187 // ok, it will collapse the node as appropriate.
188 //
189 const Type *OldTy = Ty.Ty;
190 Ty.Ty = NewTy;
Chris Lattnerd8888932002-11-09 19:25:27 +0000191 Ty.isArray = WillBeArray;
Chris Lattner08db7192002-11-06 06:20:27 +0000192 Size = NewTySize;
193
194 // Must grow links to be the appropriate size...
195 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
196
197 // Merge in the old type now... which is guaranteed to be smaller than the
198 // "current" type.
199 return mergeTypeInfo(OldTy, 0);
200 }
201
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000202 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000203 "Cannot merge something into a part of our type that doesn't exist!");
204
205 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
206 // type that starts at offset Offset.
207 //
208 unsigned O = 0;
209 const Type *SubType = Ty.Ty;
210 while (O < Offset) {
211 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
212
213 switch (SubType->getPrimitiveID()) {
214 case Type::StructTyID: {
215 const StructType *STy = cast<StructType>(SubType);
216 const StructLayout &SL = *TD.getStructLayout(STy);
217
218 unsigned i = 0, e = SL.MemberOffsets.size();
219 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
220 /* empty */;
221
222 // The offset we are looking for must be in the i'th element...
223 SubType = STy->getElementTypes()[i];
224 O += SL.MemberOffsets[i];
225 break;
226 }
227 case Type::ArrayTyID: {
228 SubType = cast<ArrayType>(SubType)->getElementType();
229 unsigned ElSize = TD.getTypeSize(SubType);
230 unsigned Remainder = (Offset-O) % ElSize;
231 O = Offset-Remainder;
232 break;
233 }
234 default:
235 assert(0 && "Unknown type!");
236 }
237 }
238
239 assert(O == Offset && "Could not achieve the correct offset!");
240
241 // If we found our type exactly, early exit
242 if (SubType == NewTy) return false;
243
244 // Okay, so we found the leader type at the offset requested. Search the list
245 // of types that starts at this offset. If SubType is currently an array or
246 // structure, the type desired may actually be the first element of the
247 // composite type...
248 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000249 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000250 while (SubType != NewTy) {
251 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000252 unsigned NextSubTypeSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000253 switch (SubType->getPrimitiveID()) {
254 case Type::StructTyID:
255 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
256 NextSubTypeSize = TD.getTypeSize(SubType);
257 break;
258 case Type::ArrayTyID:
259 NextSubType = cast<ArrayType>(SubType)->getElementType();
260 NextSubTypeSize = TD.getTypeSize(SubType);
261 break;
262 default: ;
263 // fall out
264 }
265
266 if (NextSubType == 0)
267 break; // In the default case, break out of the loop
268
269 if (NextSubTypeSize < NewTySize)
270 break; // Don't allow shrinking to a smaller type than NewTySize
271 SubType = NextSubType;
272 SubTypeSize = NextSubTypeSize;
273 }
274
275 // If we found the type exactly, return it...
276 if (SubType == NewTy)
277 return false;
278
279 // Check to see if we have a compatible, but different type...
280 if (NewTySize == SubTypeSize) {
281 // Check to see if this type is obviously convertable... int -> uint f.e.
282 if (NewTy->isLosslesslyConvertableTo(SubType))
283 return false;
284
285 // Check to see if we have a pointer & integer mismatch going on here,
286 // loading a pointer as a long, for example.
287 //
288 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
289 NewTy->isInteger() && isa<PointerType>(SubType))
290 return false;
291
292 }
293
294
Chris Lattner3c87b292002-11-07 01:54:56 +0000295 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
296 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
297 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000298
299 foldNodeCompletely();
300 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000301}
302
Chris Lattner08db7192002-11-06 06:20:27 +0000303
304
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000305// addEdgeTo - Add an edge from the current node to the specified node. This
306// can cause merging of nodes in the graph.
307//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000308void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000309 if (NH.getNode() == 0) return; // Nothing to do
310
Chris Lattner08db7192002-11-06 06:20:27 +0000311 DSNodeHandle &ExistingEdge = getLink(Offset);
312 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000313 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000314 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000315 } else { // No merging to perform...
316 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000317 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000318}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000319
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000320
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000321// MergeSortedVectors - Efficiently merge a vector into another vector where
322// duplicates are not allowed and both are sorted. This assumes that 'T's are
323// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000324//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000325template<typename T>
326void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
327 // By far, the most common cases will be the simple ones. In these cases,
328 // avoid having to allocate a temporary vector...
329 //
330 if (Src.empty()) { // Nothing to merge in...
331 return;
332 } else if (Dest.empty()) { // Just copy the result in...
333 Dest = Src;
334 } else if (Src.size() == 1) { // Insert a single element...
335 const T &V = Src[0];
336 typename vector<T>::iterator I =
337 std::lower_bound(Dest.begin(), Dest.end(), V);
338 if (I == Dest.end() || *I != Src[0]) // If not already contained...
339 Dest.insert(I, Src[0]);
340 } else if (Dest.size() == 1) {
341 T Tmp = Dest[0]; // Save value in temporary...
342 Dest = Src; // Copy over list...
343 typename vector<T>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000344 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
345 if (I == Dest.end() || *I != Tmp) // If not already contained...
346 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000347
348 } else {
349 // Make a copy to the side of Dest...
350 vector<T> Old(Dest);
351
352 // Make space for all of the type entries now...
353 Dest.resize(Dest.size()+Src.size());
354
355 // Merge the two sorted ranges together... into Dest.
356 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
357
358 // Now erase any duplicate entries that may have accumulated into the
359 // vectors (because they were in both of the input sets)
360 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
361 }
362}
363
364
365// mergeWith - Merge this node and the specified node, moving all links to and
366// from the argument node into the current node, deleting the node argument.
367// Offset indicates what offset the specified node is to be merged into the
368// current node.
369//
370// The specified node may be a null pointer (in which case, nothing happens).
371//
372void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
373 DSNode *N = NH.getNode();
374 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000375 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000376
Chris Lattner679e8e12002-11-08 21:27:12 +0000377 assert((N->NodeType & DSNode::DEAD) == 0);
378 assert((NodeType & DSNode::DEAD) == 0);
379 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
380
Chris Lattner02606632002-11-04 06:48:26 +0000381 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000382 // We cannot merge two pieces of the same node together, collapse the node
383 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000384 DEBUG(std::cerr << "Attempting to merge two chunks of"
385 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000386 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000387 return;
388 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000389
Chris Lattner5190ce82002-11-12 07:20:45 +0000390 // If both nodes are not at offset 0, make sure that we are merging the node
391 // at an later offset into the node with the zero offset.
392 //
393 if (Offset < NH.getOffset()) {
394 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
395 return;
396 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
397 // If the offsets are the same, merge the smaller node into the bigger node
398 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
399 return;
400 }
401
402 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
403 // respect to NH.Offset) is now zero. NOffset is the distance from the base
404 // of our object that N starts from.
405 //
406 unsigned NOffset = Offset-NH.getOffset();
407 unsigned NSize = N->getSize();
408
Chris Lattner08db7192002-11-06 06:20:27 +0000409 // Merge the type entries of the two nodes together...
Chris Lattner679e8e12002-11-08 21:27:12 +0000410 if (N->Ty.Ty != Type::VoidTy) {
Chris Lattner5190ce82002-11-12 07:20:45 +0000411 mergeTypeInfo(N->Ty.Ty, NOffset);
Chris Lattner08db7192002-11-06 06:20:27 +0000412
Chris Lattner679e8e12002-11-08 21:27:12 +0000413 // mergeTypeInfo can cause collapsing, which can cause this node to become
414 // dead.
415 if (hasNoReferrers()) return;
416 }
417 assert((NodeType & DSNode::DEAD) == 0);
418
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000419 // If we are merging a node with a completely folded node, then both nodes are
420 // now completely folded.
421 //
422 if (isNodeCompletelyFolded()) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000423 if (!N->isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000424 N->foldNodeCompletely();
Chris Lattner679e8e12002-11-08 21:27:12 +0000425 if (hasNoReferrers()) return;
Chris Lattner5190ce82002-11-12 07:20:45 +0000426 NSize = N->getSize();
Chris Lattner679e8e12002-11-08 21:27:12 +0000427 }
Chris Lattner02606632002-11-04 06:48:26 +0000428 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000429 foldNodeCompletely();
Chris Lattner679e8e12002-11-08 21:27:12 +0000430 if (hasNoReferrers()) return;
Chris Lattner5190ce82002-11-12 07:20:45 +0000431 Offset = 0;
432 NOffset = NH.getOffset();
433 NSize = N->getSize();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000434 }
Chris Lattner02606632002-11-04 06:48:26 +0000435 N = NH.getNode();
Chris Lattner2c0bd012002-11-06 18:01:39 +0000436 if (this == N || N == 0) return;
Chris Lattner679e8e12002-11-08 21:27:12 +0000437 assert((NodeType & DSNode::DEAD) == 0);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000438
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000439#if 0
440 std::cerr << "\n\nMerging:\n";
441 N->print(std::cerr, 0);
442 std::cerr << " and:\n";
443 print(std::cerr, 0);
444#endif
445
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000446 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000447 // Make sure to adjust their offset, not just the node pointer.
448 //
449 while (!N->Referrers.empty()) {
450 DSNodeHandle &Ref = *N->Referrers.back();
451 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
452 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000453 assert((NodeType & DSNode::DEAD) == 0);
Chris Lattner59535132002-11-05 00:01:58 +0000454
455 // Make all of the outgoing links of N now be outgoing links of this. This
456 // can cause recursive merging!
457 //
Chris Lattner08db7192002-11-06 06:20:27 +0000458 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
459 DSNodeHandle &Link = N->getLink(i);
460 if (Link.getNode()) {
461 addEdgeTo((i+NOffset) % getSize(), Link);
Chris Lattner59535132002-11-05 00:01:58 +0000462
Chris Lattner08db7192002-11-06 06:20:27 +0000463 // It's possible that after adding the new edge that some recursive
464 // merging just occured, causing THIS node to get merged into oblivion.
465 // If that happens, we must not try to merge any more edges into it!
Chris Lattner7b7200c2002-10-02 04:57:39 +0000466 //
Chris Lattner08db7192002-11-06 06:20:27 +0000467 if (Size == 0) return;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000468 }
469 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000470
471 // Now that there are no outgoing edges, all of the Links are dead.
472 N->Links.clear();
Chris Lattner08db7192002-11-06 06:20:27 +0000473 N->Size = 0;
474 N->Ty.Ty = Type::VoidTy;
475 N->Ty.isArray = false;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000476
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000477 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000478 NodeType |= N->NodeType;
Chris Lattner33312f72002-11-08 01:21:07 +0000479 N->NodeType = DEAD; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000480
481 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000482 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000483 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000484
485 // Delete the globals from the old node...
486 N->Globals.clear();
487 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000488}
489
Chris Lattner9de906c2002-10-20 22:11:44 +0000490//===----------------------------------------------------------------------===//
491// DSCallSite Implementation
492//===----------------------------------------------------------------------===//
493
Vikram S. Adve26b98262002-10-20 21:41:02 +0000494// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000495Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000496 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000497}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000498
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000499
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000500//===----------------------------------------------------------------------===//
501// DSGraph Implementation
502//===----------------------------------------------------------------------===//
503
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000504DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000505 PrintAuxCalls = false;
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000506 std::map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000507 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000508}
509
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000510DSGraph::DSGraph(const DSGraph &G,
511 std::map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000512 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000513 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000514 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000515}
516
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000517DSGraph::~DSGraph() {
518 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000519 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000520 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000521 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000522
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000523 // Drop all intra-node references, so that assertions don't fail...
524 std::for_each(Nodes.begin(), Nodes.end(),
525 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000526
527 // Delete all of the nodes themselves...
528 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
529}
530
Chris Lattner0d9bab82002-07-18 00:12:30 +0000531// dump - Allow inspection of graph in a debugger.
532void DSGraph::dump() const { print(std::cerr); }
533
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000534
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000535/// remapLinks - Change all of the Links in the current node according to the
536/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000537///
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000538void DSNode::remapLinks(std::map<const DSNode*, DSNodeHandle> &OldNodeMap) {
539 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
540 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
541 Links[i].setNode(H.getNode());
542 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
543 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000544}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000545
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000546
Chris Lattner0d9bab82002-07-18 00:12:30 +0000547// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000548// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000549// filled into the OldValMap member. If StripAllocas is set to true, Alloca
550// markers are removed from the graph, as the graph is being cloned into a
551// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000552//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000553DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
554 std::map<Value*, DSNodeHandle> &OldValMap,
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000555 std::map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000556 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000557 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000558 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000559
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000560 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000561
562 // Duplicate all of the nodes, populating the node map...
563 Nodes.reserve(FN+G.Nodes.size());
564 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000565 DSNode *Old = G.Nodes[i];
566 DSNode *New = new DSNode(*Old);
Chris Lattner679e8e12002-11-08 21:27:12 +0000567 New->NodeType &= ~DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000568 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000569 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000570 }
571
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000572 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000573 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000574 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000575
Chris Lattner460ea292002-11-07 07:06:20 +0000576 // Remove alloca markers as specified
Chris Lattner679e8e12002-11-08 21:27:12 +0000577 if (CloneFlags & StripAllocaBit)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000578 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattner460ea292002-11-07 07:06:20 +0000579 Nodes[i]->NodeType &= ~DSNode::AllocaNode;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000580
Chris Lattnercf15db32002-10-17 20:09:52 +0000581 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000582 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
583 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000584 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000585 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
586 H.setNode(MappedNode.getNode());
587 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000588
589 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000590 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
591 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000592 GVI->second.mergeWith(H);
593 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000594 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000595 }
596 }
597 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000598
Chris Lattner679e8e12002-11-08 21:27:12 +0000599 if (!(CloneFlags & DontCloneCallNodes)) {
600 // Copy the function calls list...
601 unsigned FC = FunctionCalls.size(); // FirstCall
602 FunctionCalls.reserve(FC+G.FunctionCalls.size());
603 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
604 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000605 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000606
Chris Lattneracf491f2002-11-08 22:27:09 +0000607 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000608 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000609 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000610 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
611 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
612 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
613 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000614
Chris Lattner0d9bab82002-07-18 00:12:30 +0000615 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000616 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
617 return DSNodeHandle(MappedRet.getNode(),
618 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000619}
620
Chris Lattner076c1f92002-11-07 06:31:54 +0000621/// mergeInGraph - The method is used for merging graphs together. If the
622/// argument graph is not *this, it makes a clone of the specified graph, then
623/// merges the nodes specified in the call site with the formal arguments in the
624/// graph.
625///
626void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000627 unsigned CloneFlags) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000628 std::map<Value*, DSNodeHandle> OldValMap;
629 DSNodeHandle RetVal;
630 std::map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
631
632 // If this is not a recursive call, clone the graph into this graph...
633 if (&Graph != this) {
634 // Clone the callee's graph into the current graph, keeping
635 // track of where scalars in the old graph _used_ to point,
636 // and of the new nodes matching nodes of the old graph.
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000637 std::map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000638
639 // The clone call may invalidate any of the vectors in the data
640 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000641 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000642 ScalarMap = &OldValMap;
643 } else {
644 RetVal = getRetNode();
645 ScalarMap = &getScalarMap();
646 }
647
648 // Merge the return value with the return value of the context...
649 RetVal.mergeWith(CS.getRetVal());
650
651 // Resolve all of the function arguments...
652 Function &F = Graph.getFunction();
653 Function::aiterator AI = F.abegin();
654 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
655 // Advance the argument iterator to the first pointer argument...
656 while (!isPointerType(AI->getType())) {
657 ++AI;
658#ifndef NDEBUG
659 if (AI == F.aend())
660 std::cerr << "Bad call to Function: " << F.getName() << "\n";
661#endif
662 assert(AI != F.aend() && "# Args provided is not # Args required!");
663 }
664
665 // Add the link from the argument scalar to the provided value
666 DSNodeHandle &NH = (*ScalarMap)[AI];
667 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
668 NH.mergeWith(CS.getPtrArg(i));
669 }
670}
671
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000672#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000673// cloneGlobalInto - Clone the given global node and all its target links
674// (and all their llinks, recursively).
675//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000676DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000677 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
678
679 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000680 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000681 if (ValMapEntry != 0)
682 return ValMapEntry;
683
684 // Clone the node and update the ValMap.
685 DSNode* NewNode = new DSNode(*GNode);
686 ValMapEntry = NewNode; // j=0 case of loop below!
687 Nodes.push_back(NewNode);
688 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000689 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000690
691 // Rewrite the links in the new node to point into the current graph.
692 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
693 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
694
695 return NewNode;
696}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000697#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000698
699
Chris Lattner0d9bab82002-07-18 00:12:30 +0000700// markIncompleteNodes - Mark the specified node as having contents that are not
701// known with the current analysis we have performed. Because a node makes all
702// of the nodes it can reach imcomplete if the node itself is incomplete, we
703// must recursively traverse the data structure graph, marking all reachable
704// nodes as incomplete.
705//
706static void markIncompleteNode(DSNode *N) {
707 // Stop recursion if no node, or if node already marked...
708 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
709
710 // Actually mark the node
711 N->NodeType |= DSNode::Incomplete;
712
713 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000714 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
715 if (DSNode *DSN = N->getLink(i).getNode())
716 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000717}
718
Chris Lattnere71ffc22002-11-11 03:36:55 +0000719static void markIncomplete(DSCallSite &Call) {
720 // Then the return value is certainly incomplete!
721 markIncompleteNode(Call.getRetVal().getNode());
722
723 // All objects pointed to by function arguments are incomplete!
724 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
725 markIncompleteNode(Call.getPtrArg(i).getNode());
726}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000727
728// markIncompleteNodes - Traverse the graph, identifying nodes that may be
729// modified by other functions that have not been resolved yet. This marks
730// nodes that are reachable through three sources of "unknownness":
731//
732// Global Variables, Function Calls, and Incoming Arguments
733//
734// For any node that may have unknown components (because something outside the
735// scope of current analysis may have modified it), the 'Incomplete' flag is
736// added to the NodeType.
737//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000738void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000739 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000740 if (markFormalArgs && Func)
741 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000742 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
743 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000744
745 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000746 if (!shouldPrintAuxCalls())
747 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
748 markIncomplete(FunctionCalls[i]);
749 else
750 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
751 markIncomplete(AuxFunctionCalls[i]);
752
Chris Lattner0d9bab82002-07-18 00:12:30 +0000753
Chris Lattner92673292002-11-02 00:13:20 +0000754 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000755 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000756 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000757 DSNode *N = Nodes[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000758 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
759 if (DSNode *DSN = N->getLink(i).getNode())
760 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000761 }
762}
763
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000764// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000765// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000766static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000767 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000768 while (!N->getGlobals().empty()) {
769 GlobalValue *GV = N->getGlobals().back();
770 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000771 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000772 }
773}
774
775
Chris Lattner0d9bab82002-07-18 00:12:30 +0000776// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
777// checks to see if there are simple transformations that it can do to make it
778// dead.
779//
780bool DSGraph::isNodeDead(DSNode *N) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000781 // Is it a trivially dead shadow node?
Chris Lattnerd11e9542002-11-10 07:46:08 +0000782 return N->getReferrers().empty() && (N->NodeType & ~DSNode::DEAD) == 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000783}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000784
Chris Lattneraa8146f2002-11-10 06:59:55 +0000785static inline void killIfUselessEdge(DSNodeHandle &Edge) {
786 if (DSNode *N = Edge.getNode()) // Is there an edge?
787 if (N->getReferrers().size() == 1) // Does it point to a lonely node?
788 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
789 N->getType().Ty == Type::VoidTy && !N->isNodeCompletelyFolded())
790 Edge.setNode(0); // Kill the edge!
791}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000792
Chris Lattneraa8146f2002-11-10 06:59:55 +0000793static inline bool nodeContainsExternalFunction(const DSNode *N) {
794 const std::vector<GlobalValue*> &Globals = N->getGlobals();
795 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
796 if (Globals[i]->isExternal())
797 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000798 return false;
799}
800
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000801static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000802 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000803 // Remove trivially identical function calls
804 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000805 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
806
807 // Scan the call list cleaning it up as necessary...
808 DSNode *LastCalleeNode = 0;
809 unsigned NumDuplicateCalls = 0;
810 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000811 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000812 DSCallSite &CS = Calls[i];
813
Chris Lattnere4258442002-11-11 21:35:38 +0000814 // If the Callee is a useless edge, this must be an unreachable call site,
815 // eliminate it.
816 killIfUselessEdge(CS.getCallee());
817 if (CS.getCallee().getNode() == 0) {
818 CS.swap(Calls.back());
819 Calls.pop_back();
820 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000821 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000822 // If the return value or any arguments point to a void node with no
823 // information at all in it, and the call node is the only node to point
824 // to it, remove the edge to the node (killing the node).
825 //
826 killIfUselessEdge(CS.getRetVal());
827 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
828 killIfUselessEdge(CS.getPtrArg(a));
829
830 // If this call site calls the same function as the last call site, and if
831 // the function pointer contains an external function, this node will
832 // never be resolved. Merge the arguments of the call node because no
833 // information will be lost.
834 //
835 if (CS.getCallee().getNode() == LastCalleeNode) {
836 ++NumDuplicateCalls;
837 if (NumDuplicateCalls == 1) {
838 LastCalleeContainsExternalFunction =
839 nodeContainsExternalFunction(LastCalleeNode);
840 }
841
842 if (LastCalleeContainsExternalFunction ||
843 // This should be more than enough context sensitivity!
844 // FIXME: Evaluate how many times this is tripped!
845 NumDuplicateCalls > 20) {
846 DSCallSite &OCS = Calls[i-1];
847 OCS.mergeWith(CS);
848
849 // The node will now be eliminated as a duplicate!
850 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
851 CS = OCS;
852 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
853 OCS = CS;
854 }
855 } else {
856 LastCalleeNode = CS.getCallee().getNode();
857 NumDuplicateCalls = 0;
858 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000859 }
860 }
861
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000862 Calls.erase(std::unique(Calls.begin(), Calls.end()),
863 Calls.end());
864
Chris Lattner33312f72002-11-08 01:21:07 +0000865 // Track the number of call nodes merged away...
866 NumCallNodesMerged += NumFns-Calls.size();
867
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000868 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000869 std::cerr << "Merged " << (NumFns-Calls.size())
870 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000871}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000872
Chris Lattneraa8146f2002-11-10 06:59:55 +0000873
Chris Lattnere2219762002-07-18 18:22:40 +0000874// removeTriviallyDeadNodes - After the graph has been constructed, this method
875// removes all unreachable nodes that are created because they got merged with
876// other nodes in the graph. These nodes will all be trivially unreachable, so
877// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000878//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000879void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000880 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000881 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
882
883 for (unsigned i = 0; i != Nodes.size(); ++i)
884 if (isNodeDead(Nodes[i])) { // This node is dead!
885 delete Nodes[i]; // Free memory...
886 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
887 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000888}
889
890
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000891// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000892// stuff to be alive.
893//
894static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000895 if (N == 0) return;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000896 std::set<DSNode*>::iterator I = Alive.lower_bound(N);
897 if (I != Alive.end() && *I == N) return; // Already marked alive
898 Alive.insert(I, N); // Is alive now
Chris Lattnere2219762002-07-18 18:22:40 +0000899
Chris Lattner08db7192002-11-06 06:20:27 +0000900 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattneraa8146f2002-11-10 06:59:55 +0000901 markAlive(N->getLink(i).getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000902}
903
Chris Lattneraa8146f2002-11-10 06:59:55 +0000904// markAliveIfCanReachAlive - Simple graph walker that recursively traverses the
905// graph looking for a node that is marked alive. If the node is marked alive,
906// the recursive unwind marks node alive that can point to the alive node. This
907// is basically just a post-order traversal.
908//
909// This function returns true if the specified node is alive.
910//
911static bool markAliveIfCanReachAlive(DSNode *N, std::set<DSNode*> &Alive,
912 std::set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000913 if (N == 0) return false;
914
Chris Lattneraa8146f2002-11-10 06:59:55 +0000915 // If we know that this node is alive, return so!
916 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000917
Chris Lattneraa8146f2002-11-10 06:59:55 +0000918 // Otherwise, we don't think the node is alive yet, check for infinite
919 // recursion.
920 std::set<DSNode*>::iterator VI = Visited.lower_bound(N);
921 if (VI != Visited.end() && *VI == N) return false; // Found a cycle
922 // No recursion, insert into Visited...
923 Visited.insert(VI, N);
924
925 if (N->NodeType & DSNode::GlobalNode)
926 return false; // Global nodes will be marked on their own
927
928 bool ChildrenAreAlive = false;
929
Chris Lattner08db7192002-11-06 06:20:27 +0000930 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattneraa8146f2002-11-10 06:59:55 +0000931 ChildrenAreAlive |= markAliveIfCanReachAlive(N->getLink(i).getNode(),
932 Alive, Visited);
933 if (ChildrenAreAlive)
934 markAlive(N, Alive);
935 return ChildrenAreAlive;
936}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000937
Chris Lattneraa8146f2002-11-10 06:59:55 +0000938static bool CallSiteUsesAliveArgs(DSCallSite &CS, std::set<DSNode*> &Alive,
939 std::set<DSNode*> &Visited) {
940 if (markAliveIfCanReachAlive(CS.getRetVal().getNode(), Alive, Visited) ||
941 markAliveIfCanReachAlive(CS.getCallee().getNode(), Alive, Visited))
942 return true;
943 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
944 if (markAliveIfCanReachAlive(CS.getPtrArg(j).getNode(), Alive, Visited))
945 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000946 return false;
947}
948
Chris Lattneraa8146f2002-11-10 06:59:55 +0000949static void markAlive(DSCallSite &CS, std::set<DSNode*> &Alive) {
950 markAlive(CS.getRetVal().getNode(), Alive);
951 markAlive(CS.getCallee().getNode(), Alive);
952
953 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
954 markAlive(CS.getPtrArg(j).getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000955}
Chris Lattnere2219762002-07-18 18:22:40 +0000956
957// removeDeadNodes - Use a more powerful reachability analysis to eliminate
958// subgraphs that are unreachable. This often occurs because the data
959// structure doesn't "escape" into it's caller, and thus should be eliminated
960// from the caller's graph entirely. This is only appropriate to use when
961// inlining graphs.
962//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000963void DSGraph::removeDeadNodes() {
Chris Lattnere2219762002-07-18 18:22:40 +0000964 // Reduce the amount of work we have to do...
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000965 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000966
Chris Lattnere2219762002-07-18 18:22:40 +0000967 // FIXME: Merge nontrivially identical call nodes...
968
969 // Alive - a set that holds all nodes found to be reachable/alive.
970 std::set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000971 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000972
Chris Lattneraa8146f2002-11-10 06:59:55 +0000973 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000974 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
975 E = ScalarMap.end(); I != E; ++I)
Chris Lattneraa8146f2002-11-10 06:59:55 +0000976 if (!isa<GlobalValue>(I->first)) // Don't mark globals!
977 markAlive(I->second.getNode(), Alive);
978 else // Keep track of global nodes
979 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattnere2219762002-07-18 18:22:40 +0000980
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000981 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000982 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000983
Chris Lattneraa8146f2002-11-10 06:59:55 +0000984 // If any global nodes points to a non-global that is "alive", the global is
985 // "alive" as well...
986 //
987 std::set<DSNode*> Visited;
988 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
989 markAliveIfCanReachAlive(GlobalNodes[i].second, Alive, Visited);
990
991 std::vector<bool> FCallsAlive(FunctionCalls.size());
992 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
993 if (CallSiteUsesAliveArgs(FunctionCalls[i], Alive, Visited)) {
994 markAlive(FunctionCalls[i], Alive);
995 FCallsAlive[i] = true;
996 }
997
998 std::vector<bool> AuxFCallsAlive(AuxFunctionCalls.size());
999 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1000 if (CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1001 markAlive(AuxFunctionCalls[i], Alive);
1002 AuxFCallsAlive[i] = true;
1003 }
1004
1005 // Remove all dead function calls...
1006 unsigned CurIdx = 0;
1007 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1008 if (FCallsAlive[i])
1009 FunctionCalls[CurIdx++].swap(FunctionCalls[i]);
1010 // Crop all the bad ones out...
1011 FunctionCalls.erase(FunctionCalls.begin()+CurIdx, FunctionCalls.end());
1012
1013 // Remove all dead aux function calls...
1014 CurIdx = 0;
1015 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1016 if (AuxFCallsAlive[i])
1017 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1018 // Crop all the bad ones out...
1019 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1020 AuxFunctionCalls.end());
1021
1022
1023 // Remove all unreachable globals from the ScalarMap
1024 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1025 if (!Alive.count(GlobalNodes[i].second))
1026 ScalarMap.erase(GlobalNodes[i].first);
1027
Chris Lattnere2219762002-07-18 18:22:40 +00001028 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001029 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001030 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
1031 for (unsigned i = 0; i != Nodes.size(); ++i)
1032 if (!Alive.count(Nodes[i])) {
1033 DSNode *N = Nodes[i];
1034 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
1035 DeadNodes.push_back(N); // Add node to our list of dead nodes
1036 N->dropAllReferences(); // Drop all outgoing edges
1037 }
1038
Chris Lattnere2219762002-07-18 18:22:40 +00001039 // Delete all dead nodes...
1040 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
1041}
1042
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001043#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001044//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001045// GlobalDSGraph Implementation
1046//===----------------------------------------------------------------------===//
1047
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001048#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001049// Bits used in the next function
1050static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1051
1052
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001053// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1054// visible target links (and recursively their such links) into this graph.
1055// NodeCache maps the node being cloned to its clone in the Globals graph,
1056// in order to track cycles.
1057// GlobalsAreFinal is a flag that says whether it is safe to assume that
1058// an existing global node is complete. This is important to avoid
1059// reinserting all globals when inserting Calls to functions.
1060// This is a helper function for cloneGlobals and cloneCalls.
1061//
1062DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1063 std::map<const DSNode*, DSNode*> &NodeCache,
1064 bool GlobalsAreFinal) {
1065 if (OldNode == 0) return 0;
1066
1067 // The caller should check this is an external node. Just more efficient...
1068 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1069
1070 // If a clone has already been created for OldNode, return it.
1071 DSNode*& CacheEntry = NodeCache[OldNode];
1072 if (CacheEntry != 0)
1073 return CacheEntry;
1074
1075 // The result value...
1076 DSNode* NewNode = 0;
1077
1078 // If nodes already exist for any of the globals of OldNode,
1079 // merge all such nodes together since they are merged in OldNode.
1080 // If ValueCacheIsFinal==true, look for an existing node that has
1081 // an identical list of globals and return it if it exists.
1082 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001083 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001084 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001085 if (NewNode == 0) {
1086 NewNode = PrevNode; // first existing node found
1087 if (GlobalsAreFinal && j == 0)
1088 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1089 CacheEntry = NewNode;
1090 return NewNode;
1091 }
1092 }
1093 else if (NewNode != PrevNode) { // found another, different from prev
1094 // update ValMap *before* merging PrevNode into NewNode
1095 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001096 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001097 NewNode->mergeWith(PrevNode);
1098 }
1099 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001100 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001101 }
1102
1103 // If no existing node was found, clone the node and update the ValMap.
1104 if (NewNode == 0) {
1105 NewNode = new DSNode(*OldNode);
1106 Nodes.push_back(NewNode);
1107 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1108 NewNode->setLink(j, 0);
1109 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001110 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001111 }
1112 else
1113 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1114
1115 // Add the entry to NodeCache
1116 CacheEntry = NewNode;
1117
1118 // Rewrite the links in the new node to point into the current graph,
1119 // but only for links to external nodes. Set other links to NULL.
1120 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1121 DSNode* OldTarget = OldNode->getLink(j);
1122 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1123 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1124 if (NewNode->getLink(j))
1125 NewNode->getLink(j)->mergeWith(NewLink);
1126 else
1127 NewNode->setLink(j, NewLink);
1128 }
1129 }
1130
1131 // Remove all local markers
1132 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1133
1134 return NewNode;
1135}
1136
1137
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001138// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1139// links (and recursively their such links) into this graph.
1140//
1141void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1142 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001143 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001144
1145 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1146
1147 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001148 DSCallSite& callCopy = FunctionCalls.back();
1149 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001150 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001151 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001152 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1153 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1154 : 0);
1155 }
1156
1157 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001158 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001159}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001160#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001161
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001162#endif