blob: df1c4bebd2cd096fc1e52f363225080c5c3a3b4b [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 Lattner58f98d02003-07-02 04:38:49 +000012#include "llvm/Assembly/Writer.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000013#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000015#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000016#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017
Chris Lattner08db7192002-11-06 06:20:27 +000018namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000019 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
20 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000021};
22
Chris Lattnerb1060432002-11-07 05:20:53 +000023namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000024 extern TargetData TD;
25}
Chris Lattnerb1060432002-11-07 05:20:53 +000026using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000027
Chris Lattner731b2d72003-02-13 19:09:00 +000028DSNode *DSNodeHandle::HandleForwarding() const {
29 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
30
31 // Handle node forwarding here!
32 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
33 Offset += N->ForwardNH.getOffset();
34
35 if (--N->NumReferrers == 0) {
36 // Removing the last referrer to the node, sever the forwarding link
37 N->stopForwarding();
38 }
39
40 N = Next;
41 N->NumReferrers++;
42 if (N->Size <= Offset) {
43 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
44 Offset = 0;
45 }
46 return N;
47}
48
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000049//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000050// DSNode Implementation
51//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000052
Chris Lattnerbd92b732003-06-19 21:15:11 +000053DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner58f98d02003-07-02 04:38:49 +000054 : NumReferrers(0), Size(0),
55#ifdef INCLUDE_PARENT_GRAPH
56 ParentGraph(G),
57#endif
58 Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000059 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000060 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000061 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000062}
63
Chris Lattner0d9bab82002-07-18 00:12:30 +000064// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000065DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner58f98d02003-07-02 04:38:49 +000066 : NumReferrers(0), Size(N.Size),
67#ifdef INCLUDE_PARENT_GRAPH
68 ParentGraph(G),
69#endif
70 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000071 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000072}
73
Chris Lattner72d29a42003-02-11 23:11:51 +000074void DSNode::assertOK() const {
75 assert((Ty != Type::VoidTy ||
76 Ty == Type::VoidTy && (Size == 0 ||
77 (NodeType & DSNode::Array))) &&
78 "Node not OK!");
79}
80
81/// forwardNode - Mark this node as being obsolete, and all references to it
82/// should be forwarded to the specified node and offset.
83///
84void DSNode::forwardNode(DSNode *To, unsigned Offset) {
85 assert(this != To && "Cannot forward a node to itself!");
86 assert(ForwardNH.isNull() && "Already forwarding from this node!");
87 if (To->Size <= 1) Offset = 0;
88 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
89 "Forwarded offset is wrong!");
90 ForwardNH.setNode(To);
91 ForwardNH.setOffset(Offset);
92 NodeType = DEAD;
93 Size = 0;
94 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000095}
96
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000097// addGlobal - Add an entry for a global value to the Globals list. This also
98// marks the node with the 'G' flag if it does not already have it.
99//
100void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000101 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000102 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000103 std::lower_bound(Globals.begin(), Globals.end(), GV);
104
105 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000106 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000107 Globals.insert(I, GV);
108 NodeType |= GlobalNode;
109 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000110}
111
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000112/// foldNodeCompletely - If we determine that this node has some funny
113/// behavior happening to it that we cannot represent, we fold it down to a
114/// single, completely pessimistic, node. This node is represented as a
115/// single byte with a single TypeEntry of "void".
116///
117void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000118 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000119
Chris Lattner08db7192002-11-06 06:20:27 +0000120 ++NumFolds;
121
Chris Lattner72d29a42003-02-11 23:11:51 +0000122 // Create the node we are going to forward to...
Chris Lattner58f98d02003-07-02 04:38:49 +0000123 DSNode *DestNode = new DSNode(0,
124#ifdef INCLUDE_PARENT_GRAPH
125 ParentGraph
126#else
127 0
128#endif
129 );
Chris Lattnerbd92b732003-06-19 21:15:11 +0000130 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000131 DestNode->Ty = Type::VoidTy;
132 DestNode->Size = 1;
133 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000134
Chris Lattner72d29a42003-02-11 23:11:51 +0000135 // Start forwarding to the destination node...
136 forwardNode(DestNode, 0);
137
138 if (Links.size()) {
139 DestNode->Links.push_back(Links[0]);
140 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000141
Chris Lattner72d29a42003-02-11 23:11:51 +0000142 // If we have links, merge all of our outgoing links together...
143 for (unsigned i = Links.size()-1; i != 0; --i)
144 NH.getNode()->Links[0].mergeWith(Links[i]);
145 Links.clear();
146 } else {
147 DestNode->Links.resize(1);
148 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000149}
Chris Lattner076c1f92002-11-07 06:31:54 +0000150
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000151/// isNodeCompletelyFolded - Return true if this node has been completely
152/// folded down to something that can never be expanded, effectively losing
153/// all of the field sensitivity that may be present in the node.
154///
155bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000156 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000157}
158
159
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000160namespace {
161 /// TypeElementWalker Class - Used for implementation of physical subtyping...
162 ///
163 class TypeElementWalker {
164 struct StackState {
165 const Type *Ty;
166 unsigned Offset;
167 unsigned Idx;
168 StackState(const Type *T, unsigned Off = 0)
169 : Ty(T), Offset(Off), Idx(0) {}
170 };
171
172 std::vector<StackState> Stack;
173 public:
174 TypeElementWalker(const Type *T) {
175 Stack.push_back(T);
176 StepToLeaf();
177 }
178
179 bool isDone() const { return Stack.empty(); }
180 const Type *getCurrentType() const { return Stack.back().Ty; }
181 unsigned getCurrentOffset() const { return Stack.back().Offset; }
182
183 void StepToNextType() {
184 PopStackAndAdvance();
185 StepToLeaf();
186 }
187
188 private:
189 /// PopStackAndAdvance - Pop the current element off of the stack and
190 /// advance the underlying element to the next contained member.
191 void PopStackAndAdvance() {
192 assert(!Stack.empty() && "Cannot pop an empty stack!");
193 Stack.pop_back();
194 while (!Stack.empty()) {
195 StackState &SS = Stack.back();
196 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
197 ++SS.Idx;
198 if (SS.Idx != ST->getElementTypes().size()) {
199 const StructLayout *SL = TD.getStructLayout(ST);
200 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
201 return;
202 }
203 Stack.pop_back(); // At the end of the structure
204 } else {
205 const ArrayType *AT = cast<ArrayType>(SS.Ty);
206 ++SS.Idx;
207 if (SS.Idx != AT->getNumElements()) {
208 SS.Offset += TD.getTypeSize(AT->getElementType());
209 return;
210 }
211 Stack.pop_back(); // At the end of the array
212 }
213 }
214 }
215
216 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
217 /// on the type stack.
218 void StepToLeaf() {
219 if (Stack.empty()) return;
220 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
221 StackState &SS = Stack.back();
222 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
223 if (ST->getElementTypes().empty()) {
224 assert(SS.Idx == 0);
225 PopStackAndAdvance();
226 } else {
227 // Step into the structure...
228 assert(SS.Idx < ST->getElementTypes().size());
229 const StructLayout *SL = TD.getStructLayout(ST);
230 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
231 SS.Offset+SL->MemberOffsets[SS.Idx]));
232 }
233 } else {
234 const ArrayType *AT = cast<ArrayType>(SS.Ty);
235 if (AT->getNumElements() == 0) {
236 assert(SS.Idx == 0);
237 PopStackAndAdvance();
238 } else {
239 // Step into the array...
240 assert(SS.Idx < AT->getNumElements());
241 Stack.push_back(StackState(AT->getElementType(),
242 SS.Offset+SS.Idx*
243 TD.getTypeSize(AT->getElementType())));
244 }
245 }
246 }
247 }
248 };
249}
250
251/// ElementTypesAreCompatible - Check to see if the specified types are
252/// "physically" compatible. If so, return true, else return false. We only
253/// have to check the fields in T1: T2 may be larger than T1.
254///
255static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
256 TypeElementWalker T1W(T1), T2W(T2);
257
258 while (!T1W.isDone() && !T2W.isDone()) {
259 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
260 return false;
261
262 const Type *T1 = T1W.getCurrentType();
263 const Type *T2 = T2W.getCurrentType();
264 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
265 return false;
266
267 T1W.StepToNextType();
268 T2W.StepToNextType();
269 }
270
271 return T1W.isDone();
272}
273
274
Chris Lattner08db7192002-11-06 06:20:27 +0000275/// mergeTypeInfo - This method merges the specified type into the current node
276/// at the specified offset. This may update the current node's type record if
277/// this gives more information to the node, it may do nothing to the node if
278/// this information is already known, or it may merge the node completely (and
279/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000280///
Chris Lattner08db7192002-11-06 06:20:27 +0000281/// This method returns true if the node is completely folded, otherwise false.
282///
Chris Lattner088b6392003-03-03 17:13:31 +0000283bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
284 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000285 // Check to make sure the Size member is up-to-date. Size can be one of the
286 // following:
287 // Size = 0, Ty = Void: Nothing is known about this node.
288 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
289 // Size = 1, Ty = Void, Array = 1: The node is collapsed
290 // Otherwise, sizeof(Ty) = Size
291 //
Chris Lattner18552922002-11-18 21:44:46 +0000292 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
293 (Size == 0 && !Ty->isSized() && !isArray()) ||
294 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
295 (Size == 0 && !Ty->isSized() && !isArray()) ||
296 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000297 "Size member of DSNode doesn't match the type structure!");
298 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000299
Chris Lattner18552922002-11-18 21:44:46 +0000300 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000301 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000302
Chris Lattner08db7192002-11-06 06:20:27 +0000303 // Return true immediately if the node is completely folded.
304 if (isNodeCompletelyFolded()) return true;
305
Chris Lattner23f83dc2002-11-08 22:49:57 +0000306 // If this is an array type, eliminate the outside arrays because they won't
307 // be used anyway. This greatly reduces the size of large static arrays used
308 // as global variables, for example.
309 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000310 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000311 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
312 // FIXME: we might want to keep small arrays, but must be careful about
313 // things like: [2 x [10000 x int*]]
314 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000315 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000316 }
317
Chris Lattner08db7192002-11-06 06:20:27 +0000318 // Figure out how big the new type we're merging in is...
319 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
320
321 // Otherwise check to see if we can fold this type into the current node. If
322 // we can't, we fold the node completely, if we can, we potentially update our
323 // internal state.
324 //
Chris Lattner18552922002-11-18 21:44:46 +0000325 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000326 // If this is the first type that this node has seen, just accept it without
327 // question....
328 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000329 assert(!isArray() && "This shouldn't happen!");
330 Ty = NewTy;
331 NodeType &= ~Array;
332 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000333 Size = NewTySize;
334
335 // Calculate the number of outgoing links from this node.
336 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
337 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000338 }
Chris Lattner08db7192002-11-06 06:20:27 +0000339
340 // Handle node expansion case here...
341 if (Offset+NewTySize > Size) {
342 // It is illegal to grow this node if we have treated it as an array of
343 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000344 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000345 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000346 return true;
347 }
348
349 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000350 std::cerr << "UNIMP: Trying to merge a growth type into "
351 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000352 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000353 return true;
354 }
355
356 // Okay, the situation is nice and simple, we are trying to merge a type in
357 // at offset 0 that is bigger than our current type. Implement this by
358 // switching to the new type and then merge in the smaller one, which should
359 // hit the other code path here. If the other code path decides it's not
360 // ok, it will collapse the node as appropriate.
361 //
Chris Lattner18552922002-11-18 21:44:46 +0000362 const Type *OldTy = Ty;
363 Ty = NewTy;
364 NodeType &= ~Array;
365 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000366 Size = NewTySize;
367
368 // Must grow links to be the appropriate size...
369 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
370
371 // Merge in the old type now... which is guaranteed to be smaller than the
372 // "current" type.
373 return mergeTypeInfo(OldTy, 0);
374 }
375
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000376 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000377 "Cannot merge something into a part of our type that doesn't exist!");
378
Chris Lattner18552922002-11-18 21:44:46 +0000379 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000380 // type that starts at offset Offset.
381 //
382 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000383 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000384 while (O < Offset) {
385 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
386
387 switch (SubType->getPrimitiveID()) {
388 case Type::StructTyID: {
389 const StructType *STy = cast<StructType>(SubType);
390 const StructLayout &SL = *TD.getStructLayout(STy);
391
392 unsigned i = 0, e = SL.MemberOffsets.size();
393 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
394 /* empty */;
395
396 // The offset we are looking for must be in the i'th element...
397 SubType = STy->getElementTypes()[i];
398 O += SL.MemberOffsets[i];
399 break;
400 }
401 case Type::ArrayTyID: {
402 SubType = cast<ArrayType>(SubType)->getElementType();
403 unsigned ElSize = TD.getTypeSize(SubType);
404 unsigned Remainder = (Offset-O) % ElSize;
405 O = Offset-Remainder;
406 break;
407 }
408 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000409 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000410 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000411 }
412 }
413
414 assert(O == Offset && "Could not achieve the correct offset!");
415
416 // If we found our type exactly, early exit
417 if (SubType == NewTy) return false;
418
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000419 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
420
421 // Ok, we are getting desperate now. Check for physical subtyping, where we
422 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000423 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000424 SubTypeSize && SubTypeSize < 256 &&
425 ElementTypesAreCompatible(NewTy, SubType))
426 return false;
427
Chris Lattner08db7192002-11-06 06:20:27 +0000428 // Okay, so we found the leader type at the offset requested. Search the list
429 // of types that starts at this offset. If SubType is currently an array or
430 // structure, the type desired may actually be the first element of the
431 // composite type...
432 //
Chris Lattner18552922002-11-18 21:44:46 +0000433 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000434 while (SubType != NewTy) {
435 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000436 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000437 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000438 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000439 case Type::StructTyID: {
440 const StructType *STy = cast<StructType>(SubType);
441 const StructLayout &SL = *TD.getStructLayout(STy);
442 if (SL.MemberOffsets.size() > 1)
443 NextPadSize = SL.MemberOffsets[1];
444 else
445 NextPadSize = SubTypeSize;
446 NextSubType = STy->getElementTypes()[0];
447 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000448 break;
Chris Lattner18552922002-11-18 21:44:46 +0000449 }
Chris Lattner08db7192002-11-06 06:20:27 +0000450 case Type::ArrayTyID:
451 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000452 NextSubTypeSize = TD.getTypeSize(NextSubType);
453 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000454 break;
455 default: ;
456 // fall out
457 }
458
459 if (NextSubType == 0)
460 break; // In the default case, break out of the loop
461
Chris Lattner18552922002-11-18 21:44:46 +0000462 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000463 break; // Don't allow shrinking to a smaller type than NewTySize
464 SubType = NextSubType;
465 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000466 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000467 }
468
469 // If we found the type exactly, return it...
470 if (SubType == NewTy)
471 return false;
472
473 // Check to see if we have a compatible, but different type...
474 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000475 // Check to see if this type is obviously convertible... int -> uint f.e.
476 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000477 return false;
478
479 // Check to see if we have a pointer & integer mismatch going on here,
480 // loading a pointer as a long, for example.
481 //
482 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
483 NewTy->isInteger() && isa<PointerType>(SubType))
484 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000485 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
486 // We are accessing the field, plus some structure padding. Ignore the
487 // structure padding.
488 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000489 }
490
Chris Lattner58f98d02003-07-02 04:38:49 +0000491 Module *M = 0;
492#ifdef INCLUDE_PARENT_GRAPH
493 if (getParentGraph()->getReturnNodes().size())
494 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
495#endif
496 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
497 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
498 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
499 << "SubType: ";
500 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000501
Chris Lattner088b6392003-03-03 17:13:31 +0000502 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000503 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000504}
505
Chris Lattner08db7192002-11-06 06:20:27 +0000506
507
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000508// addEdgeTo - Add an edge from the current node to the specified node. This
509// can cause merging of nodes in the graph.
510//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000511void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000512 if (NH.getNode() == 0) return; // Nothing to do
513
Chris Lattner08db7192002-11-06 06:20:27 +0000514 DSNodeHandle &ExistingEdge = getLink(Offset);
515 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000516 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000517 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000518 } else { // No merging to perform...
519 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000520 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000521}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000522
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000523
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000524// MergeSortedVectors - Efficiently merge a vector into another vector where
525// duplicates are not allowed and both are sorted. This assumes that 'T's are
526// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000527//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000528static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
529 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000530 // By far, the most common cases will be the simple ones. In these cases,
531 // avoid having to allocate a temporary vector...
532 //
533 if (Src.empty()) { // Nothing to merge in...
534 return;
535 } else if (Dest.empty()) { // Just copy the result in...
536 Dest = Src;
537 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000538 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000539 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000540 std::lower_bound(Dest.begin(), Dest.end(), V);
541 if (I == Dest.end() || *I != Src[0]) // If not already contained...
542 Dest.insert(I, Src[0]);
543 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000544 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000545 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000546 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000547 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
548 if (I == Dest.end() || *I != Tmp) // If not already contained...
549 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000550
551 } else {
552 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000553 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000554
555 // Make space for all of the type entries now...
556 Dest.resize(Dest.size()+Src.size());
557
558 // Merge the two sorted ranges together... into Dest.
559 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
560
561 // Now erase any duplicate entries that may have accumulated into the
562 // vectors (because they were in both of the input sets)
563 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
564 }
565}
566
567
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000568// MergeNodes() - Helper function for DSNode::mergeWith().
569// This function does the hard work of merging two nodes, CurNodeH
570// and NH after filtering out trivial cases and making sure that
571// CurNodeH.offset >= NH.offset.
572//
573// ***WARNING***
574// Since merging may cause either node to go away, we must always
575// use the node-handles to refer to the nodes. These node handles are
576// automatically updated during merging, so will always provide access
577// to the correct node after a merge.
578//
579void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
580 assert(CurNodeH.getOffset() >= NH.getOffset() &&
581 "This should have been enforced in the caller.");
582
583 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
584 // respect to NH.Offset) is now zero. NOffset is the distance from the base
585 // of our object that N starts from.
586 //
587 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
588 unsigned NSize = NH.getNode()->getSize();
589
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000590 // If the two nodes are of different size, and the smaller node has the array
591 // bit set, collapse!
592 if (NSize != CurNodeH.getNode()->getSize()) {
593 if (NSize < CurNodeH.getNode()->getSize()) {
594 if (NH.getNode()->isArray())
595 NH.getNode()->foldNodeCompletely();
596 } else if (CurNodeH.getNode()->isArray()) {
597 NH.getNode()->foldNodeCompletely();
598 }
599 }
600
601 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000602 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000603 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000604 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000605
606 // If we are merging a node with a completely folded node, then both nodes are
607 // now completely folded.
608 //
609 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
610 if (!NH.getNode()->isNodeCompletelyFolded()) {
611 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000612 assert(NH.getNode() && NH.getOffset() == 0 &&
613 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000614 NOffset = NH.getOffset();
615 NSize = NH.getNode()->getSize();
616 assert(NOffset == 0 && NSize == 1);
617 }
618 } else if (NH.getNode()->isNodeCompletelyFolded()) {
619 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000620 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
621 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000622 NOffset = NH.getOffset();
623 NSize = NH.getNode()->getSize();
624 assert(NOffset == 0 && NSize == 1);
625 }
626
Chris Lattner72d29a42003-02-11 23:11:51 +0000627 DSNode *N = NH.getNode();
628 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000629 assert(!CurNodeH.getNode()->isDeadNode());
630
631 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000632 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000633
Chris Lattner72d29a42003-02-11 23:11:51 +0000634 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000635 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000636 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000637
Chris Lattner72d29a42003-02-11 23:11:51 +0000638 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
639 //
640 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
641 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000642 if (Link.getNode()) {
643 // Compute the offset into the current node at which to
644 // merge this link. In the common case, this is a linear
645 // relation to the offset in the original node (with
646 // wrapping), but if the current node gets collapsed due to
647 // recursive merging, we must make sure to merge in all remaining
648 // links at offset zero.
649 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000650 DSNode *CN = CurNodeH.getNode();
651 if (CN->Size != 1)
652 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
653 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000654 }
655 }
656
657 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000658 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000659
660 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000661 if (!N->Globals.empty()) {
662 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000663
664 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000665 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000666 }
667}
668
669
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000670// mergeWith - Merge this node and the specified node, moving all links to and
671// from the argument node into the current node, deleting the node argument.
672// Offset indicates what offset the specified node is to be merged into the
673// current node.
674//
675// The specified node may be a null pointer (in which case, nothing happens).
676//
677void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
678 DSNode *N = NH.getNode();
679 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000680 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000681
Chris Lattnerbd92b732003-06-19 21:15:11 +0000682 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000683 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
684
Chris Lattner02606632002-11-04 06:48:26 +0000685 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000686 // We cannot merge two pieces of the same node together, collapse the node
687 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000688 DEBUG(std::cerr << "Attempting to merge two chunks of"
689 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000690 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000691 return;
692 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000693
Chris Lattner5190ce82002-11-12 07:20:45 +0000694 // If both nodes are not at offset 0, make sure that we are merging the node
695 // at an later offset into the node with the zero offset.
696 //
697 if (Offset < NH.getOffset()) {
698 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
699 return;
700 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
701 // If the offsets are the same, merge the smaller node into the bigger node
702 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
703 return;
704 }
705
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000706 // Ok, now we can merge the two nodes. Use a static helper that works with
707 // two node handles, since "this" may get merged away at intermediate steps.
708 DSNodeHandle CurNodeH(this, Offset);
709 DSNodeHandle NHCopy(NH);
710 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000711}
712
Chris Lattner9de906c2002-10-20 22:11:44 +0000713//===----------------------------------------------------------------------===//
714// DSCallSite Implementation
715//===----------------------------------------------------------------------===//
716
Vikram S. Adve26b98262002-10-20 21:41:02 +0000717// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000718Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000719 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000720}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000721
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000722
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000723//===----------------------------------------------------------------------===//
724// DSGraph Implementation
725//===----------------------------------------------------------------------===//
726
Chris Lattnera9d65662003-06-30 05:57:30 +0000727/// getFunctionNames - Return a space separated list of the name of the
728/// functions in this graph (if any)
729std::string DSGraph::getFunctionNames() const {
730 switch (getReturnNodes().size()) {
731 case 0: return "Globals graph";
732 case 1: return getReturnNodes().begin()->first->getName();
733 default:
734 std::string Return;
735 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
736 I != getReturnNodes().end(); ++I)
737 Return += I->first->getName() + " ";
738 Return.erase(Return.end()-1, Return.end()); // Remove last space character
739 return Return;
740 }
741}
742
743
Chris Lattner5a540632003-06-30 03:15:25 +0000744DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000745 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000746 NodeMapTy NodeMap;
747 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000748}
749
Chris Lattner5a540632003-06-30 03:15:25 +0000750DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
751 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000752 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000753 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000754}
755
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000756DSGraph::~DSGraph() {
757 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000758 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000759 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000760 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000761
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000762 // Drop all intra-node references, so that assertions don't fail...
763 std::for_each(Nodes.begin(), Nodes.end(),
764 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000765
766 // Delete all of the nodes themselves...
767 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
768}
769
Chris Lattner0d9bab82002-07-18 00:12:30 +0000770// dump - Allow inspection of graph in a debugger.
771void DSGraph::dump() const { print(std::cerr); }
772
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000773
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000774/// remapLinks - Change all of the Links in the current node according to the
775/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000776///
Chris Lattner8d327672003-06-30 03:36:09 +0000777void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000778 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
779 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
780 Links[i].setNode(H.getNode());
781 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
782 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000783}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000784
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000785
Chris Lattner5a540632003-06-30 03:15:25 +0000786/// cloneInto - Clone the specified DSGraph into the current graph. The
787/// translated ScalarMap for the old function is filled into the OldValMap
788/// member, and the translated ReturnNodes map is returned into ReturnNodes.
789///
790/// The CloneFlags member controls various aspects of the cloning process.
791///
792void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
793 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
794 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000795 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000796 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000797
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000798 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000799
800 // Duplicate all of the nodes, populating the node map...
801 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000802
803 // Remove alloca or mod/ref bits as specified...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000804 unsigned BitsToClear =((CloneFlags & StripAllocaBit) ? DSNode::AllocaNode : 0)
805 | ((CloneFlags & StripModRefBits) ? (DSNode::Modified | DSNode::Read) : 0);
806 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000807 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000808 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000809 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000810 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000811 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000812 }
813
Chris Lattner18552922002-11-18 21:44:46 +0000814#ifndef NDEBUG
815 Timer::addPeakMemoryMeasurement();
816#endif
817
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000818 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000819 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000820 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000821
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000822 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000823 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000824 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000825 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000826 DSNodeHandle &H = OldValMap[I->first];
827 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
828 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000829
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000830 // If this is a global, add the global to this fn or merge if already exists
Chris Lattner7b1ceaa2003-06-30 05:18:26 +0000831 if (isa<GlobalValue>(I->first))
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000832 ScalarMap[I->first].mergeWith(H);
Chris Lattnercf15db32002-10-17 20:09:52 +0000833 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000834
Chris Lattner679e8e12002-11-08 21:27:12 +0000835 if (!(CloneFlags & DontCloneCallNodes)) {
836 // Copy the function calls list...
837 unsigned FC = FunctionCalls.size(); // FirstCall
838 FunctionCalls.reserve(FC+G.FunctionCalls.size());
839 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
840 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000841 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000842
Chris Lattneracf491f2002-11-08 22:27:09 +0000843 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000844 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000845 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000846 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
847 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
848 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
849 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000850
Chris Lattner5a540632003-06-30 03:15:25 +0000851 // Map the return node pointers over...
852 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
853 E = G.getReturnNodes().end(); I != E; ++I) {
854 const DSNodeHandle &Ret = I->second;
855 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
856 OldReturnNodes.insert(std::make_pair(I->first,
857 DSNodeHandle(MappedRet.getNode(),
858 MappedRet.getOffset()+Ret.getOffset())));
859 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000860}
861
Chris Lattner076c1f92002-11-07 06:31:54 +0000862/// mergeInGraph - The method is used for merging graphs together. If the
863/// argument graph is not *this, it makes a clone of the specified graph, then
864/// merges the nodes specified in the call site with the formal arguments in the
865/// graph.
866///
Chris Lattner9f930552003-06-30 05:27:18 +0000867void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
868 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000869 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000870 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000871
872 // If this is not a recursive call, clone the graph into this graph...
873 if (&Graph != this) {
874 // Clone the callee's graph into the current graph, keeping
875 // track of where scalars in the old graph _used_ to point,
876 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +0000877 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000878
879 // The clone call may invalidate any of the vectors in the data
880 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +0000881 ReturnNodesTy OldRetNodes;
882 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +0000883
884 // We need to map the arguments for the function to the cloned nodes old
885 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +0000886 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +0000887 ScalarMap = &OldValMap;
888 } else {
Chris Lattner5a540632003-06-30 03:15:25 +0000889 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +0000890 ScalarMap = &getScalarMap();
891 }
892
893 // Merge the return value with the return value of the context...
894 RetVal.mergeWith(CS.getRetVal());
895
896 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +0000897 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000898
Chris Lattner076c1f92002-11-07 06:31:54 +0000899 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
900 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000901 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000902 ++AI;
903#ifndef NDEBUG
904 if (AI == F.aend())
905 std::cerr << "Bad call to Function: " << F.getName() << "\n";
906#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000907 }
Chris Lattner5d274582003-02-06 00:15:08 +0000908 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000909
910 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000911 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000912 DSNodeHandle &NH = (*ScalarMap)[AI];
913 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
914 NH.mergeWith(CS.getPtrArg(i));
915 }
916}
917
Chris Lattner58f98d02003-07-02 04:38:49 +0000918/// getCallSiteForArguments - Get the arguments and return value bindings for
919/// the specified function in the current graph.
920///
921DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
922 std::vector<DSNodeHandle> Args;
923
924 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
925 if (isPointerType(I->getType()))
926 Args.push_back(getScalarMap().find(I)->second);
927
928 return DSCallSite(*(CallInst*)0, getReturnNodeFor(F), &F, Args);
929}
930
931
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000932
Chris Lattner0d9bab82002-07-18 00:12:30 +0000933// markIncompleteNodes - Mark the specified node as having contents that are not
934// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +0000935// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +0000936// must recursively traverse the data structure graph, marking all reachable
937// nodes as incomplete.
938//
939static void markIncompleteNode(DSNode *N) {
940 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +0000941 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000942
943 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000944 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +0000945
946 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000947 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
948 if (DSNode *DSN = N->getLink(i).getNode())
949 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000950}
951
Chris Lattnere71ffc22002-11-11 03:36:55 +0000952static void markIncomplete(DSCallSite &Call) {
953 // Then the return value is certainly incomplete!
954 markIncompleteNode(Call.getRetVal().getNode());
955
956 // All objects pointed to by function arguments are incomplete!
957 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
958 markIncompleteNode(Call.getPtrArg(i).getNode());
959}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000960
961// markIncompleteNodes - Traverse the graph, identifying nodes that may be
962// modified by other functions that have not been resolved yet. This marks
963// nodes that are reachable through three sources of "unknownness":
964//
965// Global Variables, Function Calls, and Incoming Arguments
966//
967// For any node that may have unknown components (because something outside the
968// scope of current analysis may have modified it), the 'Incomplete' flag is
969// added to the NodeType.
970//
Chris Lattner394471f2003-01-23 22:05:33 +0000971void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000972 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +0000973 if (Flags & DSGraph::MarkFormalArgs)
974 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
975 FI != E; ++FI) {
976 Function &F = *FI->first;
977 if (F.getName() != "main")
978 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
979 if (isPointerType(I->getType()) &&
980 ScalarMap.find(I) != ScalarMap.end())
981 markIncompleteNode(ScalarMap[I].getNode());
982 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000983
984 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000985 if (!shouldPrintAuxCalls())
986 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
987 markIncomplete(FunctionCalls[i]);
988 else
989 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
990 markIncomplete(AuxFunctionCalls[i]);
991
Chris Lattner0d9bab82002-07-18 00:12:30 +0000992
Chris Lattner93d7a212003-02-09 18:41:49 +0000993 // Mark all global nodes as incomplete...
994 if ((Flags & DSGraph::IgnoreGlobals) == 0)
995 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +0000996 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +0000997 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000998}
999
Chris Lattneraa8146f2002-11-10 06:59:55 +00001000static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1001 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001002 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001003 // No interesting info?
1004 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001005 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001006 Edge.setNode(0); // Kill the edge!
1007}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001008
Chris Lattneraa8146f2002-11-10 06:59:55 +00001009static inline bool nodeContainsExternalFunction(const DSNode *N) {
1010 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1011 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1012 if (Globals[i]->isExternal())
1013 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001014 return false;
1015}
1016
Chris Lattner5a540632003-06-30 03:15:25 +00001017static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001018
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001019 // Remove trivially identical function calls
1020 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001021 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1022
1023 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001024 DSNode *LastCalleeNode = 0;
1025 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001026 unsigned NumDuplicateCalls = 0;
1027 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001028 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001029 DSCallSite &CS = Calls[i];
1030
Chris Lattnere4258442002-11-11 21:35:38 +00001031 // If the Callee is a useless edge, this must be an unreachable call site,
1032 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001033 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001034 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001035 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001036 CS.swap(Calls.back());
1037 Calls.pop_back();
1038 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001039 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001040 // If the return value or any arguments point to a void node with no
1041 // information at all in it, and the call node is the only node to point
1042 // to it, remove the edge to the node (killing the node).
1043 //
1044 killIfUselessEdge(CS.getRetVal());
1045 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1046 killIfUselessEdge(CS.getPtrArg(a));
1047
1048 // If this call site calls the same function as the last call site, and if
1049 // the function pointer contains an external function, this node will
1050 // never be resolved. Merge the arguments of the call node because no
1051 // information will be lost.
1052 //
Chris Lattner923fc052003-02-05 21:59:58 +00001053 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1054 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001055 ++NumDuplicateCalls;
1056 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001057 if (LastCalleeNode)
1058 LastCalleeContainsExternalFunction =
1059 nodeContainsExternalFunction(LastCalleeNode);
1060 else
1061 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001062 }
1063
Chris Lattner58f98d02003-07-02 04:38:49 +00001064#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001065 if (LastCalleeContainsExternalFunction ||
1066 // This should be more than enough context sensitivity!
1067 // FIXME: Evaluate how many times this is tripped!
1068 NumDuplicateCalls > 20) {
1069 DSCallSite &OCS = Calls[i-1];
1070 OCS.mergeWith(CS);
1071
1072 // The node will now be eliminated as a duplicate!
1073 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1074 CS = OCS;
1075 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1076 OCS = CS;
1077 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001078#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001079 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001080 if (CS.isDirectCall()) {
1081 LastCalleeFunc = CS.getCalleeFunc();
1082 LastCalleeNode = 0;
1083 } else {
1084 LastCalleeNode = CS.getCalleeNode();
1085 LastCalleeFunc = 0;
1086 }
Chris Lattnere4258442002-11-11 21:35:38 +00001087 NumDuplicateCalls = 0;
1088 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001089 }
1090 }
1091
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001092 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1093 Calls.end());
1094
Chris Lattner33312f72002-11-08 01:21:07 +00001095 // Track the number of call nodes merged away...
1096 NumCallNodesMerged += NumFns-Calls.size();
1097
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001098 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001099 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001100}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001101
Chris Lattneraa8146f2002-11-10 06:59:55 +00001102
Chris Lattnere2219762002-07-18 18:22:40 +00001103// removeTriviallyDeadNodes - After the graph has been constructed, this method
1104// removes all unreachable nodes that are created because they got merged with
1105// other nodes in the graph. These nodes will all be trivially unreachable, so
1106// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001107//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001108void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001109 removeIdenticalCalls(FunctionCalls);
1110 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001111
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001112 for (unsigned i = 0; i != Nodes.size(); ++i) {
1113 DSNode *Node = Nodes[i];
Chris Lattner72d50a02003-06-28 21:58:28 +00001114 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001115 // This is a useless node if it has no mod/ref info (checked above),
1116 // outgoing edges (which it cannot, as it is not modified in this
1117 // context), and it has no incoming edges. If it is a global node it may
1118 // have all of these properties and still have incoming edges, due to the
1119 // scalar map, so we check those now.
1120 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001121 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001122 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001123
1124 // Loop through and make sure all of the globals are referring directly
1125 // to the node...
1126 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1127 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1128 assert(N == Node && "ScalarMap doesn't match globals list!");
1129 }
1130
Chris Lattnerbd92b732003-06-19 21:15:11 +00001131 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001132 if (Node->getNumReferrers() == Globals.size()) {
1133 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1134 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001135 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001136 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001137 }
1138 }
1139
Chris Lattnerbd92b732003-06-19 21:15:11 +00001140 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001141 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001142 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001143 Nodes[i--] = Nodes.back();
1144 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001145 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001146 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001147}
1148
1149
Chris Lattner5c7380e2003-01-29 21:10:20 +00001150/// markReachableNodes - This method recursively traverses the specified
1151/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1152/// to the set, which allows it to only traverse visited nodes once.
1153///
Chris Lattner41c04f72003-02-01 04:52:08 +00001154void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001155 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001156 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001157 if (ReachableNodes.count(this)) return; // Already marked reachable
1158 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001159
Chris Lattner5c7380e2003-01-29 21:10:20 +00001160 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1161 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1162}
1163
Chris Lattner41c04f72003-02-01 04:52:08 +00001164void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001165 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001166 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001167
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001168 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1169 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001170}
1171
Chris Lattnera1220af2003-02-01 06:17:02 +00001172// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1173// looking for a node that is marked alive. If an alive node is found, return
1174// true, otherwise return false. If an alive node is reachable, this node is
1175// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001176//
Chris Lattnera1220af2003-02-01 06:17:02 +00001177static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
1178 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001179 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001180 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001181
Chris Lattneraa8146f2002-11-10 06:59:55 +00001182 // If we know that this node is alive, return so!
1183 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001184
Chris Lattneraa8146f2002-11-10 06:59:55 +00001185 // Otherwise, we don't think the node is alive yet, check for infinite
1186 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001187 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001188 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001189
Chris Lattner08db7192002-11-06 06:20:27 +00001190 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +00001191 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
1192 N->markReachableNodes(Alive);
1193 return true;
1194 }
1195 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001196}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001197
Chris Lattnera1220af2003-02-01 06:17:02 +00001198// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1199// alive nodes.
1200//
Chris Lattner41c04f72003-02-01 04:52:08 +00001201static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1202 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +00001203 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1204 return true;
1205 if (CS.isIndirectCall() &&
1206 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001207 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001208 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1209 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001210 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001211 return false;
1212}
1213
Chris Lattnere2219762002-07-18 18:22:40 +00001214// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1215// subgraphs that are unreachable. This often occurs because the data
1216// structure doesn't "escape" into it's caller, and thus should be eliminated
1217// from the caller's graph entirely. This is only appropriate to use when
1218// inlining graphs.
1219//
Chris Lattner394471f2003-01-23 22:05:33 +00001220void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001221 // Reduce the amount of work we have to do... remove dummy nodes left over by
1222 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001223 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001224
Chris Lattnere2219762002-07-18 18:22:40 +00001225 // FIXME: Merge nontrivially identical call nodes...
1226
1227 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001228 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001229 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001230
Chris Lattneraa8146f2002-11-10 06:59:55 +00001231 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001232 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001233 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001234 assert(I->second.getNode() && "Null global node?");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001235 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1236 ++I;
1237 } else {
1238 // Check to see if this is a worthless node generated for non-pointer
1239 // values, such as integers. Consider an addition of long types: A+B.
1240 // Assuming we can track all uses of the value in this context, and it is
1241 // NOT used as a pointer, we can delete the node. We will be able to
1242 // detect this situation if the node pointed to ONLY has Unknown bit set
1243 // in the node. In this case, the node is not incomplete, does not point
1244 // to any other nodes (no mod/ref bits set), and is therefore
1245 // uninteresting for data structure analysis. If we run across one of
1246 // these, prune the scalar pointing to it.
1247 //
1248 DSNode *N = I->second.getNode();
Chris Lattnerbd92b732003-06-19 21:15:11 +00001249 if (N->isUnknownNode() && !isa<Argument>(I->first)) {
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001250 ScalarMap.erase(I++);
1251 } else {
1252 I->second.getNode()->markReachableNodes(Alive);
1253 ++I;
1254 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001255 }
Chris Lattnere2219762002-07-18 18:22:40 +00001256
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001257 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001258 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1259 I != E; ++I)
1260 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001261
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001262 // Mark any nodes reachable by primary calls as alive...
1263 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1264 FunctionCalls[i].markReachableNodes(Alive);
1265
1266 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001267 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001268 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1269 do {
1270 Visited.clear();
1271 // If any global nodes points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001272 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001273 // unreachable globals in the list.
1274 //
1275 Iterate = false;
1276 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1277 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1278 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1279 GlobalNodes.pop_back(); // Erase efficiently
1280 Iterate = true;
1281 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001282
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001283 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1284 if (!AuxFCallsAlive[i] &&
1285 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1286 AuxFunctionCalls[i].markReachableNodes(Alive);
1287 AuxFCallsAlive[i] = true;
1288 Iterate = true;
1289 }
1290 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001291
1292 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001293 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001294 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1295 if (AuxFCallsAlive[i])
1296 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001297 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001298 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001299 // Move the unreachable call nodes to the globals graph...
1300 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1301 AuxFunctionCalls.begin()+CurIdx,
1302 AuxFunctionCalls.end());
1303 }
1304 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001305 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1306 AuxFunctionCalls.end());
1307
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001308 // At this point, any nodes which are visited, but not alive, are nodes which
1309 // should be moved to the globals graph. Loop over all nodes, eliminating
1310 // completely unreachable nodes, and moving visited nodes to the globals graph
1311 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001312 std::vector<DSNode*> DeadNodes;
1313 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001314 for (unsigned i = 0; i != Nodes.size(); ++i)
1315 if (!Alive.count(Nodes[i])) {
1316 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001317 Nodes[i--] = Nodes.back(); // move node to end of vector
1318 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001319 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1320 Visited.count(N)) { // Visited but not alive?
1321 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner58f98d02003-07-02 04:38:49 +00001322#ifdef INCLUDE_PARENT_GRAPH
Chris Lattner72d29a42003-02-11 23:11:51 +00001323 N->setParentGraph(GlobalsGraph);
Chris Lattner58f98d02003-07-02 04:38:49 +00001324#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001325 } else { // Otherwise, delete the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001326 assert((!N->isGlobalNode() ||
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001327 (Flags & DSGraph::RemoveUnreachableGlobals))
1328 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001329 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1330 // << "] Node is dead: "; N->dump();
1331 DeadNodes.push_back(N);
1332 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001333 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001334 } else {
1335 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001336 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001337
1338 // Now that the nodes have either been deleted or moved to the globals graph,
1339 // loop over the scalarmap, updating the entries for globals...
1340 //
1341 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1342 // In this array we start the remapping, which can cause merging. Because
1343 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1344 // must always go through the ScalarMap (which contains DSNodeHandles [which
1345 // cannot be invalidated by merging]).
1346 //
1347 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1348 Value *G = GlobalNodes[i].first;
Chris Lattner8d327672003-06-30 03:36:09 +00001349 ScalarMapTy::iterator I = ScalarMap.find(G);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001350 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1351 assert(I->second.getNode() && "Global not pointing to anything?");
1352 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1353 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1354 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1355 "Global not pointing to anything?");
1356 ScalarMap.erase(I);
1357 }
1358
1359 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1360 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001361 if (!GlobalNodes.empty())
1362 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001363 } else {
1364 // If we are in the top-down pass, remove all unreachable globals from the
1365 // ScalarMap...
1366 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1367 ScalarMap.erase(GlobalNodes[i].first);
1368 }
1369
Chris Lattner72d29a42003-02-11 23:11:51 +00001370 // Loop over all of the dead nodes now, deleting them since their referrer
1371 // count is zero.
1372 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1373 delete DeadNodes[i];
1374
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001375 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001376}
1377
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001378void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001379 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1380 Nodes[i]->assertOK();
1381 return; // FIXME: remove
Chris Lattner8d327672003-06-30 03:36:09 +00001382 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001383 E = ScalarMap.end(); I != E; ++I) {
1384 assert(I->second.getNode() && "Null node in scalarmap!");
1385 AssertNodeInGraph(I->second.getNode());
1386 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001387 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001388 "Global points to node, but node isn't global?");
1389 AssertNodeContainsGlobal(I->second.getNode(), GV);
1390 }
1391 }
1392 AssertCallNodesInGraph();
1393 AssertAuxCallNodesInGraph();
1394}