blob: 2a0dc998a0ebd294362e747d37733cb211dff5bd [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 Lattner33312f72002-11-08 01:21:07 +000029 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner0b144872004-01-27 22:03:40 +000031 Statistic<> NumNodeAllocated ("dsnode", "Number of nodes allocated");
32
33 cl::opt<bool>
34 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
35 cl::desc("Make DSA less aggressive when cloning graphs"));
Chris Lattner08db7192002-11-06 06:20:27 +000036};
37
Chris Lattner93ddd7e2004-01-22 16:36:28 +000038#if 0
39#define TIME_REGION(VARNAME, DESC) \
40 NamedRegionTimer VARNAME(DESC)
41#else
42#define TIME_REGION(VARNAME, DESC)
43#endif
44
Chris Lattnerb1060432002-11-07 05:20:53 +000045using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000046
Chris Lattner731b2d72003-02-13 19:09:00 +000047DSNode *DSNodeHandle::HandleForwarding() const {
48 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
49
50 // Handle node forwarding here!
51 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
52 Offset += N->ForwardNH.getOffset();
53
54 if (--N->NumReferrers == 0) {
55 // Removing the last referrer to the node, sever the forwarding link
56 N->stopForwarding();
57 }
58
59 N = Next;
60 N->NumReferrers++;
61 if (N->Size <= Offset) {
62 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
63 Offset = 0;
64 }
65 return N;
66}
67
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000068//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000069// DSNode Implementation
70//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000071
Chris Lattnerbd92b732003-06-19 21:15:11 +000072DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000073 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000074 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000075 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000076 G->getNodes().push_back(this);
Chris Lattner0b144872004-01-27 22:03:40 +000077 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000078}
79
Chris Lattner0d9bab82002-07-18 00:12:30 +000080// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000081DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000082 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner0b144872004-01-27 22:03:40 +000083 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
84 if (!NullLinks)
85 Links = N.Links;
86 else
87 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattner72d29a42003-02-11 23:11:51 +000088 G->getNodes().push_back(this);
Chris Lattner0b144872004-01-27 22:03:40 +000089 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000090}
91
Chris Lattner15869aa2003-11-02 22:27:28 +000092/// getTargetData - Get the target data object used to construct this node.
93///
94const TargetData &DSNode::getTargetData() const {
95 return ParentGraph->getTargetData();
96}
97
Chris Lattner72d29a42003-02-11 23:11:51 +000098void DSNode::assertOK() const {
99 assert((Ty != Type::VoidTy ||
100 Ty == Type::VoidTy && (Size == 0 ||
101 (NodeType & DSNode::Array))) &&
102 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000103
104 assert(ParentGraph && "Node has no parent?");
105 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
106 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
107 assert(SM.find(Globals[i]) != SM.end());
108 assert(SM.find(Globals[i])->second.getNode() == this);
109 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000110}
111
112/// forwardNode - Mark this node as being obsolete, and all references to it
113/// should be forwarded to the specified node and offset.
114///
115void DSNode::forwardNode(DSNode *To, unsigned Offset) {
116 assert(this != To && "Cannot forward a node to itself!");
117 assert(ForwardNH.isNull() && "Already forwarding from this node!");
118 if (To->Size <= 1) Offset = 0;
119 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
120 "Forwarded offset is wrong!");
121 ForwardNH.setNode(To);
122 ForwardNH.setOffset(Offset);
123 NodeType = DEAD;
124 Size = 0;
125 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000126}
127
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000128// addGlobal - Add an entry for a global value to the Globals list. This also
129// marks the node with the 'G' flag if it does not already have it.
130//
131void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000132 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000133 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000134 std::lower_bound(Globals.begin(), Globals.end(), GV);
135
136 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000137 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000138 Globals.insert(I, GV);
139 NodeType |= GlobalNode;
140 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000141}
142
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000143/// foldNodeCompletely - If we determine that this node has some funny
144/// behavior happening to it that we cannot represent, we fold it down to a
145/// single, completely pessimistic, node. This node is represented as a
146/// single byte with a single TypeEntry of "void".
147///
148void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000149 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000150
Chris Lattner08db7192002-11-06 06:20:27 +0000151 ++NumFolds;
152
Chris Lattner0b144872004-01-27 22:03:40 +0000153 // If this node has a size that is <= 1, we don't need to create a forwarding
154 // node.
155 if (getSize() <= 1) {
156 NodeType |= DSNode::Array;
157 Ty = Type::VoidTy;
158 Size = 1;
159 assert(Links.size() <= 1 && "Size is 1, but has more links?");
160 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000161 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000162 // Create the node we are going to forward to. This is required because
163 // some referrers may have an offset that is > 0. By forcing them to
164 // forward, the forwarder has the opportunity to correct the offset.
165 DSNode *DestNode = new DSNode(0, ParentGraph);
166 DestNode->NodeType = NodeType|DSNode::Array;
167 DestNode->Ty = Type::VoidTy;
168 DestNode->Size = 1;
169 DestNode->Globals.swap(Globals);
170
171 // Start forwarding to the destination node...
172 forwardNode(DestNode, 0);
173
174 if (!Links.empty()) {
175 DestNode->Links.reserve(1);
176
177 DSNodeHandle NH(DestNode);
178 DestNode->Links.push_back(Links[0]);
179
180 // If we have links, merge all of our outgoing links together...
181 for (unsigned i = Links.size()-1; i != 0; --i)
182 NH.getNode()->Links[0].mergeWith(Links[i]);
183 Links.clear();
184 } else {
185 DestNode->Links.resize(1);
186 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000187 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000188}
Chris Lattner076c1f92002-11-07 06:31:54 +0000189
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000190/// isNodeCompletelyFolded - Return true if this node has been completely
191/// folded down to something that can never be expanded, effectively losing
192/// all of the field sensitivity that may be present in the node.
193///
194bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000195 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000196}
197
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000198namespace {
199 /// TypeElementWalker Class - Used for implementation of physical subtyping...
200 ///
201 class TypeElementWalker {
202 struct StackState {
203 const Type *Ty;
204 unsigned Offset;
205 unsigned Idx;
206 StackState(const Type *T, unsigned Off = 0)
207 : Ty(T), Offset(Off), Idx(0) {}
208 };
209
210 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000211 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000212 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000213 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000214 Stack.push_back(T);
215 StepToLeaf();
216 }
217
218 bool isDone() const { return Stack.empty(); }
219 const Type *getCurrentType() const { return Stack.back().Ty; }
220 unsigned getCurrentOffset() const { return Stack.back().Offset; }
221
222 void StepToNextType() {
223 PopStackAndAdvance();
224 StepToLeaf();
225 }
226
227 private:
228 /// PopStackAndAdvance - Pop the current element off of the stack and
229 /// advance the underlying element to the next contained member.
230 void PopStackAndAdvance() {
231 assert(!Stack.empty() && "Cannot pop an empty stack!");
232 Stack.pop_back();
233 while (!Stack.empty()) {
234 StackState &SS = Stack.back();
235 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
236 ++SS.Idx;
237 if (SS.Idx != ST->getElementTypes().size()) {
238 const StructLayout *SL = TD.getStructLayout(ST);
239 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
240 return;
241 }
242 Stack.pop_back(); // At the end of the structure
243 } else {
244 const ArrayType *AT = cast<ArrayType>(SS.Ty);
245 ++SS.Idx;
246 if (SS.Idx != AT->getNumElements()) {
247 SS.Offset += TD.getTypeSize(AT->getElementType());
248 return;
249 }
250 Stack.pop_back(); // At the end of the array
251 }
252 }
253 }
254
255 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
256 /// on the type stack.
257 void StepToLeaf() {
258 if (Stack.empty()) return;
259 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
260 StackState &SS = Stack.back();
261 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
262 if (ST->getElementTypes().empty()) {
263 assert(SS.Idx == 0);
264 PopStackAndAdvance();
265 } else {
266 // Step into the structure...
267 assert(SS.Idx < ST->getElementTypes().size());
268 const StructLayout *SL = TD.getStructLayout(ST);
269 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
270 SS.Offset+SL->MemberOffsets[SS.Idx]));
271 }
272 } else {
273 const ArrayType *AT = cast<ArrayType>(SS.Ty);
274 if (AT->getNumElements() == 0) {
275 assert(SS.Idx == 0);
276 PopStackAndAdvance();
277 } else {
278 // Step into the array...
279 assert(SS.Idx < AT->getNumElements());
280 Stack.push_back(StackState(AT->getElementType(),
281 SS.Offset+SS.Idx*
282 TD.getTypeSize(AT->getElementType())));
283 }
284 }
285 }
286 }
287 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000288} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000289
290/// ElementTypesAreCompatible - Check to see if the specified types are
291/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000292/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
293/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000294///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000295static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000296 bool AllowLargerT1, const TargetData &TD){
297 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000298
299 while (!T1W.isDone() && !T2W.isDone()) {
300 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
301 return false;
302
303 const Type *T1 = T1W.getCurrentType();
304 const Type *T2 = T2W.getCurrentType();
305 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
306 return false;
307
308 T1W.StepToNextType();
309 T2W.StepToNextType();
310 }
311
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000312 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000313}
314
315
Chris Lattner08db7192002-11-06 06:20:27 +0000316/// mergeTypeInfo - This method merges the specified type into the current node
317/// at the specified offset. This may update the current node's type record if
318/// this gives more information to the node, it may do nothing to the node if
319/// this information is already known, or it may merge the node completely (and
320/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000321///
Chris Lattner08db7192002-11-06 06:20:27 +0000322/// This method returns true if the node is completely folded, otherwise false.
323///
Chris Lattner088b6392003-03-03 17:13:31 +0000324bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
325 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000326 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000327 // Check to make sure the Size member is up-to-date. Size can be one of the
328 // following:
329 // Size = 0, Ty = Void: Nothing is known about this node.
330 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
331 // Size = 1, Ty = Void, Array = 1: The node is collapsed
332 // Otherwise, sizeof(Ty) = Size
333 //
Chris Lattner18552922002-11-18 21:44:46 +0000334 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
335 (Size == 0 && !Ty->isSized() && !isArray()) ||
336 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
337 (Size == 0 && !Ty->isSized() && !isArray()) ||
338 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000339 "Size member of DSNode doesn't match the type structure!");
340 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000341
Chris Lattner18552922002-11-18 21:44:46 +0000342 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000343 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000344
Chris Lattner08db7192002-11-06 06:20:27 +0000345 // Return true immediately if the node is completely folded.
346 if (isNodeCompletelyFolded()) return true;
347
Chris Lattner23f83dc2002-11-08 22:49:57 +0000348 // If this is an array type, eliminate the outside arrays because they won't
349 // be used anyway. This greatly reduces the size of large static arrays used
350 // as global variables, for example.
351 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000352 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000353 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
354 // FIXME: we might want to keep small arrays, but must be careful about
355 // things like: [2 x [10000 x int*]]
356 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000357 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000358 }
359
Chris Lattner08db7192002-11-06 06:20:27 +0000360 // Figure out how big the new type we're merging in is...
361 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
362
363 // Otherwise check to see if we can fold this type into the current node. If
364 // we can't, we fold the node completely, if we can, we potentially update our
365 // internal state.
366 //
Chris Lattner18552922002-11-18 21:44:46 +0000367 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000368 // If this is the first type that this node has seen, just accept it without
369 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000370 assert(Offset == 0 && !isArray() &&
371 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000372 Ty = NewTy;
373 NodeType &= ~Array;
374 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000375 Size = NewTySize;
376
377 // Calculate the number of outgoing links from this node.
378 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
379 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000380 }
Chris Lattner08db7192002-11-06 06:20:27 +0000381
382 // Handle node expansion case here...
383 if (Offset+NewTySize > Size) {
384 // It is illegal to grow this node if we have treated it as an array of
385 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000386 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000387 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000388 return true;
389 }
390
391 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000392 std::cerr << "UNIMP: Trying to merge a growth type into "
393 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000394 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000395 return true;
396 }
397
398 // Okay, the situation is nice and simple, we are trying to merge a type in
399 // at offset 0 that is bigger than our current type. Implement this by
400 // switching to the new type and then merge in the smaller one, which should
401 // hit the other code path here. If the other code path decides it's not
402 // ok, it will collapse the node as appropriate.
403 //
Chris Lattner18552922002-11-18 21:44:46 +0000404 const Type *OldTy = Ty;
405 Ty = NewTy;
406 NodeType &= ~Array;
407 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000408 Size = NewTySize;
409
410 // Must grow links to be the appropriate size...
411 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
412
413 // Merge in the old type now... which is guaranteed to be smaller than the
414 // "current" type.
415 return mergeTypeInfo(OldTy, 0);
416 }
417
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000418 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000419 "Cannot merge something into a part of our type that doesn't exist!");
420
Chris Lattner18552922002-11-18 21:44:46 +0000421 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000422 // type that starts at offset Offset.
423 //
424 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000425 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000426 while (O < Offset) {
427 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
428
429 switch (SubType->getPrimitiveID()) {
430 case Type::StructTyID: {
431 const StructType *STy = cast<StructType>(SubType);
432 const StructLayout &SL = *TD.getStructLayout(STy);
433
434 unsigned i = 0, e = SL.MemberOffsets.size();
435 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
436 /* empty */;
437
438 // The offset we are looking for must be in the i'th element...
439 SubType = STy->getElementTypes()[i];
440 O += SL.MemberOffsets[i];
441 break;
442 }
443 case Type::ArrayTyID: {
444 SubType = cast<ArrayType>(SubType)->getElementType();
445 unsigned ElSize = TD.getTypeSize(SubType);
446 unsigned Remainder = (Offset-O) % ElSize;
447 O = Offset-Remainder;
448 break;
449 }
450 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000451 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000452 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000453 }
454 }
455
456 assert(O == Offset && "Could not achieve the correct offset!");
457
458 // If we found our type exactly, early exit
459 if (SubType == NewTy) return false;
460
Chris Lattner0b144872004-01-27 22:03:40 +0000461 // Differing function types don't require us to merge. They are not values anyway.
462 if (isa<FunctionType>(SubType) &&
463 isa<FunctionType>(NewTy)) return false;
464
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000465 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
466
467 // Ok, we are getting desperate now. Check for physical subtyping, where we
468 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000469 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000470 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000471 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000472 return false;
473
Chris Lattner08db7192002-11-06 06:20:27 +0000474 // Okay, so we found the leader type at the offset requested. Search the list
475 // of types that starts at this offset. If SubType is currently an array or
476 // structure, the type desired may actually be the first element of the
477 // composite type...
478 //
Chris Lattner18552922002-11-18 21:44:46 +0000479 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000480 while (SubType != NewTy) {
481 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000482 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000483 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000484 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000485 case Type::StructTyID: {
486 const StructType *STy = cast<StructType>(SubType);
487 const StructLayout &SL = *TD.getStructLayout(STy);
488 if (SL.MemberOffsets.size() > 1)
489 NextPadSize = SL.MemberOffsets[1];
490 else
491 NextPadSize = SubTypeSize;
492 NextSubType = STy->getElementTypes()[0];
493 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000494 break;
Chris Lattner18552922002-11-18 21:44:46 +0000495 }
Chris Lattner08db7192002-11-06 06:20:27 +0000496 case Type::ArrayTyID:
497 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000498 NextSubTypeSize = TD.getTypeSize(NextSubType);
499 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000500 break;
501 default: ;
502 // fall out
503 }
504
505 if (NextSubType == 0)
506 break; // In the default case, break out of the loop
507
Chris Lattner18552922002-11-18 21:44:46 +0000508 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000509 break; // Don't allow shrinking to a smaller type than NewTySize
510 SubType = NextSubType;
511 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000512 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000513 }
514
515 // If we found the type exactly, return it...
516 if (SubType == NewTy)
517 return false;
518
519 // Check to see if we have a compatible, but different type...
520 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000521 // Check to see if this type is obviously convertible... int -> uint f.e.
522 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000523 return false;
524
525 // Check to see if we have a pointer & integer mismatch going on here,
526 // loading a pointer as a long, for example.
527 //
528 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
529 NewTy->isInteger() && isa<PointerType>(SubType))
530 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000531 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
532 // We are accessing the field, plus some structure padding. Ignore the
533 // structure padding.
534 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000535 }
536
Chris Lattner58f98d02003-07-02 04:38:49 +0000537 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000538 if (getParentGraph()->getReturnNodes().size())
539 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000540 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
541 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
542 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
543 << "SubType: ";
544 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000545
Chris Lattner088b6392003-03-03 17:13:31 +0000546 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000547 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000548}
549
Chris Lattner08db7192002-11-06 06:20:27 +0000550
551
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000552// addEdgeTo - Add an edge from the current node to the specified node. This
553// can cause merging of nodes in the graph.
554//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000555void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000556 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000557
Chris Lattner08db7192002-11-06 06:20:27 +0000558 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000559 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000560 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000561 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000562 } else { // No merging to perform...
563 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000564 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000565}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000566
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000567
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000568// MergeSortedVectors - Efficiently merge a vector into another vector where
569// duplicates are not allowed and both are sorted. This assumes that 'T's are
570// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000571//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000572static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
573 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000574 // By far, the most common cases will be the simple ones. In these cases,
575 // avoid having to allocate a temporary vector...
576 //
577 if (Src.empty()) { // Nothing to merge in...
578 return;
579 } else if (Dest.empty()) { // Just copy the result in...
580 Dest = Src;
581 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000582 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000583 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000584 std::lower_bound(Dest.begin(), Dest.end(), V);
585 if (I == Dest.end() || *I != Src[0]) // If not already contained...
586 Dest.insert(I, Src[0]);
587 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000588 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000589 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000590 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000591 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
592 if (I == Dest.end() || *I != Tmp) // If not already contained...
593 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000594
595 } else {
596 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000597 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000598
599 // Make space for all of the type entries now...
600 Dest.resize(Dest.size()+Src.size());
601
602 // Merge the two sorted ranges together... into Dest.
603 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
604
605 // Now erase any duplicate entries that may have accumulated into the
606 // vectors (because they were in both of the input sets)
607 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
608 }
609}
610
Chris Lattner0b144872004-01-27 22:03:40 +0000611void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
612 MergeSortedVectors(Globals, RHS);
613}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000614
Chris Lattner0b144872004-01-27 22:03:40 +0000615// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000616// This function does the hard work of merging two nodes, CurNodeH
617// and NH after filtering out trivial cases and making sure that
618// CurNodeH.offset >= NH.offset.
619//
620// ***WARNING***
621// Since merging may cause either node to go away, we must always
622// use the node-handles to refer to the nodes. These node handles are
623// automatically updated during merging, so will always provide access
624// to the correct node after a merge.
625//
626void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
627 assert(CurNodeH.getOffset() >= NH.getOffset() &&
628 "This should have been enforced in the caller.");
629
630 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
631 // respect to NH.Offset) is now zero. NOffset is the distance from the base
632 // of our object that N starts from.
633 //
634 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
635 unsigned NSize = NH.getNode()->getSize();
636
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000637 // If the two nodes are of different size, and the smaller node has the array
638 // bit set, collapse!
639 if (NSize != CurNodeH.getNode()->getSize()) {
640 if (NSize < CurNodeH.getNode()->getSize()) {
641 if (NH.getNode()->isArray())
642 NH.getNode()->foldNodeCompletely();
643 } else if (CurNodeH.getNode()->isArray()) {
644 NH.getNode()->foldNodeCompletely();
645 }
646 }
647
648 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000649 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000650 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000651 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000652
653 // If we are merging a node with a completely folded node, then both nodes are
654 // now completely folded.
655 //
656 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
657 if (!NH.getNode()->isNodeCompletelyFolded()) {
658 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000659 assert(NH.getNode() && NH.getOffset() == 0 &&
660 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000661 NOffset = NH.getOffset();
662 NSize = NH.getNode()->getSize();
663 assert(NOffset == 0 && NSize == 1);
664 }
665 } else if (NH.getNode()->isNodeCompletelyFolded()) {
666 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000667 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
668 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000669 NOffset = NH.getOffset();
670 NSize = NH.getNode()->getSize();
671 assert(NOffset == 0 && NSize == 1);
672 }
673
Chris Lattner72d29a42003-02-11 23:11:51 +0000674 DSNode *N = NH.getNode();
675 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000676 assert(!CurNodeH.getNode()->isDeadNode());
677
Chris Lattner0b144872004-01-27 22:03:40 +0000678 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000679 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000680
Chris Lattner72d29a42003-02-11 23:11:51 +0000681 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000682 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000683 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000684
Chris Lattner72d29a42003-02-11 23:11:51 +0000685 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
686 //
687 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
688 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000689 if (Link.getNode()) {
690 // Compute the offset into the current node at which to
691 // merge this link. In the common case, this is a linear
692 // relation to the offset in the original node (with
693 // wrapping), but if the current node gets collapsed due to
694 // recursive merging, we must make sure to merge in all remaining
695 // links at offset zero.
696 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000697 DSNode *CN = CurNodeH.getNode();
698 if (CN->Size != 1)
699 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
700 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000701 }
702 }
703
704 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000705 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000706
707 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000708 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000709 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000710
711 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000712 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000713 }
714}
715
716
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000717// mergeWith - Merge this node and the specified node, moving all links to and
718// from the argument node into the current node, deleting the node argument.
719// Offset indicates what offset the specified node is to be merged into the
720// current node.
721//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000722// The specified node may be a null pointer (in which case, we update it to
723// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000724//
725void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
726 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000727 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000728 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000729
Chris Lattner5254a8d2004-01-22 16:31:08 +0000730 // If the RHS is a null node, make it point to this node!
731 if (N == 0) {
732 NH.mergeWith(DSNodeHandle(this, Offset));
733 return;
734 }
735
Chris Lattnerbd92b732003-06-19 21:15:11 +0000736 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000737 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
738
Chris Lattner02606632002-11-04 06:48:26 +0000739 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000740 // We cannot merge two pieces of the same node together, collapse the node
741 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000742 DEBUG(std::cerr << "Attempting to merge two chunks of"
743 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000744 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000745 return;
746 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000747
Chris Lattner5190ce82002-11-12 07:20:45 +0000748 // If both nodes are not at offset 0, make sure that we are merging the node
749 // at an later offset into the node with the zero offset.
750 //
751 if (Offset < NH.getOffset()) {
752 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
753 return;
754 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
755 // If the offsets are the same, merge the smaller node into the bigger node
756 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
757 return;
758 }
759
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000760 // Ok, now we can merge the two nodes. Use a static helper that works with
761 // two node handles, since "this" may get merged away at intermediate steps.
762 DSNodeHandle CurNodeH(this, Offset);
763 DSNodeHandle NHCopy(NH);
764 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000765}
766
Chris Lattner0b144872004-01-27 22:03:40 +0000767
768//===----------------------------------------------------------------------===//
769// ReachabilityCloner Implementation
770//===----------------------------------------------------------------------===//
771
772DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
773 if (SrcNH.isNull()) return DSNodeHandle();
774 const DSNode *SN = SrcNH.getNode();
775
776 DSNodeHandle &NH = NodeMap[SN];
777 if (!NH.isNull()) // Node already mapped?
778 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
779
780 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
781 DN->maskNodeTypes(BitsToKeep);
782 NH.setNode(DN);
783 NH.setOffset(SrcNH.getOffset());
784
785 // Next, recursively clone all outgoing links as necessary. Note that
786 // adding these links can cause the node to collapse itself at any time, and
787 // the current node may be merged with arbitrary other nodes. For this
788 // reason, we must always go through NH.
789 DN = 0;
790 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
791 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
792 if (!SrcEdge.isNull()) {
793 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
794 // Compute the offset into the current node at which to
795 // merge this link. In the common case, this is a linear
796 // relation to the offset in the original node (with
797 // wrapping), but if the current node gets collapsed due to
798 // recursive merging, we must make sure to merge in all remaining
799 // links at offset zero.
800 unsigned MergeOffset = 0;
801 DSNode *CN = NH.getNode();
802 if (CN->getSize() != 1)
803 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
804 - SrcNH.getOffset()) %CN->getSize();
805 CN->addEdgeTo(MergeOffset, DestEdge);
806 }
807 }
808
809 // If this node contains any globals, make sure they end up in the scalar
810 // map with the correct offset.
811 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
812 I != E; ++I) {
813 GlobalValue *GV = *I;
814 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
815 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
816 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
817 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
818 DestGNH.getOffset()+NH.getOffset()));
819
820 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
821 Dest.getInlinedGlobals().insert(GV);
822 }
823
824 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
825}
826
827void ReachabilityCloner::merge(const DSNodeHandle &NH,
828 const DSNodeHandle &SrcNH) {
829 if (SrcNH.isNull()) return; // Noop
830 if (NH.isNull()) {
831 // If there is no destination node, just clone the source and assign the
832 // destination node to be it.
833 NH.mergeWith(getClonedNH(SrcNH));
834 return;
835 }
836
837 // Okay, at this point, we know that we have both a destination and a source
838 // node that need to be merged. Check to see if the source node has already
839 // been cloned.
840 const DSNode *SN = SrcNH.getNode();
841 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
842 if (SCNH.getNode()) { // Node already cloned?
843 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
844 SCNH.getOffset()+SrcNH.getOffset()));
845
846 return; // Nothing to do!
847 }
848
849 // Okay, so the source node has not already been cloned. Instead of creating
850 // a new DSNode, only to merge it into the one we already have, try to perform
851 // the merge in-place. The only case we cannot handle here is when the offset
852 // into the existing node is less than the offset into the virtual node we are
853 // merging in. In this case, we have to extend the existing node, which
854 // requires an allocation anyway.
855 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
856 if (NH.getOffset() >= SrcNH.getOffset()) {
857
858 if (!DN->isNodeCompletelyFolded()) {
859 // Make sure the destination node is folded if the source node is folded.
860 if (SN->isNodeCompletelyFolded()) {
861 DN->foldNodeCompletely();
862 DN = NH.getNode();
863 } else if (SN->getSize() != DN->getSize()) {
864 // If the two nodes are of different size, and the smaller node has the
865 // array bit set, collapse!
866 if (SN->getSize() < DN->getSize()) {
867 if (SN->isArray()) {
868 DN->foldNodeCompletely();
869 DN = NH.getNode();
870 }
871 } else if (DN->isArray()) {
872 DN->foldNodeCompletely();
873 DN = NH.getNode();
874 }
875 }
876
877 // Merge the type entries of the two nodes together...
878 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
879 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
880 DN = NH.getNode();
881 }
882 }
883
884 assert(!DN->isDeadNode());
885
886 // Merge the NodeType information.
887 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
888
889 // Before we start merging outgoing links and updating the scalar map, make
890 // sure it is known that this is the representative node for the src node.
891 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
892
893 // If the source node contains any globals, make sure they end up in the
894 // scalar map with the correct offset.
895 if (SN->global_begin() != SN->global_end()) {
896 // Update the globals in the destination node itself.
897 DN->mergeGlobals(SN->getGlobals());
898
899 // Update the scalar map for the graph we are merging the source node
900 // into.
901 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
902 I != E; ++I) {
903 GlobalValue *GV = *I;
904 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
905 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
906 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
907 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
908 DestGNH.getOffset()+NH.getOffset()));
909
910 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
911 Dest.getInlinedGlobals().insert(GV);
912 }
913 }
914 } else {
915 // We cannot handle this case without allocating a temporary node. Fall
916 // back on being simple.
917
918 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
919 NewDN->maskNodeTypes(BitsToKeep);
920
921 unsigned NHOffset = NH.getOffset();
922 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
923 assert(NH.getNode() &&
924 (NH.getOffset() > NHOffset ||
925 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
926 "Merging did not adjust the offset!");
927
928 // Before we start merging outgoing links and updating the scalar map, make
929 // sure it is known that this is the representative node for the src node.
930 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
931 }
932
933
934 // Next, recursively merge all outgoing links as necessary. Note that
935 // adding these links can cause the destination node to collapse itself at
936 // any time, and the current node may be merged with arbitrary other nodes.
937 // For this reason, we must always go through NH.
938 DN = 0;
939 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
940 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
941 if (!SrcEdge.isNull()) {
942 // Compute the offset into the current node at which to
943 // merge this link. In the common case, this is a linear
944 // relation to the offset in the original node (with
945 // wrapping), but if the current node gets collapsed due to
946 // recursive merging, we must make sure to merge in all remaining
947 // links at offset zero.
948 unsigned MergeOffset = 0;
949 DSNode *CN = SCNH.getNode();
950 if (CN->getSize() != 1)
951 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
952
953 // Perform the recursive merging. Make sure to create a temporary NH,
954 // because the Link can disappear in the process of recursive merging.
955 DSNodeHandle Tmp = CN->getLink(MergeOffset);
956 merge(Tmp, SrcEdge);
957 }
958 }
959}
960
961/// mergeCallSite - Merge the nodes reachable from the specified src call
962/// site into the nodes reachable from DestCS.
963void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
964 const DSCallSite &SrcCS) {
965 merge(DestCS.getRetVal(), SrcCS.getRetVal());
966 unsigned MinArgs = DestCS.getNumPtrArgs();
967 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
968
969 for (unsigned a = 0; a != MinArgs; ++a)
970 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
971}
972
973
Chris Lattner9de906c2002-10-20 22:11:44 +0000974//===----------------------------------------------------------------------===//
975// DSCallSite Implementation
976//===----------------------------------------------------------------------===//
977
Vikram S. Adve26b98262002-10-20 21:41:02 +0000978// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000979Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000980 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000981}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000982
Chris Lattner0b144872004-01-27 22:03:40 +0000983void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
984 ReachabilityCloner &RC) {
985 NH = RC.getClonedNH(Src);
986}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000987
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000988//===----------------------------------------------------------------------===//
989// DSGraph Implementation
990//===----------------------------------------------------------------------===//
991
Chris Lattnera9d65662003-06-30 05:57:30 +0000992/// getFunctionNames - Return a space separated list of the name of the
993/// functions in this graph (if any)
994std::string DSGraph::getFunctionNames() const {
995 switch (getReturnNodes().size()) {
996 case 0: return "Globals graph";
997 case 1: return getReturnNodes().begin()->first->getName();
998 default:
999 std::string Return;
1000 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1001 I != getReturnNodes().end(); ++I)
1002 Return += I->first->getName() + " ";
1003 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1004 return Return;
1005 }
1006}
1007
1008
Chris Lattner15869aa2003-11-02 22:27:28 +00001009DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001010 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001011 NodeMapTy NodeMap;
1012 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001013}
1014
Chris Lattner5a540632003-06-30 03:15:25 +00001015DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001016 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001017 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001018 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001019}
1020
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001021DSGraph::~DSGraph() {
1022 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001023 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001024 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001025 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001026 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001027
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001028 // Drop all intra-node references, so that assertions don't fail...
1029 std::for_each(Nodes.begin(), Nodes.end(),
1030 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001031
1032 // Delete all of the nodes themselves...
1033 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
1034}
1035
Chris Lattner0d9bab82002-07-18 00:12:30 +00001036// dump - Allow inspection of graph in a debugger.
1037void DSGraph::dump() const { print(std::cerr); }
1038
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001039
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001040/// remapLinks - Change all of the Links in the current node according to the
1041/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001042///
Chris Lattner8d327672003-06-30 03:36:09 +00001043void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001044 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1045 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001046 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1047 if (ONMI != OldNodeMap.end()) {
1048 Links[i].setNode(ONMI->second.getNode());
1049 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1050 }
Chris Lattner2f561382004-01-22 16:56:13 +00001051 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001052}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001053
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001054/// updateFromGlobalGraph - This function rematerializes global nodes and
1055/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001056/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1057/// are already up-to-date in the current graph. In practice, in the TD pass,
1058/// this is likely to be a large fraction of the live global nodes in each
1059/// function (since most live nodes are likely to have been brought up-to-date
1060/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001061///
1062void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001063 TIME_REGION(X, "updateFromGlobalGraph");
1064
1065 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1066
1067 // Clone the non-up-to-date global nodes into this graph.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001068 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
1069 E = getScalarMap().end(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001070 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first))
1071 if (InlinedGlobals.count(GV) == 0) { // GNode is not up-to-date
1072 ScalarMapTy::iterator It = GlobalsGraph->ScalarMap.find(GV);
1073 if (It != GlobalsGraph->ScalarMap.end())
1074 RC.getClonedNH(It->second);
1075 }
1076
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001077 // Merging global nodes leaves behind unused nodes: get rid of them now.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001078 removeTriviallyDeadNodes();
1079}
1080
Chris Lattner5a540632003-06-30 03:15:25 +00001081/// cloneInto - Clone the specified DSGraph into the current graph. The
1082/// translated ScalarMap for the old function is filled into the OldValMap
1083/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1084///
1085/// The CloneFlags member controls various aspects of the cloning process.
1086///
1087void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
1088 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1089 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001090 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001091 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001092 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001093
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001094 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +00001095
1096 // Duplicate all of the nodes, populating the node map...
1097 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +00001098
1099 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001100 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1101 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1102 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001103 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +00001104 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001105 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001106 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001107 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +00001108 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001109 }
Chris Lattner18552922002-11-18 21:44:46 +00001110#ifndef NDEBUG
1111 Timer::addPeakMemoryMeasurement();
1112#endif
1113
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001114 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001115 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001116 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001117
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001118 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +00001119 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001120 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001121 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001122 DSNodeHandle &H = OldValMap[I->first];
1123 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1124 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001125
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001126 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001127 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1128 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001129 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1130 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001131 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001132 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001133
Chris Lattner679e8e12002-11-08 21:27:12 +00001134 if (!(CloneFlags & DontCloneCallNodes)) {
1135 // Copy the function calls list...
1136 unsigned FC = FunctionCalls.size(); // FirstCall
1137 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1138 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1139 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001140 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001141
Chris Lattneracf491f2002-11-08 22:27:09 +00001142 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001143 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001144 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001145 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1146 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1147 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1148 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001149
Chris Lattner5a540632003-06-30 03:15:25 +00001150 // Map the return node pointers over...
1151 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1152 E = G.getReturnNodes().end(); I != E; ++I) {
1153 const DSNodeHandle &Ret = I->second;
1154 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1155 OldReturnNodes.insert(std::make_pair(I->first,
1156 DSNodeHandle(MappedRet.getNode(),
1157 MappedRet.getOffset()+Ret.getOffset())));
1158 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001159}
1160
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001161
Chris Lattner076c1f92002-11-07 06:31:54 +00001162/// mergeInGraph - The method is used for merging graphs together. If the
1163/// argument graph is not *this, it makes a clone of the specified graph, then
1164/// merges the nodes specified in the call site with the formal arguments in the
1165/// graph.
1166///
Chris Lattner9f930552003-06-30 05:27:18 +00001167void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1168 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001169 TIME_REGION(X, "mergeInGraph");
1170
Chris Lattner076c1f92002-11-07 06:31:54 +00001171 // If this is not a recursive call, clone the graph into this graph...
1172 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001173 // Clone the callee's graph into the current graph, keeping track of where
1174 // scalars in the old graph _used_ to point, and of the new nodes matching
1175 // nodes of the old graph.
1176 ReachabilityCloner RC(*this, Graph, CloneFlags);
1177
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001178 // Set up argument bindings
1179 Function::aiterator AI = F.abegin();
1180 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1181 // Advance the argument iterator to the first pointer argument...
1182 while (AI != F.aend() && !isPointerType(AI->getType())) {
1183 ++AI;
Chris Lattner076c1f92002-11-07 06:31:54 +00001184#ifndef NDEBUG
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001185 if (AI == F.aend())
1186 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001187#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001188 }
1189 if (AI == F.aend()) break;
1190
1191 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001192 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001193 }
1194
Chris Lattner0b144872004-01-27 22:03:40 +00001195 // Map the return node pointer over.
1196 if (CS.getRetVal().getNode())
1197 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1198
1199 // If requested, copy the calls or aux-calls lists.
1200 if (!(CloneFlags & DontCloneCallNodes)) {
1201 // Copy the function calls list...
1202 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1203 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1204 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1205 }
1206
1207 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1208 // Copy the auxiliary function calls list...
1209 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1210 Graph.AuxFunctionCalls.size());
1211 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1212 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1213 }
1214
1215 // If the user requested it, add the nodes that we need to clone to the
1216 // RootNodes set.
1217 if (!EnableDSNodeGlobalRootsHack)
1218 for (unsigned i = 0, e = Graph.Nodes.size(); i != e; ++i)
1219 if (!Graph.Nodes[i]->getGlobals().empty())
1220 RC.getClonedNH(Graph.Nodes[i]);
1221
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001222 } else {
1223 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001224
1225 // Merge the return value with the return value of the context...
1226 RetVal.mergeWith(CS.getRetVal());
1227
1228 // Resolve all of the function arguments...
1229 Function::aiterator AI = F.abegin();
1230
1231 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1232 // Advance the argument iterator to the first pointer argument...
1233 while (AI != F.aend() && !isPointerType(AI->getType())) {
1234 ++AI;
1235#ifndef NDEBUG
1236 if (AI == F.aend())
1237 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1238#endif
1239 }
1240 if (AI == F.aend()) break;
1241
1242 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001243 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001244 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1245 NH.mergeWith(CS.getPtrArg(i));
1246 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001247 }
1248}
1249
Chris Lattner58f98d02003-07-02 04:38:49 +00001250/// getCallSiteForArguments - Get the arguments and return value bindings for
1251/// the specified function in the current graph.
1252///
1253DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1254 std::vector<DSNodeHandle> Args;
1255
1256 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1257 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001258 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001259
Chris Lattner808a7ae2003-09-20 16:34:13 +00001260 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001261}
1262
1263
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001264
Chris Lattner0d9bab82002-07-18 00:12:30 +00001265// markIncompleteNodes - Mark the specified node as having contents that are not
1266// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001267// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001268// must recursively traverse the data structure graph, marking all reachable
1269// nodes as incomplete.
1270//
1271static void markIncompleteNode(DSNode *N) {
1272 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001273 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001274
1275 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001276 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001277
Misha Brukman2f2d0652003-09-11 18:14:24 +00001278 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001279 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1280 if (DSNode *DSN = N->getLink(i).getNode())
1281 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001282}
1283
Chris Lattnere71ffc22002-11-11 03:36:55 +00001284static void markIncomplete(DSCallSite &Call) {
1285 // Then the return value is certainly incomplete!
1286 markIncompleteNode(Call.getRetVal().getNode());
1287
1288 // All objects pointed to by function arguments are incomplete!
1289 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1290 markIncompleteNode(Call.getPtrArg(i).getNode());
1291}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001292
1293// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1294// modified by other functions that have not been resolved yet. This marks
1295// nodes that are reachable through three sources of "unknownness":
1296//
1297// Global Variables, Function Calls, and Incoming Arguments
1298//
1299// For any node that may have unknown components (because something outside the
1300// scope of current analysis may have modified it), the 'Incomplete' flag is
1301// added to the NodeType.
1302//
Chris Lattner394471f2003-01-23 22:05:33 +00001303void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001304 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001305 if (Flags & DSGraph::MarkFormalArgs)
1306 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1307 FI != E; ++FI) {
1308 Function &F = *FI->first;
1309 if (F.getName() != "main")
1310 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001311 if (isPointerType(I->getType()))
1312 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001313 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001314
1315 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001316 if (!shouldPrintAuxCalls())
1317 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1318 markIncomplete(FunctionCalls[i]);
1319 else
1320 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1321 markIncomplete(AuxFunctionCalls[i]);
1322
Chris Lattner0d9bab82002-07-18 00:12:30 +00001323
Chris Lattner93d7a212003-02-09 18:41:49 +00001324 // Mark all global nodes as incomplete...
1325 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1326 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001327 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001328 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001329}
1330
Chris Lattneraa8146f2002-11-10 06:59:55 +00001331static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1332 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001333 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001334 // No interesting info?
1335 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001336 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001337 Edge.setNode(0); // Kill the edge!
1338}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001339
Chris Lattneraa8146f2002-11-10 06:59:55 +00001340static inline bool nodeContainsExternalFunction(const DSNode *N) {
1341 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1342 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1343 if (Globals[i]->isExternal())
1344 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001345 return false;
1346}
1347
Chris Lattner5a540632003-06-30 03:15:25 +00001348static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001349 // Remove trivially identical function calls
1350 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001351 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1352
Chris Lattner0b144872004-01-27 22:03:40 +00001353#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001354 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001355 DSNode *LastCalleeNode = 0;
1356 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001357 unsigned NumDuplicateCalls = 0;
1358 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001359 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001360 DSCallSite &CS = Calls[i];
1361
Chris Lattnere4258442002-11-11 21:35:38 +00001362 // If the Callee is a useless edge, this must be an unreachable call site,
1363 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001364 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001365 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001366 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001367 CS.swap(Calls.back());
1368 Calls.pop_back();
1369 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001370 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001371 // If the return value or any arguments point to a void node with no
1372 // information at all in it, and the call node is the only node to point
1373 // to it, remove the edge to the node (killing the node).
1374 //
1375 killIfUselessEdge(CS.getRetVal());
1376 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1377 killIfUselessEdge(CS.getPtrArg(a));
1378
1379 // If this call site calls the same function as the last call site, and if
1380 // the function pointer contains an external function, this node will
1381 // never be resolved. Merge the arguments of the call node because no
1382 // information will be lost.
1383 //
Chris Lattner923fc052003-02-05 21:59:58 +00001384 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1385 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001386 ++NumDuplicateCalls;
1387 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001388 if (LastCalleeNode)
1389 LastCalleeContainsExternalFunction =
1390 nodeContainsExternalFunction(LastCalleeNode);
1391 else
1392 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001393 }
Chris Lattner0b144872004-01-27 22:03:40 +00001394
1395 // It is not clear why, but enabling this code makes DSA really
1396 // sensitive to node forwarding. Basically, with this enabled, DSA
1397 // performs different number of inlinings based on which nodes are
1398 // forwarding or not. This is clearly a problem, so this code is
1399 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001400#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001401 if (LastCalleeContainsExternalFunction
1402#if 0
1403 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001404 // This should be more than enough context sensitivity!
1405 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001406 NumDuplicateCalls > 20
1407#endif
1408 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001409 DSCallSite &OCS = Calls[i-1];
1410 OCS.mergeWith(CS);
1411
1412 // The node will now be eliminated as a duplicate!
1413 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1414 CS = OCS;
1415 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1416 OCS = CS;
1417 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001418#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001419 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001420 if (CS.isDirectCall()) {
1421 LastCalleeFunc = CS.getCalleeFunc();
1422 LastCalleeNode = 0;
1423 } else {
1424 LastCalleeNode = CS.getCalleeNode();
1425 LastCalleeFunc = 0;
1426 }
Chris Lattnere4258442002-11-11 21:35:38 +00001427 NumDuplicateCalls = 0;
1428 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001429 }
1430 }
Chris Lattner0b144872004-01-27 22:03:40 +00001431#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001432 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001433
Chris Lattner33312f72002-11-08 01:21:07 +00001434 // Track the number of call nodes merged away...
1435 NumCallNodesMerged += NumFns-Calls.size();
1436
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001437 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001438 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001439}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001440
Chris Lattneraa8146f2002-11-10 06:59:55 +00001441
Chris Lattnere2219762002-07-18 18:22:40 +00001442// removeTriviallyDeadNodes - After the graph has been constructed, this method
1443// removes all unreachable nodes that are created because they got merged with
1444// other nodes in the graph. These nodes will all be trivially unreachable, so
1445// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001446//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001447void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001448 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattner5a540632003-06-30 03:15:25 +00001449 removeIdenticalCalls(FunctionCalls);
1450 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001451
Chris Lattnerbab8c282003-09-20 21:34:07 +00001452 // Loop over all of the nodes in the graph, calling getNode on each field.
1453 // This will cause all nodes to update their forwarding edges, causing
1454 // forwarded nodes to be delete-able.
1455 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1456 DSNode *N = Nodes[i];
1457 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1458 N->getLink(l*N->getPointerSize()).getNode();
1459 }
1460
Chris Lattner0b144872004-01-27 22:03:40 +00001461 // NOTE: This code is disabled. Though it should, in theory, allow us to
1462 // remove more nodes down below, the scan of the scalar map is incredibly
1463 // expensive for certain programs (with large SCCs). In the future, if we can
1464 // make the scalar map scan more efficient, then we can reenable this.
1465#if 0
1466 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1467
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001468 // Likewise, forward any edges from the scalar nodes. While we are at it,
1469 // clean house a bit.
1470 for (ScalarMapTy::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001471 I->second.getNode();
1472 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001473 }
Chris Lattner0b144872004-01-27 22:03:40 +00001474 }
1475#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001476 bool isGlobalsGraph = !GlobalsGraph;
1477
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001478 for (unsigned i = 0; i != Nodes.size(); ++i) {
1479 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001480
1481 // Do not remove *any* global nodes in the globals graph.
1482 // This is a special case because such nodes may not have I, M, R flags set.
1483 if (Node->isGlobalNode() && isGlobalsGraph)
1484 continue;
1485
Chris Lattner72d50a02003-06-28 21:58:28 +00001486 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001487 // This is a useless node if it has no mod/ref info (checked above),
1488 // outgoing edges (which it cannot, as it is not modified in this
1489 // context), and it has no incoming edges. If it is a global node it may
1490 // have all of these properties and still have incoming edges, due to the
1491 // scalar map, so we check those now.
1492 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001493 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001494 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001495
Chris Lattnerbd92b732003-06-19 21:15:11 +00001496 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner0b144872004-01-27 22:03:40 +00001497 // Remove the scalarmap entries, which will drop the actual referrer
1498 // count to zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001499 if (Node->getNumReferrers() == Globals.size()) {
1500 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1501 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001502 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001503 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001504 }
1505 }
1506
Chris Lattnerbd92b732003-06-19 21:15:11 +00001507 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001508 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001509 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001510 Nodes[i--] = Nodes.back();
1511 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001512 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001513 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001514}
1515
1516
Chris Lattner5c7380e2003-01-29 21:10:20 +00001517/// markReachableNodes - This method recursively traverses the specified
1518/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1519/// to the set, which allows it to only traverse visited nodes once.
1520///
Chris Lattner41c04f72003-02-01 04:52:08 +00001521void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001522 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001523 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001524 if (ReachableNodes.insert(this).second) // Is newly reachable?
1525 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1526 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001527}
1528
Chris Lattner41c04f72003-02-01 04:52:08 +00001529void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001530 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001531 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001532
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001533 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1534 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001535}
1536
Chris Lattnera1220af2003-02-01 06:17:02 +00001537// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1538// looking for a node that is marked alive. If an alive node is found, return
1539// true, otherwise return false. If an alive node is reachable, this node is
1540// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001541//
Chris Lattnera1220af2003-02-01 06:17:02 +00001542static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001543 hash_set<DSNode*> &Visited,
1544 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001545 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001546 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001547
Chris Lattner85cfe012003-07-03 02:03:53 +00001548 // If this is a global node, it will end up in the globals graph anyway, so we
1549 // don't need to worry about it.
1550 if (IgnoreGlobals && N->isGlobalNode()) return false;
1551
Chris Lattneraa8146f2002-11-10 06:59:55 +00001552 // If we know that this node is alive, return so!
1553 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001554
Chris Lattneraa8146f2002-11-10 06:59:55 +00001555 // Otherwise, we don't think the node is alive yet, check for infinite
1556 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001557 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001558 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001559
Chris Lattner08db7192002-11-06 06:20:27 +00001560 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001561 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1562 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001563 N->markReachableNodes(Alive);
1564 return true;
1565 }
1566 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001567}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001568
Chris Lattnera1220af2003-02-01 06:17:02 +00001569// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1570// alive nodes.
1571//
Chris Lattner41c04f72003-02-01 04:52:08 +00001572static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001573 hash_set<DSNode*> &Visited,
1574 bool IgnoreGlobals) {
1575 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1576 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001577 return true;
1578 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001579 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001580 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001581 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001582 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1583 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001584 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001585 return false;
1586}
1587
Chris Lattnere2219762002-07-18 18:22:40 +00001588// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1589// subgraphs that are unreachable. This often occurs because the data
1590// structure doesn't "escape" into it's caller, and thus should be eliminated
1591// from the caller's graph entirely. This is only appropriate to use when
1592// inlining graphs.
1593//
Chris Lattner394471f2003-01-23 22:05:33 +00001594void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001595 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001596
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001597 // Reduce the amount of work we have to do... remove dummy nodes left over by
1598 // merging...
Chris Lattner0b144872004-01-27 22:03:40 +00001599 //removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001600
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001601 TIME_REGION(X, "removeDeadNodes");
1602
Misha Brukman2f2d0652003-09-11 18:14:24 +00001603 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001604
1605 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001606 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001607 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001608
Chris Lattner0b144872004-01-27 22:03:40 +00001609 // Copy and merge all information about globals to the GlobalsGraph if this is
1610 // not a final pass (where unreachable globals are removed).
1611 //
1612 // Strip all alloca bits since the current function is only for the BU pass.
1613 // Strip all incomplete bits since they are short-lived properties and they
1614 // will be correctly computed when rematerializing nodes into the functions.
1615 //
1616 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1617 DSGraph::StripIncompleteBit);
1618
Chris Lattneraa8146f2002-11-10 06:59:55 +00001619 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner0b144872004-01-27 22:03:40 +00001620 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001621 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001622 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001623 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001624 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001625
1626 // Make sure that all globals are cloned over as roots.
1627 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1628 GGCloner.getClonedNH(I->second);
1629 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001630 } else {
Chris Lattner0b144872004-01-27 22:03:40 +00001631 // Check to see if this is a worthless node generated for non-pointer
1632 // values, such as integers. Consider an addition of long types: A+B.
1633 // Assuming we can track all uses of the value in this context, and it is
1634 // NOT used as a pointer, we can delete the node. We will be able to
1635 // detect this situation if the node pointed to ONLY has Unknown bit set
1636 // in the node. In this case, the node is not incomplete, does not point
1637 // to any other nodes (no mod/ref bits set), and is therefore
1638 // uninteresting for data structure analysis. If we run across one of
1639 // these, prune the scalar pointing to it.
1640 //
1641 DSNode *N = I->second.getNode();
1642 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1643 ScalarMap.erase(I++);
1644 else {
1645 N->markReachableNodes(Alive);
1646 ++I;
1647 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001648 }
Chris Lattnere2219762002-07-18 18:22:40 +00001649
Chris Lattner0b144872004-01-27 22:03:40 +00001650 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001651 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1652 I != E; ++I)
1653 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001654
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001655 // Mark any nodes reachable by primary calls as alive...
1656 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1657 FunctionCalls[i].markReachableNodes(Alive);
1658
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001659
1660 // Now find globals and aux call nodes that are already live or reach a live
1661 // value (which makes them live in turn), and continue till no more are found.
1662 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001663 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001664 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001665 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1666 do {
1667 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001668 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001669 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001670 // unreachable globals in the list.
1671 //
1672 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001673 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001674 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1675 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1676 Flags & DSGraph::RemoveUnreachableGlobals)) {
1677 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1678 GlobalNodes.pop_back(); // erase efficiently
1679 Iterate = true;
1680 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001681
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001682 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1683 // call nodes that get resolved will be difficult to remove from that graph.
1684 // The final unresolved call nodes must be handled specially at the end of
1685 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001686 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1687 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001688 (AuxFunctionCalls[i].isIndirectCall()
1689 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1690 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001691 AuxFunctionCalls[i].markReachableNodes(Alive);
1692 AuxFCallsAlive[i] = true;
1693 Iterate = true;
1694 }
1695 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001696
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001697 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001698 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001699 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1700 if (AuxFCallsAlive[i])
1701 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001702
1703 // Copy and merge all global nodes and dead aux call nodes into the
1704 // GlobalsGraph, and all nodes reachable from those nodes
1705 //
1706 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001707 // Copy the unreachable call nodes to the globals graph, updating their
1708 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001709 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1710 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001711 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001712 }
1713 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001714 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1715 AuxFunctionCalls.end());
1716
Chris Lattner0b144872004-01-27 22:03:40 +00001717 // We are finally done with the GGCloner so we can clear it and then get rid
1718 // of unused nodes in the GlobalsGraph produced by merging.
1719 if (GGCloner.clonedNode()) {
1720 GGCloner.destroy();
1721 GlobalsGraph->removeTriviallyDeadNodes();
1722 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001723
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001724 // At this point, any nodes which are visited, but not alive, are nodes
1725 // which can be removed. Loop over all nodes, eliminating completely
1726 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001727 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001728 std::vector<DSNode*> DeadNodes;
1729 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001730 for (unsigned i = 0; i != Nodes.size(); ++i)
1731 if (!Alive.count(Nodes[i])) {
1732 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001733 Nodes[i--] = Nodes.back(); // move node to end of vector
1734 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001735 DeadNodes.push_back(N);
1736 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001737 } else {
1738 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001739 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001740
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001741 // Remove all unreachable globals from the ScalarMap.
1742 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1743 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001744 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001745 if (!Alive.count(GlobalNodes[i].second))
1746 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001747 else
1748 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001749
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001750 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001751 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1752 delete DeadNodes[i];
1753
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001754 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001755}
1756
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001757void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001758 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1759 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001760
Chris Lattner8d327672003-06-30 03:36:09 +00001761 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001762 E = ScalarMap.end(); I != E; ++I) {
1763 assert(I->second.getNode() && "Null node in scalarmap!");
1764 AssertNodeInGraph(I->second.getNode());
1765 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001766 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001767 "Global points to node, but node isn't global?");
1768 AssertNodeContainsGlobal(I->second.getNode(), GV);
1769 }
1770 }
1771 AssertCallNodesInGraph();
1772 AssertAuxCallNodesInGraph();
1773}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001774
Chris Lattner400433d2003-11-11 05:08:59 +00001775/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1776/// nodes reachable from the two graphs, computing the mapping of nodes from
1777/// the first to the second graph.
1778///
1779void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001780 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1781 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001782 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1783 if (N1 == 0 || N2 == 0) return;
1784
1785 DSNodeHandle &Entry = NodeMap[N1];
1786 if (Entry.getNode()) {
1787 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001788 assert(!StrictChecking ||
1789 (Entry.getNode() == N2 &&
1790 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001791 "Inconsistent mapping detected!");
1792 return;
1793 }
1794
1795 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001796 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001797
1798 // Loop over all of the fields that N1 and N2 have in common, recursively
1799 // mapping the edges together now.
1800 int N2Idx = NH2.getOffset()-NH1.getOffset();
1801 unsigned N2Size = N2->getSize();
1802 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1803 if (unsigned(N2Idx)+i < N2Size)
1804 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1805}