blob: f67d0d613f1d89e41b76eb15594336bb04d7e451 [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 Lattner0b144872004-01-27 22:03:40 +000020#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000021#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000022#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000024#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000025#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner08db7192002-11-06 06:20:27 +000028namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000029 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
31 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
32 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000033 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
34 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner0b144872004-01-27 22:03:40 +000035
36 cl::opt<bool>
37 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
38 cl::desc("Make DSA less aggressive when cloning graphs"));
Chris Lattner08db7192002-11-06 06:20:27 +000039};
40
Chris Lattnera88a55c2004-01-28 02:41:32 +000041#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000042#define TIME_REGION(VARNAME, DESC) \
43 NamedRegionTimer VARNAME(DESC)
44#else
45#define TIME_REGION(VARNAME, DESC)
46#endif
47
Chris Lattnerb1060432002-11-07 05:20:53 +000048using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000049
Chris Lattner731b2d72003-02-13 19:09:00 +000050DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000051 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000052
53 // Handle node forwarding here!
54 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
55 Offset += N->ForwardNH.getOffset();
56
57 if (--N->NumReferrers == 0) {
58 // Removing the last referrer to the node, sever the forwarding link
59 N->stopForwarding();
60 }
61
62 N = Next;
63 N->NumReferrers++;
64 if (N->Size <= Offset) {
65 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
66 Offset = 0;
67 }
68 return N;
69}
70
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000071//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000072// DSNode Implementation
73//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000074
Chris Lattnerbd92b732003-06-19 21:15:11 +000075DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000076 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000077 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000078 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000079 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000080 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000081}
82
Chris Lattner0d9bab82002-07-18 00:12:30 +000083// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000084DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000085 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner0b144872004-01-27 22:03:40 +000086 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
87 if (!NullLinks)
88 Links = N.Links;
89 else
90 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000091 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000092 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000093}
94
Chris Lattner15869aa2003-11-02 22:27:28 +000095/// getTargetData - Get the target data object used to construct this node.
96///
97const TargetData &DSNode::getTargetData() const {
98 return ParentGraph->getTargetData();
99}
100
Chris Lattner72d29a42003-02-11 23:11:51 +0000101void DSNode::assertOK() const {
102 assert((Ty != Type::VoidTy ||
103 Ty == Type::VoidTy && (Size == 0 ||
104 (NodeType & DSNode::Array))) &&
105 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000106
107 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000108 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000109 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000110 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000111 assert(SM.find(Globals[i])->second.getNode() == this);
112 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000113}
114
115/// forwardNode - Mark this node as being obsolete, and all references to it
116/// should be forwarded to the specified node and offset.
117///
118void DSNode::forwardNode(DSNode *To, unsigned Offset) {
119 assert(this != To && "Cannot forward a node to itself!");
120 assert(ForwardNH.isNull() && "Already forwarding from this node!");
121 if (To->Size <= 1) Offset = 0;
122 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
123 "Forwarded offset is wrong!");
124 ForwardNH.setNode(To);
125 ForwardNH.setOffset(Offset);
126 NodeType = DEAD;
127 Size = 0;
128 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000129
130 // Remove this node from the parent graph's Nodes list.
131 ParentGraph->unlinkNode(this);
132 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000133}
134
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000135// addGlobal - Add an entry for a global value to the Globals list. This also
136// marks the node with the 'G' flag if it does not already have it.
137//
138void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000139 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000140 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000141 std::lower_bound(Globals.begin(), Globals.end(), GV);
142
143 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000144 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000145 Globals.insert(I, GV);
146 NodeType |= GlobalNode;
147 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000148}
149
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000150/// foldNodeCompletely - If we determine that this node has some funny
151/// behavior happening to it that we cannot represent, we fold it down to a
152/// single, completely pessimistic, node. This node is represented as a
153/// single byte with a single TypeEntry of "void".
154///
155void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000156 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000157
Chris Lattner08db7192002-11-06 06:20:27 +0000158 ++NumFolds;
159
Chris Lattner0b144872004-01-27 22:03:40 +0000160 // If this node has a size that is <= 1, we don't need to create a forwarding
161 // node.
162 if (getSize() <= 1) {
163 NodeType |= DSNode::Array;
164 Ty = Type::VoidTy;
165 Size = 1;
166 assert(Links.size() <= 1 && "Size is 1, but has more links?");
167 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000168 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000169 // Create the node we are going to forward to. This is required because
170 // some referrers may have an offset that is > 0. By forcing them to
171 // forward, the forwarder has the opportunity to correct the offset.
172 DSNode *DestNode = new DSNode(0, ParentGraph);
173 DestNode->NodeType = NodeType|DSNode::Array;
174 DestNode->Ty = Type::VoidTy;
175 DestNode->Size = 1;
176 DestNode->Globals.swap(Globals);
177
178 // Start forwarding to the destination node...
179 forwardNode(DestNode, 0);
180
181 if (!Links.empty()) {
182 DestNode->Links.reserve(1);
183
184 DSNodeHandle NH(DestNode);
185 DestNode->Links.push_back(Links[0]);
186
187 // If we have links, merge all of our outgoing links together...
188 for (unsigned i = Links.size()-1; i != 0; --i)
189 NH.getNode()->Links[0].mergeWith(Links[i]);
190 Links.clear();
191 } else {
192 DestNode->Links.resize(1);
193 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000194 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000195}
Chris Lattner076c1f92002-11-07 06:31:54 +0000196
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000197/// isNodeCompletelyFolded - Return true if this node has been completely
198/// folded down to something that can never be expanded, effectively losing
199/// all of the field sensitivity that may be present in the node.
200///
201bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000202 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000203}
204
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000205namespace {
206 /// TypeElementWalker Class - Used for implementation of physical subtyping...
207 ///
208 class TypeElementWalker {
209 struct StackState {
210 const Type *Ty;
211 unsigned Offset;
212 unsigned Idx;
213 StackState(const Type *T, unsigned Off = 0)
214 : Ty(T), Offset(Off), Idx(0) {}
215 };
216
217 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000218 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000219 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000220 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000221 Stack.push_back(T);
222 StepToLeaf();
223 }
224
225 bool isDone() const { return Stack.empty(); }
226 const Type *getCurrentType() const { return Stack.back().Ty; }
227 unsigned getCurrentOffset() const { return Stack.back().Offset; }
228
229 void StepToNextType() {
230 PopStackAndAdvance();
231 StepToLeaf();
232 }
233
234 private:
235 /// PopStackAndAdvance - Pop the current element off of the stack and
236 /// advance the underlying element to the next contained member.
237 void PopStackAndAdvance() {
238 assert(!Stack.empty() && "Cannot pop an empty stack!");
239 Stack.pop_back();
240 while (!Stack.empty()) {
241 StackState &SS = Stack.back();
242 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
243 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000244 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000245 const StructLayout *SL = TD.getStructLayout(ST);
246 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
247 return;
248 }
249 Stack.pop_back(); // At the end of the structure
250 } else {
251 const ArrayType *AT = cast<ArrayType>(SS.Ty);
252 ++SS.Idx;
253 if (SS.Idx != AT->getNumElements()) {
254 SS.Offset += TD.getTypeSize(AT->getElementType());
255 return;
256 }
257 Stack.pop_back(); // At the end of the array
258 }
259 }
260 }
261
262 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
263 /// on the type stack.
264 void StepToLeaf() {
265 if (Stack.empty()) return;
266 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
267 StackState &SS = Stack.back();
268 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000269 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000270 assert(SS.Idx == 0);
271 PopStackAndAdvance();
272 } else {
273 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000274 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000275 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000276 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000277 SS.Offset+SL->MemberOffsets[SS.Idx]));
278 }
279 } else {
280 const ArrayType *AT = cast<ArrayType>(SS.Ty);
281 if (AT->getNumElements() == 0) {
282 assert(SS.Idx == 0);
283 PopStackAndAdvance();
284 } else {
285 // Step into the array...
286 assert(SS.Idx < AT->getNumElements());
287 Stack.push_back(StackState(AT->getElementType(),
288 SS.Offset+SS.Idx*
289 TD.getTypeSize(AT->getElementType())));
290 }
291 }
292 }
293 }
294 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000295} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000296
297/// ElementTypesAreCompatible - Check to see if the specified types are
298/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000299/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
300/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000301///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000302static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000303 bool AllowLargerT1, const TargetData &TD){
304 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000305
306 while (!T1W.isDone() && !T2W.isDone()) {
307 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
308 return false;
309
310 const Type *T1 = T1W.getCurrentType();
311 const Type *T2 = T2W.getCurrentType();
312 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
313 return false;
314
315 T1W.StepToNextType();
316 T2W.StepToNextType();
317 }
318
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000319 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000320}
321
322
Chris Lattner08db7192002-11-06 06:20:27 +0000323/// mergeTypeInfo - This method merges the specified type into the current node
324/// at the specified offset. This may update the current node's type record if
325/// this gives more information to the node, it may do nothing to the node if
326/// this information is already known, or it may merge the node completely (and
327/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000328///
Chris Lattner08db7192002-11-06 06:20:27 +0000329/// This method returns true if the node is completely folded, otherwise false.
330///
Chris Lattner088b6392003-03-03 17:13:31 +0000331bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
332 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000333 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000334 // Check to make sure the Size member is up-to-date. Size can be one of the
335 // following:
336 // Size = 0, Ty = Void: Nothing is known about this node.
337 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
338 // Size = 1, Ty = Void, Array = 1: The node is collapsed
339 // Otherwise, sizeof(Ty) = Size
340 //
Chris Lattner18552922002-11-18 21:44:46 +0000341 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
342 (Size == 0 && !Ty->isSized() && !isArray()) ||
343 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
344 (Size == 0 && !Ty->isSized() && !isArray()) ||
345 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000346 "Size member of DSNode doesn't match the type structure!");
347 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000348
Chris Lattner18552922002-11-18 21:44:46 +0000349 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000350 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000351
Chris Lattner08db7192002-11-06 06:20:27 +0000352 // Return true immediately if the node is completely folded.
353 if (isNodeCompletelyFolded()) return true;
354
Chris Lattner23f83dc2002-11-08 22:49:57 +0000355 // If this is an array type, eliminate the outside arrays because they won't
356 // be used anyway. This greatly reduces the size of large static arrays used
357 // as global variables, for example.
358 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000359 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000360 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
361 // FIXME: we might want to keep small arrays, but must be careful about
362 // things like: [2 x [10000 x int*]]
363 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000364 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000365 }
366
Chris Lattner08db7192002-11-06 06:20:27 +0000367 // Figure out how big the new type we're merging in is...
368 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
369
370 // Otherwise check to see if we can fold this type into the current node. If
371 // we can't, we fold the node completely, if we can, we potentially update our
372 // internal state.
373 //
Chris Lattner18552922002-11-18 21:44:46 +0000374 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000375 // If this is the first type that this node has seen, just accept it without
376 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000377 assert(Offset == 0 && !isArray() &&
378 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000379 Ty = NewTy;
380 NodeType &= ~Array;
381 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000382 Size = NewTySize;
383
384 // Calculate the number of outgoing links from this node.
385 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
386 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000387 }
Chris Lattner08db7192002-11-06 06:20:27 +0000388
389 // Handle node expansion case here...
390 if (Offset+NewTySize > Size) {
391 // It is illegal to grow this node if we have treated it as an array of
392 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000393 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000394 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000395 return true;
396 }
397
398 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000399 std::cerr << "UNIMP: Trying to merge a growth type into "
400 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000401 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000402 return true;
403 }
404
405 // Okay, the situation is nice and simple, we are trying to merge a type in
406 // at offset 0 that is bigger than our current type. Implement this by
407 // switching to the new type and then merge in the smaller one, which should
408 // hit the other code path here. If the other code path decides it's not
409 // ok, it will collapse the node as appropriate.
410 //
Chris Lattner18552922002-11-18 21:44:46 +0000411 const Type *OldTy = Ty;
412 Ty = NewTy;
413 NodeType &= ~Array;
414 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000415 Size = NewTySize;
416
417 // Must grow links to be the appropriate size...
418 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
419
420 // Merge in the old type now... which is guaranteed to be smaller than the
421 // "current" type.
422 return mergeTypeInfo(OldTy, 0);
423 }
424
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000425 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000426 "Cannot merge something into a part of our type that doesn't exist!");
427
Chris Lattner18552922002-11-18 21:44:46 +0000428 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000429 // type that starts at offset Offset.
430 //
431 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000432 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000433 while (O < Offset) {
434 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
435
436 switch (SubType->getPrimitiveID()) {
437 case Type::StructTyID: {
438 const StructType *STy = cast<StructType>(SubType);
439 const StructLayout &SL = *TD.getStructLayout(STy);
440
441 unsigned i = 0, e = SL.MemberOffsets.size();
442 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
443 /* empty */;
444
445 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000446 SubType = STy->getElementType(i);
Chris Lattner08db7192002-11-06 06:20:27 +0000447 O += SL.MemberOffsets[i];
448 break;
449 }
450 case Type::ArrayTyID: {
451 SubType = cast<ArrayType>(SubType)->getElementType();
452 unsigned ElSize = TD.getTypeSize(SubType);
453 unsigned Remainder = (Offset-O) % ElSize;
454 O = Offset-Remainder;
455 break;
456 }
457 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000458 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000459 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000460 }
461 }
462
463 assert(O == Offset && "Could not achieve the correct offset!");
464
465 // If we found our type exactly, early exit
466 if (SubType == NewTy) return false;
467
Chris Lattner0b144872004-01-27 22:03:40 +0000468 // Differing function types don't require us to merge. They are not values anyway.
469 if (isa<FunctionType>(SubType) &&
470 isa<FunctionType>(NewTy)) return false;
471
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000472 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
473
474 // Ok, we are getting desperate now. Check for physical subtyping, where we
475 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000476 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000477 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000478 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000479 return false;
480
Chris Lattner08db7192002-11-06 06:20:27 +0000481 // Okay, so we found the leader type at the offset requested. Search the list
482 // of types that starts at this offset. If SubType is currently an array or
483 // structure, the type desired may actually be the first element of the
484 // composite type...
485 //
Chris Lattner18552922002-11-18 21:44:46 +0000486 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000487 while (SubType != NewTy) {
488 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000489 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000490 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000491 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000492 case Type::StructTyID: {
493 const StructType *STy = cast<StructType>(SubType);
494 const StructLayout &SL = *TD.getStructLayout(STy);
495 if (SL.MemberOffsets.size() > 1)
496 NextPadSize = SL.MemberOffsets[1];
497 else
498 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000499 NextSubType = STy->getElementType(0);
Chris Lattner18552922002-11-18 21:44:46 +0000500 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000501 break;
Chris Lattner18552922002-11-18 21:44:46 +0000502 }
Chris Lattner08db7192002-11-06 06:20:27 +0000503 case Type::ArrayTyID:
504 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000505 NextSubTypeSize = TD.getTypeSize(NextSubType);
506 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000507 break;
508 default: ;
509 // fall out
510 }
511
512 if (NextSubType == 0)
513 break; // In the default case, break out of the loop
514
Chris Lattner18552922002-11-18 21:44:46 +0000515 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000516 break; // Don't allow shrinking to a smaller type than NewTySize
517 SubType = NextSubType;
518 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000519 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000520 }
521
522 // If we found the type exactly, return it...
523 if (SubType == NewTy)
524 return false;
525
526 // Check to see if we have a compatible, but different type...
527 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000528 // Check to see if this type is obviously convertible... int -> uint f.e.
529 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000530 return false;
531
532 // Check to see if we have a pointer & integer mismatch going on here,
533 // loading a pointer as a long, for example.
534 //
535 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
536 NewTy->isInteger() && isa<PointerType>(SubType))
537 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000538 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
539 // We are accessing the field, plus some structure padding. Ignore the
540 // structure padding.
541 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000542 }
543
Chris Lattner58f98d02003-07-02 04:38:49 +0000544 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000545 if (getParentGraph()->getReturnNodes().size())
546 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000547 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
548 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
549 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
550 << "SubType: ";
551 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000552
Chris Lattner088b6392003-03-03 17:13:31 +0000553 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000554 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000555}
556
Chris Lattner08db7192002-11-06 06:20:27 +0000557
558
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000559// addEdgeTo - Add an edge from the current node to the specified node. This
560// can cause merging of nodes in the graph.
561//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000562void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000563 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000564
Chris Lattner08db7192002-11-06 06:20:27 +0000565 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000566 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000567 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000568 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000569 } else { // No merging to perform...
570 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000572}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000574
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000575// MergeSortedVectors - Efficiently merge a vector into another vector where
576// duplicates are not allowed and both are sorted. This assumes that 'T's are
577// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000578//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000579static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
580 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000581 // By far, the most common cases will be the simple ones. In these cases,
582 // avoid having to allocate a temporary vector...
583 //
584 if (Src.empty()) { // Nothing to merge in...
585 return;
586 } else if (Dest.empty()) { // Just copy the result in...
587 Dest = Src;
588 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000589 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000590 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000591 std::lower_bound(Dest.begin(), Dest.end(), V);
592 if (I == Dest.end() || *I != Src[0]) // If not already contained...
593 Dest.insert(I, Src[0]);
594 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000595 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000596 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000597 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000598 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
599 if (I == Dest.end() || *I != Tmp) // If not already contained...
600 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000601
602 } else {
603 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000604 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000605
606 // Make space for all of the type entries now...
607 Dest.resize(Dest.size()+Src.size());
608
609 // Merge the two sorted ranges together... into Dest.
610 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
611
612 // Now erase any duplicate entries that may have accumulated into the
613 // vectors (because they were in both of the input sets)
614 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
615 }
616}
617
Chris Lattner0b144872004-01-27 22:03:40 +0000618void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
619 MergeSortedVectors(Globals, RHS);
620}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000621
Chris Lattner0b144872004-01-27 22:03:40 +0000622// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000623// This function does the hard work of merging two nodes, CurNodeH
624// and NH after filtering out trivial cases and making sure that
625// CurNodeH.offset >= NH.offset.
626//
627// ***WARNING***
628// Since merging may cause either node to go away, we must always
629// use the node-handles to refer to the nodes. These node handles are
630// automatically updated during merging, so will always provide access
631// to the correct node after a merge.
632//
633void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
634 assert(CurNodeH.getOffset() >= NH.getOffset() &&
635 "This should have been enforced in the caller.");
636
637 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
638 // respect to NH.Offset) is now zero. NOffset is the distance from the base
639 // of our object that N starts from.
640 //
641 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
642 unsigned NSize = NH.getNode()->getSize();
643
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000644 // If the two nodes are of different size, and the smaller node has the array
645 // bit set, collapse!
646 if (NSize != CurNodeH.getNode()->getSize()) {
647 if (NSize < CurNodeH.getNode()->getSize()) {
648 if (NH.getNode()->isArray())
649 NH.getNode()->foldNodeCompletely();
650 } else if (CurNodeH.getNode()->isArray()) {
651 NH.getNode()->foldNodeCompletely();
652 }
653 }
654
655 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000656 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000657 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000658 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000659
660 // If we are merging a node with a completely folded node, then both nodes are
661 // now completely folded.
662 //
663 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
664 if (!NH.getNode()->isNodeCompletelyFolded()) {
665 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000666 assert(NH.getNode() && NH.getOffset() == 0 &&
667 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000668 NOffset = NH.getOffset();
669 NSize = NH.getNode()->getSize();
670 assert(NOffset == 0 && NSize == 1);
671 }
672 } else if (NH.getNode()->isNodeCompletelyFolded()) {
673 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000674 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
675 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000676 NOffset = NH.getOffset();
677 NSize = NH.getNode()->getSize();
678 assert(NOffset == 0 && NSize == 1);
679 }
680
Chris Lattner72d29a42003-02-11 23:11:51 +0000681 DSNode *N = NH.getNode();
682 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000683 assert(!CurNodeH.getNode()->isDeadNode());
684
Chris Lattner0b144872004-01-27 22:03:40 +0000685 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000686 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000687
Chris Lattner72d29a42003-02-11 23:11:51 +0000688 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000689 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000690 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000691
Chris Lattner72d29a42003-02-11 23:11:51 +0000692 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
693 //
694 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
695 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000696 if (Link.getNode()) {
697 // Compute the offset into the current node at which to
698 // merge this link. In the common case, this is a linear
699 // relation to the offset in the original node (with
700 // wrapping), but if the current node gets collapsed due to
701 // recursive merging, we must make sure to merge in all remaining
702 // links at offset zero.
703 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000704 DSNode *CN = CurNodeH.getNode();
705 if (CN->Size != 1)
706 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
707 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000708 }
709 }
710
711 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000712 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000713
714 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000715 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000716 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000717
718 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000719 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000720 }
721}
722
723
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000724// mergeWith - Merge this node and the specified node, moving all links to and
725// from the argument node into the current node, deleting the node argument.
726// Offset indicates what offset the specified node is to be merged into the
727// current node.
728//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000729// The specified node may be a null pointer (in which case, we update it to
730// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000731//
732void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
733 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000734 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000735 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000736
Chris Lattner5254a8d2004-01-22 16:31:08 +0000737 // If the RHS is a null node, make it point to this node!
738 if (N == 0) {
739 NH.mergeWith(DSNodeHandle(this, Offset));
740 return;
741 }
742
Chris Lattnerbd92b732003-06-19 21:15:11 +0000743 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000744 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
745
Chris Lattner02606632002-11-04 06:48:26 +0000746 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000747 // We cannot merge two pieces of the same node together, collapse the node
748 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000749 DEBUG(std::cerr << "Attempting to merge two chunks of"
750 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000751 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000752 return;
753 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000754
Chris Lattner5190ce82002-11-12 07:20:45 +0000755 // If both nodes are not at offset 0, make sure that we are merging the node
756 // at an later offset into the node with the zero offset.
757 //
758 if (Offset < NH.getOffset()) {
759 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
760 return;
761 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
762 // If the offsets are the same, merge the smaller node into the bigger node
763 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
764 return;
765 }
766
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000767 // Ok, now we can merge the two nodes. Use a static helper that works with
768 // two node handles, since "this" may get merged away at intermediate steps.
769 DSNodeHandle CurNodeH(this, Offset);
770 DSNodeHandle NHCopy(NH);
771 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000772}
773
Chris Lattner0b144872004-01-27 22:03:40 +0000774
775//===----------------------------------------------------------------------===//
776// ReachabilityCloner Implementation
777//===----------------------------------------------------------------------===//
778
779DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
780 if (SrcNH.isNull()) return DSNodeHandle();
781 const DSNode *SN = SrcNH.getNode();
782
783 DSNodeHandle &NH = NodeMap[SN];
784 if (!NH.isNull()) // Node already mapped?
785 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
786
787 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
788 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000789 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000790
791 // Next, recursively clone all outgoing links as necessary. Note that
792 // adding these links can cause the node to collapse itself at any time, and
793 // the current node may be merged with arbitrary other nodes. For this
794 // reason, we must always go through NH.
795 DN = 0;
796 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
797 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
798 if (!SrcEdge.isNull()) {
799 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
800 // Compute the offset into the current node at which to
801 // merge this link. In the common case, this is a linear
802 // relation to the offset in the original node (with
803 // wrapping), but if the current node gets collapsed due to
804 // recursive merging, we must make sure to merge in all remaining
805 // links at offset zero.
806 unsigned MergeOffset = 0;
807 DSNode *CN = NH.getNode();
808 if (CN->getSize() != 1)
809 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
810 - SrcNH.getOffset()) %CN->getSize();
811 CN->addEdgeTo(MergeOffset, DestEdge);
812 }
813 }
814
815 // If this node contains any globals, make sure they end up in the scalar
816 // map with the correct offset.
817 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
818 I != E; ++I) {
819 GlobalValue *GV = *I;
820 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
821 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
822 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
823 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000824 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000825
826 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
827 Dest.getInlinedGlobals().insert(GV);
828 }
829
830 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
831}
832
833void ReachabilityCloner::merge(const DSNodeHandle &NH,
834 const DSNodeHandle &SrcNH) {
835 if (SrcNH.isNull()) return; // Noop
836 if (NH.isNull()) {
837 // If there is no destination node, just clone the source and assign the
838 // destination node to be it.
839 NH.mergeWith(getClonedNH(SrcNH));
840 return;
841 }
842
843 // Okay, at this point, we know that we have both a destination and a source
844 // node that need to be merged. Check to see if the source node has already
845 // been cloned.
846 const DSNode *SN = SrcNH.getNode();
847 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
848 if (SCNH.getNode()) { // Node already cloned?
849 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
850 SCNH.getOffset()+SrcNH.getOffset()));
851
852 return; // Nothing to do!
853 }
854
855 // Okay, so the source node has not already been cloned. Instead of creating
856 // a new DSNode, only to merge it into the one we already have, try to perform
857 // the merge in-place. The only case we cannot handle here is when the offset
858 // into the existing node is less than the offset into the virtual node we are
859 // merging in. In this case, we have to extend the existing node, which
860 // requires an allocation anyway.
861 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
862 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000863 if (!DN->isNodeCompletelyFolded()) {
864 // Make sure the destination node is folded if the source node is folded.
865 if (SN->isNodeCompletelyFolded()) {
866 DN->foldNodeCompletely();
867 DN = NH.getNode();
868 } else if (SN->getSize() != DN->getSize()) {
869 // If the two nodes are of different size, and the smaller node has the
870 // array bit set, collapse!
871 if (SN->getSize() < DN->getSize()) {
872 if (SN->isArray()) {
873 DN->foldNodeCompletely();
874 DN = NH.getNode();
875 }
876 } else if (DN->isArray()) {
877 DN->foldNodeCompletely();
878 DN = NH.getNode();
879 }
880 }
881
882 // Merge the type entries of the two nodes together...
883 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
884 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
885 DN = NH.getNode();
886 }
887 }
888
889 assert(!DN->isDeadNode());
890
891 // Merge the NodeType information.
892 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
893
894 // Before we start merging outgoing links and updating the scalar map, make
895 // sure it is known that this is the representative node for the src node.
896 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
897
898 // If the source node contains any globals, make sure they end up in the
899 // scalar map with the correct offset.
900 if (SN->global_begin() != SN->global_end()) {
901 // Update the globals in the destination node itself.
902 DN->mergeGlobals(SN->getGlobals());
903
904 // Update the scalar map for the graph we are merging the source node
905 // into.
906 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
907 I != E; ++I) {
908 GlobalValue *GV = *I;
909 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
910 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
911 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
912 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000913 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000914
915 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
916 Dest.getInlinedGlobals().insert(GV);
917 }
918 }
919 } else {
920 // We cannot handle this case without allocating a temporary node. Fall
921 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000922 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
923 NewDN->maskNodeTypes(BitsToKeep);
924
925 unsigned NHOffset = NH.getOffset();
926 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000927
Chris Lattner0b144872004-01-27 22:03:40 +0000928 assert(NH.getNode() &&
929 (NH.getOffset() > NHOffset ||
930 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
931 "Merging did not adjust the offset!");
932
933 // Before we start merging outgoing links and updating the scalar map, make
934 // sure it is known that this is the representative node for the src node.
935 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000936
937 // If the source node contained any globals, make sure to create entries
938 // in the scalar map for them!
939 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
940 I != E; ++I) {
941 GlobalValue *GV = *I;
942 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
943 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
944 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
945 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
946 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
947 DestGNH.getOffset()+SrcGNH.getOffset()));
948
949 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
950 Dest.getInlinedGlobals().insert(GV);
951 }
Chris Lattner0b144872004-01-27 22:03:40 +0000952 }
953
954
955 // Next, recursively merge all outgoing links as necessary. Note that
956 // adding these links can cause the destination node to collapse itself at
957 // any time, and the current node may be merged with arbitrary other nodes.
958 // For this reason, we must always go through NH.
959 DN = 0;
960 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
961 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
962 if (!SrcEdge.isNull()) {
963 // Compute the offset into the current node at which to
964 // merge this link. In the common case, this is a linear
965 // relation to the offset in the original node (with
966 // wrapping), but if the current node gets collapsed due to
967 // recursive merging, we must make sure to merge in all remaining
968 // links at offset zero.
969 unsigned MergeOffset = 0;
970 DSNode *CN = SCNH.getNode();
971 if (CN->getSize() != 1)
972 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
973
974 // Perform the recursive merging. Make sure to create a temporary NH,
975 // because the Link can disappear in the process of recursive merging.
976 DSNodeHandle Tmp = CN->getLink(MergeOffset);
977 merge(Tmp, SrcEdge);
978 }
979 }
980}
981
982/// mergeCallSite - Merge the nodes reachable from the specified src call
983/// site into the nodes reachable from DestCS.
984void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
985 const DSCallSite &SrcCS) {
986 merge(DestCS.getRetVal(), SrcCS.getRetVal());
987 unsigned MinArgs = DestCS.getNumPtrArgs();
988 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
989
990 for (unsigned a = 0; a != MinArgs; ++a)
991 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
992}
993
994
Chris Lattner9de906c2002-10-20 22:11:44 +0000995//===----------------------------------------------------------------------===//
996// DSCallSite Implementation
997//===----------------------------------------------------------------------===//
998
Vikram S. Adve26b98262002-10-20 21:41:02 +0000999// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001000Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001001 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001002}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001003
Chris Lattner0b144872004-01-27 22:03:40 +00001004void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1005 ReachabilityCloner &RC) {
1006 NH = RC.getClonedNH(Src);
1007}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001008
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001009//===----------------------------------------------------------------------===//
1010// DSGraph Implementation
1011//===----------------------------------------------------------------------===//
1012
Chris Lattnera9d65662003-06-30 05:57:30 +00001013/// getFunctionNames - Return a space separated list of the name of the
1014/// functions in this graph (if any)
1015std::string DSGraph::getFunctionNames() const {
1016 switch (getReturnNodes().size()) {
1017 case 0: return "Globals graph";
1018 case 1: return getReturnNodes().begin()->first->getName();
1019 default:
1020 std::string Return;
1021 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1022 I != getReturnNodes().end(); ++I)
1023 Return += I->first->getName() + " ";
1024 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1025 return Return;
1026 }
1027}
1028
1029
Chris Lattner15869aa2003-11-02 22:27:28 +00001030DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001031 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001032 NodeMapTy NodeMap;
1033 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001034}
1035
Chris Lattner5a540632003-06-30 03:15:25 +00001036DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001037 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001038 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001039 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001040}
1041
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001042DSGraph::~DSGraph() {
1043 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001044 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001045 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001046 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001047 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001048
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001049 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001050 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1051 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001052
Chris Lattner28897e12004-02-08 00:53:26 +00001053 // Free all of the nodes.
1054 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001055}
1056
Chris Lattner0d9bab82002-07-18 00:12:30 +00001057// dump - Allow inspection of graph in a debugger.
1058void DSGraph::dump() const { print(std::cerr); }
1059
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001060
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001061/// remapLinks - Change all of the Links in the current node according to the
1062/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001063///
Chris Lattner8d327672003-06-30 03:36:09 +00001064void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001065 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1066 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001067 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1068 if (ONMI != OldNodeMap.end()) {
1069 Links[i].setNode(ONMI->second.getNode());
1070 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1071 }
Chris Lattner2f561382004-01-22 16:56:13 +00001072 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001073}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001074
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001075/// updateFromGlobalGraph - This function rematerializes global nodes and
1076/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001077/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1078/// are already up-to-date in the current graph. In practice, in the TD pass,
1079/// this is likely to be a large fraction of the live global nodes in each
1080/// function (since most live nodes are likely to have been brought up-to-date
1081/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001082///
1083void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001084 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001085 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1086
1087 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001088 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1089 E = getScalarMap().global_end(); I != E; ++I)
1090 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001091 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001092 if (It != GlobalsGraph->ScalarMap.end())
1093 RC.merge(getNodeForValue(*I), It->second);
1094 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001095}
1096
Chris Lattner5a540632003-06-30 03:15:25 +00001097/// cloneInto - Clone the specified DSGraph into the current graph. The
1098/// translated ScalarMap for the old function is filled into the OldValMap
1099/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1100///
1101/// The CloneFlags member controls various aspects of the cloning process.
1102///
Chris Lattner62482e52004-01-28 09:15:42 +00001103void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001104 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1105 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001106 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001107 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001108 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001109
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001110 // Remember the last node that existed before, or node_end() if there are no
1111 // nodes.
1112 node_iterator FN = node_end();
1113 if (FN != node_begin()) --FN;
Chris Lattner1e883692003-02-03 20:08:51 +00001114
1115 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001116 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1117 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1118 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001119 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001120 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I)
1121 if (!(*I)->isForwarding()) {
1122 DSNode *New = new DSNode(**I, this);
Chris Lattnera5ca28c2004-02-07 22:00:03 +00001123 New->maskNodeTypes(~BitsToClear);
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001124 OldNodeMap[*I] = New;
Chris Lattnera5ca28c2004-02-07 22:00:03 +00001125 }
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001126
Chris Lattner18552922002-11-18 21:44:46 +00001127#ifndef NDEBUG
1128 Timer::addPeakMemoryMeasurement();
1129#endif
1130
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001131 // Move FN to the first newly added node.
1132 if (FN != node_end())
1133 ++FN;
1134 else
1135 FN = node_begin();
1136
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001137 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001138 for (; FN != node_end(); ++FN)
1139 (*FN)->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001140
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001141 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001142 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001143 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001144 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001145 DSNodeHandle &H = OldValMap[I->first];
1146 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1147 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001148
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001149 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001150 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1151 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001152 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1153 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001154 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001155 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001156
Chris Lattner679e8e12002-11-08 21:27:12 +00001157 if (!(CloneFlags & DontCloneCallNodes)) {
1158 // Copy the function calls list...
1159 unsigned FC = FunctionCalls.size(); // FirstCall
1160 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1161 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1162 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001163 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001164
Chris Lattneracf491f2002-11-08 22:27:09 +00001165 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001166 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001167 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001168 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1169 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1170 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1171 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001172
Chris Lattner5a540632003-06-30 03:15:25 +00001173 // Map the return node pointers over...
1174 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1175 E = G.getReturnNodes().end(); I != E; ++I) {
1176 const DSNodeHandle &Ret = I->second;
1177 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1178 OldReturnNodes.insert(std::make_pair(I->first,
1179 DSNodeHandle(MappedRet.getNode(),
1180 MappedRet.getOffset()+Ret.getOffset())));
1181 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001182}
1183
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001184
Chris Lattner076c1f92002-11-07 06:31:54 +00001185/// mergeInGraph - The method is used for merging graphs together. If the
1186/// argument graph is not *this, it makes a clone of the specified graph, then
1187/// merges the nodes specified in the call site with the formal arguments in the
1188/// graph.
1189///
Chris Lattner9f930552003-06-30 05:27:18 +00001190void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1191 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001192 TIME_REGION(X, "mergeInGraph");
1193
Chris Lattner076c1f92002-11-07 06:31:54 +00001194 // If this is not a recursive call, clone the graph into this graph...
1195 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001196 // Clone the callee's graph into the current graph, keeping track of where
1197 // scalars in the old graph _used_ to point, and of the new nodes matching
1198 // nodes of the old graph.
1199 ReachabilityCloner RC(*this, Graph, CloneFlags);
1200
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001201 // Set up argument bindings
1202 Function::aiterator AI = F.abegin();
1203 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1204 // Advance the argument iterator to the first pointer argument...
1205 while (AI != F.aend() && !isPointerType(AI->getType())) {
1206 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001207#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1208 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001209 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001210#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001211 }
1212 if (AI == F.aend()) break;
1213
1214 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001215 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001216 }
1217
Chris Lattner0b144872004-01-27 22:03:40 +00001218 // Map the return node pointer over.
1219 if (CS.getRetVal().getNode())
1220 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1221
1222 // If requested, copy the calls or aux-calls lists.
1223 if (!(CloneFlags & DontCloneCallNodes)) {
1224 // Copy the function calls list...
1225 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1226 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1227 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1228 }
1229
1230 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1231 // Copy the auxiliary function calls list...
1232 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1233 Graph.AuxFunctionCalls.size());
1234 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1235 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1236 }
1237
1238 // If the user requested it, add the nodes that we need to clone to the
1239 // RootNodes set.
1240 if (!EnableDSNodeGlobalRootsHack)
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001241 for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1242 NI != E; ++NI)
1243 if (!(*NI)->getGlobals().empty())
1244 RC.getClonedNH(*NI);
Chris Lattner0b144872004-01-27 22:03:40 +00001245
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001246 } else {
1247 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001248
1249 // Merge the return value with the return value of the context...
1250 RetVal.mergeWith(CS.getRetVal());
1251
1252 // Resolve all of the function arguments...
1253 Function::aiterator AI = F.abegin();
1254
1255 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1256 // Advance the argument iterator to the first pointer argument...
1257 while (AI != F.aend() && !isPointerType(AI->getType())) {
1258 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001259#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1260 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001261 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1262#endif
1263 }
1264 if (AI == F.aend()) break;
1265
1266 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001267 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001268 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1269 NH.mergeWith(CS.getPtrArg(i));
1270 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001271 }
1272}
1273
Chris Lattner58f98d02003-07-02 04:38:49 +00001274/// getCallSiteForArguments - Get the arguments and return value bindings for
1275/// the specified function in the current graph.
1276///
1277DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1278 std::vector<DSNodeHandle> Args;
1279
1280 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1281 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001282 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001283
Chris Lattner808a7ae2003-09-20 16:34:13 +00001284 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001285}
1286
1287
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001288
Chris Lattner0d9bab82002-07-18 00:12:30 +00001289// markIncompleteNodes - Mark the specified node as having contents that are not
1290// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001291// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001292// must recursively traverse the data structure graph, marking all reachable
1293// nodes as incomplete.
1294//
1295static void markIncompleteNode(DSNode *N) {
1296 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001297 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001298
1299 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001300 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001301
Misha Brukman2f2d0652003-09-11 18:14:24 +00001302 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001303 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1304 if (DSNode *DSN = N->getLink(i).getNode())
1305 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001306}
1307
Chris Lattnere71ffc22002-11-11 03:36:55 +00001308static void markIncomplete(DSCallSite &Call) {
1309 // Then the return value is certainly incomplete!
1310 markIncompleteNode(Call.getRetVal().getNode());
1311
1312 // All objects pointed to by function arguments are incomplete!
1313 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1314 markIncompleteNode(Call.getPtrArg(i).getNode());
1315}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001316
1317// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1318// modified by other functions that have not been resolved yet. This marks
1319// nodes that are reachable through three sources of "unknownness":
1320//
1321// Global Variables, Function Calls, and Incoming Arguments
1322//
1323// For any node that may have unknown components (because something outside the
1324// scope of current analysis may have modified it), the 'Incomplete' flag is
1325// added to the NodeType.
1326//
Chris Lattner394471f2003-01-23 22:05:33 +00001327void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001328 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001329 if (Flags & DSGraph::MarkFormalArgs)
1330 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1331 FI != E; ++FI) {
1332 Function &F = *FI->first;
1333 if (F.getName() != "main")
1334 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001335 if (isPointerType(I->getType()))
1336 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001337 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001338
1339 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001340 if (!shouldPrintAuxCalls())
1341 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1342 markIncomplete(FunctionCalls[i]);
1343 else
1344 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1345 markIncomplete(AuxFunctionCalls[i]);
1346
Chris Lattner0d9bab82002-07-18 00:12:30 +00001347
Chris Lattner93d7a212003-02-09 18:41:49 +00001348 // Mark all global nodes as incomplete...
1349 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001350 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1351 if ((*NI)->isGlobalNode() && (*NI)->getNumLinks())
1352 markIncompleteNode(*NI);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001353}
1354
Chris Lattneraa8146f2002-11-10 06:59:55 +00001355static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1356 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001357 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001358 // No interesting info?
1359 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001360 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001361 Edge.setNode(0); // Kill the edge!
1362}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001363
Chris Lattneraa8146f2002-11-10 06:59:55 +00001364static inline bool nodeContainsExternalFunction(const DSNode *N) {
1365 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1366 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1367 if (Globals[i]->isExternal())
1368 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001369 return false;
1370}
1371
Chris Lattner5a540632003-06-30 03:15:25 +00001372static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001373 // Remove trivially identical function calls
1374 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001375 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1376
Chris Lattner0b144872004-01-27 22:03:40 +00001377#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001378 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001379 DSNode *LastCalleeNode = 0;
1380 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001381 unsigned NumDuplicateCalls = 0;
1382 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001383 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001384 DSCallSite &CS = Calls[i];
1385
Chris Lattnere4258442002-11-11 21:35:38 +00001386 // If the Callee is a useless edge, this must be an unreachable call site,
1387 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001388 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001389 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001390#ifndef NDEBUG
Chris Lattner923fc052003-02-05 21:59:58 +00001391 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001392#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001393 CS.swap(Calls.back());
1394 Calls.pop_back();
1395 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001396 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001397 // If the return value or any arguments point to a void node with no
1398 // information at all in it, and the call node is the only node to point
1399 // to it, remove the edge to the node (killing the node).
1400 //
1401 killIfUselessEdge(CS.getRetVal());
1402 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1403 killIfUselessEdge(CS.getPtrArg(a));
1404
1405 // If this call site calls the same function as the last call site, and if
1406 // the function pointer contains an external function, this node will
1407 // never be resolved. Merge the arguments of the call node because no
1408 // information will be lost.
1409 //
Chris Lattner923fc052003-02-05 21:59:58 +00001410 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1411 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001412 ++NumDuplicateCalls;
1413 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001414 if (LastCalleeNode)
1415 LastCalleeContainsExternalFunction =
1416 nodeContainsExternalFunction(LastCalleeNode);
1417 else
1418 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001419 }
Chris Lattner0b144872004-01-27 22:03:40 +00001420
1421 // It is not clear why, but enabling this code makes DSA really
1422 // sensitive to node forwarding. Basically, with this enabled, DSA
1423 // performs different number of inlinings based on which nodes are
1424 // forwarding or not. This is clearly a problem, so this code is
1425 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001426#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001427 if (LastCalleeContainsExternalFunction
1428#if 0
1429 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001430 // This should be more than enough context sensitivity!
1431 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001432 NumDuplicateCalls > 20
1433#endif
1434 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001435 DSCallSite &OCS = Calls[i-1];
1436 OCS.mergeWith(CS);
1437
1438 // The node will now be eliminated as a duplicate!
1439 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1440 CS = OCS;
1441 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1442 OCS = CS;
1443 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001444#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001445 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001446 if (CS.isDirectCall()) {
1447 LastCalleeFunc = CS.getCalleeFunc();
1448 LastCalleeNode = 0;
1449 } else {
1450 LastCalleeNode = CS.getCalleeNode();
1451 LastCalleeFunc = 0;
1452 }
Chris Lattnere4258442002-11-11 21:35:38 +00001453 NumDuplicateCalls = 0;
1454 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001455 }
1456 }
Chris Lattner0b144872004-01-27 22:03:40 +00001457#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001458 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001459
Chris Lattner33312f72002-11-08 01:21:07 +00001460 // Track the number of call nodes merged away...
1461 NumCallNodesMerged += NumFns-Calls.size();
1462
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001463 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001464 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001465}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001466
Chris Lattneraa8146f2002-11-10 06:59:55 +00001467
Chris Lattnere2219762002-07-18 18:22:40 +00001468// removeTriviallyDeadNodes - After the graph has been constructed, this method
1469// removes all unreachable nodes that are created because they got merged with
1470// other nodes in the graph. These nodes will all be trivially unreachable, so
1471// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001472//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001473void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001474 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001475
Chris Lattnerbab8c282003-09-20 21:34:07 +00001476 // Loop over all of the nodes in the graph, calling getNode on each field.
1477 // This will cause all nodes to update their forwarding edges, causing
1478 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001479 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1480 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001481 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1482 N->getLink(l*N->getPointerSize()).getNode();
1483 }
1484
Chris Lattner0b144872004-01-27 22:03:40 +00001485 // NOTE: This code is disabled. Though it should, in theory, allow us to
1486 // remove more nodes down below, the scan of the scalar map is incredibly
1487 // expensive for certain programs (with large SCCs). In the future, if we can
1488 // make the scalar map scan more efficient, then we can reenable this.
1489#if 0
1490 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1491
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001492 // Likewise, forward any edges from the scalar nodes. While we are at it,
1493 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001494 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001495 I->second.getNode();
1496 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001497 }
Chris Lattner0b144872004-01-27 22:03:40 +00001498 }
1499#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001500 bool isGlobalsGraph = !GlobalsGraph;
1501
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001502 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001503 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001504
1505 // Do not remove *any* global nodes in the globals graph.
1506 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001507 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001508 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001509 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001510 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001511
Chris Lattner28897e12004-02-08 00:53:26 +00001512 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001513 // This is a useless node if it has no mod/ref info (checked above),
1514 // outgoing edges (which it cannot, as it is not modified in this
1515 // context), and it has no incoming edges. If it is a global node it may
1516 // have all of these properties and still have incoming edges, due to the
1517 // scalar map, so we check those now.
1518 //
Chris Lattner28897e12004-02-08 00:53:26 +00001519 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1520 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001521
Chris Lattner17a93e22004-01-29 03:32:15 +00001522 // Loop through and make sure all of the globals are referring directly
1523 // to the node...
1524 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1525 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001526 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001527 }
1528
Chris Lattnerbd92b732003-06-19 21:15:11 +00001529 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001530 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001531 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1532 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001533 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001534 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001535 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001536 }
1537 }
1538
Chris Lattner28897e12004-02-08 00:53:26 +00001539 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001540 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001541 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001542 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001543 } else {
1544 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001545 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001546 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001547
1548 removeIdenticalCalls(FunctionCalls);
1549 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001550}
1551
1552
Chris Lattner5c7380e2003-01-29 21:10:20 +00001553/// markReachableNodes - This method recursively traverses the specified
1554/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1555/// to the set, which allows it to only traverse visited nodes once.
1556///
Chris Lattner41c04f72003-02-01 04:52:08 +00001557void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001558 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001559 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001560 if (ReachableNodes.insert(this).second) // Is newly reachable?
1561 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1562 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001563}
1564
Chris Lattner41c04f72003-02-01 04:52:08 +00001565void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001566 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001567 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001568
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001569 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1570 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001571}
1572
Chris Lattnera1220af2003-02-01 06:17:02 +00001573// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1574// looking for a node that is marked alive. If an alive node is found, return
1575// true, otherwise return false. If an alive node is reachable, this node is
1576// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001577//
Chris Lattnera1220af2003-02-01 06:17:02 +00001578static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001579 hash_set<DSNode*> &Visited,
1580 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001581 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001582 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001583
Chris Lattner85cfe012003-07-03 02:03:53 +00001584 // If this is a global node, it will end up in the globals graph anyway, so we
1585 // don't need to worry about it.
1586 if (IgnoreGlobals && N->isGlobalNode()) return false;
1587
Chris Lattneraa8146f2002-11-10 06:59:55 +00001588 // If we know that this node is alive, return so!
1589 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001590
Chris Lattneraa8146f2002-11-10 06:59:55 +00001591 // Otherwise, we don't think the node is alive yet, check for infinite
1592 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001593 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001594 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001595
Chris Lattner08db7192002-11-06 06:20:27 +00001596 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001597 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1598 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001599 N->markReachableNodes(Alive);
1600 return true;
1601 }
1602 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001603}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001604
Chris Lattnera1220af2003-02-01 06:17:02 +00001605// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1606// alive nodes.
1607//
Chris Lattner41c04f72003-02-01 04:52:08 +00001608static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001609 hash_set<DSNode*> &Visited,
1610 bool IgnoreGlobals) {
1611 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1612 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001613 return true;
1614 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001615 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001616 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001617 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001618 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1619 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001620 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001621 return false;
1622}
1623
Chris Lattnere2219762002-07-18 18:22:40 +00001624// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1625// subgraphs that are unreachable. This often occurs because the data
1626// structure doesn't "escape" into it's caller, and thus should be eliminated
1627// from the caller's graph entirely. This is only appropriate to use when
1628// inlining graphs.
1629//
Chris Lattner394471f2003-01-23 22:05:33 +00001630void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001631 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001632
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001633 // Reduce the amount of work we have to do... remove dummy nodes left over by
1634 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001635 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001636
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001637 TIME_REGION(X, "removeDeadNodes");
1638
Misha Brukman2f2d0652003-09-11 18:14:24 +00001639 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001640
1641 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001642 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001643 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001644
Chris Lattner0b144872004-01-27 22:03:40 +00001645 // Copy and merge all information about globals to the GlobalsGraph if this is
1646 // not a final pass (where unreachable globals are removed).
1647 //
1648 // Strip all alloca bits since the current function is only for the BU pass.
1649 // Strip all incomplete bits since they are short-lived properties and they
1650 // will be correctly computed when rematerializing nodes into the functions.
1651 //
1652 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1653 DSGraph::StripIncompleteBit);
1654
Chris Lattneraa8146f2002-11-10 06:59:55 +00001655 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001656 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001657 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001658 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001659 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001660 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001661 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001662
1663 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001664 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1665 DSGraph::ScalarMapTy::iterator SMI =
1666 GlobalsGraph->getScalarMap().find(I->first);
1667 if (SMI != GlobalsGraph->getScalarMap().end())
1668 GGCloner.merge(SMI->second, I->second);
1669 else
1670 GGCloner.getClonedNH(I->second);
1671 }
Chris Lattner0b144872004-01-27 22:03:40 +00001672 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001673 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001674 DSNode *N = I->second.getNode();
1675#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001676 // Check to see if this is a worthless node generated for non-pointer
1677 // values, such as integers. Consider an addition of long types: A+B.
1678 // Assuming we can track all uses of the value in this context, and it is
1679 // NOT used as a pointer, we can delete the node. We will be able to
1680 // detect this situation if the node pointed to ONLY has Unknown bit set
1681 // in the node. In this case, the node is not incomplete, does not point
1682 // to any other nodes (no mod/ref bits set), and is therefore
1683 // uninteresting for data structure analysis. If we run across one of
1684 // these, prune the scalar pointing to it.
1685 //
Chris Lattner0b144872004-01-27 22:03:40 +00001686 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1687 ScalarMap.erase(I++);
1688 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001689#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001690 N->markReachableNodes(Alive);
1691 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001692 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001693 }
Chris Lattner00948c02004-01-28 02:05:05 +00001694 }
Chris Lattnere2219762002-07-18 18:22:40 +00001695
Chris Lattner0b144872004-01-27 22:03:40 +00001696 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001697 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1698 I != E; ++I)
1699 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001700
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001701 // Mark any nodes reachable by primary calls as alive...
1702 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1703 FunctionCalls[i].markReachableNodes(Alive);
1704
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001705
1706 // Now find globals and aux call nodes that are already live or reach a live
1707 // value (which makes them live in turn), and continue till no more are found.
1708 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001709 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001710 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001711 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1712 do {
1713 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001714 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001715 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001716 // unreachable globals in the list.
1717 //
1718 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001719 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001720 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1721 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1722 Flags & DSGraph::RemoveUnreachableGlobals)) {
1723 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1724 GlobalNodes.pop_back(); // erase efficiently
1725 Iterate = true;
1726 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001727
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001728 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1729 // call nodes that get resolved will be difficult to remove from that graph.
1730 // The final unresolved call nodes must be handled specially at the end of
1731 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001732 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1733 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001734 (AuxFunctionCalls[i].isIndirectCall()
1735 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1736 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001737 AuxFunctionCalls[i].markReachableNodes(Alive);
1738 AuxFCallsAlive[i] = true;
1739 Iterate = true;
1740 }
1741 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001742
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001743 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001744 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001745 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1746 if (AuxFCallsAlive[i])
1747 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001748
1749 // Copy and merge all global nodes and dead aux call nodes into the
1750 // GlobalsGraph, and all nodes reachable from those nodes
1751 //
1752 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001753 // Copy the unreachable call nodes to the globals graph, updating their
1754 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001755 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1756 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001757 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001758 }
1759 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001760 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1761 AuxFunctionCalls.end());
1762
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001763 // We are finally done with the GGCloner so we can destroy it.
1764 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001765
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001766 // At this point, any nodes which are visited, but not alive, are nodes
1767 // which can be removed. Loop over all nodes, eliminating completely
1768 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001769 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001770 std::vector<DSNode*> DeadNodes;
1771 DeadNodes.reserve(Nodes.size());
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001772 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;)
Chris Lattner28897e12004-02-08 00:53:26 +00001773 if (!Alive.count(NI)) {
Chris Lattnere92e7642004-02-07 23:58:05 +00001774 ++NumDNE;
Chris Lattner28897e12004-02-08 00:53:26 +00001775 DSNode *N = Nodes.remove(NI++);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001776 DeadNodes.push_back(N);
1777 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001778 } else {
Chris Lattner28897e12004-02-08 00:53:26 +00001779 assert(NI->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001780 ++NI;
Chris Lattnere2219762002-07-18 18:22:40 +00001781 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001782
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001783 // Remove all unreachable globals from the ScalarMap.
1784 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1785 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001786 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001787 if (!Alive.count(GlobalNodes[i].second))
1788 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001789 else
1790 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001791
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001792 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001793 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1794 delete DeadNodes[i];
1795
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001796 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001797}
1798
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001799void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001800 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1801 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001802
Chris Lattner8d327672003-06-30 03:36:09 +00001803 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001804 E = ScalarMap.end(); I != E; ++I) {
1805 assert(I->second.getNode() && "Null node in scalarmap!");
1806 AssertNodeInGraph(I->second.getNode());
1807 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001808 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001809 "Global points to node, but node isn't global?");
1810 AssertNodeContainsGlobal(I->second.getNode(), GV);
1811 }
1812 }
1813 AssertCallNodesInGraph();
1814 AssertAuxCallNodesInGraph();
1815}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001816
Chris Lattner400433d2003-11-11 05:08:59 +00001817/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1818/// nodes reachable from the two graphs, computing the mapping of nodes from
1819/// the first to the second graph.
1820///
1821void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001822 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1823 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001824 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1825 if (N1 == 0 || N2 == 0) return;
1826
1827 DSNodeHandle &Entry = NodeMap[N1];
1828 if (Entry.getNode()) {
1829 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001830 assert(!StrictChecking ||
1831 (Entry.getNode() == N2 &&
1832 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001833 "Inconsistent mapping detected!");
1834 return;
1835 }
1836
1837 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001838 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001839
1840 // Loop over all of the fields that N1 and N2 have in common, recursively
1841 // mapping the edges together now.
1842 int N2Idx = NH2.getOffset()-NH1.getOffset();
1843 unsigned N2Size = N2->getSize();
1844 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1845 if (unsigned(N2Idx)+i < N2Size)
1846 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1847}