blob: c5e81a71a916c74ddf81c5b6b8df4a84f3c28ccd [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 Lattner18552922002-11-18 21:44:46 +000014#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000015#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000016
Chris Lattner08db7192002-11-06 06:20:27 +000017namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000018 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
19 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000020};
21
Chris Lattnerb1060432002-11-07 05:20:53 +000022namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023 extern TargetData TD;
24}
Chris Lattnerb1060432002-11-07 05:20:53 +000025using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000026
Chris Lattner731b2d72003-02-13 19:09:00 +000027DSNode *DSNodeHandle::HandleForwarding() const {
28 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
29
30 // Handle node forwarding here!
31 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
32 Offset += N->ForwardNH.getOffset();
33
34 if (--N->NumReferrers == 0) {
35 // Removing the last referrer to the node, sever the forwarding link
36 N->stopForwarding();
37 }
38
39 N = Next;
40 N->NumReferrers++;
41 if (N->Size <= Offset) {
42 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
43 Offset = 0;
44 }
45 return N;
46}
47
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000048//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000049// DSNode Implementation
50//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000051
Chris Lattnerbd92b732003-06-19 21:15:11 +000052DSNode::DSNode(const Type *T, DSGraph *G)
53 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000054 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000055 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000056 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000057}
58
Chris Lattner0d9bab82002-07-18 00:12:30 +000059// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000060DSNode::DSNode(const DSNode &N, DSGraph *G)
61 : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
62 Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
63 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000064}
65
Chris Lattner72d29a42003-02-11 23:11:51 +000066void DSNode::assertOK() const {
67 assert((Ty != Type::VoidTy ||
68 Ty == Type::VoidTy && (Size == 0 ||
69 (NodeType & DSNode::Array))) &&
70 "Node not OK!");
71}
72
73/// forwardNode - Mark this node as being obsolete, and all references to it
74/// should be forwarded to the specified node and offset.
75///
76void DSNode::forwardNode(DSNode *To, unsigned Offset) {
77 assert(this != To && "Cannot forward a node to itself!");
78 assert(ForwardNH.isNull() && "Already forwarding from this node!");
79 if (To->Size <= 1) Offset = 0;
80 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
81 "Forwarded offset is wrong!");
82 ForwardNH.setNode(To);
83 ForwardNH.setOffset(Offset);
84 NodeType = DEAD;
85 Size = 0;
86 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000087}
88
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000089// addGlobal - Add an entry for a global value to the Globals list. This also
90// marks the node with the 'G' flag if it does not already have it.
91//
92void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000093 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000094 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000095 std::lower_bound(Globals.begin(), Globals.end(), GV);
96
97 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000098 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000099 Globals.insert(I, GV);
100 NodeType |= GlobalNode;
101 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000102}
103
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000104/// foldNodeCompletely - If we determine that this node has some funny
105/// behavior happening to it that we cannot represent, we fold it down to a
106/// single, completely pessimistic, node. This node is represented as a
107/// single byte with a single TypeEntry of "void".
108///
109void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000110 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000111
Chris Lattner08db7192002-11-06 06:20:27 +0000112 ++NumFolds;
113
Chris Lattner72d29a42003-02-11 23:11:51 +0000114 // Create the node we are going to forward to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000115 DSNode *DestNode = new DSNode(0, ParentGraph);
116 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000117 DestNode->Ty = Type::VoidTy;
118 DestNode->Size = 1;
119 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000120
Chris Lattner72d29a42003-02-11 23:11:51 +0000121 // Start forwarding to the destination node...
122 forwardNode(DestNode, 0);
123
124 if (Links.size()) {
125 DestNode->Links.push_back(Links[0]);
126 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000127
Chris Lattner72d29a42003-02-11 23:11:51 +0000128 // If we have links, merge all of our outgoing links together...
129 for (unsigned i = Links.size()-1; i != 0; --i)
130 NH.getNode()->Links[0].mergeWith(Links[i]);
131 Links.clear();
132 } else {
133 DestNode->Links.resize(1);
134 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000135}
Chris Lattner076c1f92002-11-07 06:31:54 +0000136
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000137/// isNodeCompletelyFolded - Return true if this node has been completely
138/// folded down to something that can never be expanded, effectively losing
139/// all of the field sensitivity that may be present in the node.
140///
141bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000142 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000143}
144
145
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000146namespace {
147 /// TypeElementWalker Class - Used for implementation of physical subtyping...
148 ///
149 class TypeElementWalker {
150 struct StackState {
151 const Type *Ty;
152 unsigned Offset;
153 unsigned Idx;
154 StackState(const Type *T, unsigned Off = 0)
155 : Ty(T), Offset(Off), Idx(0) {}
156 };
157
158 std::vector<StackState> Stack;
159 public:
160 TypeElementWalker(const Type *T) {
161 Stack.push_back(T);
162 StepToLeaf();
163 }
164
165 bool isDone() const { return Stack.empty(); }
166 const Type *getCurrentType() const { return Stack.back().Ty; }
167 unsigned getCurrentOffset() const { return Stack.back().Offset; }
168
169 void StepToNextType() {
170 PopStackAndAdvance();
171 StepToLeaf();
172 }
173
174 private:
175 /// PopStackAndAdvance - Pop the current element off of the stack and
176 /// advance the underlying element to the next contained member.
177 void PopStackAndAdvance() {
178 assert(!Stack.empty() && "Cannot pop an empty stack!");
179 Stack.pop_back();
180 while (!Stack.empty()) {
181 StackState &SS = Stack.back();
182 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
183 ++SS.Idx;
184 if (SS.Idx != ST->getElementTypes().size()) {
185 const StructLayout *SL = TD.getStructLayout(ST);
186 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
187 return;
188 }
189 Stack.pop_back(); // At the end of the structure
190 } else {
191 const ArrayType *AT = cast<ArrayType>(SS.Ty);
192 ++SS.Idx;
193 if (SS.Idx != AT->getNumElements()) {
194 SS.Offset += TD.getTypeSize(AT->getElementType());
195 return;
196 }
197 Stack.pop_back(); // At the end of the array
198 }
199 }
200 }
201
202 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
203 /// on the type stack.
204 void StepToLeaf() {
205 if (Stack.empty()) return;
206 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
207 StackState &SS = Stack.back();
208 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
209 if (ST->getElementTypes().empty()) {
210 assert(SS.Idx == 0);
211 PopStackAndAdvance();
212 } else {
213 // Step into the structure...
214 assert(SS.Idx < ST->getElementTypes().size());
215 const StructLayout *SL = TD.getStructLayout(ST);
216 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
217 SS.Offset+SL->MemberOffsets[SS.Idx]));
218 }
219 } else {
220 const ArrayType *AT = cast<ArrayType>(SS.Ty);
221 if (AT->getNumElements() == 0) {
222 assert(SS.Idx == 0);
223 PopStackAndAdvance();
224 } else {
225 // Step into the array...
226 assert(SS.Idx < AT->getNumElements());
227 Stack.push_back(StackState(AT->getElementType(),
228 SS.Offset+SS.Idx*
229 TD.getTypeSize(AT->getElementType())));
230 }
231 }
232 }
233 }
234 };
235}
236
237/// ElementTypesAreCompatible - Check to see if the specified types are
238/// "physically" compatible. If so, return true, else return false. We only
239/// have to check the fields in T1: T2 may be larger than T1.
240///
241static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
242 TypeElementWalker T1W(T1), T2W(T2);
243
244 while (!T1W.isDone() && !T2W.isDone()) {
245 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
246 return false;
247
248 const Type *T1 = T1W.getCurrentType();
249 const Type *T2 = T2W.getCurrentType();
250 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
251 return false;
252
253 T1W.StepToNextType();
254 T2W.StepToNextType();
255 }
256
257 return T1W.isDone();
258}
259
260
Chris Lattner08db7192002-11-06 06:20:27 +0000261/// mergeTypeInfo - This method merges the specified type into the current node
262/// at the specified offset. This may update the current node's type record if
263/// this gives more information to the node, it may do nothing to the node if
264/// this information is already known, or it may merge the node completely (and
265/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000266///
Chris Lattner08db7192002-11-06 06:20:27 +0000267/// This method returns true if the node is completely folded, otherwise false.
268///
Chris Lattner088b6392003-03-03 17:13:31 +0000269bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
270 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000271 // Check to make sure the Size member is up-to-date. Size can be one of the
272 // following:
273 // Size = 0, Ty = Void: Nothing is known about this node.
274 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
275 // Size = 1, Ty = Void, Array = 1: The node is collapsed
276 // Otherwise, sizeof(Ty) = Size
277 //
Chris Lattner18552922002-11-18 21:44:46 +0000278 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
279 (Size == 0 && !Ty->isSized() && !isArray()) ||
280 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
281 (Size == 0 && !Ty->isSized() && !isArray()) ||
282 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000283 "Size member of DSNode doesn't match the type structure!");
284 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000285
Chris Lattner18552922002-11-18 21:44:46 +0000286 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000287 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000288
Chris Lattner08db7192002-11-06 06:20:27 +0000289 // Return true immediately if the node is completely folded.
290 if (isNodeCompletelyFolded()) return true;
291
Chris Lattner23f83dc2002-11-08 22:49:57 +0000292 // If this is an array type, eliminate the outside arrays because they won't
293 // be used anyway. This greatly reduces the size of large static arrays used
294 // as global variables, for example.
295 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000296 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000297 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
298 // FIXME: we might want to keep small arrays, but must be careful about
299 // things like: [2 x [10000 x int*]]
300 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000301 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000302 }
303
Chris Lattner08db7192002-11-06 06:20:27 +0000304 // Figure out how big the new type we're merging in is...
305 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
306
307 // Otherwise check to see if we can fold this type into the current node. If
308 // we can't, we fold the node completely, if we can, we potentially update our
309 // internal state.
310 //
Chris Lattner18552922002-11-18 21:44:46 +0000311 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000312 // If this is the first type that this node has seen, just accept it without
313 // question....
314 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000315 assert(!isArray() && "This shouldn't happen!");
316 Ty = NewTy;
317 NodeType &= ~Array;
318 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000319 Size = NewTySize;
320
321 // Calculate the number of outgoing links from this node.
322 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
323 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000324 }
Chris Lattner08db7192002-11-06 06:20:27 +0000325
326 // Handle node expansion case here...
327 if (Offset+NewTySize > Size) {
328 // It is illegal to grow this node if we have treated it as an array of
329 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000330 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000331 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000332 return true;
333 }
334
335 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000336 std::cerr << "UNIMP: Trying to merge a growth type into "
337 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000338 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000339 return true;
340 }
341
342 // Okay, the situation is nice and simple, we are trying to merge a type in
343 // at offset 0 that is bigger than our current type. Implement this by
344 // switching to the new type and then merge in the smaller one, which should
345 // hit the other code path here. If the other code path decides it's not
346 // ok, it will collapse the node as appropriate.
347 //
Chris Lattner18552922002-11-18 21:44:46 +0000348 const Type *OldTy = Ty;
349 Ty = NewTy;
350 NodeType &= ~Array;
351 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000352 Size = NewTySize;
353
354 // Must grow links to be the appropriate size...
355 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
356
357 // Merge in the old type now... which is guaranteed to be smaller than the
358 // "current" type.
359 return mergeTypeInfo(OldTy, 0);
360 }
361
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000362 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000363 "Cannot merge something into a part of our type that doesn't exist!");
364
Chris Lattner18552922002-11-18 21:44:46 +0000365 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000366 // type that starts at offset Offset.
367 //
368 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000369 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000370 while (O < Offset) {
371 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
372
373 switch (SubType->getPrimitiveID()) {
374 case Type::StructTyID: {
375 const StructType *STy = cast<StructType>(SubType);
376 const StructLayout &SL = *TD.getStructLayout(STy);
377
378 unsigned i = 0, e = SL.MemberOffsets.size();
379 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
380 /* empty */;
381
382 // The offset we are looking for must be in the i'th element...
383 SubType = STy->getElementTypes()[i];
384 O += SL.MemberOffsets[i];
385 break;
386 }
387 case Type::ArrayTyID: {
388 SubType = cast<ArrayType>(SubType)->getElementType();
389 unsigned ElSize = TD.getTypeSize(SubType);
390 unsigned Remainder = (Offset-O) % ElSize;
391 O = Offset-Remainder;
392 break;
393 }
394 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000395 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000396 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000397 }
398 }
399
400 assert(O == Offset && "Could not achieve the correct offset!");
401
402 // If we found our type exactly, early exit
403 if (SubType == NewTy) return false;
404
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000405 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
406
407 // Ok, we are getting desperate now. Check for physical subtyping, where we
408 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000409 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000410 SubTypeSize && SubTypeSize < 256 &&
411 ElementTypesAreCompatible(NewTy, SubType))
412 return false;
413
Chris Lattner08db7192002-11-06 06:20:27 +0000414 // Okay, so we found the leader type at the offset requested. Search the list
415 // of types that starts at this offset. If SubType is currently an array or
416 // structure, the type desired may actually be the first element of the
417 // composite type...
418 //
Chris Lattner18552922002-11-18 21:44:46 +0000419 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000420 while (SubType != NewTy) {
421 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000422 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000423 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000424 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000425 case Type::StructTyID: {
426 const StructType *STy = cast<StructType>(SubType);
427 const StructLayout &SL = *TD.getStructLayout(STy);
428 if (SL.MemberOffsets.size() > 1)
429 NextPadSize = SL.MemberOffsets[1];
430 else
431 NextPadSize = SubTypeSize;
432 NextSubType = STy->getElementTypes()[0];
433 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000434 break;
Chris Lattner18552922002-11-18 21:44:46 +0000435 }
Chris Lattner08db7192002-11-06 06:20:27 +0000436 case Type::ArrayTyID:
437 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000438 NextSubTypeSize = TD.getTypeSize(NextSubType);
439 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000440 break;
441 default: ;
442 // fall out
443 }
444
445 if (NextSubType == 0)
446 break; // In the default case, break out of the loop
447
Chris Lattner18552922002-11-18 21:44:46 +0000448 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000449 break; // Don't allow shrinking to a smaller type than NewTySize
450 SubType = NextSubType;
451 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000452 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000453 }
454
455 // If we found the type exactly, return it...
456 if (SubType == NewTy)
457 return false;
458
459 // Check to see if we have a compatible, but different type...
460 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000461 // Check to see if this type is obviously convertible... int -> uint f.e.
462 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000463 return false;
464
465 // Check to see if we have a pointer & integer mismatch going on here,
466 // loading a pointer as a long, for example.
467 //
468 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
469 NewTy->isInteger() && isa<PointerType>(SubType))
470 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000471 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
472 // We are accessing the field, plus some structure padding. Ignore the
473 // structure padding.
474 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000475 }
476
Chris Lattner18552922002-11-18 21:44:46 +0000477 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000478 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
479 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000480
Chris Lattner088b6392003-03-03 17:13:31 +0000481 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000482 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000483}
484
Chris Lattner08db7192002-11-06 06:20:27 +0000485
486
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000487// addEdgeTo - Add an edge from the current node to the specified node. This
488// can cause merging of nodes in the graph.
489//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000490void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000491 if (NH.getNode() == 0) return; // Nothing to do
492
Chris Lattner08db7192002-11-06 06:20:27 +0000493 DSNodeHandle &ExistingEdge = getLink(Offset);
494 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000495 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000496 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000497 } else { // No merging to perform...
498 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000499 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000500}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000501
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000502
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000503// MergeSortedVectors - Efficiently merge a vector into another vector where
504// duplicates are not allowed and both are sorted. This assumes that 'T's are
505// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000506//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000507static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
508 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000509 // By far, the most common cases will be the simple ones. In these cases,
510 // avoid having to allocate a temporary vector...
511 //
512 if (Src.empty()) { // Nothing to merge in...
513 return;
514 } else if (Dest.empty()) { // Just copy the result in...
515 Dest = Src;
516 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000517 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000518 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000519 std::lower_bound(Dest.begin(), Dest.end(), V);
520 if (I == Dest.end() || *I != Src[0]) // If not already contained...
521 Dest.insert(I, Src[0]);
522 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000523 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000524 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000525 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000526 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
527 if (I == Dest.end() || *I != Tmp) // If not already contained...
528 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000529
530 } else {
531 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000532 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000533
534 // Make space for all of the type entries now...
535 Dest.resize(Dest.size()+Src.size());
536
537 // Merge the two sorted ranges together... into Dest.
538 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
539
540 // Now erase any duplicate entries that may have accumulated into the
541 // vectors (because they were in both of the input sets)
542 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
543 }
544}
545
546
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000547// MergeNodes() - Helper function for DSNode::mergeWith().
548// This function does the hard work of merging two nodes, CurNodeH
549// and NH after filtering out trivial cases and making sure that
550// CurNodeH.offset >= NH.offset.
551//
552// ***WARNING***
553// Since merging may cause either node to go away, we must always
554// use the node-handles to refer to the nodes. These node handles are
555// automatically updated during merging, so will always provide access
556// to the correct node after a merge.
557//
558void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
559 assert(CurNodeH.getOffset() >= NH.getOffset() &&
560 "This should have been enforced in the caller.");
561
562 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
563 // respect to NH.Offset) is now zero. NOffset is the distance from the base
564 // of our object that N starts from.
565 //
566 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
567 unsigned NSize = NH.getNode()->getSize();
568
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000569 // If the two nodes are of different size, and the smaller node has the array
570 // bit set, collapse!
571 if (NSize != CurNodeH.getNode()->getSize()) {
572 if (NSize < CurNodeH.getNode()->getSize()) {
573 if (NH.getNode()->isArray())
574 NH.getNode()->foldNodeCompletely();
575 } else if (CurNodeH.getNode()->isArray()) {
576 NH.getNode()->foldNodeCompletely();
577 }
578 }
579
580 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000581 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000582 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000583 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000584
585 // If we are merging a node with a completely folded node, then both nodes are
586 // now completely folded.
587 //
588 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
589 if (!NH.getNode()->isNodeCompletelyFolded()) {
590 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000591 assert(NH.getNode() && NH.getOffset() == 0 &&
592 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000593 NOffset = NH.getOffset();
594 NSize = NH.getNode()->getSize();
595 assert(NOffset == 0 && NSize == 1);
596 }
597 } else if (NH.getNode()->isNodeCompletelyFolded()) {
598 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000599 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
600 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000601 NOffset = NH.getOffset();
602 NSize = NH.getNode()->getSize();
603 assert(NOffset == 0 && NSize == 1);
604 }
605
Chris Lattner72d29a42003-02-11 23:11:51 +0000606 DSNode *N = NH.getNode();
607 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000608 assert(!CurNodeH.getNode()->isDeadNode());
609
610 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000611 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000612
Chris Lattner72d29a42003-02-11 23:11:51 +0000613 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000614 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000615 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000616
Chris Lattner72d29a42003-02-11 23:11:51 +0000617 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
618 //
619 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
620 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000621 if (Link.getNode()) {
622 // Compute the offset into the current node at which to
623 // merge this link. In the common case, this is a linear
624 // relation to the offset in the original node (with
625 // wrapping), but if the current node gets collapsed due to
626 // recursive merging, we must make sure to merge in all remaining
627 // links at offset zero.
628 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000629 DSNode *CN = CurNodeH.getNode();
630 if (CN->Size != 1)
631 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
632 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000633 }
634 }
635
636 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000637 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000638
639 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000640 if (!N->Globals.empty()) {
641 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000642
643 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000644 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000645 }
646}
647
648
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000649// mergeWith - Merge this node and the specified node, moving all links to and
650// from the argument node into the current node, deleting the node argument.
651// Offset indicates what offset the specified node is to be merged into the
652// current node.
653//
654// The specified node may be a null pointer (in which case, nothing happens).
655//
656void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
657 DSNode *N = NH.getNode();
658 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000659 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000660
Chris Lattnerbd92b732003-06-19 21:15:11 +0000661 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000662 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
663
Chris Lattner02606632002-11-04 06:48:26 +0000664 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000665 // We cannot merge two pieces of the same node together, collapse the node
666 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000667 DEBUG(std::cerr << "Attempting to merge two chunks of"
668 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000669 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000670 return;
671 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000672
Chris Lattner5190ce82002-11-12 07:20:45 +0000673 // If both nodes are not at offset 0, make sure that we are merging the node
674 // at an later offset into the node with the zero offset.
675 //
676 if (Offset < NH.getOffset()) {
677 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
678 return;
679 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
680 // If the offsets are the same, merge the smaller node into the bigger node
681 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
682 return;
683 }
684
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000685 // Ok, now we can merge the two nodes. Use a static helper that works with
686 // two node handles, since "this" may get merged away at intermediate steps.
687 DSNodeHandle CurNodeH(this, Offset);
688 DSNodeHandle NHCopy(NH);
689 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000690}
691
Chris Lattner9de906c2002-10-20 22:11:44 +0000692//===----------------------------------------------------------------------===//
693// DSCallSite Implementation
694//===----------------------------------------------------------------------===//
695
Vikram S. Adve26b98262002-10-20 21:41:02 +0000696// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000697Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000698 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000699}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000700
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000701
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000702//===----------------------------------------------------------------------===//
703// DSGraph Implementation
704//===----------------------------------------------------------------------===//
705
Chris Lattner5a540632003-06-30 03:15:25 +0000706DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000707 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000708 NodeMapTy NodeMap;
709 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000710}
711
Chris Lattner5a540632003-06-30 03:15:25 +0000712DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
713 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000714 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000715 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000716}
717
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000718DSGraph::~DSGraph() {
719 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000720 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000721 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000722 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000723
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000724 // Drop all intra-node references, so that assertions don't fail...
725 std::for_each(Nodes.begin(), Nodes.end(),
726 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000727
728 // Delete all of the nodes themselves...
729 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
730}
731
Chris Lattner0d9bab82002-07-18 00:12:30 +0000732// dump - Allow inspection of graph in a debugger.
733void DSGraph::dump() const { print(std::cerr); }
734
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000735
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000736/// remapLinks - Change all of the Links in the current node according to the
737/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000738///
Chris Lattner8d327672003-06-30 03:36:09 +0000739void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000740 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
741 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
742 Links[i].setNode(H.getNode());
743 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
744 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000745}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000746
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000747
Chris Lattner5a540632003-06-30 03:15:25 +0000748/// cloneInto - Clone the specified DSGraph into the current graph. The
749/// translated ScalarMap for the old function is filled into the OldValMap
750/// member, and the translated ReturnNodes map is returned into ReturnNodes.
751///
752/// The CloneFlags member controls various aspects of the cloning process.
753///
754void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
755 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
756 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000757 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000758 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000759
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000760 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000761
762 // Duplicate all of the nodes, populating the node map...
763 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000764
765 // Remove alloca or mod/ref bits as specified...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000766 unsigned BitsToClear =((CloneFlags & StripAllocaBit) ? DSNode::AllocaNode : 0)
767 | ((CloneFlags & StripModRefBits) ? (DSNode::Modified | DSNode::Read) : 0);
768 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000769 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000770 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000771 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000772 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000773 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000774 }
775
Chris Lattner18552922002-11-18 21:44:46 +0000776#ifndef NDEBUG
777 Timer::addPeakMemoryMeasurement();
778#endif
779
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000780 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000781 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000782 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000783
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000784 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000785 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000786 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000787 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000788 DSNodeHandle &H = OldValMap[I->first];
789 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
790 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000791
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000792 // If this is a global, add the global to this fn or merge if already exists
793 if (isa<GlobalValue>(I->first) && &OldNodeMap != &ScalarMap)
794 ScalarMap[I->first].mergeWith(H);
Chris Lattnercf15db32002-10-17 20:09:52 +0000795 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000796
Chris Lattner679e8e12002-11-08 21:27:12 +0000797 if (!(CloneFlags & DontCloneCallNodes)) {
798 // Copy the function calls list...
799 unsigned FC = FunctionCalls.size(); // FirstCall
800 FunctionCalls.reserve(FC+G.FunctionCalls.size());
801 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
802 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000803 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000804
Chris Lattneracf491f2002-11-08 22:27:09 +0000805 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000806 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000807 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000808 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
809 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
810 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
811 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000812
Chris Lattner5a540632003-06-30 03:15:25 +0000813 // Map the return node pointers over...
814 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
815 E = G.getReturnNodes().end(); I != E; ++I) {
816 const DSNodeHandle &Ret = I->second;
817 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
818 OldReturnNodes.insert(std::make_pair(I->first,
819 DSNodeHandle(MappedRet.getNode(),
820 MappedRet.getOffset()+Ret.getOffset())));
821 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000822}
823
Chris Lattner076c1f92002-11-07 06:31:54 +0000824/// mergeInGraph - The method is used for merging graphs together. If the
825/// argument graph is not *this, it makes a clone of the specified graph, then
826/// merges the nodes specified in the call site with the formal arguments in the
827/// graph.
828///
Chris Lattner5a540632003-06-30 03:15:25 +0000829void DSGraph::mergeInGraph(DSCallSite &CS, Function &F, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000830 unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000831 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000832 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000833
834 // If this is not a recursive call, clone the graph into this graph...
835 if (&Graph != this) {
836 // Clone the callee's graph into the current graph, keeping
837 // track of where scalars in the old graph _used_ to point,
838 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +0000839 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000840
841 // The clone call may invalidate any of the vectors in the data
842 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +0000843 ReturnNodesTy OldRetNodes;
844 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
845 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +0000846 ScalarMap = &OldValMap;
847 } else {
Chris Lattner5a540632003-06-30 03:15:25 +0000848 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +0000849 ScalarMap = &getScalarMap();
850 }
851
852 // Merge the return value with the return value of the context...
853 RetVal.mergeWith(CS.getRetVal());
854
855 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +0000856 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000857
Chris Lattner076c1f92002-11-07 06:31:54 +0000858 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
859 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000860 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000861 ++AI;
862#ifndef NDEBUG
863 if (AI == F.aend())
864 std::cerr << "Bad call to Function: " << F.getName() << "\n";
865#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000866 }
Chris Lattner5d274582003-02-06 00:15:08 +0000867 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000868
869 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000870 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000871 DSNodeHandle &NH = (*ScalarMap)[AI];
872 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
873 NH.mergeWith(CS.getPtrArg(i));
874 }
875}
876
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000877
Chris Lattner0d9bab82002-07-18 00:12:30 +0000878// markIncompleteNodes - Mark the specified node as having contents that are not
879// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +0000880// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +0000881// must recursively traverse the data structure graph, marking all reachable
882// nodes as incomplete.
883//
884static void markIncompleteNode(DSNode *N) {
885 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +0000886 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000887
888 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000889 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +0000890
891 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000892 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
893 if (DSNode *DSN = N->getLink(i).getNode())
894 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000895}
896
Chris Lattnere71ffc22002-11-11 03:36:55 +0000897static void markIncomplete(DSCallSite &Call) {
898 // Then the return value is certainly incomplete!
899 markIncompleteNode(Call.getRetVal().getNode());
900
901 // All objects pointed to by function arguments are incomplete!
902 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
903 markIncompleteNode(Call.getPtrArg(i).getNode());
904}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000905
906// markIncompleteNodes - Traverse the graph, identifying nodes that may be
907// modified by other functions that have not been resolved yet. This marks
908// nodes that are reachable through three sources of "unknownness":
909//
910// Global Variables, Function Calls, and Incoming Arguments
911//
912// For any node that may have unknown components (because something outside the
913// scope of current analysis may have modified it), the 'Incomplete' flag is
914// added to the NodeType.
915//
Chris Lattner394471f2003-01-23 22:05:33 +0000916void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000917 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +0000918 if (Flags & DSGraph::MarkFormalArgs)
919 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
920 FI != E; ++FI) {
921 Function &F = *FI->first;
922 if (F.getName() != "main")
923 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
924 if (isPointerType(I->getType()) &&
925 ScalarMap.find(I) != ScalarMap.end())
926 markIncompleteNode(ScalarMap[I].getNode());
927 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000928
929 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000930 if (!shouldPrintAuxCalls())
931 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
932 markIncomplete(FunctionCalls[i]);
933 else
934 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
935 markIncomplete(AuxFunctionCalls[i]);
936
Chris Lattner0d9bab82002-07-18 00:12:30 +0000937
Chris Lattner93d7a212003-02-09 18:41:49 +0000938 // Mark all global nodes as incomplete...
939 if ((Flags & DSGraph::IgnoreGlobals) == 0)
940 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +0000941 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +0000942 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000943}
944
Chris Lattneraa8146f2002-11-10 06:59:55 +0000945static inline void killIfUselessEdge(DSNodeHandle &Edge) {
946 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +0000947 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +0000948 // No interesting info?
949 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +0000950 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000951 Edge.setNode(0); // Kill the edge!
952}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000953
Chris Lattneraa8146f2002-11-10 06:59:55 +0000954static inline bool nodeContainsExternalFunction(const DSNode *N) {
955 const std::vector<GlobalValue*> &Globals = N->getGlobals();
956 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
957 if (Globals[i]->isExternal())
958 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000959 return false;
960}
961
Chris Lattner5a540632003-06-30 03:15:25 +0000962static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000963 // Remove trivially identical function calls
964 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000965 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
966
967 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +0000968 DSNode *LastCalleeNode = 0;
969 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000970 unsigned NumDuplicateCalls = 0;
971 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000972 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000973 DSCallSite &CS = Calls[i];
974
Chris Lattnere4258442002-11-11 21:35:38 +0000975 // If the Callee is a useless edge, this must be an unreachable call site,
976 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +0000977 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +0000978 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +0000979 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +0000980 CS.swap(Calls.back());
981 Calls.pop_back();
982 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000983 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000984 // If the return value or any arguments point to a void node with no
985 // information at all in it, and the call node is the only node to point
986 // to it, remove the edge to the node (killing the node).
987 //
988 killIfUselessEdge(CS.getRetVal());
989 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
990 killIfUselessEdge(CS.getPtrArg(a));
991
992 // If this call site calls the same function as the last call site, and if
993 // the function pointer contains an external function, this node will
994 // never be resolved. Merge the arguments of the call node because no
995 // information will be lost.
996 //
Chris Lattner923fc052003-02-05 21:59:58 +0000997 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
998 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +0000999 ++NumDuplicateCalls;
1000 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001001 if (LastCalleeNode)
1002 LastCalleeContainsExternalFunction =
1003 nodeContainsExternalFunction(LastCalleeNode);
1004 else
1005 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001006 }
1007
1008 if (LastCalleeContainsExternalFunction ||
1009 // This should be more than enough context sensitivity!
1010 // FIXME: Evaluate how many times this is tripped!
1011 NumDuplicateCalls > 20) {
1012 DSCallSite &OCS = Calls[i-1];
1013 OCS.mergeWith(CS);
1014
1015 // The node will now be eliminated as a duplicate!
1016 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1017 CS = OCS;
1018 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1019 OCS = CS;
1020 }
1021 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001022 if (CS.isDirectCall()) {
1023 LastCalleeFunc = CS.getCalleeFunc();
1024 LastCalleeNode = 0;
1025 } else {
1026 LastCalleeNode = CS.getCalleeNode();
1027 LastCalleeFunc = 0;
1028 }
Chris Lattnere4258442002-11-11 21:35:38 +00001029 NumDuplicateCalls = 0;
1030 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001031 }
1032 }
1033
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001034 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1035 Calls.end());
1036
Chris Lattner33312f72002-11-08 01:21:07 +00001037 // Track the number of call nodes merged away...
1038 NumCallNodesMerged += NumFns-Calls.size();
1039
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001040 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001041 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001042}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001043
Chris Lattneraa8146f2002-11-10 06:59:55 +00001044
Chris Lattnere2219762002-07-18 18:22:40 +00001045// removeTriviallyDeadNodes - After the graph has been constructed, this method
1046// removes all unreachable nodes that are created because they got merged with
1047// other nodes in the graph. These nodes will all be trivially unreachable, so
1048// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001049//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001050void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001051 removeIdenticalCalls(FunctionCalls);
1052 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001053
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001054 for (unsigned i = 0; i != Nodes.size(); ++i) {
1055 DSNode *Node = Nodes[i];
Chris Lattner72d50a02003-06-28 21:58:28 +00001056 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001057 // This is a useless node if it has no mod/ref info (checked above),
1058 // outgoing edges (which it cannot, as it is not modified in this
1059 // context), and it has no incoming edges. If it is a global node it may
1060 // have all of these properties and still have incoming edges, due to the
1061 // scalar map, so we check those now.
1062 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001063 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001064 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001065
1066 // Loop through and make sure all of the globals are referring directly
1067 // to the node...
1068 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1069 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1070 assert(N == Node && "ScalarMap doesn't match globals list!");
1071 }
1072
Chris Lattnerbd92b732003-06-19 21:15:11 +00001073 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001074 if (Node->getNumReferrers() == Globals.size()) {
1075 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1076 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001077 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001078 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001079 }
1080 }
1081
Chris Lattnerbd92b732003-06-19 21:15:11 +00001082 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001083 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001084 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001085 Nodes[i--] = Nodes.back();
1086 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001087 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001088 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001089}
1090
1091
Chris Lattner5c7380e2003-01-29 21:10:20 +00001092/// markReachableNodes - This method recursively traverses the specified
1093/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1094/// to the set, which allows it to only traverse visited nodes once.
1095///
Chris Lattner41c04f72003-02-01 04:52:08 +00001096void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001097 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001098 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001099 if (ReachableNodes.count(this)) return; // Already marked reachable
1100 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001101
Chris Lattner5c7380e2003-01-29 21:10:20 +00001102 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1103 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1104}
1105
Chris Lattner41c04f72003-02-01 04:52:08 +00001106void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001107 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001108 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001109
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001110 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1111 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001112}
1113
Chris Lattnera1220af2003-02-01 06:17:02 +00001114// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1115// looking for a node that is marked alive. If an alive node is found, return
1116// true, otherwise return false. If an alive node is reachable, this node is
1117// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001118//
Chris Lattnera1220af2003-02-01 06:17:02 +00001119static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1120 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001121 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001122 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001123
Chris Lattneraa8146f2002-11-10 06:59:55 +00001124 // If we know that this node is alive, return so!
1125 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001126
Chris Lattneraa8146f2002-11-10 06:59:55 +00001127 // Otherwise, we don't think the node is alive yet, check for infinite
1128 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001129 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001130 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001131
Chris Lattner08db7192002-11-06 06:20:27 +00001132 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +00001133 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
1134 N->markReachableNodes(Alive);
1135 return true;
1136 }
1137 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001138}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001139
Chris Lattnera1220af2003-02-01 06:17:02 +00001140// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1141// alive nodes.
1142//
Chris Lattner41c04f72003-02-01 04:52:08 +00001143static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1144 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +00001145 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1146 return true;
1147 if (CS.isIndirectCall() &&
1148 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001149 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001150 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1151 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001152 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001153 return false;
1154}
1155
Chris Lattnere2219762002-07-18 18:22:40 +00001156// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1157// subgraphs that are unreachable. This often occurs because the data
1158// structure doesn't "escape" into it's caller, and thus should be eliminated
1159// from the caller's graph entirely. This is only appropriate to use when
1160// inlining graphs.
1161//
Chris Lattner394471f2003-01-23 22:05:33 +00001162void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001163 // Reduce the amount of work we have to do... remove dummy nodes left over by
1164 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001165 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001166
Chris Lattnere2219762002-07-18 18:22:40 +00001167 // FIXME: Merge nontrivially identical call nodes...
1168
1169 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001170 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001171 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001172
Chris Lattneraa8146f2002-11-10 06:59:55 +00001173 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001174 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001175 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001176 assert(I->second.getNode() && "Null global node?");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001177 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1178 ++I;
1179 } else {
1180 // Check to see if this is a worthless node generated for non-pointer
1181 // values, such as integers. Consider an addition of long types: A+B.
1182 // Assuming we can track all uses of the value in this context, and it is
1183 // NOT used as a pointer, we can delete the node. We will be able to
1184 // detect this situation if the node pointed to ONLY has Unknown bit set
1185 // in the node. In this case, the node is not incomplete, does not point
1186 // to any other nodes (no mod/ref bits set), and is therefore
1187 // uninteresting for data structure analysis. If we run across one of
1188 // these, prune the scalar pointing to it.
1189 //
1190 DSNode *N = I->second.getNode();
Chris Lattnerbd92b732003-06-19 21:15:11 +00001191 if (N->isUnknownNode() && !isa<Argument>(I->first)) {
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001192 ScalarMap.erase(I++);
1193 } else {
1194 I->second.getNode()->markReachableNodes(Alive);
1195 ++I;
1196 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001197 }
Chris Lattnere2219762002-07-18 18:22:40 +00001198
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001199 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001200 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1201 I != E; ++I)
1202 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001203
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001204 // Mark any nodes reachable by primary calls as alive...
1205 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1206 FunctionCalls[i].markReachableNodes(Alive);
1207
1208 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001209 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001210 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1211 do {
1212 Visited.clear();
1213 // If any global nodes points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001214 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001215 // unreachable globals in the list.
1216 //
1217 Iterate = false;
1218 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1219 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1220 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1221 GlobalNodes.pop_back(); // Erase efficiently
1222 Iterate = true;
1223 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001224
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001225 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1226 if (!AuxFCallsAlive[i] &&
1227 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1228 AuxFunctionCalls[i].markReachableNodes(Alive);
1229 AuxFCallsAlive[i] = true;
1230 Iterate = true;
1231 }
1232 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001233
1234 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001235 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001236 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1237 if (AuxFCallsAlive[i])
1238 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001239 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001240 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001241 // Move the unreachable call nodes to the globals graph...
1242 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1243 AuxFunctionCalls.begin()+CurIdx,
1244 AuxFunctionCalls.end());
1245 }
1246 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001247 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1248 AuxFunctionCalls.end());
1249
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001250 // At this point, any nodes which are visited, but not alive, are nodes which
1251 // should be moved to the globals graph. Loop over all nodes, eliminating
1252 // completely unreachable nodes, and moving visited nodes to the globals graph
1253 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001254 std::vector<DSNode*> DeadNodes;
1255 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001256 for (unsigned i = 0; i != Nodes.size(); ++i)
1257 if (!Alive.count(Nodes[i])) {
1258 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001259 Nodes[i--] = Nodes.back(); // move node to end of vector
1260 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001261 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1262 Visited.count(N)) { // Visited but not alive?
1263 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner72d29a42003-02-11 23:11:51 +00001264 N->setParentGraph(GlobalsGraph);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001265 } else { // Otherwise, delete the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001266 assert((!N->isGlobalNode() ||
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001267 (Flags & DSGraph::RemoveUnreachableGlobals))
1268 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001269 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1270 // << "] Node is dead: "; N->dump();
1271 DeadNodes.push_back(N);
1272 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001273 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001274 } else {
1275 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001276 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001277
1278 // Now that the nodes have either been deleted or moved to the globals graph,
1279 // loop over the scalarmap, updating the entries for globals...
1280 //
1281 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1282 // In this array we start the remapping, which can cause merging. Because
1283 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1284 // must always go through the ScalarMap (which contains DSNodeHandles [which
1285 // cannot be invalidated by merging]).
1286 //
1287 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1288 Value *G = GlobalNodes[i].first;
Chris Lattner8d327672003-06-30 03:36:09 +00001289 ScalarMapTy::iterator I = ScalarMap.find(G);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001290 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1291 assert(I->second.getNode() && "Global not pointing to anything?");
1292 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1293 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1294 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1295 "Global not pointing to anything?");
1296 ScalarMap.erase(I);
1297 }
1298
1299 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1300 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001301 if (!GlobalNodes.empty())
1302 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001303 } else {
1304 // If we are in the top-down pass, remove all unreachable globals from the
1305 // ScalarMap...
1306 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1307 ScalarMap.erase(GlobalNodes[i].first);
1308 }
1309
Chris Lattner72d29a42003-02-11 23:11:51 +00001310 // Loop over all of the dead nodes now, deleting them since their referrer
1311 // count is zero.
1312 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1313 delete DeadNodes[i];
1314
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001315 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001316}
1317
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001318void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001319 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1320 Nodes[i]->assertOK();
1321 return; // FIXME: remove
Chris Lattner8d327672003-06-30 03:36:09 +00001322 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001323 E = ScalarMap.end(); I != E; ++I) {
1324 assert(I->second.getNode() && "Null node in scalarmap!");
1325 AssertNodeInGraph(I->second.getNode());
1326 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001327 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001328 "Global points to node, but node isn't global?");
1329 AssertNodeContainsGlobal(I->second.getNode(), GV);
1330 }
1331 }
1332 AssertCallNodesInGraph();
1333 AssertAuxCallNodesInGraph();
1334}