blob: 77407ad47a957f49229393ae49f852962a8cae5d [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
23namespace DS {
24 const unsigned PointerShift = 3; // 64bit ptrs = 3, 32 bit ptrs = 2
25 const unsigned PointerSize = 1 << PointerShift;
26};
27
Chris Lattner92673292002-11-02 00:13:20 +000028namespace DataStructureAnalysis { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000029 // isPointerType - Return true if this first class type is big enough to hold
30 // a pointer.
31 //
32 bool isPointerType(const Type *Ty);
33 extern TargetData TD;
34}
35using namespace DataStructureAnalysis;
36
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000037//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000038// DSNode Implementation
39//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000040
Chris Lattner08db7192002-11-06 06:20:27 +000041DSNode::DSNode(enum NodeTy NT, const Type *T)
42 : Ty(Type::VoidTy), Size(0), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000043 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000044 if (T) mergeTypeInfo(T, 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000045}
46
Chris Lattner0d9bab82002-07-18 00:12:30 +000047// DSNode copy constructor... do not copy over the referrers list!
48DSNode::DSNode(const DSNode &N)
Chris Lattner08db7192002-11-06 06:20:27 +000049 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
50 NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000051}
52
Chris Lattnerc68c31b2002-07-10 22:38:08 +000053void DSNode::removeReferrer(DSNodeHandle *H) {
54 // Search backwards, because we depopulate the list from the back for
55 // efficiency (because it's a vector).
Chris Lattnere2219762002-07-18 18:22:40 +000056 vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000057 std::find(Referrers.rbegin(), Referrers.rend(), H);
58 assert(I != Referrers.rend() && "Referrer not pointing to node!");
59 Referrers.erase(I.base()-1);
60}
61
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000062// addGlobal - Add an entry for a global value to the Globals list. This also
63// marks the node with the 'G' flag if it does not already have it.
64//
65void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000066 // Keep the list sorted.
Chris Lattnere2219762002-07-18 18:22:40 +000067 vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000068 std::lower_bound(Globals.begin(), Globals.end(), GV);
69
70 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000071 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000072 Globals.insert(I, GV);
73 NodeType |= GlobalNode;
74 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000075}
76
Chris Lattner8f0a16e2002-10-31 05:45:02 +000077/// foldNodeCompletely - If we determine that this node has some funny
78/// behavior happening to it that we cannot represent, we fold it down to a
79/// single, completely pessimistic, node. This node is represented as a
80/// single byte with a single TypeEntry of "void".
81///
82void DSNode::foldNodeCompletely() {
Chris Lattner08db7192002-11-06 06:20:27 +000083 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000084
Chris Lattner08db7192002-11-06 06:20:27 +000085 ++NumFolds;
86
87 // We are no longer typed at all...
88 Ty = DSTypeRec(Type::VoidTy, true);
89 Size = 1;
90
91 // Loop over all of our referrers, making them point to our zero bytes of
92 // space.
Chris Lattner8f0a16e2002-10-31 05:45:02 +000093 for (vector<DSNodeHandle*>::iterator I = Referrers.begin(), E=Referrers.end();
94 I != E; ++I)
95 (*I)->setOffset(0);
96
Chris Lattner8f0a16e2002-10-31 05:45:02 +000097 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000098 for (unsigned i = 1, e = Links.size(); i < e; ++i)
99 Links[0].mergeWith(Links[i]);
100 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000101}
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000102/// isNodeCompletelyFolded - Return true if this node has been completely
103/// folded down to something that can never be expanded, effectively losing
104/// all of the field sensitivity that may be present in the node.
105///
106bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner08db7192002-11-06 06:20:27 +0000107 return getSize() == 1 && Ty.Ty == Type::VoidTy && Ty.isArray;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000108}
109
110
Chris Lattner08db7192002-11-06 06:20:27 +0000111/// mergeTypeInfo - This method merges the specified type into the current node
112/// at the specified offset. This may update the current node's type record if
113/// this gives more information to the node, it may do nothing to the node if
114/// this information is already known, or it may merge the node completely (and
115/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000116///
Chris Lattner08db7192002-11-06 06:20:27 +0000117/// This method returns true if the node is completely folded, otherwise false.
118///
119bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
120 // Check to make sure the Size member is up-to-date. Size can be one of the
121 // following:
122 // Size = 0, Ty = Void: Nothing is known about this node.
123 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
124 // Size = 1, Ty = Void, Array = 1: The node is collapsed
125 // Otherwise, sizeof(Ty) = Size
126 //
127 assert(((Size == 0 && Ty.Ty == Type::VoidTy && !Ty.isArray) ||
128 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
129 (Size == 1 && Ty.Ty == Type::VoidTy && Ty.isArray) ||
130 (Size == 0 && !Ty.Ty->isSized() && !Ty.isArray) ||
131 (TD.getTypeSize(Ty.Ty) == Size)) &&
132 "Size member of DSNode doesn't match the type structure!");
133 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000134
Chris Lattner08db7192002-11-06 06:20:27 +0000135 if (Offset == 0 && NewTy == Ty.Ty)
136 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000137
Chris Lattner08db7192002-11-06 06:20:27 +0000138 // Return true immediately if the node is completely folded.
139 if (isNodeCompletelyFolded()) return true;
140
141 // Figure out how big the new type we're merging in is...
142 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
143
144 // Otherwise check to see if we can fold this type into the current node. If
145 // we can't, we fold the node completely, if we can, we potentially update our
146 // internal state.
147 //
148 if (Ty.Ty == Type::VoidTy) {
149 // If this is the first type that this node has seen, just accept it without
150 // question....
151 assert(Offset == 0 && "Cannot have an offset into a void node!");
152 assert(Ty.isArray == false && "This shouldn't happen!");
153 Ty.Ty = NewTy;
154 Size = NewTySize;
155
156 // Calculate the number of outgoing links from this node.
157 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
158 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000159 }
Chris Lattner08db7192002-11-06 06:20:27 +0000160
161 // Handle node expansion case here...
162 if (Offset+NewTySize > Size) {
163 // It is illegal to grow this node if we have treated it as an array of
164 // objects...
165 if (Ty.isArray) {
166 foldNodeCompletely();
167 return true;
168 }
169
170 if (Offset) { // We could handle this case, but we don't for now...
171 std::cerr << "UNIMP: Trying to merge a growth type into offset != 0: "
172 << "Collapsing!\n";
173 foldNodeCompletely();
174 return true;
175 }
176
177 // Okay, the situation is nice and simple, we are trying to merge a type in
178 // at offset 0 that is bigger than our current type. Implement this by
179 // switching to the new type and then merge in the smaller one, which should
180 // hit the other code path here. If the other code path decides it's not
181 // ok, it will collapse the node as appropriate.
182 //
183 const Type *OldTy = Ty.Ty;
184 Ty.Ty = NewTy;
185 Size = NewTySize;
186
187 // Must grow links to be the appropriate size...
188 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
189
190 // Merge in the old type now... which is guaranteed to be smaller than the
191 // "current" type.
192 return mergeTypeInfo(OldTy, 0);
193 }
194
195 assert(Offset < Size &&
196 "Cannot merge something into a part of our type that doesn't exist!");
197
198 // Find the section of Ty.Ty that NewTy overlaps with... first we find the
199 // type that starts at offset Offset.
200 //
201 unsigned O = 0;
202 const Type *SubType = Ty.Ty;
203 while (O < Offset) {
204 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
205
206 switch (SubType->getPrimitiveID()) {
207 case Type::StructTyID: {
208 const StructType *STy = cast<StructType>(SubType);
209 const StructLayout &SL = *TD.getStructLayout(STy);
210
211 unsigned i = 0, e = SL.MemberOffsets.size();
212 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
213 /* empty */;
214
215 // The offset we are looking for must be in the i'th element...
216 SubType = STy->getElementTypes()[i];
217 O += SL.MemberOffsets[i];
218 break;
219 }
220 case Type::ArrayTyID: {
221 SubType = cast<ArrayType>(SubType)->getElementType();
222 unsigned ElSize = TD.getTypeSize(SubType);
223 unsigned Remainder = (Offset-O) % ElSize;
224 O = Offset-Remainder;
225 break;
226 }
227 default:
228 assert(0 && "Unknown type!");
229 }
230 }
231
232 assert(O == Offset && "Could not achieve the correct offset!");
233
234 // If we found our type exactly, early exit
235 if (SubType == NewTy) return false;
236
237 // Okay, so we found the leader type at the offset requested. Search the list
238 // of types that starts at this offset. If SubType is currently an array or
239 // structure, the type desired may actually be the first element of the
240 // composite type...
241 //
242 unsigned SubTypeSize = TD.getTypeSize(SubType);
243 while (SubType != NewTy) {
244 const Type *NextSubType = 0;
245 unsigned NextSubTypeSize;
246 switch (SubType->getPrimitiveID()) {
247 case Type::StructTyID:
248 NextSubType = cast<StructType>(SubType)->getElementTypes()[0];
249 NextSubTypeSize = TD.getTypeSize(SubType);
250 break;
251 case Type::ArrayTyID:
252 NextSubType = cast<ArrayType>(SubType)->getElementType();
253 NextSubTypeSize = TD.getTypeSize(SubType);
254 break;
255 default: ;
256 // fall out
257 }
258
259 if (NextSubType == 0)
260 break; // In the default case, break out of the loop
261
262 if (NextSubTypeSize < NewTySize)
263 break; // Don't allow shrinking to a smaller type than NewTySize
264 SubType = NextSubType;
265 SubTypeSize = NextSubTypeSize;
266 }
267
268 // If we found the type exactly, return it...
269 if (SubType == NewTy)
270 return false;
271
272 // Check to see if we have a compatible, but different type...
273 if (NewTySize == SubTypeSize) {
274 // Check to see if this type is obviously convertable... int -> uint f.e.
275 if (NewTy->isLosslesslyConvertableTo(SubType))
276 return false;
277
278 // Check to see if we have a pointer & integer mismatch going on here,
279 // loading a pointer as a long, for example.
280 //
281 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
282 NewTy->isInteger() && isa<PointerType>(SubType))
283 return false;
284
285 }
286
287
288
289 std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty.Ty
290 << "\n due to:" << NewTy << " @ " << Offset << "!\n";
291 std::cerr << "SubType: " << SubType << "\n\n";
292
293 foldNodeCompletely();
294 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000295}
296
Chris Lattner08db7192002-11-06 06:20:27 +0000297
298
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000299// addEdgeTo - Add an edge from the current node to the specified node. This
300// can cause merging of nodes in the graph.
301//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000302void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000303 if (NH.getNode() == 0) return; // Nothing to do
304
Chris Lattner08db7192002-11-06 06:20:27 +0000305 DSNodeHandle &ExistingEdge = getLink(Offset);
306 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000307 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000308 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000309 } else { // No merging to perform...
310 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000311 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000312}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000313
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000314
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000315// MergeSortedVectors - Efficiently merge a vector into another vector where
316// duplicates are not allowed and both are sorted. This assumes that 'T's are
317// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000318//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000319template<typename T>
320void MergeSortedVectors(vector<T> &Dest, const vector<T> &Src) {
321 // By far, the most common cases will be the simple ones. In these cases,
322 // avoid having to allocate a temporary vector...
323 //
324 if (Src.empty()) { // Nothing to merge in...
325 return;
326 } else if (Dest.empty()) { // Just copy the result in...
327 Dest = Src;
328 } else if (Src.size() == 1) { // Insert a single element...
329 const T &V = Src[0];
330 typename vector<T>::iterator I =
331 std::lower_bound(Dest.begin(), Dest.end(), V);
332 if (I == Dest.end() || *I != Src[0]) // If not already contained...
333 Dest.insert(I, Src[0]);
334 } else if (Dest.size() == 1) {
335 T Tmp = Dest[0]; // Save value in temporary...
336 Dest = Src; // Copy over list...
337 typename vector<T>::iterator I =
338 std::lower_bound(Dest.begin(), Dest.end(),Tmp);
339 if (I == Dest.end() || *I != Src[0]) // If not already contained...
340 Dest.insert(I, Src[0]);
341
342 } else {
343 // Make a copy to the side of Dest...
344 vector<T> Old(Dest);
345
346 // Make space for all of the type entries now...
347 Dest.resize(Dest.size()+Src.size());
348
349 // Merge the two sorted ranges together... into Dest.
350 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
351
352 // Now erase any duplicate entries that may have accumulated into the
353 // vectors (because they were in both of the input sets)
354 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
355 }
356}
357
358
359// mergeWith - Merge this node and the specified node, moving all links to and
360// from the argument node into the current node, deleting the node argument.
361// Offset indicates what offset the specified node is to be merged into the
362// current node.
363//
364// The specified node may be a null pointer (in which case, nothing happens).
365//
366void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
367 DSNode *N = NH.getNode();
368 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000369 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000370
Chris Lattner02606632002-11-04 06:48:26 +0000371 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000372 // We cannot merge two pieces of the same node together, collapse the node
373 // completely.
374 std::cerr << "Attempting to merge two chunks of the same node together!\n";
375 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000376 return;
377 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000378
Chris Lattner08db7192002-11-06 06:20:27 +0000379 // Merge the type entries of the two nodes together...
380 if (N->Ty.Ty != Type::VoidTy)
381 mergeTypeInfo(N->Ty.Ty, Offset);
382
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000383 // If we are merging a node with a completely folded node, then both nodes are
384 // now completely folded.
385 //
386 if (isNodeCompletelyFolded()) {
Chris Lattner02606632002-11-04 06:48:26 +0000387 if (!N->isNodeCompletelyFolded())
388 N->foldNodeCompletely();
389 } else if (N->isNodeCompletelyFolded()) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000390 foldNodeCompletely();
391 Offset = 0;
392 }
Chris Lattner02606632002-11-04 06:48:26 +0000393 N = NH.getNode();
394
395 if (this == N) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000396
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000397 // If both nodes are not at offset 0, make sure that we are merging the node
398 // at an later offset into the node with the zero offset.
399 //
400 if (Offset > NH.getOffset()) {
401 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
402 return;
Chris Lattner9b87c5c2002-10-31 22:41:15 +0000403 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
404 // If the offsets are the same, merge the smaller node into the bigger node
405 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
406 return;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000407 }
408
409#if 0
410 std::cerr << "\n\nMerging:\n";
411 N->print(std::cerr, 0);
412 std::cerr << " and:\n";
413 print(std::cerr, 0);
414#endif
415
416 // Now we know that Offset <= NH.Offset, so convert it so our "Offset" (with
417 // respect to NH.Offset) is now zero.
418 //
419 unsigned NOffset = NH.getOffset()-Offset;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000420 unsigned NSize = N->getSize();
Chris Lattner7b7200c2002-10-02 04:57:39 +0000421
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000422 // Remove all edges pointing at N, causing them to point to 'this' instead.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000423 // Make sure to adjust their offset, not just the node pointer.
424 //
425 while (!N->Referrers.empty()) {
426 DSNodeHandle &Ref = *N->Referrers.back();
427 Ref = DSNodeHandle(this, NOffset+Ref.getOffset());
428 }
Chris Lattner59535132002-11-05 00:01:58 +0000429
430 // Make all of the outgoing links of N now be outgoing links of this. This
431 // can cause recursive merging!
432 //
Chris Lattner08db7192002-11-06 06:20:27 +0000433 for (unsigned i = 0; i < NSize; i += DS::PointerSize) {
434 DSNodeHandle &Link = N->getLink(i);
435 if (Link.getNode()) {
436 addEdgeTo((i+NOffset) % getSize(), Link);
Chris Lattner59535132002-11-05 00:01:58 +0000437
Chris Lattner08db7192002-11-06 06:20:27 +0000438 // It's possible that after adding the new edge that some recursive
439 // merging just occured, causing THIS node to get merged into oblivion.
440 // If that happens, we must not try to merge any more edges into it!
Chris Lattner7b7200c2002-10-02 04:57:39 +0000441 //
Chris Lattner08db7192002-11-06 06:20:27 +0000442 if (Size == 0) return;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000443 }
444 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000445
446 // Now that there are no outgoing edges, all of the Links are dead.
447 N->Links.clear();
Chris Lattner08db7192002-11-06 06:20:27 +0000448 N->Size = 0;
449 N->Ty.Ty = Type::VoidTy;
450 N->Ty.isArray = false;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000451
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000452 // Merge the node types
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000453 NodeType |= N->NodeType;
454 N->NodeType = 0; // N is now a dead node.
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000455
456 // Merge the globals list...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000457 if (!N->Globals.empty()) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000458 MergeSortedVectors(Globals, N->Globals);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000459
460 // Delete the globals from the old node...
461 N->Globals.clear();
462 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000463}
464
Chris Lattner9de906c2002-10-20 22:11:44 +0000465//===----------------------------------------------------------------------===//
466// DSCallSite Implementation
467//===----------------------------------------------------------------------===//
468
Vikram S. Adve26b98262002-10-20 21:41:02 +0000469// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000470Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000471 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000472}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000473
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000474
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000475//===----------------------------------------------------------------------===//
476// DSGraph Implementation
477//===----------------------------------------------------------------------===//
478
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000479DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
480 std::map<const DSNode*, DSNode*> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000481 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000482}
483
Chris Lattnereff0da92002-10-21 15:32:34 +0000484DSGraph::DSGraph(const DSGraph &G, std::map<const DSNode*, DSNode*> &NodeMap)
485 : Func(G.Func) {
Chris Lattnerc875f022002-11-03 21:27:48 +0000486 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000487}
488
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000489DSGraph::~DSGraph() {
490 FunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000491 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000492 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000493
494#ifndef NDEBUG
495 // Drop all intra-node references, so that assertions don't fail...
496 std::for_each(Nodes.begin(), Nodes.end(),
497 std::mem_fun(&DSNode::dropAllReferences));
498#endif
499
500 // Delete all of the nodes themselves...
501 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
502}
503
Chris Lattner0d9bab82002-07-18 00:12:30 +0000504// dump - Allow inspection of graph in a debugger.
505void DSGraph::dump() const { print(std::cerr); }
506
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000507
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000508// Helper function used to clone a function list.
509//
510static void CopyFunctionCallsList(const vector<DSCallSite>& fromCalls,
511 vector<DSCallSite> &toCalls,
512 std::map<const DSNode*, DSNode*> &NodeMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000513 unsigned FC = toCalls.size(); // FirstCall
514 toCalls.reserve(FC+fromCalls.size());
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000515 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i)
Chris Lattner99a22842002-10-21 15:04:18 +0000516 toCalls.push_back(DSCallSite(fromCalls[i], NodeMap));
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000517}
518
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000519/// remapLinks - Change all of the Links in the current node according to the
520/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000521///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000522void DSNode::remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap) {
523 for (unsigned i = 0, e = Links.size(); i != e; ++i)
524 Links[i].setNode(OldNodeMap[Links[i].getNode()]);
525}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000526
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000527
Chris Lattner0d9bab82002-07-18 00:12:30 +0000528// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000529// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000530// filled into the OldValMap member. If StripAllocas is set to true, Alloca
531// markers are removed from the graph, as the graph is being cloned into a
532// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000533//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000534DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
535 std::map<Value*, DSNodeHandle> &OldValMap,
536 std::map<const DSNode*, DSNode*> &OldNodeMap,
Chris Lattner92673292002-11-02 00:13:20 +0000537 bool StripAllocas) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000538 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000539
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000540 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000541
542 // Duplicate all of the nodes, populating the node map...
543 Nodes.reserve(FN+G.Nodes.size());
544 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000545 DSNode *Old = G.Nodes[i];
546 DSNode *New = new DSNode(*Old);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000547 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000548 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000549 }
550
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000551 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000552 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000553 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000554
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000555 // Remove local markers as specified
Chris Lattner92673292002-11-02 00:13:20 +0000556 unsigned char StripBits = StripAllocas ? DSNode::AllocaNode : 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000557 if (StripBits)
Chris Lattner0d9bab82002-07-18 00:12:30 +0000558 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000559 Nodes[i]->NodeType &= ~StripBits;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000560
Chris Lattnercf15db32002-10-17 20:09:52 +0000561 // Copy the value map... and merge all of the global nodes...
Chris Lattnerc875f022002-11-03 21:27:48 +0000562 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
563 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000564 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner92673292002-11-02 00:13:20 +0000565 H.setNode(OldNodeMap[I->second.getNode()]);
566 H.setOffset(I->second.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000567
568 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattnerc875f022002-11-03 21:27:48 +0000569 std::map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
570 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000571 GVI->second.mergeWith(H);
572 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000573 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000574 }
575 }
576 }
Chris Lattnere2219762002-07-18 18:22:40 +0000577 // Copy the function calls list...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000578 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000579
Chris Lattnercf15db32002-10-17 20:09:52 +0000580
Chris Lattner0d9bab82002-07-18 00:12:30 +0000581 // Return the returned node pointer...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000582 return DSNodeHandle(OldNodeMap[G.RetNode.getNode()], G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000583}
584
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000585#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000586// cloneGlobalInto - Clone the given global node and all its target links
587// (and all their llinks, recursively).
588//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000589DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000590 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
591
592 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000593 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000594 if (ValMapEntry != 0)
595 return ValMapEntry;
596
597 // Clone the node and update the ValMap.
598 DSNode* NewNode = new DSNode(*GNode);
599 ValMapEntry = NewNode; // j=0 case of loop below!
600 Nodes.push_back(NewNode);
601 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000602 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000603
604 // Rewrite the links in the new node to point into the current graph.
605 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
606 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
607
608 return NewNode;
609}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000610#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000611
612
Chris Lattner0d9bab82002-07-18 00:12:30 +0000613// markIncompleteNodes - Mark the specified node as having contents that are not
614// known with the current analysis we have performed. Because a node makes all
615// of the nodes it can reach imcomplete if the node itself is incomplete, we
616// must recursively traverse the data structure graph, marking all reachable
617// nodes as incomplete.
618//
619static void markIncompleteNode(DSNode *N) {
620 // Stop recursion if no node, or if node already marked...
621 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
622
623 // Actually mark the node
624 N->NodeType |= DSNode::Incomplete;
625
626 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000627 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
628 if (DSNode *DSN = N->getLink(i).getNode())
629 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000630}
631
632
633// markIncompleteNodes - Traverse the graph, identifying nodes that may be
634// modified by other functions that have not been resolved yet. This marks
635// nodes that are reachable through three sources of "unknownness":
636//
637// Global Variables, Function Calls, and Incoming Arguments
638//
639// For any node that may have unknown components (because something outside the
640// scope of current analysis may have modified it), the 'Incomplete' flag is
641// added to the NodeType.
642//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000643void DSGraph::markIncompleteNodes(bool markFormalArgs) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000644 // Mark any incoming arguments as incomplete...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000645 if (markFormalArgs && Func)
646 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000647 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
648 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000649
650 // Mark stuff passed into functions calls as being incomplete...
651 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
Vikram S. Adve26b98262002-10-20 21:41:02 +0000652 DSCallSite &Call = FunctionCalls[i];
Chris Lattnere2219762002-07-18 18:22:40 +0000653 // Then the return value is certainly incomplete!
Chris Lattner0969c502002-10-21 02:08:03 +0000654 markIncompleteNode(Call.getRetVal().getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000655
Chris Lattner92673292002-11-02 00:13:20 +0000656 // All objects pointed to by function arguments are incomplete though!
Vikram S. Adve26b98262002-10-20 21:41:02 +0000657 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
Chris Lattner0969c502002-10-21 02:08:03 +0000658 markIncompleteNode(Call.getPtrArg(i).getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000659 }
660
Chris Lattner92673292002-11-02 00:13:20 +0000661 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000662 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000663 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000664 DSNode *N = Nodes[i];
Chris Lattner92673292002-11-02 00:13:20 +0000665 // FIXME: Make more efficient by looking over Links directly
Chris Lattner08db7192002-11-06 06:20:27 +0000666 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
667 if (DSNode *DSN = N->getLink(i).getNode())
668 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000669 }
670}
671
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000672// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000673// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000674static void removeRefsToGlobal(DSNode* N,
Chris Lattnerc875f022002-11-03 21:27:48 +0000675 std::map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000676 while (!N->getGlobals().empty()) {
677 GlobalValue *GV = N->getGlobals().back();
678 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000679 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000680 }
681}
682
683
Chris Lattner0d9bab82002-07-18 00:12:30 +0000684// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
685// checks to see if there are simple transformations that it can do to make it
686// dead.
687//
688bool DSGraph::isNodeDead(DSNode *N) {
689 // Is it a trivially dead shadow node...
690 if (N->getReferrers().empty() && N->NodeType == 0)
691 return true;
692
693 // Is it a function node or some other trivially unused global?
Chris Lattner92673292002-11-02 00:13:20 +0000694 if ((N->NodeType & ~DSNode::GlobalNode) == 0 && N->getSize() == 0 &&
Chris Lattner0d9bab82002-07-18 00:12:30 +0000695 N->getReferrers().size() == N->getGlobals().size()) {
696
Chris Lattnerc875f022002-11-03 21:27:48 +0000697 // Remove the globals from the ScalarMap, so that the referrer count will go
Chris Lattner0d9bab82002-07-18 00:12:30 +0000698 // down to zero.
Chris Lattnerc875f022002-11-03 21:27:48 +0000699 removeRefsToGlobal(N, ScalarMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000700 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
701 return true;
702 }
703
704 return false;
705}
706
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000707static void removeIdenticalCalls(vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000708 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000709 // Remove trivially identical function calls
710 unsigned NumFns = Calls.size();
711 std::sort(Calls.begin(), Calls.end());
712 Calls.erase(std::unique(Calls.begin(), Calls.end()),
713 Calls.end());
714
715 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000716 std::cerr << "Merged " << (NumFns-Calls.size())
717 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000718}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000719
Chris Lattnere2219762002-07-18 18:22:40 +0000720// removeTriviallyDeadNodes - After the graph has been constructed, this method
721// removes all unreachable nodes that are created because they got merged with
722// other nodes in the graph. These nodes will all be trivially unreachable, so
723// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000724//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000725void DSGraph::removeTriviallyDeadNodes(bool KeepAllGlobals) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000726 for (unsigned i = 0; i != Nodes.size(); ++i)
Chris Lattnera00397e2002-10-03 21:55:28 +0000727 if (!KeepAllGlobals || !(Nodes[i]->NodeType & DSNode::GlobalNode))
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000728 if (isNodeDead(Nodes[i])) { // This node is dead!
729 delete Nodes[i]; // Free memory...
730 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
731 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000732
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000733 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000734}
735
736
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000737// markAlive - Simple graph walker that recursively traverses the graph, marking
Chris Lattnere2219762002-07-18 18:22:40 +0000738// stuff to be alive.
739//
740static void markAlive(DSNode *N, std::set<DSNode*> &Alive) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000741 if (N == 0) return;
Chris Lattnere2219762002-07-18 18:22:40 +0000742
743 Alive.insert(N);
Chris Lattner08db7192002-11-06 06:20:27 +0000744 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
745 if (DSNode *DSN = N->getLink(i).getNode())
746 if (!Alive.count(DSN))
747 markAlive(DSN, Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000748}
749
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000750static bool checkGlobalAlive(DSNode *N, std::set<DSNode*> &Alive,
751 std::set<DSNode*> &Visiting) {
752 if (N == 0) return false;
753
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000754 if (Visiting.count(N)) return false; // terminate recursion on a cycle
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000755 Visiting.insert(N);
756
757 // If any immediate successor is alive, N is alive
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 if (Alive.count(DSN)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000761 Visiting.erase(N);
762 return true;
763 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000764
765 // Else if any successor reaches a live node, N is alive
Chris Lattner08db7192002-11-06 06:20:27 +0000766 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
767 if (DSNode *DSN = N->getLink(i).getNode())
768 if (checkGlobalAlive(DSN, Alive, Visiting)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000769 Visiting.erase(N); return true;
770 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000771
772 Visiting.erase(N);
773 return false;
774}
775
776
777// markGlobalsIteration - Recursive helper function for markGlobalsAlive().
778// This would be unnecessary if function calls were real nodes! In that case,
779// the simple iterative loop in the first few lines below suffice.
780//
781static void markGlobalsIteration(std::set<DSNode*>& GlobalNodes,
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000782 vector<DSCallSite> &Calls,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000783 std::set<DSNode*> &Alive,
784 bool FilterCalls) {
785
786 // Iterate, marking globals or cast nodes alive until no new live nodes
787 // are added to Alive
788 std::set<DSNode*> Visiting; // Used to identify cycles
Chris Lattner0969c502002-10-21 02:08:03 +0000789 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000790 for (size_t liveCount = 0; liveCount < Alive.size(); ) {
791 liveCount = Alive.size();
792 for ( ; I != E; ++I)
793 if (Alive.count(*I) == 0) {
794 Visiting.clear();
795 if (checkGlobalAlive(*I, Alive, Visiting))
796 markAlive(*I, Alive);
797 }
798 }
799
800 // Find function calls with some dead and some live nodes.
801 // Since all call nodes must be live if any one is live, we have to mark
802 // all nodes of the call as live and continue the iteration (via recursion).
803 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000804 bool Recurse = false;
805 for (unsigned i = 0, ei = Calls.size(); i < ei; ++i) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000806 bool CallIsDead = true, CallHasDeadArg = false;
Chris Lattner0969c502002-10-21 02:08:03 +0000807 DSCallSite &CS = Calls[i];
808 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
809 if (DSNode *N = CS.getPtrArg(j).getNode()) {
810 bool ArgIsDead = !Alive.count(N);
811 CallHasDeadArg |= ArgIsDead;
812 CallIsDead &= ArgIsDead;
813 }
814
815 if (DSNode *N = CS.getRetVal().getNode()) {
816 bool RetIsDead = !Alive.count(N);
817 CallHasDeadArg |= RetIsDead;
818 CallIsDead &= RetIsDead;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000819 }
Chris Lattner0969c502002-10-21 02:08:03 +0000820
821 DSNode *N = CS.getCallee().getNode();
822 bool FnIsDead = !Alive.count(N);
823 CallHasDeadArg |= FnIsDead;
824 CallIsDead &= FnIsDead;
825
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000826 if (!CallIsDead && CallHasDeadArg) {
827 // Some node in this call is live and another is dead.
828 // Mark all nodes of call as live and iterate once more.
Chris Lattner0969c502002-10-21 02:08:03 +0000829 Recurse = true;
830 for (unsigned j = 0, ej = CS.getNumPtrArgs(); j != ej; ++j)
831 markAlive(CS.getPtrArg(j).getNode(), Alive);
832 markAlive(CS.getRetVal().getNode(), Alive);
833 markAlive(CS.getCallee().getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000834 }
835 }
Chris Lattner0969c502002-10-21 02:08:03 +0000836 if (Recurse)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000837 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
838 }
839}
840
841
842// markGlobalsAlive - Mark global nodes and cast nodes alive if they
843// can reach any other live node. Since this can produce new live nodes,
844// we use a simple iterative algorithm.
845//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000846static void markGlobalsAlive(DSGraph &G, std::set<DSNode*> &Alive,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000847 bool FilterCalls) {
848 // Add global and cast nodes to a set so we don't walk all nodes every time
849 std::set<DSNode*> GlobalNodes;
850 for (unsigned i = 0, e = G.getNodes().size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000851 if (G.getNodes()[i]->NodeType & DSNode::GlobalNode)
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000852 GlobalNodes.insert(G.getNodes()[i]);
853
854 // Add all call nodes to the same set
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000855 vector<DSCallSite> &Calls = G.getFunctionCalls();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000856 if (FilterCalls) {
Chris Lattner0969c502002-10-21 02:08:03 +0000857 for (unsigned i = 0, e = Calls.size(); i != e; ++i) {
858 for (unsigned j = 0, e = Calls[i].getNumPtrArgs(); j != e; ++j)
859 if (DSNode *N = Calls[i].getPtrArg(j).getNode())
860 GlobalNodes.insert(N);
861 if (DSNode *N = Calls[i].getRetVal().getNode())
862 GlobalNodes.insert(N);
863 if (DSNode *N = Calls[i].getCallee().getNode())
864 GlobalNodes.insert(N);
865 }
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000866 }
867
868 // Iterate and recurse until no new live node are discovered.
869 // This would be a simple iterative loop if function calls were real nodes!
870 markGlobalsIteration(GlobalNodes, Calls, Alive, FilterCalls);
871
Chris Lattnerc875f022002-11-03 21:27:48 +0000872 // Free up references to dead globals from the ScalarMap
Chris Lattner92673292002-11-02 00:13:20 +0000873 std::set<DSNode*>::iterator I = GlobalNodes.begin(), E = GlobalNodes.end();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000874 for( ; I != E; ++I)
875 if (Alive.count(*I) == 0)
Chris Lattnerc875f022002-11-03 21:27:48 +0000876 removeRefsToGlobal(*I, G.getScalarMap());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000877
878 // Delete dead function calls
879 if (FilterCalls)
880 for (int ei = Calls.size(), i = ei-1; i >= 0; --i) {
881 bool CallIsDead = true;
Chris Lattner0969c502002-10-21 02:08:03 +0000882 for (unsigned j = 0, ej = Calls[i].getNumPtrArgs();
883 CallIsDead && j != ej; ++j)
884 CallIsDead = Alive.count(Calls[i].getPtrArg(j).getNode()) == 0;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000885 if (CallIsDead)
886 Calls.erase(Calls.begin() + i); // remove the call entirely
887 }
888}
Chris Lattnere2219762002-07-18 18:22:40 +0000889
890// removeDeadNodes - Use a more powerful reachability analysis to eliminate
891// subgraphs that are unreachable. This often occurs because the data
892// structure doesn't "escape" into it's caller, and thus should be eliminated
893// from the caller's graph entirely. This is only appropriate to use when
894// inlining graphs.
895//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000896void DSGraph::removeDeadNodes(bool KeepAllGlobals, bool KeepCalls) {
897 assert((!KeepAllGlobals || KeepCalls) &&
898 "KeepAllGlobals without KeepCalls is meaningless");
899
Chris Lattnere2219762002-07-18 18:22:40 +0000900 // Reduce the amount of work we have to do...
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000901 removeTriviallyDeadNodes(KeepAllGlobals);
902
Chris Lattnere2219762002-07-18 18:22:40 +0000903 // FIXME: Merge nontrivially identical call nodes...
904
905 // Alive - a set that holds all nodes found to be reachable/alive.
906 std::set<DSNode*> Alive;
907
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000908 // If KeepCalls, mark all nodes reachable by call nodes as alive...
909 if (KeepCalls)
Chris Lattner0969c502002-10-21 02:08:03 +0000910 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
911 for (unsigned j = 0, e = FunctionCalls[i].getNumPtrArgs(); j != e; ++j)
912 markAlive(FunctionCalls[i].getPtrArg(j).getNode(), Alive);
913 markAlive(FunctionCalls[i].getRetVal().getNode(), Alive);
914 markAlive(FunctionCalls[i].getCallee().getNode(), Alive);
915 }
Chris Lattnere2219762002-07-18 18:22:40 +0000916
Chris Lattner92673292002-11-02 00:13:20 +0000917 // Mark all nodes reachable by scalar nodes as alive...
Chris Lattnerc875f022002-11-03 21:27:48 +0000918 for (std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
919 E = ScalarMap.end(); I != E; ++I)
Chris Lattner92673292002-11-02 00:13:20 +0000920 markAlive(I->second.getNode(), Alive);
Chris Lattnere2219762002-07-18 18:22:40 +0000921
Chris Lattner92673292002-11-02 00:13:20 +0000922#if 0
923 // Marge all nodes reachable by global nodes, as alive. Isn't this covered by
Chris Lattnerc875f022002-11-03 21:27:48 +0000924 // the ScalarMap?
Chris Lattner92673292002-11-02 00:13:20 +0000925 //
926 if (KeepAllGlobals)
927 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
928 if (Nodes[i]->NodeType & DSNode::GlobalNode)
929 markAlive(Nodes[i], Alive);
930#endif
Chris Lattnere2219762002-07-18 18:22:40 +0000931
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000932 // The return value is alive as well...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000933 markAlive(RetNode.getNode(), Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000934
935 // Mark all globals or cast nodes that can reach a live node as alive.
936 // This also marks all nodes reachable from such nodes as alive.
937 // Of course, if KeepAllGlobals is specified, they would be live already.
Chris Lattner0969c502002-10-21 02:08:03 +0000938 if (!KeepAllGlobals)
Chris Lattner92673292002-11-02 00:13:20 +0000939 markGlobalsAlive(*this, Alive, !KeepCalls);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000940
Chris Lattnere2219762002-07-18 18:22:40 +0000941 // Loop over all unreachable nodes, dropping their references...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000942 vector<DSNode*> DeadNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000943 DeadNodes.reserve(Nodes.size()); // Only one allocation is allowed.
944 for (unsigned i = 0; i != Nodes.size(); ++i)
945 if (!Alive.count(Nodes[i])) {
946 DSNode *N = Nodes[i];
947 Nodes.erase(Nodes.begin()+i--); // Erase node from alive list.
948 DeadNodes.push_back(N); // Add node to our list of dead nodes
949 N->dropAllReferences(); // Drop all outgoing edges
950 }
951
Chris Lattnere2219762002-07-18 18:22:40 +0000952 // Delete all dead nodes...
953 std::for_each(DeadNodes.begin(), DeadNodes.end(), deleter<DSNode>);
954}
955
956
957
Chris Lattner0d9bab82002-07-18 00:12:30 +0000958// maskNodeTypes - Apply a mask to all of the node types in the graph. This
959// is useful for clearing out markers like Scalar or Incomplete.
960//
961void DSGraph::maskNodeTypes(unsigned char Mask) {
962 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
963 Nodes[i]->NodeType &= Mask;
964}
965
966
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000967#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000968//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000969// GlobalDSGraph Implementation
970//===----------------------------------------------------------------------===//
971
972GlobalDSGraph::GlobalDSGraph() : DSGraph(*(Function*)0, this) {
973}
974
975GlobalDSGraph::~GlobalDSGraph() {
976 assert(Referrers.size() == 0 &&
977 "Deleting global graph while references from other graphs exist");
978}
979
980void GlobalDSGraph::addReference(const DSGraph* referrer) {
981 if (referrer != this)
982 Referrers.insert(referrer);
983}
984
985void GlobalDSGraph::removeReference(const DSGraph* referrer) {
986 if (referrer != this) {
987 assert(Referrers.find(referrer) != Referrers.end() && "This is very bad!");
988 Referrers.erase(referrer);
989 if (Referrers.size() == 0)
990 delete this;
991 }
992}
993
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000994#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +0000995// Bits used in the next function
996static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
997
998
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000999// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1000// visible target links (and recursively their such links) into this graph.
1001// NodeCache maps the node being cloned to its clone in the Globals graph,
1002// in order to track cycles.
1003// GlobalsAreFinal is a flag that says whether it is safe to assume that
1004// an existing global node is complete. This is important to avoid
1005// reinserting all globals when inserting Calls to functions.
1006// This is a helper function for cloneGlobals and cloneCalls.
1007//
1008DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
1009 std::map<const DSNode*, DSNode*> &NodeCache,
1010 bool GlobalsAreFinal) {
1011 if (OldNode == 0) return 0;
1012
1013 // The caller should check this is an external node. Just more efficient...
1014 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1015
1016 // If a clone has already been created for OldNode, return it.
1017 DSNode*& CacheEntry = NodeCache[OldNode];
1018 if (CacheEntry != 0)
1019 return CacheEntry;
1020
1021 // The result value...
1022 DSNode* NewNode = 0;
1023
1024 // If nodes already exist for any of the globals of OldNode,
1025 // merge all such nodes together since they are merged in OldNode.
1026 // If ValueCacheIsFinal==true, look for an existing node that has
1027 // an identical list of globals and return it if it exists.
1028 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001029 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001030 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001031 if (NewNode == 0) {
1032 NewNode = PrevNode; // first existing node found
1033 if (GlobalsAreFinal && j == 0)
1034 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1035 CacheEntry = NewNode;
1036 return NewNode;
1037 }
1038 }
1039 else if (NewNode != PrevNode) { // found another, different from prev
1040 // update ValMap *before* merging PrevNode into NewNode
1041 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001042 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001043 NewNode->mergeWith(PrevNode);
1044 }
1045 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001046 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001047 }
1048
1049 // If no existing node was found, clone the node and update the ValMap.
1050 if (NewNode == 0) {
1051 NewNode = new DSNode(*OldNode);
1052 Nodes.push_back(NewNode);
1053 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1054 NewNode->setLink(j, 0);
1055 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001056 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001057 }
1058 else
1059 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1060
1061 // Add the entry to NodeCache
1062 CacheEntry = NewNode;
1063
1064 // Rewrite the links in the new node to point into the current graph,
1065 // but only for links to external nodes. Set other links to NULL.
1066 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1067 DSNode* OldTarget = OldNode->getLink(j);
1068 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1069 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1070 if (NewNode->getLink(j))
1071 NewNode->getLink(j)->mergeWith(NewLink);
1072 else
1073 NewNode->setLink(j, NewLink);
1074 }
1075 }
1076
1077 // Remove all local markers
1078 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1079
1080 return NewNode;
1081}
1082
1083
1084// GlobalDSGraph::cloneGlobals - Clone global nodes and all their externally
1085// visible target links (and recursively their such links) into this graph.
1086//
1087void GlobalDSGraph::cloneGlobals(DSGraph& Graph, bool CloneCalls) {
1088 std::map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001089#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001090 for (unsigned i = 0, N = Graph.Nodes.size(); i < N; ++i)
1091 if (Graph.Nodes[i]->NodeType & DSNode::GlobalNode)
1092 GlobalsGraph->cloneNodeInto(Graph.Nodes[i], NodeCache, false);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001093 if (CloneCalls)
1094 GlobalsGraph->cloneCalls(Graph);
1095
1096 GlobalsGraph->removeDeadNodes(/*KeepAllGlobals*/ true, /*KeepCalls*/ true);
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001097#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001098}
1099
1100
1101// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1102// links (and recursively their such links) into this graph.
1103//
1104void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
1105 std::map<const DSNode*, DSNode*> NodeCache;
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001106 vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001107
1108 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1109
1110 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001111 DSCallSite& callCopy = FunctionCalls.back();
1112 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001113 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001114 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001115 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1116 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1117 : 0);
1118 }
1119
1120 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001121 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001122}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001123#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001124
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001125#endif