blob: 03f010a963321c39d9f8c594a99d42b3853df4af [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "llvm/Analysis/DSGraph.h"
15#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000016#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000018#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000019#include "llvm/Assembly/Writer.h"
Chris Lattner0b144872004-01-27 22:03:40 +000020#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000021#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000022#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000024#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000025#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattner08db7192002-11-06 06:20:27 +000028namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000029 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
31 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
32 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattner0b144872004-01-27 22:03:40 +000033
34 cl::opt<bool>
35 EnableDSNodeGlobalRootsHack("enable-dsa-globalrootshack", cl::Hidden,
36 cl::desc("Make DSA less aggressive when cloning graphs"));
Chris Lattner08db7192002-11-06 06:20:27 +000037};
38
Chris Lattnera88a55c2004-01-28 02:41:32 +000039#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000040#define TIME_REGION(VARNAME, DESC) \
41 NamedRegionTimer VARNAME(DESC)
42#else
43#define TIME_REGION(VARNAME, DESC)
44#endif
45
Chris Lattnerb1060432002-11-07 05:20:53 +000046using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000047
Chris Lattner731b2d72003-02-13 19:09:00 +000048DSNode *DSNodeHandle::HandleForwarding() const {
49 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
50
51 // Handle node forwarding here!
52 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
53 Offset += N->ForwardNH.getOffset();
54
55 if (--N->NumReferrers == 0) {
56 // Removing the last referrer to the node, sever the forwarding link
57 N->stopForwarding();
58 }
59
60 N = Next;
61 N->NumReferrers++;
62 if (N->Size <= Offset) {
63 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
64 Offset = 0;
65 }
66 return N;
67}
68
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000069//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000070// DSNode Implementation
71//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000072
Chris Lattnerbd92b732003-06-19 21:15:11 +000073DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000074 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000075 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000076 if (T) mergeTypeInfo(T, 0);
Chris Lattnere92e7642004-02-07 23:58:05 +000077 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000078 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000079}
80
Chris Lattner0d9bab82002-07-18 00:12:30 +000081// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000082DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000083 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner0b144872004-01-27 22:03:40 +000084 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
85 if (!NullLinks)
86 Links = N.Links;
87 else
88 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000089 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000090 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000091}
92
Chris Lattner15869aa2003-11-02 22:27:28 +000093/// getTargetData - Get the target data object used to construct this node.
94///
95const TargetData &DSNode::getTargetData() const {
96 return ParentGraph->getTargetData();
97}
98
Chris Lattner72d29a42003-02-11 23:11:51 +000099void DSNode::assertOK() const {
100 assert((Ty != Type::VoidTy ||
101 Ty == Type::VoidTy && (Size == 0 ||
102 (NodeType & DSNode::Array))) &&
103 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000104
105 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000106 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000107 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000108 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000109 assert(SM.find(Globals[i])->second.getNode() == this);
110 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000111}
112
113/// forwardNode - Mark this node as being obsolete, and all references to it
114/// should be forwarded to the specified node and offset.
115///
116void DSNode::forwardNode(DSNode *To, unsigned Offset) {
117 assert(this != To && "Cannot forward a node to itself!");
118 assert(ForwardNH.isNull() && "Already forwarding from this node!");
119 if (To->Size <= 1) Offset = 0;
120 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
121 "Forwarded offset is wrong!");
122 ForwardNH.setNode(To);
123 ForwardNH.setOffset(Offset);
124 NodeType = DEAD;
125 Size = 0;
126 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000127}
128
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000129// addGlobal - Add an entry for a global value to the Globals list. This also
130// marks the node with the 'G' flag if it does not already have it.
131//
132void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000133 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000134 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000135 std::lower_bound(Globals.begin(), Globals.end(), GV);
136
137 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000138 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000139 Globals.insert(I, GV);
140 NodeType |= GlobalNode;
141 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000142}
143
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000144/// foldNodeCompletely - If we determine that this node has some funny
145/// behavior happening to it that we cannot represent, we fold it down to a
146/// single, completely pessimistic, node. This node is represented as a
147/// single byte with a single TypeEntry of "void".
148///
149void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000150 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000151
Chris Lattner08db7192002-11-06 06:20:27 +0000152 ++NumFolds;
153
Chris Lattner0b144872004-01-27 22:03:40 +0000154 // If this node has a size that is <= 1, we don't need to create a forwarding
155 // node.
156 if (getSize() <= 1) {
157 NodeType |= DSNode::Array;
158 Ty = Type::VoidTy;
159 Size = 1;
160 assert(Links.size() <= 1 && "Size is 1, but has more links?");
161 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000162 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000163 // Create the node we are going to forward to. This is required because
164 // some referrers may have an offset that is > 0. By forcing them to
165 // forward, the forwarder has the opportunity to correct the offset.
166 DSNode *DestNode = new DSNode(0, ParentGraph);
167 DestNode->NodeType = NodeType|DSNode::Array;
168 DestNode->Ty = Type::VoidTy;
169 DestNode->Size = 1;
170 DestNode->Globals.swap(Globals);
171
172 // Start forwarding to the destination node...
173 forwardNode(DestNode, 0);
174
175 if (!Links.empty()) {
176 DestNode->Links.reserve(1);
177
178 DSNodeHandle NH(DestNode);
179 DestNode->Links.push_back(Links[0]);
180
181 // If we have links, merge all of our outgoing links together...
182 for (unsigned i = Links.size()-1; i != 0; --i)
183 NH.getNode()->Links[0].mergeWith(Links[i]);
184 Links.clear();
185 } else {
186 DestNode->Links.resize(1);
187 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000188 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000189}
Chris Lattner076c1f92002-11-07 06:31:54 +0000190
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000191/// isNodeCompletelyFolded - Return true if this node has been completely
192/// folded down to something that can never be expanded, effectively losing
193/// all of the field sensitivity that may be present in the node.
194///
195bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000196 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000197}
198
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000199namespace {
200 /// TypeElementWalker Class - Used for implementation of physical subtyping...
201 ///
202 class TypeElementWalker {
203 struct StackState {
204 const Type *Ty;
205 unsigned Offset;
206 unsigned Idx;
207 StackState(const Type *T, unsigned Off = 0)
208 : Ty(T), Offset(Off), Idx(0) {}
209 };
210
211 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000212 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000213 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000214 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000215 Stack.push_back(T);
216 StepToLeaf();
217 }
218
219 bool isDone() const { return Stack.empty(); }
220 const Type *getCurrentType() const { return Stack.back().Ty; }
221 unsigned getCurrentOffset() const { return Stack.back().Offset; }
222
223 void StepToNextType() {
224 PopStackAndAdvance();
225 StepToLeaf();
226 }
227
228 private:
229 /// PopStackAndAdvance - Pop the current element off of the stack and
230 /// advance the underlying element to the next contained member.
231 void PopStackAndAdvance() {
232 assert(!Stack.empty() && "Cannot pop an empty stack!");
233 Stack.pop_back();
234 while (!Stack.empty()) {
235 StackState &SS = Stack.back();
236 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
237 ++SS.Idx;
238 if (SS.Idx != ST->getElementTypes().size()) {
239 const StructLayout *SL = TD.getStructLayout(ST);
240 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
241 return;
242 }
243 Stack.pop_back(); // At the end of the structure
244 } else {
245 const ArrayType *AT = cast<ArrayType>(SS.Ty);
246 ++SS.Idx;
247 if (SS.Idx != AT->getNumElements()) {
248 SS.Offset += TD.getTypeSize(AT->getElementType());
249 return;
250 }
251 Stack.pop_back(); // At the end of the array
252 }
253 }
254 }
255
256 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
257 /// on the type stack.
258 void StepToLeaf() {
259 if (Stack.empty()) return;
260 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
261 StackState &SS = Stack.back();
262 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
263 if (ST->getElementTypes().empty()) {
264 assert(SS.Idx == 0);
265 PopStackAndAdvance();
266 } else {
267 // Step into the structure...
268 assert(SS.Idx < ST->getElementTypes().size());
269 const StructLayout *SL = TD.getStructLayout(ST);
270 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
271 SS.Offset+SL->MemberOffsets[SS.Idx]));
272 }
273 } else {
274 const ArrayType *AT = cast<ArrayType>(SS.Ty);
275 if (AT->getNumElements() == 0) {
276 assert(SS.Idx == 0);
277 PopStackAndAdvance();
278 } else {
279 // Step into the array...
280 assert(SS.Idx < AT->getNumElements());
281 Stack.push_back(StackState(AT->getElementType(),
282 SS.Offset+SS.Idx*
283 TD.getTypeSize(AT->getElementType())));
284 }
285 }
286 }
287 }
288 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000289} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000290
291/// ElementTypesAreCompatible - Check to see if the specified types are
292/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000293/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
294/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000295///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000296static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000297 bool AllowLargerT1, const TargetData &TD){
298 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000299
300 while (!T1W.isDone() && !T2W.isDone()) {
301 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
302 return false;
303
304 const Type *T1 = T1W.getCurrentType();
305 const Type *T2 = T2W.getCurrentType();
306 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
307 return false;
308
309 T1W.StepToNextType();
310 T2W.StepToNextType();
311 }
312
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000313 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000314}
315
316
Chris Lattner08db7192002-11-06 06:20:27 +0000317/// mergeTypeInfo - This method merges the specified type into the current node
318/// at the specified offset. This may update the current node's type record if
319/// this gives more information to the node, it may do nothing to the node if
320/// this information is already known, or it may merge the node completely (and
321/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000322///
Chris Lattner08db7192002-11-06 06:20:27 +0000323/// This method returns true if the node is completely folded, otherwise false.
324///
Chris Lattner088b6392003-03-03 17:13:31 +0000325bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
326 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000327 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000328 // Check to make sure the Size member is up-to-date. Size can be one of the
329 // following:
330 // Size = 0, Ty = Void: Nothing is known about this node.
331 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
332 // Size = 1, Ty = Void, Array = 1: The node is collapsed
333 // Otherwise, sizeof(Ty) = Size
334 //
Chris Lattner18552922002-11-18 21:44:46 +0000335 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
336 (Size == 0 && !Ty->isSized() && !isArray()) ||
337 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
338 (Size == 0 && !Ty->isSized() && !isArray()) ||
339 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000340 "Size member of DSNode doesn't match the type structure!");
341 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000342
Chris Lattner18552922002-11-18 21:44:46 +0000343 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000344 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000345
Chris Lattner08db7192002-11-06 06:20:27 +0000346 // Return true immediately if the node is completely folded.
347 if (isNodeCompletelyFolded()) return true;
348
Chris Lattner23f83dc2002-11-08 22:49:57 +0000349 // If this is an array type, eliminate the outside arrays because they won't
350 // be used anyway. This greatly reduces the size of large static arrays used
351 // as global variables, for example.
352 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000353 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000354 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
355 // FIXME: we might want to keep small arrays, but must be careful about
356 // things like: [2 x [10000 x int*]]
357 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000358 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000359 }
360
Chris Lattner08db7192002-11-06 06:20:27 +0000361 // Figure out how big the new type we're merging in is...
362 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
363
364 // Otherwise check to see if we can fold this type into the current node. If
365 // we can't, we fold the node completely, if we can, we potentially update our
366 // internal state.
367 //
Chris Lattner18552922002-11-18 21:44:46 +0000368 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000369 // If this is the first type that this node has seen, just accept it without
370 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000371 assert(Offset == 0 && !isArray() &&
372 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000373 Ty = NewTy;
374 NodeType &= ~Array;
375 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000376 Size = NewTySize;
377
378 // Calculate the number of outgoing links from this node.
379 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
380 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000381 }
Chris Lattner08db7192002-11-06 06:20:27 +0000382
383 // Handle node expansion case here...
384 if (Offset+NewTySize > Size) {
385 // It is illegal to grow this node if we have treated it as an array of
386 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000387 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000388 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000389 return true;
390 }
391
392 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000393 std::cerr << "UNIMP: Trying to merge a growth type into "
394 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000395 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000396 return true;
397 }
398
399 // Okay, the situation is nice and simple, we are trying to merge a type in
400 // at offset 0 that is bigger than our current type. Implement this by
401 // switching to the new type and then merge in the smaller one, which should
402 // hit the other code path here. If the other code path decides it's not
403 // ok, it will collapse the node as appropriate.
404 //
Chris Lattner18552922002-11-18 21:44:46 +0000405 const Type *OldTy = Ty;
406 Ty = NewTy;
407 NodeType &= ~Array;
408 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000409 Size = NewTySize;
410
411 // Must grow links to be the appropriate size...
412 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
413
414 // Merge in the old type now... which is guaranteed to be smaller than the
415 // "current" type.
416 return mergeTypeInfo(OldTy, 0);
417 }
418
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000419 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000420 "Cannot merge something into a part of our type that doesn't exist!");
421
Chris Lattner18552922002-11-18 21:44:46 +0000422 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000423 // type that starts at offset Offset.
424 //
425 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000426 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000427 while (O < Offset) {
428 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
429
430 switch (SubType->getPrimitiveID()) {
431 case Type::StructTyID: {
432 const StructType *STy = cast<StructType>(SubType);
433 const StructLayout &SL = *TD.getStructLayout(STy);
434
435 unsigned i = 0, e = SL.MemberOffsets.size();
436 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
437 /* empty */;
438
439 // The offset we are looking for must be in the i'th element...
440 SubType = STy->getElementTypes()[i];
441 O += SL.MemberOffsets[i];
442 break;
443 }
444 case Type::ArrayTyID: {
445 SubType = cast<ArrayType>(SubType)->getElementType();
446 unsigned ElSize = TD.getTypeSize(SubType);
447 unsigned Remainder = (Offset-O) % ElSize;
448 O = Offset-Remainder;
449 break;
450 }
451 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000452 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000453 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000454 }
455 }
456
457 assert(O == Offset && "Could not achieve the correct offset!");
458
459 // If we found our type exactly, early exit
460 if (SubType == NewTy) return false;
461
Chris Lattner0b144872004-01-27 22:03:40 +0000462 // Differing function types don't require us to merge. They are not values anyway.
463 if (isa<FunctionType>(SubType) &&
464 isa<FunctionType>(NewTy)) return false;
465
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000466 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
467
468 // Ok, we are getting desperate now. Check for physical subtyping, where we
469 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000470 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000471 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000472 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000473 return false;
474
Chris Lattner08db7192002-11-06 06:20:27 +0000475 // Okay, so we found the leader type at the offset requested. Search the list
476 // of types that starts at this offset. If SubType is currently an array or
477 // structure, the type desired may actually be the first element of the
478 // composite type...
479 //
Chris Lattner18552922002-11-18 21:44:46 +0000480 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000481 while (SubType != NewTy) {
482 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000483 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000484 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000485 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000486 case Type::StructTyID: {
487 const StructType *STy = cast<StructType>(SubType);
488 const StructLayout &SL = *TD.getStructLayout(STy);
489 if (SL.MemberOffsets.size() > 1)
490 NextPadSize = SL.MemberOffsets[1];
491 else
492 NextPadSize = SubTypeSize;
493 NextSubType = STy->getElementTypes()[0];
494 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000495 break;
Chris Lattner18552922002-11-18 21:44:46 +0000496 }
Chris Lattner08db7192002-11-06 06:20:27 +0000497 case Type::ArrayTyID:
498 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000499 NextSubTypeSize = TD.getTypeSize(NextSubType);
500 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000501 break;
502 default: ;
503 // fall out
504 }
505
506 if (NextSubType == 0)
507 break; // In the default case, break out of the loop
508
Chris Lattner18552922002-11-18 21:44:46 +0000509 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000510 break; // Don't allow shrinking to a smaller type than NewTySize
511 SubType = NextSubType;
512 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000513 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000514 }
515
516 // If we found the type exactly, return it...
517 if (SubType == NewTy)
518 return false;
519
520 // Check to see if we have a compatible, but different type...
521 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000522 // Check to see if this type is obviously convertible... int -> uint f.e.
523 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000524 return false;
525
526 // Check to see if we have a pointer & integer mismatch going on here,
527 // loading a pointer as a long, for example.
528 //
529 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
530 NewTy->isInteger() && isa<PointerType>(SubType))
531 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000532 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
533 // We are accessing the field, plus some structure padding. Ignore the
534 // structure padding.
535 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000536 }
537
Chris Lattner58f98d02003-07-02 04:38:49 +0000538 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000539 if (getParentGraph()->getReturnNodes().size())
540 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000541 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
542 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
543 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
544 << "SubType: ";
545 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000546
Chris Lattner088b6392003-03-03 17:13:31 +0000547 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000548 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000549}
550
Chris Lattner08db7192002-11-06 06:20:27 +0000551
552
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000553// addEdgeTo - Add an edge from the current node to the specified node. This
554// can cause merging of nodes in the graph.
555//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000556void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000557 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000558
Chris Lattner08db7192002-11-06 06:20:27 +0000559 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000560 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000561 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000562 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000563 } else { // No merging to perform...
564 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000565 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000566}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000567
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000568
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000569// MergeSortedVectors - Efficiently merge a vector into another vector where
570// duplicates are not allowed and both are sorted. This assumes that 'T's are
571// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000572//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000573static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
574 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000575 // By far, the most common cases will be the simple ones. In these cases,
576 // avoid having to allocate a temporary vector...
577 //
578 if (Src.empty()) { // Nothing to merge in...
579 return;
580 } else if (Dest.empty()) { // Just copy the result in...
581 Dest = Src;
582 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000583 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000584 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000585 std::lower_bound(Dest.begin(), Dest.end(), V);
586 if (I == Dest.end() || *I != Src[0]) // If not already contained...
587 Dest.insert(I, Src[0]);
588 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000589 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000590 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000591 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000592 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
593 if (I == Dest.end() || *I != Tmp) // If not already contained...
594 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000595
596 } else {
597 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000598 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000599
600 // Make space for all of the type entries now...
601 Dest.resize(Dest.size()+Src.size());
602
603 // Merge the two sorted ranges together... into Dest.
604 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
605
606 // Now erase any duplicate entries that may have accumulated into the
607 // vectors (because they were in both of the input sets)
608 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
609 }
610}
611
Chris Lattner0b144872004-01-27 22:03:40 +0000612void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
613 MergeSortedVectors(Globals, RHS);
614}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000615
Chris Lattner0b144872004-01-27 22:03:40 +0000616// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000617// This function does the hard work of merging two nodes, CurNodeH
618// and NH after filtering out trivial cases and making sure that
619// CurNodeH.offset >= NH.offset.
620//
621// ***WARNING***
622// Since merging may cause either node to go away, we must always
623// use the node-handles to refer to the nodes. These node handles are
624// automatically updated during merging, so will always provide access
625// to the correct node after a merge.
626//
627void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
628 assert(CurNodeH.getOffset() >= NH.getOffset() &&
629 "This should have been enforced in the caller.");
630
631 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
632 // respect to NH.Offset) is now zero. NOffset is the distance from the base
633 // of our object that N starts from.
634 //
635 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
636 unsigned NSize = NH.getNode()->getSize();
637
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000638 // If the two nodes are of different size, and the smaller node has the array
639 // bit set, collapse!
640 if (NSize != CurNodeH.getNode()->getSize()) {
641 if (NSize < CurNodeH.getNode()->getSize()) {
642 if (NH.getNode()->isArray())
643 NH.getNode()->foldNodeCompletely();
644 } else if (CurNodeH.getNode()->isArray()) {
645 NH.getNode()->foldNodeCompletely();
646 }
647 }
648
649 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000650 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000651 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000652 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000653
654 // If we are merging a node with a completely folded node, then both nodes are
655 // now completely folded.
656 //
657 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
658 if (!NH.getNode()->isNodeCompletelyFolded()) {
659 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000660 assert(NH.getNode() && NH.getOffset() == 0 &&
661 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000662 NOffset = NH.getOffset();
663 NSize = NH.getNode()->getSize();
664 assert(NOffset == 0 && NSize == 1);
665 }
666 } else if (NH.getNode()->isNodeCompletelyFolded()) {
667 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000668 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
669 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000670 NOffset = NH.getOffset();
671 NSize = NH.getNode()->getSize();
672 assert(NOffset == 0 && NSize == 1);
673 }
674
Chris Lattner72d29a42003-02-11 23:11:51 +0000675 DSNode *N = NH.getNode();
676 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000677 assert(!CurNodeH.getNode()->isDeadNode());
678
Chris Lattner0b144872004-01-27 22:03:40 +0000679 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000680 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000681
Chris Lattner72d29a42003-02-11 23:11:51 +0000682 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000683 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000684 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000685
Chris Lattner72d29a42003-02-11 23:11:51 +0000686 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
687 //
688 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
689 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000690 if (Link.getNode()) {
691 // Compute the offset into the current node at which to
692 // merge this link. In the common case, this is a linear
693 // relation to the offset in the original node (with
694 // wrapping), but if the current node gets collapsed due to
695 // recursive merging, we must make sure to merge in all remaining
696 // links at offset zero.
697 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000698 DSNode *CN = CurNodeH.getNode();
699 if (CN->Size != 1)
700 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
701 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000702 }
703 }
704
705 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000706 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000707
708 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000709 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000710 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000711
712 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000713 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000714 }
715}
716
717
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000718// mergeWith - Merge this node and the specified node, moving all links to and
719// from the argument node into the current node, deleting the node argument.
720// Offset indicates what offset the specified node is to be merged into the
721// current node.
722//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000723// The specified node may be a null pointer (in which case, we update it to
724// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000725//
726void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
727 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000728 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000729 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000730
Chris Lattner5254a8d2004-01-22 16:31:08 +0000731 // If the RHS is a null node, make it point to this node!
732 if (N == 0) {
733 NH.mergeWith(DSNodeHandle(this, Offset));
734 return;
735 }
736
Chris Lattnerbd92b732003-06-19 21:15:11 +0000737 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000738 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
739
Chris Lattner02606632002-11-04 06:48:26 +0000740 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000741 // We cannot merge two pieces of the same node together, collapse the node
742 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000743 DEBUG(std::cerr << "Attempting to merge two chunks of"
744 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000745 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000746 return;
747 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000748
Chris Lattner5190ce82002-11-12 07:20:45 +0000749 // If both nodes are not at offset 0, make sure that we are merging the node
750 // at an later offset into the node with the zero offset.
751 //
752 if (Offset < NH.getOffset()) {
753 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
754 return;
755 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
756 // If the offsets are the same, merge the smaller node into the bigger node
757 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
758 return;
759 }
760
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000761 // Ok, now we can merge the two nodes. Use a static helper that works with
762 // two node handles, since "this" may get merged away at intermediate steps.
763 DSNodeHandle CurNodeH(this, Offset);
764 DSNodeHandle NHCopy(NH);
765 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000766}
767
Chris Lattner0b144872004-01-27 22:03:40 +0000768
769//===----------------------------------------------------------------------===//
770// ReachabilityCloner Implementation
771//===----------------------------------------------------------------------===//
772
773DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
774 if (SrcNH.isNull()) return DSNodeHandle();
775 const DSNode *SN = SrcNH.getNode();
776
777 DSNodeHandle &NH = NodeMap[SN];
778 if (!NH.isNull()) // Node already mapped?
779 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
780
781 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
782 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000783 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000784
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(),
Chris Lattner00948c02004-01-28 02:05:05 +0000818 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000819
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()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000857 if (!DN->isNodeCompletelyFolded()) {
858 // Make sure the destination node is folded if the source node is folded.
859 if (SN->isNodeCompletelyFolded()) {
860 DN->foldNodeCompletely();
861 DN = NH.getNode();
862 } else if (SN->getSize() != DN->getSize()) {
863 // If the two nodes are of different size, and the smaller node has the
864 // array bit set, collapse!
865 if (SN->getSize() < DN->getSize()) {
866 if (SN->isArray()) {
867 DN->foldNodeCompletely();
868 DN = NH.getNode();
869 }
870 } else if (DN->isArray()) {
871 DN->foldNodeCompletely();
872 DN = NH.getNode();
873 }
874 }
875
876 // Merge the type entries of the two nodes together...
877 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
878 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
879 DN = NH.getNode();
880 }
881 }
882
883 assert(!DN->isDeadNode());
884
885 // Merge the NodeType information.
886 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
887
888 // Before we start merging outgoing links and updating the scalar map, make
889 // sure it is known that this is the representative node for the src node.
890 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
891
892 // If the source node contains any globals, make sure they end up in the
893 // scalar map with the correct offset.
894 if (SN->global_begin() != SN->global_end()) {
895 // Update the globals in the destination node itself.
896 DN->mergeGlobals(SN->getGlobals());
897
898 // Update the scalar map for the graph we are merging the source node
899 // into.
900 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
901 I != E; ++I) {
902 GlobalValue *GV = *I;
903 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
904 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
905 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
906 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000907 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000908
909 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
910 Dest.getInlinedGlobals().insert(GV);
911 }
912 }
913 } else {
914 // We cannot handle this case without allocating a temporary node. Fall
915 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000916 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
917 NewDN->maskNodeTypes(BitsToKeep);
918
919 unsigned NHOffset = NH.getOffset();
920 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000921
Chris Lattner0b144872004-01-27 22:03:40 +0000922 assert(NH.getNode() &&
923 (NH.getOffset() > NHOffset ||
924 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
925 "Merging did not adjust the offset!");
926
927 // Before we start merging outgoing links and updating the scalar map, make
928 // sure it is known that this is the representative node for the src node.
929 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000930
931 // If the source node contained any globals, make sure to create entries
932 // in the scalar map for them!
933 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
934 I != E; ++I) {
935 GlobalValue *GV = *I;
936 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
937 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
938 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
939 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
940 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
941 DestGNH.getOffset()+SrcGNH.getOffset()));
942
943 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
944 Dest.getInlinedGlobals().insert(GV);
945 }
Chris Lattner0b144872004-01-27 22:03:40 +0000946 }
947
948
949 // Next, recursively merge all outgoing links as necessary. Note that
950 // adding these links can cause the destination node to collapse itself at
951 // any time, and the current node may be merged with arbitrary other nodes.
952 // For this reason, we must always go through NH.
953 DN = 0;
954 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
955 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
956 if (!SrcEdge.isNull()) {
957 // Compute the offset into the current node at which to
958 // merge this link. In the common case, this is a linear
959 // relation to the offset in the original node (with
960 // wrapping), but if the current node gets collapsed due to
961 // recursive merging, we must make sure to merge in all remaining
962 // links at offset zero.
963 unsigned MergeOffset = 0;
964 DSNode *CN = SCNH.getNode();
965 if (CN->getSize() != 1)
966 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
967
968 // Perform the recursive merging. Make sure to create a temporary NH,
969 // because the Link can disappear in the process of recursive merging.
970 DSNodeHandle Tmp = CN->getLink(MergeOffset);
971 merge(Tmp, SrcEdge);
972 }
973 }
974}
975
976/// mergeCallSite - Merge the nodes reachable from the specified src call
977/// site into the nodes reachable from DestCS.
978void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
979 const DSCallSite &SrcCS) {
980 merge(DestCS.getRetVal(), SrcCS.getRetVal());
981 unsigned MinArgs = DestCS.getNumPtrArgs();
982 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
983
984 for (unsigned a = 0; a != MinArgs; ++a)
985 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
986}
987
988
Chris Lattner9de906c2002-10-20 22:11:44 +0000989//===----------------------------------------------------------------------===//
990// DSCallSite Implementation
991//===----------------------------------------------------------------------===//
992
Vikram S. Adve26b98262002-10-20 21:41:02 +0000993// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000994Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000995 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000996}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000997
Chris Lattner0b144872004-01-27 22:03:40 +0000998void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
999 ReachabilityCloner &RC) {
1000 NH = RC.getClonedNH(Src);
1001}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001002
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001003//===----------------------------------------------------------------------===//
1004// DSGraph Implementation
1005//===----------------------------------------------------------------------===//
1006
Chris Lattnera9d65662003-06-30 05:57:30 +00001007/// getFunctionNames - Return a space separated list of the name of the
1008/// functions in this graph (if any)
1009std::string DSGraph::getFunctionNames() const {
1010 switch (getReturnNodes().size()) {
1011 case 0: return "Globals graph";
1012 case 1: return getReturnNodes().begin()->first->getName();
1013 default:
1014 std::string Return;
1015 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1016 I != getReturnNodes().end(); ++I)
1017 Return += I->first->getName() + " ";
1018 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1019 return Return;
1020 }
1021}
1022
1023
Chris Lattner15869aa2003-11-02 22:27:28 +00001024DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001025 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001026 NodeMapTy NodeMap;
1027 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001028}
1029
Chris Lattner5a540632003-06-30 03:15:25 +00001030DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001031 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001032 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001033 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001034}
1035
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001036DSGraph::~DSGraph() {
1037 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001038 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001039 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001040 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001041 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001042
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001043 // Drop all intra-node references, so that assertions don't fail...
1044 std::for_each(Nodes.begin(), Nodes.end(),
1045 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001046
1047 // Delete all of the nodes themselves...
1048 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
1049}
1050
Chris Lattner0d9bab82002-07-18 00:12:30 +00001051// dump - Allow inspection of graph in a debugger.
1052void DSGraph::dump() const { print(std::cerr); }
1053
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001054
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001055/// remapLinks - Change all of the Links in the current node according to the
1056/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001057///
Chris Lattner8d327672003-06-30 03:36:09 +00001058void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001059 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1060 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001061 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1062 if (ONMI != OldNodeMap.end()) {
1063 Links[i].setNode(ONMI->second.getNode());
1064 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1065 }
Chris Lattner2f561382004-01-22 16:56:13 +00001066 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001067}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001068
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001069/// updateFromGlobalGraph - This function rematerializes global nodes and
1070/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001071/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1072/// are already up-to-date in the current graph. In practice, in the TD pass,
1073/// this is likely to be a large fraction of the live global nodes in each
1074/// function (since most live nodes are likely to have been brought up-to-date
1075/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001076///
1077void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001078 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001079 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1080
1081 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001082 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1083 E = getScalarMap().global_end(); I != E; ++I)
1084 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001085 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001086 if (It != GlobalsGraph->ScalarMap.end())
1087 RC.merge(getNodeForValue(*I), It->second);
1088 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001089}
1090
Chris Lattner5a540632003-06-30 03:15:25 +00001091/// cloneInto - Clone the specified DSGraph into the current graph. The
1092/// translated ScalarMap for the old function is filled into the OldValMap
1093/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1094///
1095/// The CloneFlags member controls various aspects of the cloning process.
1096///
Chris Lattner62482e52004-01-28 09:15:42 +00001097void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001098 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1099 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001100 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001101 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001102 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001103
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001104 // Remember the last node that existed before, or node_end() if there are no
1105 // nodes.
1106 node_iterator FN = node_end();
1107 if (FN != node_begin()) --FN;
Chris Lattner1e883692003-02-03 20:08:51 +00001108
1109 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001110 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1111 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1112 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001113 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001114 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I)
1115 if (!(*I)->isForwarding()) {
1116 DSNode *New = new DSNode(**I, this);
Chris Lattnera5ca28c2004-02-07 22:00:03 +00001117 New->maskNodeTypes(~BitsToClear);
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001118 OldNodeMap[*I] = New;
Chris Lattnera5ca28c2004-02-07 22:00:03 +00001119 }
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001120
Chris Lattner18552922002-11-18 21:44:46 +00001121#ifndef NDEBUG
1122 Timer::addPeakMemoryMeasurement();
1123#endif
1124
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001125 // Move FN to the first newly added node.
1126 if (FN != node_end())
1127 ++FN;
1128 else
1129 FN = node_begin();
1130
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001131 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001132 for (; FN != node_end(); ++FN)
1133 (*FN)->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001134
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001135 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001136 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001137 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001138 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001139 DSNodeHandle &H = OldValMap[I->first];
1140 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1141 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001142
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001143 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001144 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1145 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001146 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1147 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001148 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001149 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001150
Chris Lattner679e8e12002-11-08 21:27:12 +00001151 if (!(CloneFlags & DontCloneCallNodes)) {
1152 // Copy the function calls list...
1153 unsigned FC = FunctionCalls.size(); // FirstCall
1154 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1155 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1156 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001157 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001158
Chris Lattneracf491f2002-11-08 22:27:09 +00001159 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001160 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001161 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001162 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1163 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1164 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1165 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001166
Chris Lattner5a540632003-06-30 03:15:25 +00001167 // Map the return node pointers over...
1168 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1169 E = G.getReturnNodes().end(); I != E; ++I) {
1170 const DSNodeHandle &Ret = I->second;
1171 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1172 OldReturnNodes.insert(std::make_pair(I->first,
1173 DSNodeHandle(MappedRet.getNode(),
1174 MappedRet.getOffset()+Ret.getOffset())));
1175 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001176}
1177
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001178
Chris Lattner076c1f92002-11-07 06:31:54 +00001179/// mergeInGraph - The method is used for merging graphs together. If the
1180/// argument graph is not *this, it makes a clone of the specified graph, then
1181/// merges the nodes specified in the call site with the formal arguments in the
1182/// graph.
1183///
Chris Lattner9f930552003-06-30 05:27:18 +00001184void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1185 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001186 TIME_REGION(X, "mergeInGraph");
1187
Chris Lattner076c1f92002-11-07 06:31:54 +00001188 // If this is not a recursive call, clone the graph into this graph...
1189 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001190 // Clone the callee's graph into the current graph, keeping track of where
1191 // scalars in the old graph _used_ to point, and of the new nodes matching
1192 // nodes of the old graph.
1193 ReachabilityCloner RC(*this, Graph, CloneFlags);
1194
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001195 // Set up argument bindings
1196 Function::aiterator AI = F.abegin();
1197 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1198 // Advance the argument iterator to the first pointer argument...
1199 while (AI != F.aend() && !isPointerType(AI->getType())) {
1200 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001201#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1202 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001203 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001204#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001205 }
1206 if (AI == F.aend()) break;
1207
1208 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001209 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001210 }
1211
Chris Lattner0b144872004-01-27 22:03:40 +00001212 // Map the return node pointer over.
1213 if (CS.getRetVal().getNode())
1214 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
1215
1216 // If requested, copy the calls or aux-calls lists.
1217 if (!(CloneFlags & DontCloneCallNodes)) {
1218 // Copy the function calls list...
1219 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1220 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1221 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1222 }
1223
1224 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1225 // Copy the auxiliary function calls list...
1226 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1227 Graph.AuxFunctionCalls.size());
1228 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1229 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i], RC));
1230 }
1231
1232 // If the user requested it, add the nodes that we need to clone to the
1233 // RootNodes set.
1234 if (!EnableDSNodeGlobalRootsHack)
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001235 for (node_iterator NI = Graph.node_begin(), E = Graph.node_end();
1236 NI != E; ++NI)
1237 if (!(*NI)->getGlobals().empty())
1238 RC.getClonedNH(*NI);
Chris Lattner0b144872004-01-27 22:03:40 +00001239
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001240 } else {
1241 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001242
1243 // Merge the return value with the return value of the context...
1244 RetVal.mergeWith(CS.getRetVal());
1245
1246 // Resolve all of the function arguments...
1247 Function::aiterator AI = F.abegin();
1248
1249 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1250 // Advance the argument iterator to the first pointer argument...
1251 while (AI != F.aend() && !isPointerType(AI->getType())) {
1252 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001253#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1254 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001255 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1256#endif
1257 }
1258 if (AI == F.aend()) break;
1259
1260 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001261 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001262 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1263 NH.mergeWith(CS.getPtrArg(i));
1264 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001265 }
1266}
1267
Chris Lattner58f98d02003-07-02 04:38:49 +00001268/// getCallSiteForArguments - Get the arguments and return value bindings for
1269/// the specified function in the current graph.
1270///
1271DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1272 std::vector<DSNodeHandle> Args;
1273
1274 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1275 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001276 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001277
Chris Lattner808a7ae2003-09-20 16:34:13 +00001278 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001279}
1280
1281
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001282
Chris Lattner0d9bab82002-07-18 00:12:30 +00001283// markIncompleteNodes - Mark the specified node as having contents that are not
1284// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001285// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001286// must recursively traverse the data structure graph, marking all reachable
1287// nodes as incomplete.
1288//
1289static void markIncompleteNode(DSNode *N) {
1290 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001291 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001292
1293 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001294 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001295
Misha Brukman2f2d0652003-09-11 18:14:24 +00001296 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001297 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1298 if (DSNode *DSN = N->getLink(i).getNode())
1299 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001300}
1301
Chris Lattnere71ffc22002-11-11 03:36:55 +00001302static void markIncomplete(DSCallSite &Call) {
1303 // Then the return value is certainly incomplete!
1304 markIncompleteNode(Call.getRetVal().getNode());
1305
1306 // All objects pointed to by function arguments are incomplete!
1307 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1308 markIncompleteNode(Call.getPtrArg(i).getNode());
1309}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001310
1311// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1312// modified by other functions that have not been resolved yet. This marks
1313// nodes that are reachable through three sources of "unknownness":
1314//
1315// Global Variables, Function Calls, and Incoming Arguments
1316//
1317// For any node that may have unknown components (because something outside the
1318// scope of current analysis may have modified it), the 'Incomplete' flag is
1319// added to the NodeType.
1320//
Chris Lattner394471f2003-01-23 22:05:33 +00001321void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001322 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001323 if (Flags & DSGraph::MarkFormalArgs)
1324 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1325 FI != E; ++FI) {
1326 Function &F = *FI->first;
1327 if (F.getName() != "main")
1328 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001329 if (isPointerType(I->getType()))
1330 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001331 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001332
1333 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001334 if (!shouldPrintAuxCalls())
1335 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1336 markIncomplete(FunctionCalls[i]);
1337 else
1338 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1339 markIncomplete(AuxFunctionCalls[i]);
1340
Chris Lattner0d9bab82002-07-18 00:12:30 +00001341
Chris Lattner93d7a212003-02-09 18:41:49 +00001342 // Mark all global nodes as incomplete...
1343 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001344 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1345 if ((*NI)->isGlobalNode() && (*NI)->getNumLinks())
1346 markIncompleteNode(*NI);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001347}
1348
Chris Lattneraa8146f2002-11-10 06:59:55 +00001349static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1350 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001351 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001352 // No interesting info?
1353 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001354 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001355 Edge.setNode(0); // Kill the edge!
1356}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001357
Chris Lattneraa8146f2002-11-10 06:59:55 +00001358static inline bool nodeContainsExternalFunction(const DSNode *N) {
1359 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1360 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1361 if (Globals[i]->isExternal())
1362 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001363 return false;
1364}
1365
Chris Lattner5a540632003-06-30 03:15:25 +00001366static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001367 // Remove trivially identical function calls
1368 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001369 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1370
Chris Lattner0b144872004-01-27 22:03:40 +00001371#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001372 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001373 DSNode *LastCalleeNode = 0;
1374 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001375 unsigned NumDuplicateCalls = 0;
1376 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001377 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001378 DSCallSite &CS = Calls[i];
1379
Chris Lattnere4258442002-11-11 21:35:38 +00001380 // If the Callee is a useless edge, this must be an unreachable call site,
1381 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001382 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001383 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001384#ifndef NDEBUG
Chris Lattner923fc052003-02-05 21:59:58 +00001385 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001386#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001387 CS.swap(Calls.back());
1388 Calls.pop_back();
1389 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001390 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001391 // If the return value or any arguments point to a void node with no
1392 // information at all in it, and the call node is the only node to point
1393 // to it, remove the edge to the node (killing the node).
1394 //
1395 killIfUselessEdge(CS.getRetVal());
1396 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1397 killIfUselessEdge(CS.getPtrArg(a));
1398
1399 // If this call site calls the same function as the last call site, and if
1400 // the function pointer contains an external function, this node will
1401 // never be resolved. Merge the arguments of the call node because no
1402 // information will be lost.
1403 //
Chris Lattner923fc052003-02-05 21:59:58 +00001404 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1405 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001406 ++NumDuplicateCalls;
1407 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001408 if (LastCalleeNode)
1409 LastCalleeContainsExternalFunction =
1410 nodeContainsExternalFunction(LastCalleeNode);
1411 else
1412 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001413 }
Chris Lattner0b144872004-01-27 22:03:40 +00001414
1415 // It is not clear why, but enabling this code makes DSA really
1416 // sensitive to node forwarding. Basically, with this enabled, DSA
1417 // performs different number of inlinings based on which nodes are
1418 // forwarding or not. This is clearly a problem, so this code is
1419 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001420#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001421 if (LastCalleeContainsExternalFunction
1422#if 0
1423 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001424 // This should be more than enough context sensitivity!
1425 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001426 NumDuplicateCalls > 20
1427#endif
1428 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001429 DSCallSite &OCS = Calls[i-1];
1430 OCS.mergeWith(CS);
1431
1432 // The node will now be eliminated as a duplicate!
1433 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1434 CS = OCS;
1435 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1436 OCS = CS;
1437 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001438#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001439 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001440 if (CS.isDirectCall()) {
1441 LastCalleeFunc = CS.getCalleeFunc();
1442 LastCalleeNode = 0;
1443 } else {
1444 LastCalleeNode = CS.getCalleeNode();
1445 LastCalleeFunc = 0;
1446 }
Chris Lattnere4258442002-11-11 21:35:38 +00001447 NumDuplicateCalls = 0;
1448 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001449 }
1450 }
Chris Lattner0b144872004-01-27 22:03:40 +00001451#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001452 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001453
Chris Lattner33312f72002-11-08 01:21:07 +00001454 // Track the number of call nodes merged away...
1455 NumCallNodesMerged += NumFns-Calls.size();
1456
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001457 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001458 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001459}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001460
Chris Lattneraa8146f2002-11-10 06:59:55 +00001461
Chris Lattnere2219762002-07-18 18:22:40 +00001462// removeTriviallyDeadNodes - After the graph has been constructed, this method
1463// removes all unreachable nodes that are created because they got merged with
1464// other nodes in the graph. These nodes will all be trivially unreachable, so
1465// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001466//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001467void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001468 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattner5a540632003-06-30 03:15:25 +00001469 removeIdenticalCalls(FunctionCalls);
1470 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001471
Chris Lattnerbab8c282003-09-20 21:34:07 +00001472 // Loop over all of the nodes in the graph, calling getNode on each field.
1473 // This will cause all nodes to update their forwarding edges, causing
1474 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001475 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1476 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001477 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1478 N->getLink(l*N->getPointerSize()).getNode();
1479 }
1480
Chris Lattner0b144872004-01-27 22:03:40 +00001481 // NOTE: This code is disabled. Though it should, in theory, allow us to
1482 // remove more nodes down below, the scan of the scalar map is incredibly
1483 // expensive for certain programs (with large SCCs). In the future, if we can
1484 // make the scalar map scan more efficient, then we can reenable this.
1485#if 0
1486 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1487
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001488 // Likewise, forward any edges from the scalar nodes. While we are at it,
1489 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001490 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001491 I->second.getNode();
1492 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001493 }
Chris Lattner0b144872004-01-27 22:03:40 +00001494 }
1495#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001496 bool isGlobalsGraph = !GlobalsGraph;
1497
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001498 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
1499 DSNode *Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001500
1501 // Do not remove *any* global nodes in the globals graph.
1502 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001503 if (Node->isGlobalNode() && isGlobalsGraph) {
1504 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001505 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001506 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001507
Chris Lattner72d50a02003-06-28 21:58:28 +00001508 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001509 // This is a useless node if it has no mod/ref info (checked above),
1510 // outgoing edges (which it cannot, as it is not modified in this
1511 // context), and it has no incoming edges. If it is a global node it may
1512 // have all of these properties and still have incoming edges, due to the
1513 // scalar map, so we check those now.
1514 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001515 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001516 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001517
Chris Lattner17a93e22004-01-29 03:32:15 +00001518 // Loop through and make sure all of the globals are referring directly
1519 // to the node...
1520 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1521 DSNode *N = getNodeForValue(Globals[j]).getNode();
1522 assert(N == Node && "ScalarMap doesn't match globals list!");
1523 }
1524
Chris Lattnerbd92b732003-06-19 21:15:11 +00001525 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001526 if (Node->getNumReferrers() == Globals.size()) {
1527 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1528 ScalarMap.erase(Globals[j]);
Chris Lattner17a93e22004-01-29 03:32:15 +00001529 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001530 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001531 }
1532 }
1533
Chris Lattnerbd92b732003-06-19 21:15:11 +00001534 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001535 // This node is dead!
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001536 delete Node; // Free node memory.
1537 NI = Nodes.erase(NI); // Remove from node list.
1538 } else {
1539 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001540 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001541 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001542}
1543
1544
Chris Lattner5c7380e2003-01-29 21:10:20 +00001545/// markReachableNodes - This method recursively traverses the specified
1546/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1547/// to the set, which allows it to only traverse visited nodes once.
1548///
Chris Lattner41c04f72003-02-01 04:52:08 +00001549void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001550 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001551 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001552 if (ReachableNodes.insert(this).second) // Is newly reachable?
1553 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1554 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001555}
1556
Chris Lattner41c04f72003-02-01 04:52:08 +00001557void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001558 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001559 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001560
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001561 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1562 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001563}
1564
Chris Lattnera1220af2003-02-01 06:17:02 +00001565// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1566// looking for a node that is marked alive. If an alive node is found, return
1567// true, otherwise return false. If an alive node is reachable, this node is
1568// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001569//
Chris Lattnera1220af2003-02-01 06:17:02 +00001570static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001571 hash_set<DSNode*> &Visited,
1572 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001573 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001574 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001575
Chris Lattner85cfe012003-07-03 02:03:53 +00001576 // If this is a global node, it will end up in the globals graph anyway, so we
1577 // don't need to worry about it.
1578 if (IgnoreGlobals && N->isGlobalNode()) return false;
1579
Chris Lattneraa8146f2002-11-10 06:59:55 +00001580 // If we know that this node is alive, return so!
1581 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001582
Chris Lattneraa8146f2002-11-10 06:59:55 +00001583 // Otherwise, we don't think the node is alive yet, check for infinite
1584 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001585 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001586 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001587
Chris Lattner08db7192002-11-06 06:20:27 +00001588 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001589 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1590 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001591 N->markReachableNodes(Alive);
1592 return true;
1593 }
1594 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001595}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001596
Chris Lattnera1220af2003-02-01 06:17:02 +00001597// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1598// alive nodes.
1599//
Chris Lattner41c04f72003-02-01 04:52:08 +00001600static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001601 hash_set<DSNode*> &Visited,
1602 bool IgnoreGlobals) {
1603 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1604 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001605 return true;
1606 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001607 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001608 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001609 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001610 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1611 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001612 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001613 return false;
1614}
1615
Chris Lattnere2219762002-07-18 18:22:40 +00001616// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1617// subgraphs that are unreachable. This often occurs because the data
1618// structure doesn't "escape" into it's caller, and thus should be eliminated
1619// from the caller's graph entirely. This is only appropriate to use when
1620// inlining graphs.
1621//
Chris Lattner394471f2003-01-23 22:05:33 +00001622void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001623 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001624
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001625 // Reduce the amount of work we have to do... remove dummy nodes left over by
1626 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001627 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001628
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001629 TIME_REGION(X, "removeDeadNodes");
1630
Misha Brukman2f2d0652003-09-11 18:14:24 +00001631 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001632
1633 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001634 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001635 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001636
Chris Lattner0b144872004-01-27 22:03:40 +00001637 // Copy and merge all information about globals to the GlobalsGraph if this is
1638 // not a final pass (where unreachable globals are removed).
1639 //
1640 // Strip all alloca bits since the current function is only for the BU pass.
1641 // Strip all incomplete bits since they are short-lived properties and they
1642 // will be correctly computed when rematerializing nodes into the functions.
1643 //
1644 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1645 DSGraph::StripIncompleteBit);
1646
Chris Lattneraa8146f2002-11-10 06:59:55 +00001647 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001648 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001649 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001650 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001651 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001652 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001653 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001654
1655 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001656 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1657 DSGraph::ScalarMapTy::iterator SMI =
1658 GlobalsGraph->getScalarMap().find(I->first);
1659 if (SMI != GlobalsGraph->getScalarMap().end())
1660 GGCloner.merge(SMI->second, I->second);
1661 else
1662 GGCloner.getClonedNH(I->second);
1663 }
Chris Lattner0b144872004-01-27 22:03:40 +00001664 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001665 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001666 DSNode *N = I->second.getNode();
1667#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001668 // Check to see if this is a worthless node generated for non-pointer
1669 // values, such as integers. Consider an addition of long types: A+B.
1670 // Assuming we can track all uses of the value in this context, and it is
1671 // NOT used as a pointer, we can delete the node. We will be able to
1672 // detect this situation if the node pointed to ONLY has Unknown bit set
1673 // in the node. In this case, the node is not incomplete, does not point
1674 // to any other nodes (no mod/ref bits set), and is therefore
1675 // uninteresting for data structure analysis. If we run across one of
1676 // these, prune the scalar pointing to it.
1677 //
Chris Lattner0b144872004-01-27 22:03:40 +00001678 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1679 ScalarMap.erase(I++);
1680 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001681#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001682 N->markReachableNodes(Alive);
1683 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001684 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001685 }
Chris Lattner00948c02004-01-28 02:05:05 +00001686 }
Chris Lattnere2219762002-07-18 18:22:40 +00001687
Chris Lattner0b144872004-01-27 22:03:40 +00001688 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001689 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1690 I != E; ++I)
1691 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001692
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001693 // Mark any nodes reachable by primary calls as alive...
1694 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1695 FunctionCalls[i].markReachableNodes(Alive);
1696
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001697
1698 // Now find globals and aux call nodes that are already live or reach a live
1699 // value (which makes them live in turn), and continue till no more are found.
1700 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001701 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001702 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001703 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1704 do {
1705 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001706 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001707 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001708 // unreachable globals in the list.
1709 //
1710 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001711 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001712 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1713 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1714 Flags & DSGraph::RemoveUnreachableGlobals)) {
1715 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1716 GlobalNodes.pop_back(); // erase efficiently
1717 Iterate = true;
1718 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001719
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001720 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1721 // call nodes that get resolved will be difficult to remove from that graph.
1722 // The final unresolved call nodes must be handled specially at the end of
1723 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001724 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1725 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001726 (AuxFunctionCalls[i].isIndirectCall()
1727 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1728 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001729 AuxFunctionCalls[i].markReachableNodes(Alive);
1730 AuxFCallsAlive[i] = true;
1731 Iterate = true;
1732 }
1733 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001734
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001735 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001736 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001737 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1738 if (AuxFCallsAlive[i])
1739 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001740
1741 // Copy and merge all global nodes and dead aux call nodes into the
1742 // GlobalsGraph, and all nodes reachable from those nodes
1743 //
1744 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001745 // Copy the unreachable call nodes to the globals graph, updating their
1746 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001747 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1748 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001749 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001750 }
1751 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001752 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1753 AuxFunctionCalls.end());
1754
Chris Lattner0b144872004-01-27 22:03:40 +00001755 // We are finally done with the GGCloner so we can clear it and then get rid
1756 // of unused nodes in the GlobalsGraph produced by merging.
1757 if (GGCloner.clonedNode()) {
1758 GGCloner.destroy();
1759 GlobalsGraph->removeTriviallyDeadNodes();
1760 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001761
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001762 // At this point, any nodes which are visited, but not alive, are nodes
1763 // which can be removed. Loop over all nodes, eliminating completely
1764 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001765 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001766 std::vector<DSNode*> DeadNodes;
1767 DeadNodes.reserve(Nodes.size());
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001768 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;)
1769 if (!Alive.count(*NI)) {
Chris Lattnere92e7642004-02-07 23:58:05 +00001770 ++NumDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001771 DSNode *N = *NI;
1772 NI = Nodes.erase(NI); // Erase node from list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001773 DeadNodes.push_back(N);
1774 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001775 } else {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001776 assert((*NI)->getForwardNode() == 0 && "Alive forwarded node?");
1777 ++NI;
Chris Lattnere2219762002-07-18 18:22:40 +00001778 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001779
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001780 // Remove all unreachable globals from the ScalarMap.
1781 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1782 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001783 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001784 if (!Alive.count(GlobalNodes[i].second))
1785 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001786 else
1787 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001788
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001789 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001790 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1791 delete DeadNodes[i];
1792
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001793 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001794}
1795
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001796void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001797 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1798 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001799
Chris Lattner8d327672003-06-30 03:36:09 +00001800 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001801 E = ScalarMap.end(); I != E; ++I) {
1802 assert(I->second.getNode() && "Null node in scalarmap!");
1803 AssertNodeInGraph(I->second.getNode());
1804 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001805 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001806 "Global points to node, but node isn't global?");
1807 AssertNodeContainsGlobal(I->second.getNode(), GV);
1808 }
1809 }
1810 AssertCallNodesInGraph();
1811 AssertAuxCallNodesInGraph();
1812}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001813
Chris Lattner400433d2003-11-11 05:08:59 +00001814/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1815/// nodes reachable from the two graphs, computing the mapping of nodes from
1816/// the first to the second graph.
1817///
1818void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001819 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1820 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001821 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1822 if (N1 == 0 || N2 == 0) return;
1823
1824 DSNodeHandle &Entry = NodeMap[N1];
1825 if (Entry.getNode()) {
1826 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001827 assert(!StrictChecking ||
1828 (Entry.getNode() == N2 &&
1829 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001830 "Inconsistent mapping detected!");
1831 return;
1832 }
1833
1834 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001835 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001836
1837 // Loop over all of the fields that N1 and N2 have in common, recursively
1838 // mapping the edges together now.
1839 int N2Idx = NH2.getOffset()-NH1.getOffset();
1840 unsigned N2Size = N2->getSize();
1841 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1842 if (unsigned(N2Idx)+i < N2Size)
1843 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1844}