blob: b125b5d67f396ad67dd8a461ed8dbc7cc5116362 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "llvm/Analysis/DSGraph.h"
15#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000016#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000018#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000019#include "llvm/Assembly/Writer.h"
Chris Lattner6806f562003-08-01 22:15:03 +000020#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000021#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000022#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000023#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000024#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000025
Chris Lattner08db7192002-11-06 06:20:27 +000026namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000027 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
28 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000029};
30
Chris Lattnerb1060432002-11-07 05:20:53 +000031namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000032 extern TargetData TD;
33}
Chris Lattnerb1060432002-11-07 05:20:53 +000034using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000035
Chris Lattner731b2d72003-02-13 19:09:00 +000036DSNode *DSNodeHandle::HandleForwarding() const {
37 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
38
39 // Handle node forwarding here!
40 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
41 Offset += N->ForwardNH.getOffset();
42
43 if (--N->NumReferrers == 0) {
44 // Removing the last referrer to the node, sever the forwarding link
45 N->stopForwarding();
46 }
47
48 N = Next;
49 N->NumReferrers++;
50 if (N->Size <= Offset) {
51 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
52 Offset = 0;
53 }
54 return N;
55}
56
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000057//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000058// DSNode Implementation
59//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000060
Chris Lattnerbd92b732003-06-19 21:15:11 +000061DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000062 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000063 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000064 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000065 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000066}
67
Chris Lattner0d9bab82002-07-18 00:12:30 +000068// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000069DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000070 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000071 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000072 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000073}
74
Chris Lattner72d29a42003-02-11 23:11:51 +000075void DSNode::assertOK() const {
76 assert((Ty != Type::VoidTy ||
77 Ty == Type::VoidTy && (Size == 0 ||
78 (NodeType & DSNode::Array))) &&
79 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +000080
81 assert(ParentGraph && "Node has no parent?");
82 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
83 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
84 assert(SM.find(Globals[i]) != SM.end());
85 assert(SM.find(Globals[i])->second.getNode() == this);
86 }
Chris Lattner72d29a42003-02-11 23:11:51 +000087}
88
89/// forwardNode - Mark this node as being obsolete, and all references to it
90/// should be forwarded to the specified node and offset.
91///
92void DSNode::forwardNode(DSNode *To, unsigned Offset) {
93 assert(this != To && "Cannot forward a node to itself!");
94 assert(ForwardNH.isNull() && "Already forwarding from this node!");
95 if (To->Size <= 1) Offset = 0;
96 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
97 "Forwarded offset is wrong!");
98 ForwardNH.setNode(To);
99 ForwardNH.setOffset(Offset);
100 NodeType = DEAD;
101 Size = 0;
102 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000103}
104
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000105// addGlobal - Add an entry for a global value to the Globals list. This also
106// marks the node with the 'G' flag if it does not already have it.
107//
108void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000109 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000110 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000111 std::lower_bound(Globals.begin(), Globals.end(), GV);
112
113 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000114 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000115 Globals.insert(I, GV);
116 NodeType |= GlobalNode;
117 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000118}
119
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000120/// foldNodeCompletely - If we determine that this node has some funny
121/// behavior happening to it that we cannot represent, we fold it down to a
122/// single, completely pessimistic, node. This node is represented as a
123/// single byte with a single TypeEntry of "void".
124///
125void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000126 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000127
Chris Lattner08db7192002-11-06 06:20:27 +0000128 ++NumFolds;
129
Chris Lattner72d29a42003-02-11 23:11:51 +0000130 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000131 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000132 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000133 DestNode->Ty = Type::VoidTy;
134 DestNode->Size = 1;
135 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000136
Chris Lattner72d29a42003-02-11 23:11:51 +0000137 // Start forwarding to the destination node...
138 forwardNode(DestNode, 0);
139
140 if (Links.size()) {
141 DestNode->Links.push_back(Links[0]);
142 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000143
Chris Lattner72d29a42003-02-11 23:11:51 +0000144 // If we have links, merge all of our outgoing links together...
145 for (unsigned i = Links.size()-1; i != 0; --i)
146 NH.getNode()->Links[0].mergeWith(Links[i]);
147 Links.clear();
148 } else {
149 DestNode->Links.resize(1);
150 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000151}
Chris Lattner076c1f92002-11-07 06:31:54 +0000152
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000153/// isNodeCompletelyFolded - Return true if this node has been completely
154/// folded down to something that can never be expanded, effectively losing
155/// all of the field sensitivity that may be present in the node.
156///
157bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000158 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000159}
160
161
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000162namespace {
163 /// TypeElementWalker Class - Used for implementation of physical subtyping...
164 ///
165 class TypeElementWalker {
166 struct StackState {
167 const Type *Ty;
168 unsigned Offset;
169 unsigned Idx;
170 StackState(const Type *T, unsigned Off = 0)
171 : Ty(T), Offset(Off), Idx(0) {}
172 };
173
174 std::vector<StackState> Stack;
175 public:
176 TypeElementWalker(const Type *T) {
177 Stack.push_back(T);
178 StepToLeaf();
179 }
180
181 bool isDone() const { return Stack.empty(); }
182 const Type *getCurrentType() const { return Stack.back().Ty; }
183 unsigned getCurrentOffset() const { return Stack.back().Offset; }
184
185 void StepToNextType() {
186 PopStackAndAdvance();
187 StepToLeaf();
188 }
189
190 private:
191 /// PopStackAndAdvance - Pop the current element off of the stack and
192 /// advance the underlying element to the next contained member.
193 void PopStackAndAdvance() {
194 assert(!Stack.empty() && "Cannot pop an empty stack!");
195 Stack.pop_back();
196 while (!Stack.empty()) {
197 StackState &SS = Stack.back();
198 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
199 ++SS.Idx;
200 if (SS.Idx != ST->getElementTypes().size()) {
201 const StructLayout *SL = TD.getStructLayout(ST);
202 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
203 return;
204 }
205 Stack.pop_back(); // At the end of the structure
206 } else {
207 const ArrayType *AT = cast<ArrayType>(SS.Ty);
208 ++SS.Idx;
209 if (SS.Idx != AT->getNumElements()) {
210 SS.Offset += TD.getTypeSize(AT->getElementType());
211 return;
212 }
213 Stack.pop_back(); // At the end of the array
214 }
215 }
216 }
217
218 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
219 /// on the type stack.
220 void StepToLeaf() {
221 if (Stack.empty()) return;
222 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
223 StackState &SS = Stack.back();
224 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
225 if (ST->getElementTypes().empty()) {
226 assert(SS.Idx == 0);
227 PopStackAndAdvance();
228 } else {
229 // Step into the structure...
230 assert(SS.Idx < ST->getElementTypes().size());
231 const StructLayout *SL = TD.getStructLayout(ST);
232 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
233 SS.Offset+SL->MemberOffsets[SS.Idx]));
234 }
235 } else {
236 const ArrayType *AT = cast<ArrayType>(SS.Ty);
237 if (AT->getNumElements() == 0) {
238 assert(SS.Idx == 0);
239 PopStackAndAdvance();
240 } else {
241 // Step into the array...
242 assert(SS.Idx < AT->getNumElements());
243 Stack.push_back(StackState(AT->getElementType(),
244 SS.Offset+SS.Idx*
245 TD.getTypeSize(AT->getElementType())));
246 }
247 }
248 }
249 }
250 };
251}
252
253/// ElementTypesAreCompatible - Check to see if the specified types are
254/// "physically" compatible. If so, return true, else return false. We only
255/// have to check the fields in T1: T2 may be larger than T1.
256///
257static bool ElementTypesAreCompatible(const Type *T1, const Type *T2) {
258 TypeElementWalker T1W(T1), T2W(T2);
259
260 while (!T1W.isDone() && !T2W.isDone()) {
261 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
262 return false;
263
264 const Type *T1 = T1W.getCurrentType();
265 const Type *T2 = T2W.getCurrentType();
266 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
267 return false;
268
269 T1W.StepToNextType();
270 T2W.StepToNextType();
271 }
272
273 return T1W.isDone();
274}
275
276
Chris Lattner08db7192002-11-06 06:20:27 +0000277/// mergeTypeInfo - This method merges the specified type into the current node
278/// at the specified offset. This may update the current node's type record if
279/// this gives more information to the node, it may do nothing to the node if
280/// this information is already known, or it may merge the node completely (and
281/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000282///
Chris Lattner08db7192002-11-06 06:20:27 +0000283/// This method returns true if the node is completely folded, otherwise false.
284///
Chris Lattner088b6392003-03-03 17:13:31 +0000285bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
286 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000287 // Check to make sure the Size member is up-to-date. Size can be one of the
288 // following:
289 // Size = 0, Ty = Void: Nothing is known about this node.
290 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
291 // Size = 1, Ty = Void, Array = 1: The node is collapsed
292 // Otherwise, sizeof(Ty) = Size
293 //
Chris Lattner18552922002-11-18 21:44:46 +0000294 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
295 (Size == 0 && !Ty->isSized() && !isArray()) ||
296 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
297 (Size == 0 && !Ty->isSized() && !isArray()) ||
298 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000299 "Size member of DSNode doesn't match the type structure!");
300 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000301
Chris Lattner18552922002-11-18 21:44:46 +0000302 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000303 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000304
Chris Lattner08db7192002-11-06 06:20:27 +0000305 // Return true immediately if the node is completely folded.
306 if (isNodeCompletelyFolded()) return true;
307
Chris Lattner23f83dc2002-11-08 22:49:57 +0000308 // If this is an array type, eliminate the outside arrays because they won't
309 // be used anyway. This greatly reduces the size of large static arrays used
310 // as global variables, for example.
311 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000312 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000313 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
314 // FIXME: we might want to keep small arrays, but must be careful about
315 // things like: [2 x [10000 x int*]]
316 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000317 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000318 }
319
Chris Lattner08db7192002-11-06 06:20:27 +0000320 // Figure out how big the new type we're merging in is...
321 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
322
323 // Otherwise check to see if we can fold this type into the current node. If
324 // we can't, we fold the node completely, if we can, we potentially update our
325 // internal state.
326 //
Chris Lattner18552922002-11-18 21:44:46 +0000327 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000328 // If this is the first type that this node has seen, just accept it without
329 // question....
330 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000331 assert(!isArray() && "This shouldn't happen!");
332 Ty = NewTy;
333 NodeType &= ~Array;
334 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000335 Size = NewTySize;
336
337 // Calculate the number of outgoing links from this node.
338 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
339 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000340 }
Chris Lattner08db7192002-11-06 06:20:27 +0000341
342 // Handle node expansion case here...
343 if (Offset+NewTySize > Size) {
344 // It is illegal to grow this node if we have treated it as an array of
345 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000346 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000347 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000348 return true;
349 }
350
351 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000352 std::cerr << "UNIMP: Trying to merge a growth type into "
353 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000354 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000355 return true;
356 }
357
358 // Okay, the situation is nice and simple, we are trying to merge a type in
359 // at offset 0 that is bigger than our current type. Implement this by
360 // switching to the new type and then merge in the smaller one, which should
361 // hit the other code path here. If the other code path decides it's not
362 // ok, it will collapse the node as appropriate.
363 //
Chris Lattner18552922002-11-18 21:44:46 +0000364 const Type *OldTy = Ty;
365 Ty = NewTy;
366 NodeType &= ~Array;
367 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000368 Size = NewTySize;
369
370 // Must grow links to be the appropriate size...
371 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
372
373 // Merge in the old type now... which is guaranteed to be smaller than the
374 // "current" type.
375 return mergeTypeInfo(OldTy, 0);
376 }
377
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000378 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000379 "Cannot merge something into a part of our type that doesn't exist!");
380
Chris Lattner18552922002-11-18 21:44:46 +0000381 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000382 // type that starts at offset Offset.
383 //
384 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000385 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000386 while (O < Offset) {
387 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
388
389 switch (SubType->getPrimitiveID()) {
390 case Type::StructTyID: {
391 const StructType *STy = cast<StructType>(SubType);
392 const StructLayout &SL = *TD.getStructLayout(STy);
393
394 unsigned i = 0, e = SL.MemberOffsets.size();
395 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
396 /* empty */;
397
398 // The offset we are looking for must be in the i'th element...
399 SubType = STy->getElementTypes()[i];
400 O += SL.MemberOffsets[i];
401 break;
402 }
403 case Type::ArrayTyID: {
404 SubType = cast<ArrayType>(SubType)->getElementType();
405 unsigned ElSize = TD.getTypeSize(SubType);
406 unsigned Remainder = (Offset-O) % ElSize;
407 O = Offset-Remainder;
408 break;
409 }
410 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000411 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000412 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000413 }
414 }
415
416 assert(O == Offset && "Could not achieve the correct offset!");
417
418 // If we found our type exactly, early exit
419 if (SubType == NewTy) return false;
420
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000421 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
422
423 // Ok, we are getting desperate now. Check for physical subtyping, where we
424 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000425 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000426 SubTypeSize && SubTypeSize < 256 &&
427 ElementTypesAreCompatible(NewTy, SubType))
428 return false;
429
Chris Lattner08db7192002-11-06 06:20:27 +0000430 // Okay, so we found the leader type at the offset requested. Search the list
431 // of types that starts at this offset. If SubType is currently an array or
432 // structure, the type desired may actually be the first element of the
433 // composite type...
434 //
Chris Lattner18552922002-11-18 21:44:46 +0000435 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000436 while (SubType != NewTy) {
437 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000438 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000439 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000440 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000441 case Type::StructTyID: {
442 const StructType *STy = cast<StructType>(SubType);
443 const StructLayout &SL = *TD.getStructLayout(STy);
444 if (SL.MemberOffsets.size() > 1)
445 NextPadSize = SL.MemberOffsets[1];
446 else
447 NextPadSize = SubTypeSize;
448 NextSubType = STy->getElementTypes()[0];
449 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000450 break;
Chris Lattner18552922002-11-18 21:44:46 +0000451 }
Chris Lattner08db7192002-11-06 06:20:27 +0000452 case Type::ArrayTyID:
453 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000454 NextSubTypeSize = TD.getTypeSize(NextSubType);
455 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000456 break;
457 default: ;
458 // fall out
459 }
460
461 if (NextSubType == 0)
462 break; // In the default case, break out of the loop
463
Chris Lattner18552922002-11-18 21:44:46 +0000464 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000465 break; // Don't allow shrinking to a smaller type than NewTySize
466 SubType = NextSubType;
467 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000468 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000469 }
470
471 // If we found the type exactly, return it...
472 if (SubType == NewTy)
473 return false;
474
475 // Check to see if we have a compatible, but different type...
476 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000477 // Check to see if this type is obviously convertible... int -> uint f.e.
478 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000479 return false;
480
481 // Check to see if we have a pointer & integer mismatch going on here,
482 // loading a pointer as a long, for example.
483 //
484 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
485 NewTy->isInteger() && isa<PointerType>(SubType))
486 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000487 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
488 // We are accessing the field, plus some structure padding. Ignore the
489 // structure padding.
490 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000491 }
492
Chris Lattner58f98d02003-07-02 04:38:49 +0000493 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000494 if (getParentGraph()->getReturnNodes().size())
495 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000496 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 Lattner808a7ae2003-09-20 16:34:13 +0000719 return *Site.getInstruction()->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);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000748 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattner0d9bab82002-07-18 00:12:30 +0000749}
750
Chris Lattner5a540632003-06-30 03:15:25 +0000751DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
752 : GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000753 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000754 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000755 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattnereff0da92002-10-21 15:32:34 +0000756}
757
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000758DSGraph::~DSGraph() {
759 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000760 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000761 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000762 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000763 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000764
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000765 // Drop all intra-node references, so that assertions don't fail...
766 std::for_each(Nodes.begin(), Nodes.end(),
767 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000768
769 // Delete all of the nodes themselves...
770 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
771}
772
Chris Lattner0d9bab82002-07-18 00:12:30 +0000773// dump - Allow inspection of graph in a debugger.
774void DSGraph::dump() const { print(std::cerr); }
775
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000776
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000777/// remapLinks - Change all of the Links in the current node according to the
778/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000779///
Chris Lattner8d327672003-06-30 03:36:09 +0000780void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000781 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
782 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
783 Links[i].setNode(H.getNode());
784 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
785 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000786}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000787
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000788
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000789/// cloneReachableNodes - Clone all reachable nodes from *Node into the
790/// current graph. This is a recursive function. The map OldNodeMap is a
791/// map from the original nodes to their clones.
792///
793void DSGraph::cloneReachableNodes(const DSNode* Node,
794 unsigned BitsToClear,
795 NodeMapTy& OldNodeMap,
796 NodeMapTy& CompletedNodeMap) {
797 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
798 return;
799
800 DSNodeHandle& NH = OldNodeMap[Node];
801 if (NH.getNode() != NULL)
802 return;
803
804 // else Node has not yet been cloned: clone it and clear the specified bits
805 NH = new DSNode(*Node, this); // enters in OldNodeMap
806 NH.getNode()->maskNodeTypes(~BitsToClear);
807
808 // now recursively clone nodes pointed to by this node
809 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
810 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
811 if (const DSNode* nextNode = Link.getNode())
812 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
813 }
814}
815
816void DSGraph::cloneReachableSubgraph(const DSGraph& G,
817 const hash_set<const DSNode*>& RootNodes,
818 NodeMapTy& OldNodeMap,
819 NodeMapTy& CompletedNodeMap,
820 unsigned CloneFlags) {
821 if (RootNodes.empty())
822 return;
823
824 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
825 assert(&G != this && "Cannot clone graph into itself!");
826 assert((*RootNodes.begin())->getParentGraph() == &G &&
827 "Root nodes do not belong to this graph!");
828
829 // Remove alloca or mod/ref bits as specified...
830 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
831 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
832 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
833 BitsToClear |= DSNode::DEAD; // Clear dead flag...
834
835 // Clone all nodes reachable from each root node, using a recursive helper
836 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
837 E = RootNodes.end(); I != E; ++I)
838 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
839
840 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
841 NodeMapTy MergedMap(OldNodeMap);
842 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
843
844 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
845 // to point into the current graph. MergedMap gives the full mapping.
846 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
847 I->second.getNode()->remapLinks(MergedMap);
848
849 // Now merge cloned global nodes with their copies in the current graph
850 // Just look through OldNodeMap to find such nodes!
851 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
852 if (I->first->isGlobalNode()) {
853 DSNodeHandle &GClone = I->second;
854 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
855 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
856 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
857 DSNodeHandle &GH = ScalarMap[Globals[gi]];
858 GH.mergeWith(GClone);
859 }
860 }
861}
862
863
864/// updateFromGlobalGraph - This function rematerializes global nodes and
865/// nodes reachable from them from the globals graph into the current graph.
866/// It invokes cloneReachableSubgraph, using the globals in the current graph
867/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
868/// merging globals that are already up-to-date in the current graph. In
869/// practice, in the TD pass, this is likely to be a large fraction of the
870/// live global nodes in each function (since most live nodes are likely to
871/// have been brought up-to-date in at _some_ caller or callee).
872///
873void DSGraph::updateFromGlobalGraph() {
874
875 // Use a map to keep track of the mapping between nodes in the globals graph
876 // and this graph for up-to-date global nodes, which do not need to be cloned.
877 NodeMapTy CompletedMap;
878
879 // Put the live, non-up-to-date global nodes into a set and the up-to-date
880 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
881 hash_set<const DSNode*> GlobalNodeSet;
882 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
883 E = getScalarMap().end(); I != E; ++I)
884 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
885 DSNode* GNode = I->second.getNode();
886 assert(GNode && "No node for live global in current Graph?");
887 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
888 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
889 GlobalNodeSet.insert(GGNode);
890 else { // GNode is up-to-date
891 CompletedMap[GGNode] = I->second;
892 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
893 "Links dont match in a node that is supposed to be up-to-date?"
894 "\nremapLinks() will not work if the links don't match!");
895 }
896 }
897
898 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
899 // and merge the cloned global nodes with the corresponding ones, if any.
900 NodeMapTy OldNodeMap;
901 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
902
903 // Merging global nodes leaves behind unused nodes: get rid of them now.
904 OldNodeMap.clear(); // remove references before dead node cleanup
905 CompletedMap.clear(); // remove references before dead node cleanup
906 removeTriviallyDeadNodes();
907}
908
Chris Lattner5a540632003-06-30 03:15:25 +0000909/// cloneInto - Clone the specified DSGraph into the current graph. The
910/// translated ScalarMap for the old function is filled into the OldValMap
911/// member, and the translated ReturnNodes map is returned into ReturnNodes.
912///
913/// The CloneFlags member controls various aspects of the cloning process.
914///
915void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
916 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
917 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000918 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000919 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000920
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000921 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000922
923 // Duplicate all of the nodes, populating the node map...
924 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000925
926 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000927 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
928 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
929 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000930 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000931 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000932 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000933 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000934 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000935 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000936 }
937
Chris Lattner18552922002-11-18 21:44:46 +0000938#ifndef NDEBUG
939 Timer::addPeakMemoryMeasurement();
940#endif
941
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000942 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000943 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000944 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000945
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000946 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000947 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000948 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000949 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000950 DSNodeHandle &H = OldValMap[I->first];
951 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
952 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000953
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000954 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000955 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
956 ScalarMap[GV].mergeWith(H);
957 InlinedGlobals.insert(GV);
958 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000959 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000960
Chris Lattner679e8e12002-11-08 21:27:12 +0000961 if (!(CloneFlags & DontCloneCallNodes)) {
962 // Copy the function calls list...
963 unsigned FC = FunctionCalls.size(); // FirstCall
964 FunctionCalls.reserve(FC+G.FunctionCalls.size());
965 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
966 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000967 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000968
Chris Lattneracf491f2002-11-08 22:27:09 +0000969 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000970 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000971 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000972 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
973 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
974 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
975 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000976
Chris Lattner5a540632003-06-30 03:15:25 +0000977 // Map the return node pointers over...
978 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
979 E = G.getReturnNodes().end(); I != E; ++I) {
980 const DSNodeHandle &Ret = I->second;
981 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
982 OldReturnNodes.insert(std::make_pair(I->first,
983 DSNodeHandle(MappedRet.getNode(),
984 MappedRet.getOffset()+Ret.getOffset())));
985 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000986}
987
Chris Lattner076c1f92002-11-07 06:31:54 +0000988/// mergeInGraph - The method is used for merging graphs together. If the
989/// argument graph is not *this, it makes a clone of the specified graph, then
990/// merges the nodes specified in the call site with the formal arguments in the
991/// graph.
992///
Chris Lattner9f930552003-06-30 05:27:18 +0000993void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
994 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000995 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000996 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +0000997
998 // If this is not a recursive call, clone the graph into this graph...
999 if (&Graph != this) {
1000 // Clone the callee's graph into the current graph, keeping
1001 // track of where scalars in the old graph _used_ to point,
1002 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +00001003 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +00001004
1005 // The clone call may invalidate any of the vectors in the data
1006 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +00001007 ReturnNodesTy OldRetNodes;
1008 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +00001009
1010 // We need to map the arguments for the function to the cloned nodes old
1011 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +00001012 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +00001013 ScalarMap = &OldValMap;
1014 } else {
Chris Lattner5a540632003-06-30 03:15:25 +00001015 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +00001016 ScalarMap = &getScalarMap();
1017 }
1018
1019 // Merge the return value with the return value of the context...
1020 RetVal.mergeWith(CS.getRetVal());
1021
1022 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +00001023 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +00001024
Chris Lattner076c1f92002-11-07 06:31:54 +00001025 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1026 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +00001027 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001028 ++AI;
1029#ifndef NDEBUG
1030 if (AI == F.aend())
1031 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1032#endif
Chris Lattner076c1f92002-11-07 06:31:54 +00001033 }
Chris Lattner5d274582003-02-06 00:15:08 +00001034 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +00001035
1036 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +00001037 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +00001038 DSNodeHandle &NH = (*ScalarMap)[AI];
1039 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1040 NH.mergeWith(CS.getPtrArg(i));
1041 }
1042}
1043
Chris Lattner58f98d02003-07-02 04:38:49 +00001044/// getCallSiteForArguments - Get the arguments and return value bindings for
1045/// the specified function in the current graph.
1046///
1047DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1048 std::vector<DSNodeHandle> Args;
1049
1050 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1051 if (isPointerType(I->getType()))
1052 Args.push_back(getScalarMap().find(I)->second);
1053
Chris Lattner808a7ae2003-09-20 16:34:13 +00001054 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001055}
1056
1057
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001058
Chris Lattner0d9bab82002-07-18 00:12:30 +00001059// markIncompleteNodes - Mark the specified node as having contents that are not
1060// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001061// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001062// must recursively traverse the data structure graph, marking all reachable
1063// nodes as incomplete.
1064//
1065static void markIncompleteNode(DSNode *N) {
1066 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001067 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001068
1069 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001070 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001071
Misha Brukman2f2d0652003-09-11 18:14:24 +00001072 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001073 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1074 if (DSNode *DSN = N->getLink(i).getNode())
1075 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001076}
1077
Chris Lattnere71ffc22002-11-11 03:36:55 +00001078static void markIncomplete(DSCallSite &Call) {
1079 // Then the return value is certainly incomplete!
1080 markIncompleteNode(Call.getRetVal().getNode());
1081
1082 // All objects pointed to by function arguments are incomplete!
1083 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1084 markIncompleteNode(Call.getPtrArg(i).getNode());
1085}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001086
1087// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1088// modified by other functions that have not been resolved yet. This marks
1089// nodes that are reachable through three sources of "unknownness":
1090//
1091// Global Variables, Function Calls, and Incoming Arguments
1092//
1093// For any node that may have unknown components (because something outside the
1094// scope of current analysis may have modified it), the 'Incomplete' flag is
1095// added to the NodeType.
1096//
Chris Lattner394471f2003-01-23 22:05:33 +00001097void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001098 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001099 if (Flags & DSGraph::MarkFormalArgs)
1100 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1101 FI != E; ++FI) {
1102 Function &F = *FI->first;
1103 if (F.getName() != "main")
1104 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1105 if (isPointerType(I->getType()) &&
1106 ScalarMap.find(I) != ScalarMap.end())
1107 markIncompleteNode(ScalarMap[I].getNode());
1108 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001109
1110 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001111 if (!shouldPrintAuxCalls())
1112 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1113 markIncomplete(FunctionCalls[i]);
1114 else
1115 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1116 markIncomplete(AuxFunctionCalls[i]);
1117
Chris Lattner0d9bab82002-07-18 00:12:30 +00001118
Chris Lattner93d7a212003-02-09 18:41:49 +00001119 // Mark all global nodes as incomplete...
1120 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1121 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001122 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001123 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001124}
1125
Chris Lattneraa8146f2002-11-10 06:59:55 +00001126static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1127 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001128 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001129 // No interesting info?
1130 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001131 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001132 Edge.setNode(0); // Kill the edge!
1133}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001134
Chris Lattneraa8146f2002-11-10 06:59:55 +00001135static inline bool nodeContainsExternalFunction(const DSNode *N) {
1136 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1137 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1138 if (Globals[i]->isExternal())
1139 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001140 return false;
1141}
1142
Chris Lattner5a540632003-06-30 03:15:25 +00001143static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001144
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001145 // Remove trivially identical function calls
1146 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001147 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1148
1149 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001150 DSNode *LastCalleeNode = 0;
1151 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001152 unsigned NumDuplicateCalls = 0;
1153 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001154 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001155 DSCallSite &CS = Calls[i];
1156
Chris Lattnere4258442002-11-11 21:35:38 +00001157 // If the Callee is a useless edge, this must be an unreachable call site,
1158 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001159 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001160 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001161 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001162 CS.swap(Calls.back());
1163 Calls.pop_back();
1164 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001165 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001166 // If the return value or any arguments point to a void node with no
1167 // information at all in it, and the call node is the only node to point
1168 // to it, remove the edge to the node (killing the node).
1169 //
1170 killIfUselessEdge(CS.getRetVal());
1171 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1172 killIfUselessEdge(CS.getPtrArg(a));
1173
1174 // If this call site calls the same function as the last call site, and if
1175 // the function pointer contains an external function, this node will
1176 // never be resolved. Merge the arguments of the call node because no
1177 // information will be lost.
1178 //
Chris Lattner923fc052003-02-05 21:59:58 +00001179 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1180 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001181 ++NumDuplicateCalls;
1182 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001183 if (LastCalleeNode)
1184 LastCalleeContainsExternalFunction =
1185 nodeContainsExternalFunction(LastCalleeNode);
1186 else
1187 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001188 }
1189
Chris Lattner58f98d02003-07-02 04:38:49 +00001190#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001191 if (LastCalleeContainsExternalFunction ||
1192 // This should be more than enough context sensitivity!
1193 // FIXME: Evaluate how many times this is tripped!
1194 NumDuplicateCalls > 20) {
1195 DSCallSite &OCS = Calls[i-1];
1196 OCS.mergeWith(CS);
1197
1198 // The node will now be eliminated as a duplicate!
1199 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1200 CS = OCS;
1201 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1202 OCS = CS;
1203 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001204#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001205 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001206 if (CS.isDirectCall()) {
1207 LastCalleeFunc = CS.getCalleeFunc();
1208 LastCalleeNode = 0;
1209 } else {
1210 LastCalleeNode = CS.getCalleeNode();
1211 LastCalleeFunc = 0;
1212 }
Chris Lattnere4258442002-11-11 21:35:38 +00001213 NumDuplicateCalls = 0;
1214 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001215 }
1216 }
1217
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001218 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1219 Calls.end());
1220
Chris Lattner33312f72002-11-08 01:21:07 +00001221 // Track the number of call nodes merged away...
1222 NumCallNodesMerged += NumFns-Calls.size();
1223
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001224 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001225 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001226}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001227
Chris Lattneraa8146f2002-11-10 06:59:55 +00001228
Chris Lattnere2219762002-07-18 18:22:40 +00001229// removeTriviallyDeadNodes - After the graph has been constructed, this method
1230// removes all unreachable nodes that are created because they got merged with
1231// other nodes in the graph. These nodes will all be trivially unreachable, so
1232// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001233//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001234void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001235 removeIdenticalCalls(FunctionCalls);
1236 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001237
Chris Lattnerbab8c282003-09-20 21:34:07 +00001238 // Loop over all of the nodes in the graph, calling getNode on each field.
1239 // This will cause all nodes to update their forwarding edges, causing
1240 // forwarded nodes to be delete-able.
1241 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1242 DSNode *N = Nodes[i];
1243 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1244 N->getLink(l*N->getPointerSize()).getNode();
1245 }
1246
1247 // Likewise, forward any edges from the scalar nodes...
1248 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1249 I != E; ++I)
1250 I->second.getNode();
1251
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001252 bool isGlobalsGraph = !GlobalsGraph;
1253
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001254 for (unsigned i = 0; i != Nodes.size(); ++i) {
1255 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001256
1257 // Do not remove *any* global nodes in the globals graph.
1258 // This is a special case because such nodes may not have I, M, R flags set.
1259 if (Node->isGlobalNode() && isGlobalsGraph)
1260 continue;
1261
Chris Lattner72d50a02003-06-28 21:58:28 +00001262 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001263 // This is a useless node if it has no mod/ref info (checked above),
1264 // outgoing edges (which it cannot, as it is not modified in this
1265 // context), and it has no incoming edges. If it is a global node it may
1266 // have all of these properties and still have incoming edges, due to the
1267 // scalar map, so we check those now.
1268 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001269 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001270 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001271
1272 // Loop through and make sure all of the globals are referring directly
1273 // to the node...
1274 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1275 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1276 assert(N == Node && "ScalarMap doesn't match globals list!");
1277 }
1278
Chris Lattnerbd92b732003-06-19 21:15:11 +00001279 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001280 if (Node->getNumReferrers() == Globals.size()) {
1281 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1282 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001283 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001284 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001285 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001286
1287#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1288 //
1289 // *** It seems to me that we should be able to simply check if
1290 // *** there are fewer or equal #referrers as #globals and make
1291 // *** sure that all those referrers are in the scalar map?
1292 //
1293 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1294 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1295
1296#ifndef NDEBUG
1297 // Loop through and make sure all of the globals are referring directly
1298 // to the node...
1299 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1300 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1301 assert(N == Node && "ScalarMap doesn't match globals list!");
1302 }
1303#endif
1304
1305 // Make sure NumReferrers still agrees. The node is truly dead.
1306 assert(Node->getNumReferrers() == Globals.size());
1307 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1308 ScalarMap.erase(Globals[j]);
1309 Node->makeNodeDead();
1310 }
1311#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001312 }
1313
Chris Lattnerbd92b732003-06-19 21:15:11 +00001314 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001315 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001316 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001317 Nodes[i--] = Nodes.back();
1318 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001319 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001320 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001321}
1322
1323
Chris Lattner5c7380e2003-01-29 21:10:20 +00001324/// markReachableNodes - This method recursively traverses the specified
1325/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1326/// to the set, which allows it to only traverse visited nodes once.
1327///
Chris Lattner41c04f72003-02-01 04:52:08 +00001328void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001329 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001330 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001331 if (ReachableNodes.count(this)) return; // Already marked reachable
1332 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001333
Chris Lattner5c7380e2003-01-29 21:10:20 +00001334 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1335 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1336}
1337
Chris Lattner41c04f72003-02-01 04:52:08 +00001338void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001339 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001340 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001341
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001342 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1343 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001344}
1345
Chris Lattnera1220af2003-02-01 06:17:02 +00001346// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1347// looking for a node that is marked alive. If an alive node is found, return
1348// true, otherwise return false. If an alive node is reachable, this node is
1349// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001350//
Chris Lattnera1220af2003-02-01 06:17:02 +00001351static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001352 hash_set<DSNode*> &Visited,
1353 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001354 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001355 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001356
Chris Lattner85cfe012003-07-03 02:03:53 +00001357 // If this is a global node, it will end up in the globals graph anyway, so we
1358 // don't need to worry about it.
1359 if (IgnoreGlobals && N->isGlobalNode()) return false;
1360
Chris Lattneraa8146f2002-11-10 06:59:55 +00001361 // If we know that this node is alive, return so!
1362 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001363
Chris Lattneraa8146f2002-11-10 06:59:55 +00001364 // Otherwise, we don't think the node is alive yet, check for infinite
1365 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001366 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001367 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001368
Chris Lattner08db7192002-11-06 06:20:27 +00001369 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001370 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1371 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001372 N->markReachableNodes(Alive);
1373 return true;
1374 }
1375 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001376}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001377
Chris Lattnera1220af2003-02-01 06:17:02 +00001378// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1379// alive nodes.
1380//
Chris Lattner41c04f72003-02-01 04:52:08 +00001381static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001382 hash_set<DSNode*> &Visited,
1383 bool IgnoreGlobals) {
1384 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1385 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001386 return true;
1387 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001388 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001389 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001390 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001391 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1392 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001393 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001394 return false;
1395}
1396
Chris Lattnere2219762002-07-18 18:22:40 +00001397// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1398// subgraphs that are unreachable. This often occurs because the data
1399// structure doesn't "escape" into it's caller, and thus should be eliminated
1400// from the caller's graph entirely. This is only appropriate to use when
1401// inlining graphs.
1402//
Chris Lattner394471f2003-01-23 22:05:33 +00001403void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner85cfe012003-07-03 02:03:53 +00001404 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
1405
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001406 // Reduce the amount of work we have to do... remove dummy nodes left over by
1407 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001408 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001409
Misha Brukman2f2d0652003-09-11 18:14:24 +00001410 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001411
1412 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001413 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001414 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001415
Chris Lattneraa8146f2002-11-10 06:59:55 +00001416 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001417 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001418 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001419 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001420 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001421 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1422 ++I;
1423 } else {
1424 // Check to see if this is a worthless node generated for non-pointer
1425 // values, such as integers. Consider an addition of long types: A+B.
1426 // Assuming we can track all uses of the value in this context, and it is
1427 // NOT used as a pointer, we can delete the node. We will be able to
1428 // detect this situation if the node pointed to ONLY has Unknown bit set
1429 // in the node. In this case, the node is not incomplete, does not point
1430 // to any other nodes (no mod/ref bits set), and is therefore
1431 // uninteresting for data structure analysis. If we run across one of
1432 // these, prune the scalar pointing to it.
1433 //
1434 DSNode *N = I->second.getNode();
Chris Lattner85cfe012003-07-03 02:03:53 +00001435 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001436 ScalarMap.erase(I++);
1437 } else {
1438 I->second.getNode()->markReachableNodes(Alive);
1439 ++I;
1440 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001441 }
Chris Lattnere2219762002-07-18 18:22:40 +00001442
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001443 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001444 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1445 I != E; ++I)
1446 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001447
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001448 // Mark any nodes reachable by primary calls as alive...
1449 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1450 FunctionCalls[i].markReachableNodes(Alive);
1451
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001452 // Copy and merge all information about globals to the GlobalsGraph
1453 // if this is not a final pass (where unreachable globals are removed)
1454 NodeMapTy GlobalNodeMap;
1455 hash_set<const DSNode*> GlobalNodeSet;
1456
1457 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1458 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1459 GlobalNodeSet.insert(I->second); // put global nodes into a set
1460
1461 // Now find globals and aux call nodes that are already live or reach a live
1462 // value (which makes them live in turn), and continue till no more are found.
1463 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001464 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001465 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001466 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1467 do {
1468 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001469 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001470 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001471 // unreachable globals in the list.
1472 //
1473 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001474 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1475 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1476 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1477 Flags & DSGraph::RemoveUnreachableGlobals)) {
1478 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1479 GlobalNodes.pop_back(); // erase efficiently
1480 Iterate = true;
1481 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001482
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001483 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1484 // call nodes that get resolved will be difficult to remove from that graph.
1485 // The final unresolved call nodes must be handled specially at the end of
1486 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001487 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1488 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001489 (AuxFunctionCalls[i].isIndirectCall()
1490 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1491 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001492 AuxFunctionCalls[i].markReachableNodes(Alive);
1493 AuxFCallsAlive[i] = true;
1494 Iterate = true;
1495 }
1496 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001497
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001498 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001499 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001500 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1501 if (AuxFCallsAlive[i])
1502 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001503
1504 // Copy and merge all global nodes and dead aux call nodes into the
1505 // GlobalsGraph, and all nodes reachable from those nodes
1506 //
1507 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1508
1509 // First, add the dead aux call nodes to the set of root nodes for cloning
1510 // -- return value at this call site, if any
1511 // -- actual arguments passed at this call site
1512 // -- callee node at this call site, if this is an indirect call
1513 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1514 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1515 GlobalNodeSet.insert(RetNode);
1516 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1517 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1518 GlobalNodeSet.insert(ArgTarget);
1519 if (AuxFunctionCalls[i].isIndirectCall())
1520 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1521 }
1522
1523 // There are no "pre-completed" nodes so use any empty map for those.
1524 // Strip all alloca bits since the current function is only for the BU pass.
1525 // Strip all incomplete bits since they are short-lived properties and they
1526 // will be correctly computed when rematerializing nodes into the functions.
1527 //
1528 NodeMapTy CompletedMap;
1529 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1530 GlobalNodeMap, CompletedMap,
1531 (DSGraph::StripAllocaBit |
1532 DSGraph::StripIncompleteBit));
1533 }
1534
1535 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001536 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001537 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001538
1539 // Copy the unreachable call nodes to the globals graph, updating
1540 // their target pointers using the GlobalNodeMap
1541 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1542 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1543 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001544 }
1545 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001546 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1547 AuxFunctionCalls.end());
1548
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001549 // We are finally done with the GlobalNodeMap so we can clear it and
1550 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1551 GlobalNodeMap.clear();
1552 GlobalsGraph->removeTriviallyDeadNodes();
1553
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001554 // At this point, any nodes which are visited, but not alive, are nodes
1555 // which can be removed. Loop over all nodes, eliminating completely
1556 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001557 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001558 std::vector<DSNode*> DeadNodes;
1559 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001560 for (unsigned i = 0; i != Nodes.size(); ++i)
1561 if (!Alive.count(Nodes[i])) {
1562 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001563 Nodes[i--] = Nodes.back(); // move node to end of vector
1564 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001565 DeadNodes.push_back(N);
1566 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001567 } else {
1568 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001569 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001570
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001571 // Remove all unreachable globals from the ScalarMap.
1572 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1573 // In either case, the dead nodes will not be in the set Alive.
1574 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1575 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1576 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1577 if (!Alive.count(GlobalNodes[i].second))
1578 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001579 }
1580
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001581 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001582 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1583 delete DeadNodes[i];
1584
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001585 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001586}
1587
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001588void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001589 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1590 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001591
Chris Lattner8d327672003-06-30 03:36:09 +00001592 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001593 E = ScalarMap.end(); I != E; ++I) {
1594 assert(I->second.getNode() && "Null node in scalarmap!");
1595 AssertNodeInGraph(I->second.getNode());
1596 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001597 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001598 "Global points to node, but node isn't global?");
1599 AssertNodeContainsGlobal(I->second.getNode(), GV);
1600 }
1601 }
1602 AssertCallNodesInGraph();
1603 AssertAuxCallNodesInGraph();
1604}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001605
Chris Lattner7ddb0132003-08-05 18:38:37 +00001606/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1607/// globals graph into the DS, BU or TD graph for a function. This code retains
1608/// all globals, i.e., does not delete unreachable globals after they are
1609/// inlined.
1610///
1611void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001612 NodeMapTy GlobalNodeMap;
1613 ScalarMapTy OldValMap;
1614 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001615 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1616 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1617 DSGraph::DontCloneAuxCallNodes);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001618
1619 // Now merge existing global nodes in the GlobalsGraph with their copies
1620 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1621 I != E; ++I)
1622 if (isa<GlobalValue>(I->first)) { // Found a global node
1623 DSNodeHandle &GH = I->second;
1624 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1625 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1626 }
1627
1628 // Merging leaves behind unused nodes: get rid of them now.
1629 GlobalNodeMap.clear();
1630 OldValMap.clear();
1631 OldRetNodes.clear();
1632 removeTriviallyDeadNodes();
1633}