blob: a15f3743d8337e047a6a5c09e8b9b6e066c9663b [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 Lattnerc4ebdce2004-03-03 22:01:09 +000014#include "llvm/Analysis/DSGraphTraits.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000016#include "llvm/GlobalVariable.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000017#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000018#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000019#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000020#include "llvm/Assembly/Writer.h"
Chris Lattner0b144872004-01-27 22:03:40 +000021#include "Support/CommandLine.h"
Chris Lattner6806f562003-08-01 22:15:03 +000022#include "Support/Debug.h"
Chris Lattnerc4ebdce2004-03-03 22:01:09 +000023#include "Support/DepthFirstIterator.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000024#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000025#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000026#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000027#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner08db7192002-11-06 06:20:27 +000030namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000031 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
32 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
33 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
34 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000035 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
36 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
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 {
Chris Lattner4ff0b962004-02-08 01:27:18 +000049 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000050
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 Lattner9857c1a2004-02-08 01:05:37 +000077 if (G) 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 Lattnerf590ced2004-03-04 17:06:53 +000084 Ty(N.Ty), NodeType(N.NodeType) {
85 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +000086 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +000087 Globals = N.Globals;
88 } else
Chris Lattner0b144872004-01-27 22:03:40 +000089 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000090 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000091 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +000092}
93
Chris Lattner15869aa2003-11-02 22:27:28 +000094/// getTargetData - Get the target data object used to construct this node.
95///
96const TargetData &DSNode::getTargetData() const {
97 return ParentGraph->getTargetData();
98}
99
Chris Lattner72d29a42003-02-11 23:11:51 +0000100void DSNode::assertOK() const {
101 assert((Ty != Type::VoidTy ||
102 Ty == Type::VoidTy && (Size == 0 ||
103 (NodeType & DSNode::Array))) &&
104 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000105
106 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000107 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000108 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000109 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000110 assert(SM.find(Globals[i])->second.getNode() == this);
111 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000112}
113
114/// forwardNode - Mark this node as being obsolete, and all references to it
115/// should be forwarded to the specified node and offset.
116///
117void DSNode::forwardNode(DSNode *To, unsigned Offset) {
118 assert(this != To && "Cannot forward a node to itself!");
119 assert(ForwardNH.isNull() && "Already forwarding from this node!");
120 if (To->Size <= 1) Offset = 0;
121 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
122 "Forwarded offset is wrong!");
123 ForwardNH.setNode(To);
124 ForwardNH.setOffset(Offset);
125 NodeType = DEAD;
126 Size = 0;
127 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000128
129 // Remove this node from the parent graph's Nodes list.
130 ParentGraph->unlinkNode(this);
131 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000132}
133
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000134// addGlobal - Add an entry for a global value to the Globals list. This also
135// marks the node with the 'G' flag if it does not already have it.
136//
137void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000138 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000139 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000140 std::lower_bound(Globals.begin(), Globals.end(), GV);
141
142 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000143 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000144 Globals.insert(I, GV);
145 NodeType |= GlobalNode;
146 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000147}
148
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000149/// foldNodeCompletely - If we determine that this node has some funny
150/// behavior happening to it that we cannot represent, we fold it down to a
151/// single, completely pessimistic, node. This node is represented as a
152/// single byte with a single TypeEntry of "void".
153///
154void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000155 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000156
Chris Lattner08db7192002-11-06 06:20:27 +0000157 ++NumFolds;
158
Chris Lattner0b144872004-01-27 22:03:40 +0000159 // If this node has a size that is <= 1, we don't need to create a forwarding
160 // node.
161 if (getSize() <= 1) {
162 NodeType |= DSNode::Array;
163 Ty = Type::VoidTy;
164 Size = 1;
165 assert(Links.size() <= 1 && "Size is 1, but has more links?");
166 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000167 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000168 // Create the node we are going to forward to. This is required because
169 // some referrers may have an offset that is > 0. By forcing them to
170 // forward, the forwarder has the opportunity to correct the offset.
171 DSNode *DestNode = new DSNode(0, ParentGraph);
172 DestNode->NodeType = NodeType|DSNode::Array;
173 DestNode->Ty = Type::VoidTy;
174 DestNode->Size = 1;
175 DestNode->Globals.swap(Globals);
176
177 // Start forwarding to the destination node...
178 forwardNode(DestNode, 0);
179
180 if (!Links.empty()) {
181 DestNode->Links.reserve(1);
182
183 DSNodeHandle NH(DestNode);
184 DestNode->Links.push_back(Links[0]);
185
186 // If we have links, merge all of our outgoing links together...
187 for (unsigned i = Links.size()-1; i != 0; --i)
188 NH.getNode()->Links[0].mergeWith(Links[i]);
189 Links.clear();
190 } else {
191 DestNode->Links.resize(1);
192 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000193 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000194}
Chris Lattner076c1f92002-11-07 06:31:54 +0000195
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000196/// isNodeCompletelyFolded - Return true if this node has been completely
197/// folded down to something that can never be expanded, effectively losing
198/// all of the field sensitivity that may be present in the node.
199///
200bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000201 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000202}
203
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000204namespace {
205 /// TypeElementWalker Class - Used for implementation of physical subtyping...
206 ///
207 class TypeElementWalker {
208 struct StackState {
209 const Type *Ty;
210 unsigned Offset;
211 unsigned Idx;
212 StackState(const Type *T, unsigned Off = 0)
213 : Ty(T), Offset(Off), Idx(0) {}
214 };
215
216 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000217 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000218 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000219 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000220 Stack.push_back(T);
221 StepToLeaf();
222 }
223
224 bool isDone() const { return Stack.empty(); }
225 const Type *getCurrentType() const { return Stack.back().Ty; }
226 unsigned getCurrentOffset() const { return Stack.back().Offset; }
227
228 void StepToNextType() {
229 PopStackAndAdvance();
230 StepToLeaf();
231 }
232
233 private:
234 /// PopStackAndAdvance - Pop the current element off of the stack and
235 /// advance the underlying element to the next contained member.
236 void PopStackAndAdvance() {
237 assert(!Stack.empty() && "Cannot pop an empty stack!");
238 Stack.pop_back();
239 while (!Stack.empty()) {
240 StackState &SS = Stack.back();
241 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
242 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000243 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000244 const StructLayout *SL = TD.getStructLayout(ST);
245 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
246 return;
247 }
248 Stack.pop_back(); // At the end of the structure
249 } else {
250 const ArrayType *AT = cast<ArrayType>(SS.Ty);
251 ++SS.Idx;
252 if (SS.Idx != AT->getNumElements()) {
253 SS.Offset += TD.getTypeSize(AT->getElementType());
254 return;
255 }
256 Stack.pop_back(); // At the end of the array
257 }
258 }
259 }
260
261 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
262 /// on the type stack.
263 void StepToLeaf() {
264 if (Stack.empty()) return;
265 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
266 StackState &SS = Stack.back();
267 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000268 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000269 assert(SS.Idx == 0);
270 PopStackAndAdvance();
271 } else {
272 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000273 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000274 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000275 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000276 SS.Offset+SL->MemberOffsets[SS.Idx]));
277 }
278 } else {
279 const ArrayType *AT = cast<ArrayType>(SS.Ty);
280 if (AT->getNumElements() == 0) {
281 assert(SS.Idx == 0);
282 PopStackAndAdvance();
283 } else {
284 // Step into the array...
285 assert(SS.Idx < AT->getNumElements());
286 Stack.push_back(StackState(AT->getElementType(),
287 SS.Offset+SS.Idx*
288 TD.getTypeSize(AT->getElementType())));
289 }
290 }
291 }
292 }
293 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000294} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000295
296/// ElementTypesAreCompatible - Check to see if the specified types are
297/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000298/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
299/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000300///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000301static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000302 bool AllowLargerT1, const TargetData &TD){
303 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000304
305 while (!T1W.isDone() && !T2W.isDone()) {
306 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
307 return false;
308
309 const Type *T1 = T1W.getCurrentType();
310 const Type *T2 = T2W.getCurrentType();
311 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
312 return false;
313
314 T1W.StepToNextType();
315 T2W.StepToNextType();
316 }
317
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000318 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000319}
320
321
Chris Lattner08db7192002-11-06 06:20:27 +0000322/// mergeTypeInfo - This method merges the specified type into the current node
323/// at the specified offset. This may update the current node's type record if
324/// this gives more information to the node, it may do nothing to the node if
325/// this information is already known, or it may merge the node completely (and
326/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000327///
Chris Lattner08db7192002-11-06 06:20:27 +0000328/// This method returns true if the node is completely folded, otherwise false.
329///
Chris Lattner088b6392003-03-03 17:13:31 +0000330bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
331 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000332 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000333 // Check to make sure the Size member is up-to-date. Size can be one of the
334 // following:
335 // Size = 0, Ty = Void: Nothing is known about this node.
336 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
337 // Size = 1, Ty = Void, Array = 1: The node is collapsed
338 // Otherwise, sizeof(Ty) = Size
339 //
Chris Lattner18552922002-11-18 21:44:46 +0000340 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
341 (Size == 0 && !Ty->isSized() && !isArray()) ||
342 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
343 (Size == 0 && !Ty->isSized() && !isArray()) ||
344 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000345 "Size member of DSNode doesn't match the type structure!");
346 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000347
Chris Lattner18552922002-11-18 21:44:46 +0000348 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000349 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000350
Chris Lattner08db7192002-11-06 06:20:27 +0000351 // Return true immediately if the node is completely folded.
352 if (isNodeCompletelyFolded()) return true;
353
Chris Lattner23f83dc2002-11-08 22:49:57 +0000354 // If this is an array type, eliminate the outside arrays because they won't
355 // be used anyway. This greatly reduces the size of large static arrays used
356 // as global variables, for example.
357 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000358 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000359 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
360 // FIXME: we might want to keep small arrays, but must be careful about
361 // things like: [2 x [10000 x int*]]
362 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000363 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000364 }
365
Chris Lattner08db7192002-11-06 06:20:27 +0000366 // Figure out how big the new type we're merging in is...
367 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
368
369 // Otherwise check to see if we can fold this type into the current node. If
370 // we can't, we fold the node completely, if we can, we potentially update our
371 // internal state.
372 //
Chris Lattner18552922002-11-18 21:44:46 +0000373 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000374 // If this is the first type that this node has seen, just accept it without
375 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000376 assert(Offset == 0 && !isArray() &&
377 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000378 Ty = NewTy;
379 NodeType &= ~Array;
380 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000381 Size = NewTySize;
382
383 // Calculate the number of outgoing links from this node.
384 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
385 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000386 }
Chris Lattner08db7192002-11-06 06:20:27 +0000387
388 // Handle node expansion case here...
389 if (Offset+NewTySize > Size) {
390 // It is illegal to grow this node if we have treated it as an array of
391 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000392 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000393 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000394 return true;
395 }
396
397 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000398 std::cerr << "UNIMP: Trying to merge a growth type into "
399 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000400 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000401 return true;
402 }
403
404 // Okay, the situation is nice and simple, we are trying to merge a type in
405 // at offset 0 that is bigger than our current type. Implement this by
406 // switching to the new type and then merge in the smaller one, which should
407 // hit the other code path here. If the other code path decides it's not
408 // ok, it will collapse the node as appropriate.
409 //
Chris Lattner18552922002-11-18 21:44:46 +0000410 const Type *OldTy = Ty;
411 Ty = NewTy;
412 NodeType &= ~Array;
413 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000414 Size = NewTySize;
415
416 // Must grow links to be the appropriate size...
417 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
418
419 // Merge in the old type now... which is guaranteed to be smaller than the
420 // "current" type.
421 return mergeTypeInfo(OldTy, 0);
422 }
423
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000424 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000425 "Cannot merge something into a part of our type that doesn't exist!");
426
Chris Lattner18552922002-11-18 21:44:46 +0000427 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000428 // type that starts at offset Offset.
429 //
430 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000431 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000432 while (O < Offset) {
433 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
434
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000435 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000436 case Type::StructTyID: {
437 const StructType *STy = cast<StructType>(SubType);
438 const StructLayout &SL = *TD.getStructLayout(STy);
439
440 unsigned i = 0, e = SL.MemberOffsets.size();
441 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
442 /* empty */;
443
444 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000445 SubType = STy->getElementType(i);
Chris Lattner08db7192002-11-06 06:20:27 +0000446 O += SL.MemberOffsets[i];
447 break;
448 }
449 case Type::ArrayTyID: {
450 SubType = cast<ArrayType>(SubType)->getElementType();
451 unsigned ElSize = TD.getTypeSize(SubType);
452 unsigned Remainder = (Offset-O) % ElSize;
453 O = Offset-Remainder;
454 break;
455 }
456 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000457 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000458 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000459 }
460 }
461
462 assert(O == Offset && "Could not achieve the correct offset!");
463
464 // If we found our type exactly, early exit
465 if (SubType == NewTy) return false;
466
Misha Brukman96a8bd72004-04-29 04:05:30 +0000467 // Differing function types don't require us to merge. They are not values
468 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000469 if (isa<FunctionType>(SubType) &&
470 isa<FunctionType>(NewTy)) return false;
471
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000472 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
473
474 // Ok, we are getting desperate now. Check for physical subtyping, where we
475 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000476 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000477 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000478 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000479 return false;
480
Chris Lattner08db7192002-11-06 06:20:27 +0000481 // Okay, so we found the leader type at the offset requested. Search the list
482 // of types that starts at this offset. If SubType is currently an array or
483 // structure, the type desired may actually be the first element of the
484 // composite type...
485 //
Chris Lattner18552922002-11-18 21:44:46 +0000486 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000487 while (SubType != NewTy) {
488 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000489 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000490 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000491 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000492 case Type::StructTyID: {
493 const StructType *STy = cast<StructType>(SubType);
494 const StructLayout &SL = *TD.getStructLayout(STy);
495 if (SL.MemberOffsets.size() > 1)
496 NextPadSize = SL.MemberOffsets[1];
497 else
498 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000499 NextSubType = STy->getElementType(0);
Chris Lattner18552922002-11-18 21:44:46 +0000500 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000501 break;
Chris Lattner18552922002-11-18 21:44:46 +0000502 }
Chris Lattner08db7192002-11-06 06:20:27 +0000503 case Type::ArrayTyID:
504 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000505 NextSubTypeSize = TD.getTypeSize(NextSubType);
506 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000507 break;
508 default: ;
509 // fall out
510 }
511
512 if (NextSubType == 0)
513 break; // In the default case, break out of the loop
514
Chris Lattner18552922002-11-18 21:44:46 +0000515 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000516 break; // Don't allow shrinking to a smaller type than NewTySize
517 SubType = NextSubType;
518 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000519 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000520 }
521
522 // If we found the type exactly, return it...
523 if (SubType == NewTy)
524 return false;
525
526 // Check to see if we have a compatible, but different type...
527 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000528 // Check to see if this type is obviously convertible... int -> uint f.e.
529 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000530 return false;
531
532 // Check to see if we have a pointer & integer mismatch going on here,
533 // loading a pointer as a long, for example.
534 //
535 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
536 NewTy->isInteger() && isa<PointerType>(SubType))
537 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000538 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
539 // We are accessing the field, plus some structure padding. Ignore the
540 // structure padding.
541 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000542 }
543
Chris Lattner58f98d02003-07-02 04:38:49 +0000544 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000545 if (getParentGraph()->getReturnNodes().size())
546 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000547 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
548 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
549 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
550 << "SubType: ";
551 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000552
Chris Lattner088b6392003-03-03 17:13:31 +0000553 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000554 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000555}
556
Chris Lattner08db7192002-11-06 06:20:27 +0000557
558
Misha Brukman96a8bd72004-04-29 04:05:30 +0000559/// addEdgeTo - Add an edge from the current node to the specified node. This
560/// can cause merging of nodes in the graph.
561///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000562void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000563 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000564
Chris Lattner08db7192002-11-06 06:20:27 +0000565 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000566 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000567 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000568 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000569 } else { // No merging to perform...
570 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000572}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000574
Misha Brukman96a8bd72004-04-29 04:05:30 +0000575/// MergeSortedVectors - Efficiently merge a vector into another vector where
576/// duplicates are not allowed and both are sorted. This assumes that 'T's are
577/// efficiently copyable and have sane comparison semantics.
578///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000579static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
580 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000581 // By far, the most common cases will be the simple ones. In these cases,
582 // avoid having to allocate a temporary vector...
583 //
584 if (Src.empty()) { // Nothing to merge in...
585 return;
586 } else if (Dest.empty()) { // Just copy the result in...
587 Dest = Src;
588 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000589 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000590 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000591 std::lower_bound(Dest.begin(), Dest.end(), V);
592 if (I == Dest.end() || *I != Src[0]) // If not already contained...
593 Dest.insert(I, Src[0]);
594 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000595 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000596 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000597 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000598 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
599 if (I == Dest.end() || *I != Tmp) // If not already contained...
600 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000601
602 } else {
603 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000604 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000605
606 // Make space for all of the type entries now...
607 Dest.resize(Dest.size()+Src.size());
608
609 // Merge the two sorted ranges together... into Dest.
610 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
611
612 // Now erase any duplicate entries that may have accumulated into the
613 // vectors (because they were in both of the input sets)
614 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
615 }
616}
617
Chris Lattner0b144872004-01-27 22:03:40 +0000618void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
619 MergeSortedVectors(Globals, RHS);
620}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000621
Chris Lattner0b144872004-01-27 22:03:40 +0000622// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000623// This function does the hard work of merging two nodes, CurNodeH
624// and NH after filtering out trivial cases and making sure that
625// CurNodeH.offset >= NH.offset.
626//
627// ***WARNING***
628// Since merging may cause either node to go away, we must always
629// use the node-handles to refer to the nodes. These node handles are
630// automatically updated during merging, so will always provide access
631// to the correct node after a merge.
632//
633void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
634 assert(CurNodeH.getOffset() >= NH.getOffset() &&
635 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000636 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
637 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000638
639 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
640 // respect to NH.Offset) is now zero. NOffset is the distance from the base
641 // of our object that N starts from.
642 //
643 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
644 unsigned NSize = NH.getNode()->getSize();
645
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000646 // If the two nodes are of different size, and the smaller node has the array
647 // bit set, collapse!
648 if (NSize != CurNodeH.getNode()->getSize()) {
649 if (NSize < CurNodeH.getNode()->getSize()) {
650 if (NH.getNode()->isArray())
651 NH.getNode()->foldNodeCompletely();
652 } else if (CurNodeH.getNode()->isArray()) {
653 NH.getNode()->foldNodeCompletely();
654 }
655 }
656
657 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000658 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000659 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000660 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000661
662 // If we are merging a node with a completely folded node, then both nodes are
663 // now completely folded.
664 //
665 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
666 if (!NH.getNode()->isNodeCompletelyFolded()) {
667 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000668 assert(NH.getNode() && NH.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 } else if (NH.getNode()->isNodeCompletelyFolded()) {
675 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000676 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
677 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000678 NOffset = NH.getOffset();
679 NSize = NH.getNode()->getSize();
680 assert(NOffset == 0 && NSize == 1);
681 }
682
Chris Lattner72d29a42003-02-11 23:11:51 +0000683 DSNode *N = NH.getNode();
684 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000685 assert(!CurNodeH.getNode()->isDeadNode());
686
Chris Lattner0b144872004-01-27 22:03:40 +0000687 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000688 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000689
Chris Lattner72d29a42003-02-11 23:11:51 +0000690 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000691 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000692 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000693
Chris Lattner72d29a42003-02-11 23:11:51 +0000694 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
695 //
696 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
697 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000698 if (Link.getNode()) {
699 // Compute the offset into the current node at which to
700 // merge this link. In the common case, this is a linear
701 // relation to the offset in the original node (with
702 // wrapping), but if the current node gets collapsed due to
703 // recursive merging, we must make sure to merge in all remaining
704 // links at offset zero.
705 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000706 DSNode *CN = CurNodeH.getNode();
707 if (CN->Size != 1)
708 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
709 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000710 }
711 }
712
713 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000714 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000715
716 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000717 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000718 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000719
720 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000721 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000722 }
723}
724
725
Misha Brukman96a8bd72004-04-29 04:05:30 +0000726/// mergeWith - Merge this node and the specified node, moving all links to and
727/// from the argument node into the current node, deleting the node argument.
728/// Offset indicates what offset the specified node is to be merged into the
729/// current node.
730///
731/// The specified node may be a null pointer (in which case, we update it to
732/// point to this node).
733///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000734void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
735 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000736 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000737 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000738
Chris Lattner5254a8d2004-01-22 16:31:08 +0000739 // If the RHS is a null node, make it point to this node!
740 if (N == 0) {
741 NH.mergeWith(DSNodeHandle(this, Offset));
742 return;
743 }
744
Chris Lattnerbd92b732003-06-19 21:15:11 +0000745 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000746 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
747
Chris Lattner02606632002-11-04 06:48:26 +0000748 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000749 // We cannot merge two pieces of the same node together, collapse the node
750 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000751 DEBUG(std::cerr << "Attempting to merge two chunks of"
752 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000753 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000754 return;
755 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000756
Chris Lattner5190ce82002-11-12 07:20:45 +0000757 // If both nodes are not at offset 0, make sure that we are merging the node
758 // at an later offset into the node with the zero offset.
759 //
760 if (Offset < NH.getOffset()) {
761 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
762 return;
763 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
764 // If the offsets are the same, merge the smaller node into the bigger node
765 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
766 return;
767 }
768
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000769 // Ok, now we can merge the two nodes. Use a static helper that works with
770 // two node handles, since "this" may get merged away at intermediate steps.
771 DSNodeHandle CurNodeH(this, Offset);
772 DSNodeHandle NHCopy(NH);
773 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000774}
775
Chris Lattner0b144872004-01-27 22:03:40 +0000776
777//===----------------------------------------------------------------------===//
778// ReachabilityCloner Implementation
779//===----------------------------------------------------------------------===//
780
781DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
782 if (SrcNH.isNull()) return DSNodeHandle();
783 const DSNode *SN = SrcNH.getNode();
784
785 DSNodeHandle &NH = NodeMap[SN];
786 if (!NH.isNull()) // Node already mapped?
787 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
788
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000789 // If SrcNH has globals and the destination graph has one of the same globals,
790 // merge this node with the destination node, which is much more efficient.
791 if (SN->global_begin() != SN->global_end()) {
792 DSScalarMap &DestSM = Dest.getScalarMap();
793 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
794 I != E; ++I) {
795 GlobalValue *GV = *I;
796 DSScalarMap::iterator GI = DestSM.find(GV);
797 if (GI != DestSM.end() && !GI->second.isNull()) {
798 // We found one, use merge instead!
799 merge(GI->second, Src.getNodeForValue(GV));
800 assert(!NH.isNull() && "Didn't merge node!");
801 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
802 }
803 }
804 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000805
Chris Lattner0b144872004-01-27 22:03:40 +0000806 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
807 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000808 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000809
810 // Next, recursively clone all outgoing links as necessary. Note that
811 // adding these links can cause the node to collapse itself at any time, and
812 // the current node may be merged with arbitrary other nodes. For this
813 // reason, we must always go through NH.
814 DN = 0;
815 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
816 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
817 if (!SrcEdge.isNull()) {
818 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
819 // Compute the offset into the current node at which to
820 // merge this link. In the common case, this is a linear
821 // relation to the offset in the original node (with
822 // wrapping), but if the current node gets collapsed due to
823 // recursive merging, we must make sure to merge in all remaining
824 // links at offset zero.
825 unsigned MergeOffset = 0;
826 DSNode *CN = NH.getNode();
827 if (CN->getSize() != 1)
828 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()
829 - SrcNH.getOffset()) %CN->getSize();
830 CN->addEdgeTo(MergeOffset, DestEdge);
831 }
832 }
833
834 // If this node contains any globals, make sure they end up in the scalar
835 // map with the correct offset.
836 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
837 I != E; ++I) {
838 GlobalValue *GV = *I;
839 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
840 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
841 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
842 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000843 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000844
845 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
846 Dest.getInlinedGlobals().insert(GV);
847 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000848 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000849
850 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
851}
852
853void ReachabilityCloner::merge(const DSNodeHandle &NH,
854 const DSNodeHandle &SrcNH) {
855 if (SrcNH.isNull()) return; // Noop
856 if (NH.isNull()) {
857 // If there is no destination node, just clone the source and assign the
858 // destination node to be it.
859 NH.mergeWith(getClonedNH(SrcNH));
860 return;
861 }
862
863 // Okay, at this point, we know that we have both a destination and a source
864 // node that need to be merged. Check to see if the source node has already
865 // been cloned.
866 const DSNode *SN = SrcNH.getNode();
867 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000868 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner0b144872004-01-27 22:03:40 +0000869 NH.mergeWith(DSNodeHandle(SCNH.getNode(),
870 SCNH.getOffset()+SrcNH.getOffset()));
871
872 return; // Nothing to do!
873 }
874
875 // Okay, so the source node has not already been cloned. Instead of creating
876 // a new DSNode, only to merge it into the one we already have, try to perform
877 // the merge in-place. The only case we cannot handle here is when the offset
878 // into the existing node is less than the offset into the virtual node we are
879 // merging in. In this case, we have to extend the existing node, which
880 // requires an allocation anyway.
881 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
882 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000883 if (!DN->isNodeCompletelyFolded()) {
884 // Make sure the destination node is folded if the source node is folded.
885 if (SN->isNodeCompletelyFolded()) {
886 DN->foldNodeCompletely();
887 DN = NH.getNode();
888 } else if (SN->getSize() != DN->getSize()) {
889 // If the two nodes are of different size, and the smaller node has the
890 // array bit set, collapse!
891 if (SN->getSize() < DN->getSize()) {
892 if (SN->isArray()) {
893 DN->foldNodeCompletely();
894 DN = NH.getNode();
895 }
896 } else if (DN->isArray()) {
897 DN->foldNodeCompletely();
898 DN = NH.getNode();
899 }
900 }
901
902 // Merge the type entries of the two nodes together...
903 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
904 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
905 DN = NH.getNode();
906 }
907 }
908
909 assert(!DN->isDeadNode());
910
911 // Merge the NodeType information.
912 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
913
914 // Before we start merging outgoing links and updating the scalar map, make
915 // sure it is known that this is the representative node for the src node.
916 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
917
918 // If the source node contains any globals, make sure they end up in the
919 // scalar map with the correct offset.
920 if (SN->global_begin() != SN->global_end()) {
921 // Update the globals in the destination node itself.
922 DN->mergeGlobals(SN->getGlobals());
923
924 // Update the scalar map for the graph we are merging the source node
925 // into.
926 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
927 I != E; ++I) {
928 GlobalValue *GV = *I;
929 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
930 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
931 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
932 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000933 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000934
935 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
936 Dest.getInlinedGlobals().insert(GV);
937 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000938 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000939 }
940 } else {
941 // We cannot handle this case without allocating a temporary node. Fall
942 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000943 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
944 NewDN->maskNodeTypes(BitsToKeep);
945
946 unsigned NHOffset = NH.getOffset();
947 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000948
Chris Lattner0b144872004-01-27 22:03:40 +0000949 assert(NH.getNode() &&
950 (NH.getOffset() > NHOffset ||
951 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
952 "Merging did not adjust the offset!");
953
954 // Before we start merging outgoing links and updating the scalar map, make
955 // sure it is known that this is the representative node for the src node.
956 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000957
958 // If the source node contained any globals, make sure to create entries
959 // in the scalar map for them!
960 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
961 I != E; ++I) {
962 GlobalValue *GV = *I;
963 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
964 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
965 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
966 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
967 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
968 DestGNH.getOffset()+SrcGNH.getOffset()));
969
970 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
971 Dest.getInlinedGlobals().insert(GV);
972 }
Chris Lattner0b144872004-01-27 22:03:40 +0000973 }
974
975
976 // Next, recursively merge all outgoing links as necessary. Note that
977 // adding these links can cause the destination node to collapse itself at
978 // any time, and the current node may be merged with arbitrary other nodes.
979 // For this reason, we must always go through NH.
980 DN = 0;
981 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
982 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
983 if (!SrcEdge.isNull()) {
984 // Compute the offset into the current node at which to
985 // merge this link. In the common case, this is a linear
986 // relation to the offset in the original node (with
987 // wrapping), but if the current node gets collapsed due to
988 // recursive merging, we must make sure to merge in all remaining
989 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +0000990 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +0000991 unsigned MergeOffset =
992 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000993
Chris Lattnerf590ced2004-03-04 17:06:53 +0000994 DSNodeHandle Tmp = CN->getLink(MergeOffset);
995 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +0000996 // Perform the recursive merging. Make sure to create a temporary NH,
997 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +0000998 merge(Tmp, SrcEdge);
999 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001000 Tmp.mergeWith(getClonedNH(SrcEdge));
1001 // Merging this could cause all kinds of recursive things to happen,
1002 // culminating in the current node being eliminated. Since this is
1003 // possible, make sure to reaquire the link from 'CN'.
1004
1005 unsigned MergeOffset = 0;
1006 CN = SCNH.getNode();
1007 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1008 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001009 }
Chris Lattner0b144872004-01-27 22:03:40 +00001010 }
1011 }
1012}
1013
1014/// mergeCallSite - Merge the nodes reachable from the specified src call
1015/// site into the nodes reachable from DestCS.
1016void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1017 const DSCallSite &SrcCS) {
1018 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1019 unsigned MinArgs = DestCS.getNumPtrArgs();
1020 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1021
1022 for (unsigned a = 0; a != MinArgs; ++a)
1023 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1024}
1025
1026
Chris Lattner9de906c2002-10-20 22:11:44 +00001027//===----------------------------------------------------------------------===//
1028// DSCallSite Implementation
1029//===----------------------------------------------------------------------===//
1030
Vikram S. Adve26b98262002-10-20 21:41:02 +00001031// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001032Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001033 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001034}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001035
Chris Lattner0b144872004-01-27 22:03:40 +00001036void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1037 ReachabilityCloner &RC) {
1038 NH = RC.getClonedNH(Src);
1039}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001040
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001041//===----------------------------------------------------------------------===//
1042// DSGraph Implementation
1043//===----------------------------------------------------------------------===//
1044
Chris Lattnera9d65662003-06-30 05:57:30 +00001045/// getFunctionNames - Return a space separated list of the name of the
1046/// functions in this graph (if any)
1047std::string DSGraph::getFunctionNames() const {
1048 switch (getReturnNodes().size()) {
1049 case 0: return "Globals graph";
1050 case 1: return getReturnNodes().begin()->first->getName();
1051 default:
1052 std::string Return;
1053 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1054 I != getReturnNodes().end(); ++I)
1055 Return += I->first->getName() + " ";
1056 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1057 return Return;
1058 }
1059}
1060
1061
Chris Lattner15869aa2003-11-02 22:27:28 +00001062DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001063 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001064 NodeMapTy NodeMap;
1065 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001066}
1067
Chris Lattner5a540632003-06-30 03:15:25 +00001068DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001069 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001070 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001071 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001072}
1073
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001074DSGraph::~DSGraph() {
1075 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001076 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001077 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001078 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001079 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001080
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001081 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001082 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1083 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001084
Chris Lattner28897e12004-02-08 00:53:26 +00001085 // Free all of the nodes.
1086 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001087}
1088
Chris Lattner0d9bab82002-07-18 00:12:30 +00001089// dump - Allow inspection of graph in a debugger.
1090void DSGraph::dump() const { print(std::cerr); }
1091
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001092
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001093/// remapLinks - Change all of the Links in the current node according to the
1094/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001095///
Chris Lattner8d327672003-06-30 03:36:09 +00001096void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001097 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1098 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001099 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
1100 if (ONMI != OldNodeMap.end()) {
1101 Links[i].setNode(ONMI->second.getNode());
1102 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
1103 }
Chris Lattner2f561382004-01-22 16:56:13 +00001104 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001105}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001106
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001107/// updateFromGlobalGraph - This function rematerializes global nodes and
1108/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001109/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1110/// are already up-to-date in the current graph. In practice, in the TD pass,
1111/// this is likely to be a large fraction of the live global nodes in each
1112/// function (since most live nodes are likely to have been brought up-to-date
1113/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001114///
1115void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001116 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001117 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1118
1119 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001120 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1121 E = getScalarMap().global_end(); I != E; ++I)
1122 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001123 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001124 if (It != GlobalsGraph->ScalarMap.end())
1125 RC.merge(getNodeForValue(*I), It->second);
1126 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001127}
1128
Chris Lattner5a540632003-06-30 03:15:25 +00001129/// cloneInto - Clone the specified DSGraph into the current graph. The
1130/// translated ScalarMap for the old function is filled into the OldValMap
1131/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1132///
1133/// The CloneFlags member controls various aspects of the cloning process.
1134///
Chris Lattner62482e52004-01-28 09:15:42 +00001135void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001136 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1137 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001138 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001139 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001140 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001141
Chris Lattner1e883692003-02-03 20:08:51 +00001142 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001143 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1144 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1145 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001146 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001147
Chris Lattnerd85645f2004-02-21 22:28:26 +00001148 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1149 assert(!(*I)->isForwarding() &&
1150 "Forward nodes shouldn't be in node list!");
1151 DSNode *New = new DSNode(**I, this);
1152 New->maskNodeTypes(~BitsToClear);
1153 OldNodeMap[*I] = New;
1154 }
1155
Chris Lattner18552922002-11-18 21:44:46 +00001156#ifndef NDEBUG
1157 Timer::addPeakMemoryMeasurement();
1158#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001159
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001160 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001161 // Note that we don't loop over the node's list to do this. The problem is
1162 // that remaping links can cause recursive merging to happen, which means
1163 // that node_iterator's can get easily invalidated! Because of this, we
1164 // loop over the OldNodeMap, which contains all of the new nodes as the
1165 // .second element of the map elements. Also note that if we remap a node
1166 // more than once, we won't break anything.
1167 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1168 I != E; ++I)
1169 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001170
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001171 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001172 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001173 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001174 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001175 DSNodeHandle &H = OldValMap[I->first];
1176 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
1177 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001178
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001179 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001180 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1181 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001182 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1183 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001184 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001185 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001186
Chris Lattner679e8e12002-11-08 21:27:12 +00001187 if (!(CloneFlags & DontCloneCallNodes)) {
1188 // Copy the function calls list...
1189 unsigned FC = FunctionCalls.size(); // FirstCall
1190 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1191 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1192 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001193 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001194
Chris Lattneracf491f2002-11-08 22:27:09 +00001195 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +00001196 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +00001197 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +00001198 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1199 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1200 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1201 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001202
Chris Lattner5a540632003-06-30 03:15:25 +00001203 // Map the return node pointers over...
1204 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1205 E = G.getReturnNodes().end(); I != E; ++I) {
1206 const DSNodeHandle &Ret = I->second;
1207 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1208 OldReturnNodes.insert(std::make_pair(I->first,
1209 DSNodeHandle(MappedRet.getNode(),
1210 MappedRet.getOffset()+Ret.getOffset())));
1211 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001212}
1213
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001214static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001215 if (N)
1216 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1217 if (RC.hasClonedNode(*I))
1218 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001219 return false;
1220}
1221
Chris Lattner2f346902004-03-04 03:57:53 +00001222static bool PathExistsToClonedNode(const DSCallSite &CS,
1223 ReachabilityCloner &RC) {
1224 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1225 return true;
1226 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1227 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1228 return true;
1229 return false;
1230}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001231
Chris Lattner076c1f92002-11-07 06:31:54 +00001232/// mergeInGraph - The method is used for merging graphs together. If the
1233/// argument graph is not *this, it makes a clone of the specified graph, then
1234/// merges the nodes specified in the call site with the formal arguments in the
1235/// graph.
1236///
Chris Lattner9f930552003-06-30 05:27:18 +00001237void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1238 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001239 TIME_REGION(X, "mergeInGraph");
1240
Chris Lattner2c7725a2004-03-03 20:55:27 +00001241 // Fastpath for a noop inline.
1242 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1243 return;
1244
Chris Lattner076c1f92002-11-07 06:31:54 +00001245 // If this is not a recursive call, clone the graph into this graph...
1246 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001247 // Clone the callee's graph into the current graph, keeping track of where
1248 // scalars in the old graph _used_ to point, and of the new nodes matching
1249 // nodes of the old graph.
1250 ReachabilityCloner RC(*this, Graph, CloneFlags);
1251
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001252 // Set up argument bindings
1253 Function::aiterator AI = F.abegin();
1254 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1255 // Advance the argument iterator to the first pointer argument...
1256 while (AI != F.aend() && !isPointerType(AI->getType())) {
1257 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001258#ifndef NDEBUG // FIXME: We should merge vararg arguments!
1259 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001260 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001261#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001262 }
1263 if (AI == F.aend()) break;
1264
1265 // Add the link from the argument scalar to the provided value.
Chris Lattner0b144872004-01-27 22:03:40 +00001266 RC.merge(CS.getPtrArg(i), Graph.getNodeForValue(AI));
Chris Lattner076c1f92002-11-07 06:31:54 +00001267 }
1268
Chris Lattner0b144872004-01-27 22:03:40 +00001269 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001270 if (!CS.getRetVal().isNull())
Chris Lattner0b144872004-01-27 22:03:40 +00001271 RC.merge(CS.getRetVal(), Graph.getReturnNodeFor(F));
Chris Lattnerf590ced2004-03-04 17:06:53 +00001272
Chris Lattner2f346902004-03-04 03:57:53 +00001273 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001274 if (!(CloneFlags & DontCloneCallNodes)) {
1275 // Copy the function calls list...
1276 FunctionCalls.reserve(FunctionCalls.size()+Graph.FunctionCalls.size());
1277 for (unsigned i = 0, ei = Graph.FunctionCalls.size(); i != ei; ++i)
1278 FunctionCalls.push_back(DSCallSite(Graph.FunctionCalls[i], RC));
1279 }
Chris Lattner2f346902004-03-04 03:57:53 +00001280
1281 // If the user has us copying aux calls (the normal case), set up a data
1282 // structure to keep track of which ones we've copied over.
1283 std::vector<bool> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001284 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001285 AuxFunctionCalls.reserve(AuxFunctionCalls.size()+
1286 Graph.AuxFunctionCalls.size());
Chris Lattner2f346902004-03-04 03:57:53 +00001287 CopiedAuxCall.resize(Graph.AuxFunctionCalls.size());
Chris Lattner0b144872004-01-27 22:03:40 +00001288 }
1289
Chris Lattner0321b682004-02-27 20:05:15 +00001290 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001291 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001292 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1293 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1294 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1295 if (ScalarMap.count(GV))
1296 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001297 else
1298 NonCopiedGlobals.insert(GV);
1299
1300 // If the global does not appear in the callers graph we generally don't
1301 // want to copy the node. However, if there is a path from the node global
1302 // node to a node that we did copy in the graph, we *must* copy it to
1303 // maintain the connection information. Every time we decide to include a
1304 // new global, this might make other globals live, so we must iterate
1305 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001306 bool MadeChange = true;
1307 while (MadeChange) {
1308 MadeChange = false;
1309 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1310 I != NonCopiedGlobals.end();) {
1311 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1312 if (RC.hasClonedNode(GlobalNode)) {
1313 // Already cloned it, remove from set.
1314 NonCopiedGlobals.erase(I++);
1315 MadeChange = true;
1316 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1317 RC.getClonedNH(Graph.getNodeForValue(*I));
1318 NonCopiedGlobals.erase(I++);
1319 MadeChange = true;
1320 } else {
1321 ++I;
1322 }
1323 }
1324
1325 // If requested, copy any aux calls that can reach copied nodes.
1326 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1327 for (unsigned i = 0, ei = Graph.AuxFunctionCalls.size(); i != ei; ++i)
1328 if (!CopiedAuxCall[i] &&
1329 PathExistsToClonedNode(Graph.AuxFunctionCalls[i], RC)) {
1330 AuxFunctionCalls.push_back(DSCallSite(Graph.AuxFunctionCalls[i],
1331 RC));
1332 CopiedAuxCall[i] = true;
1333 MadeChange = true;
1334 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001335 }
1336 }
1337
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001338 } else {
1339 DSNodeHandle RetVal = getReturnNodeFor(F);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001340
1341 // Merge the return value with the return value of the context...
1342 RetVal.mergeWith(CS.getRetVal());
1343
1344 // Resolve all of the function arguments...
1345 Function::aiterator AI = F.abegin();
1346
1347 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1348 // Advance the argument iterator to the first pointer argument...
1349 while (AI != F.aend() && !isPointerType(AI->getType())) {
1350 ++AI;
Chris Lattner17a93e22004-01-29 03:32:15 +00001351#ifndef NDEBUG // FIXME: We should merge varargs arguments!!
1352 if (AI == F.aend() && !F.getFunctionType()->isVarArg())
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001353 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1354#endif
1355 }
1356 if (AI == F.aend()) break;
1357
1358 // Add the link from the argument scalar to the provided value
Chris Lattner0b144872004-01-27 22:03:40 +00001359 DSNodeHandle &NH = getNodeForValue(AI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001360 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1361 NH.mergeWith(CS.getPtrArg(i));
1362 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001363 }
1364}
1365
Chris Lattner58f98d02003-07-02 04:38:49 +00001366/// getCallSiteForArguments - Get the arguments and return value bindings for
1367/// the specified function in the current graph.
1368///
1369DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1370 std::vector<DSNodeHandle> Args;
1371
1372 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1373 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001374 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001375
Chris Lattner808a7ae2003-09-20 16:34:13 +00001376 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001377}
1378
Chris Lattner85fb1be2004-03-09 19:37:06 +00001379/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1380/// the context of this graph, return the DSCallSite for it.
1381DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1382 DSNodeHandle RetVal;
1383 Instruction *I = CS.getInstruction();
1384 if (isPointerType(I->getType()))
1385 RetVal = getNodeForValue(I);
1386
1387 std::vector<DSNodeHandle> Args;
1388 Args.reserve(CS.arg_end()-CS.arg_begin());
1389
1390 // Calculate the arguments vector...
1391 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1392 if (isPointerType((*I)->getType()))
1393 Args.push_back(getNodeForValue(*I));
1394
1395 // Add a new function call entry...
1396 if (Function *F = CS.getCalledFunction())
1397 return DSCallSite(CS, RetVal, F, Args);
1398 else
1399 return DSCallSite(CS, RetVal,
1400 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1401}
1402
Chris Lattner58f98d02003-07-02 04:38:49 +00001403
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001404
Chris Lattner0d9bab82002-07-18 00:12:30 +00001405// markIncompleteNodes - Mark the specified node as having contents that are not
1406// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001407// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001408// must recursively traverse the data structure graph, marking all reachable
1409// nodes as incomplete.
1410//
1411static void markIncompleteNode(DSNode *N) {
1412 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001413 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001414
1415 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001416 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001417
Misha Brukman2f2d0652003-09-11 18:14:24 +00001418 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001419 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1420 if (DSNode *DSN = N->getLink(i).getNode())
1421 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001422}
1423
Chris Lattnere71ffc22002-11-11 03:36:55 +00001424static void markIncomplete(DSCallSite &Call) {
1425 // Then the return value is certainly incomplete!
1426 markIncompleteNode(Call.getRetVal().getNode());
1427
1428 // All objects pointed to by function arguments are incomplete!
1429 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1430 markIncompleteNode(Call.getPtrArg(i).getNode());
1431}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001432
1433// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1434// modified by other functions that have not been resolved yet. This marks
1435// nodes that are reachable through three sources of "unknownness":
1436//
1437// Global Variables, Function Calls, and Incoming Arguments
1438//
1439// For any node that may have unknown components (because something outside the
1440// scope of current analysis may have modified it), the 'Incomplete' flag is
1441// added to the NodeType.
1442//
Chris Lattner394471f2003-01-23 22:05:33 +00001443void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001444 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001445 if (Flags & DSGraph::MarkFormalArgs)
1446 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1447 FI != E; ++FI) {
1448 Function &F = *FI->first;
1449 if (F.getName() != "main")
1450 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001451 if (isPointerType(I->getType()))
1452 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001453 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001454
1455 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001456 if (!shouldPrintAuxCalls())
1457 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1458 markIncomplete(FunctionCalls[i]);
1459 else
1460 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1461 markIncomplete(AuxFunctionCalls[i]);
1462
Chris Lattner0d9bab82002-07-18 00:12:30 +00001463
Chris Lattner93d7a212003-02-09 18:41:49 +00001464 // Mark all global nodes as incomplete...
1465 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001466 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1467 E = ScalarMap.global_end(); I != E; ++I)
Chris Lattnercf14e712004-02-25 23:36:08 +00001468 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattnerd84d3502004-03-08 03:52:24 +00001469 if (!GV->isConstant() || !GV->hasInitializer())
Chris Lattnercf14e712004-02-25 23:36:08 +00001470 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001471}
1472
Chris Lattneraa8146f2002-11-10 06:59:55 +00001473static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1474 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001475 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001476 // No interesting info?
1477 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001478 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001479 Edge.setNode(0); // Kill the edge!
1480}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001481
Chris Lattneraa8146f2002-11-10 06:59:55 +00001482static inline bool nodeContainsExternalFunction(const DSNode *N) {
1483 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1484 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1485 if (Globals[i]->isExternal())
1486 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001487 return false;
1488}
1489
Chris Lattner5a540632003-06-30 03:15:25 +00001490static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001491 // Remove trivially identical function calls
1492 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001493 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1494
Chris Lattner0b144872004-01-27 22:03:40 +00001495#if 1
Chris Lattneraa8146f2002-11-10 06:59:55 +00001496 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001497 DSNode *LastCalleeNode = 0;
1498 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001499 unsigned NumDuplicateCalls = 0;
1500 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001501 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001502 DSCallSite &CS = Calls[i];
1503
Chris Lattnere4258442002-11-11 21:35:38 +00001504 // If the Callee is a useless edge, this must be an unreachable call site,
1505 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001506 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001507 CS.getCalleeNode()->isComplete() &&
Chris Lattneraf6926a2004-02-26 03:45:03 +00001508 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001509#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001510 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001511#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001512 CS.swap(Calls.back());
1513 Calls.pop_back();
1514 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001515 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001516 // If the return value or any arguments point to a void node with no
1517 // information at all in it, and the call node is the only node to point
1518 // to it, remove the edge to the node (killing the node).
1519 //
1520 killIfUselessEdge(CS.getRetVal());
1521 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1522 killIfUselessEdge(CS.getPtrArg(a));
1523
1524 // If this call site calls the same function as the last call site, and if
1525 // the function pointer contains an external function, this node will
1526 // never be resolved. Merge the arguments of the call node because no
1527 // information will be lost.
1528 //
Chris Lattner923fc052003-02-05 21:59:58 +00001529 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1530 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001531 ++NumDuplicateCalls;
1532 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001533 if (LastCalleeNode)
1534 LastCalleeContainsExternalFunction =
1535 nodeContainsExternalFunction(LastCalleeNode);
1536 else
1537 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001538 }
Chris Lattner0b144872004-01-27 22:03:40 +00001539
1540 // It is not clear why, but enabling this code makes DSA really
1541 // sensitive to node forwarding. Basically, with this enabled, DSA
1542 // performs different number of inlinings based on which nodes are
1543 // forwarding or not. This is clearly a problem, so this code is
1544 // disabled until this can be resolved.
Chris Lattner58f98d02003-07-02 04:38:49 +00001545#if 1
Chris Lattner0b144872004-01-27 22:03:40 +00001546 if (LastCalleeContainsExternalFunction
1547#if 0
1548 ||
Chris Lattnere4258442002-11-11 21:35:38 +00001549 // This should be more than enough context sensitivity!
1550 // FIXME: Evaluate how many times this is tripped!
Chris Lattner0b144872004-01-27 22:03:40 +00001551 NumDuplicateCalls > 20
1552#endif
1553 ) {
Chris Lattnere4258442002-11-11 21:35:38 +00001554 DSCallSite &OCS = Calls[i-1];
1555 OCS.mergeWith(CS);
1556
1557 // The node will now be eliminated as a duplicate!
1558 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1559 CS = OCS;
1560 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1561 OCS = CS;
1562 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001563#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001564 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001565 if (CS.isDirectCall()) {
1566 LastCalleeFunc = CS.getCalleeFunc();
1567 LastCalleeNode = 0;
1568 } else {
1569 LastCalleeNode = CS.getCalleeNode();
1570 LastCalleeFunc = 0;
1571 }
Chris Lattnere4258442002-11-11 21:35:38 +00001572 NumDuplicateCalls = 0;
1573 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001574 }
1575 }
Chris Lattner0b144872004-01-27 22:03:40 +00001576#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001577 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001578
Chris Lattner33312f72002-11-08 01:21:07 +00001579 // Track the number of call nodes merged away...
1580 NumCallNodesMerged += NumFns-Calls.size();
1581
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001582 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001583 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001584}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001585
Chris Lattneraa8146f2002-11-10 06:59:55 +00001586
Chris Lattnere2219762002-07-18 18:22:40 +00001587// removeTriviallyDeadNodes - After the graph has been constructed, this method
1588// removes all unreachable nodes that are created because they got merged with
1589// other nodes in the graph. These nodes will all be trivially unreachable, so
1590// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001591//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001592void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001593 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001594
Chris Lattnerbab8c282003-09-20 21:34:07 +00001595 // Loop over all of the nodes in the graph, calling getNode on each field.
1596 // This will cause all nodes to update their forwarding edges, causing
1597 // forwarded nodes to be delete-able.
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001598 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1599 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001600 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1601 N->getLink(l*N->getPointerSize()).getNode();
1602 }
1603
Chris Lattner0b144872004-01-27 22:03:40 +00001604 // NOTE: This code is disabled. Though it should, in theory, allow us to
1605 // remove more nodes down below, the scan of the scalar map is incredibly
1606 // expensive for certain programs (with large SCCs). In the future, if we can
1607 // make the scalar map scan more efficient, then we can reenable this.
1608#if 0
1609 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1610
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001611 // Likewise, forward any edges from the scalar nodes. While we are at it,
1612 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001613 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001614 I->second.getNode();
1615 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001616 }
Chris Lattner0b144872004-01-27 22:03:40 +00001617 }
1618#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001619 bool isGlobalsGraph = !GlobalsGraph;
1620
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001621 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001622 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001623
1624 // Do not remove *any* global nodes in the globals graph.
1625 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001626 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001627 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001628 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001629 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001630
Chris Lattner28897e12004-02-08 00:53:26 +00001631 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001632 // This is a useless node if it has no mod/ref info (checked above),
1633 // outgoing edges (which it cannot, as it is not modified in this
1634 // context), and it has no incoming edges. If it is a global node it may
1635 // have all of these properties and still have incoming edges, due to the
1636 // scalar map, so we check those now.
1637 //
Chris Lattner28897e12004-02-08 00:53:26 +00001638 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1639 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001640
Chris Lattner17a93e22004-01-29 03:32:15 +00001641 // Loop through and make sure all of the globals are referring directly
1642 // to the node...
1643 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1644 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001645 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001646 }
1647
Chris Lattnerbd92b732003-06-19 21:15:11 +00001648 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001649 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001650 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1651 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001652 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001653 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001654 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001655 }
1656 }
1657
Chris Lattner28897e12004-02-08 00:53:26 +00001658 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001659 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001660 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001661 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001662 } else {
1663 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001664 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001665 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001666
1667 removeIdenticalCalls(FunctionCalls);
1668 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001669}
1670
1671
Chris Lattner5c7380e2003-01-29 21:10:20 +00001672/// markReachableNodes - This method recursively traverses the specified
1673/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1674/// to the set, which allows it to only traverse visited nodes once.
1675///
Chris Lattner41c04f72003-02-01 04:52:08 +00001676void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001677 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001678 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001679 if (ReachableNodes.insert(this).second) // Is newly reachable?
1680 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1681 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001682}
1683
Chris Lattner41c04f72003-02-01 04:52:08 +00001684void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001685 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001686 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001687
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001688 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1689 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001690}
1691
Chris Lattnera1220af2003-02-01 06:17:02 +00001692// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1693// looking for a node that is marked alive. If an alive node is found, return
1694// true, otherwise return false. If an alive node is reachable, this node is
1695// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001696//
Chris Lattnera1220af2003-02-01 06:17:02 +00001697static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001698 hash_set<DSNode*> &Visited,
1699 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001700 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001701 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001702
Chris Lattner85cfe012003-07-03 02:03:53 +00001703 // If this is a global node, it will end up in the globals graph anyway, so we
1704 // don't need to worry about it.
1705 if (IgnoreGlobals && N->isGlobalNode()) return false;
1706
Chris Lattneraa8146f2002-11-10 06:59:55 +00001707 // If we know that this node is alive, return so!
1708 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001709
Chris Lattneraa8146f2002-11-10 06:59:55 +00001710 // Otherwise, we don't think the node is alive yet, check for infinite
1711 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001712 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001713 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001714
Chris Lattner08db7192002-11-06 06:20:27 +00001715 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001716 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1717 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001718 N->markReachableNodes(Alive);
1719 return true;
1720 }
1721 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001722}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001723
Chris Lattnera1220af2003-02-01 06:17:02 +00001724// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1725// alive nodes.
1726//
Chris Lattner41c04f72003-02-01 04:52:08 +00001727static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001728 hash_set<DSNode*> &Visited,
1729 bool IgnoreGlobals) {
1730 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1731 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001732 return true;
1733 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001734 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001735 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001736 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001737 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1738 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001739 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001740 return false;
1741}
1742
Chris Lattnere2219762002-07-18 18:22:40 +00001743// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1744// subgraphs that are unreachable. This often occurs because the data
1745// structure doesn't "escape" into it's caller, and thus should be eliminated
1746// from the caller's graph entirely. This is only appropriate to use when
1747// inlining graphs.
1748//
Chris Lattner394471f2003-01-23 22:05:33 +00001749void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001750 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001751
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001752 // Reduce the amount of work we have to do... remove dummy nodes left over by
1753 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001754 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001755
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001756 TIME_REGION(X, "removeDeadNodes");
1757
Misha Brukman2f2d0652003-09-11 18:14:24 +00001758 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001759
1760 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001761 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001762 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001763
Chris Lattner0b144872004-01-27 22:03:40 +00001764 // Copy and merge all information about globals to the GlobalsGraph if this is
1765 // not a final pass (where unreachable globals are removed).
1766 //
1767 // Strip all alloca bits since the current function is only for the BU pass.
1768 // Strip all incomplete bits since they are short-lived properties and they
1769 // will be correctly computed when rematerializing nodes into the functions.
1770 //
1771 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1772 DSGraph::StripIncompleteBit);
1773
Chris Lattneraa8146f2002-11-10 06:59:55 +00001774 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001775 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001776 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001777 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001778 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001779 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001780 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001781
1782 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001783 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1784 DSGraph::ScalarMapTy::iterator SMI =
1785 GlobalsGraph->getScalarMap().find(I->first);
1786 if (SMI != GlobalsGraph->getScalarMap().end())
1787 GGCloner.merge(SMI->second, I->second);
1788 else
1789 GGCloner.getClonedNH(I->second);
1790 }
Chris Lattner0b144872004-01-27 22:03:40 +00001791 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001792 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001793 DSNode *N = I->second.getNode();
1794#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001795 // Check to see if this is a worthless node generated for non-pointer
1796 // values, such as integers. Consider an addition of long types: A+B.
1797 // Assuming we can track all uses of the value in this context, and it is
1798 // NOT used as a pointer, we can delete the node. We will be able to
1799 // detect this situation if the node pointed to ONLY has Unknown bit set
1800 // in the node. In this case, the node is not incomplete, does not point
1801 // to any other nodes (no mod/ref bits set), and is therefore
1802 // uninteresting for data structure analysis. If we run across one of
1803 // these, prune the scalar pointing to it.
1804 //
Chris Lattner0b144872004-01-27 22:03:40 +00001805 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1806 ScalarMap.erase(I++);
1807 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001808#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001809 N->markReachableNodes(Alive);
1810 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001811 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001812 }
Chris Lattner00948c02004-01-28 02:05:05 +00001813 }
Chris Lattnere2219762002-07-18 18:22:40 +00001814
Chris Lattner0b144872004-01-27 22:03:40 +00001815 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001816 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1817 I != E; ++I)
1818 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001819
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001820 // Mark any nodes reachable by primary calls as alive...
1821 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1822 FunctionCalls[i].markReachableNodes(Alive);
1823
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001824
1825 // Now find globals and aux call nodes that are already live or reach a live
1826 // value (which makes them live in turn), and continue till no more are found.
1827 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001828 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001829 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001830 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1831 do {
1832 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001833 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001834 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001835 // unreachable globals in the list.
1836 //
1837 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001838 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001839 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1840 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1841 Flags & DSGraph::RemoveUnreachableGlobals)) {
1842 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1843 GlobalNodes.pop_back(); // erase efficiently
1844 Iterate = true;
1845 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001846
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001847 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1848 // call nodes that get resolved will be difficult to remove from that graph.
1849 // The final unresolved call nodes must be handled specially at the end of
1850 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001851 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1852 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001853 (AuxFunctionCalls[i].isIndirectCall()
1854 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1855 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001856 AuxFunctionCalls[i].markReachableNodes(Alive);
1857 AuxFCallsAlive[i] = true;
1858 Iterate = true;
1859 }
1860 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001861
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001862 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001863 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001864 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1865 if (AuxFCallsAlive[i])
1866 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001867
1868 // Copy and merge all global nodes and dead aux call nodes into the
1869 // GlobalsGraph, and all nodes reachable from those nodes
1870 //
1871 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattner0b144872004-01-27 22:03:40 +00001872 // Copy the unreachable call nodes to the globals graph, updating their
1873 // target pointers using the GGCloner
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001874 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1875 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
Chris Lattner0b144872004-01-27 22:03:40 +00001876 GGCloner));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001877 }
1878 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001879 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1880 AuxFunctionCalls.end());
1881
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001882 // We are finally done with the GGCloner so we can destroy it.
1883 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001884
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001885 // At this point, any nodes which are visited, but not alive, are nodes
1886 // which can be removed. Loop over all nodes, eliminating completely
1887 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001888 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001889 std::vector<DSNode*> DeadNodes;
1890 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001891 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1892 DSNode *N = NI++;
1893 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1894
1895 if (!Alive.count(N)) {
1896 Nodes.remove(N);
1897 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001898 DeadNodes.push_back(N);
1899 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001900 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001901 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001902 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001903
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001904 // Remove all unreachable globals from the ScalarMap.
1905 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1906 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001907 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001908 if (!Alive.count(GlobalNodes[i].second))
1909 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001910 else
1911 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001912
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001913 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001914 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1915 delete DeadNodes[i];
1916
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001917 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001918}
1919
Chris Lattner2c7725a2004-03-03 20:55:27 +00001920void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1921 if (CS.isIndirectCall()) {
1922 AssertNodeInGraph(CS.getCalleeNode());
1923#if 0
1924 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
1925 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
1926 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
1927#endif
1928 }
1929 AssertNodeInGraph(CS.getRetVal().getNode());
1930 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
1931 AssertNodeInGraph(CS.getPtrArg(j).getNode());
1932}
1933
1934void DSGraph::AssertCallNodesInGraph() const {
1935 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1936 AssertCallSiteInGraph(FunctionCalls[i]);
1937}
1938void DSGraph::AssertAuxCallNodesInGraph() const {
1939 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1940 AssertCallSiteInGraph(AuxFunctionCalls[i]);
1941}
1942
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001943void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001944 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1945 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001946
Chris Lattner8d327672003-06-30 03:36:09 +00001947 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001948 E = ScalarMap.end(); I != E; ++I) {
1949 assert(I->second.getNode() && "Null node in scalarmap!");
1950 AssertNodeInGraph(I->second.getNode());
1951 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001952 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001953 "Global points to node, but node isn't global?");
1954 AssertNodeContainsGlobal(I->second.getNode(), GV);
1955 }
1956 }
1957 AssertCallNodesInGraph();
1958 AssertAuxCallNodesInGraph();
1959}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001960
Chris Lattner400433d2003-11-11 05:08:59 +00001961/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1962/// nodes reachable from the two graphs, computing the mapping of nodes from
1963/// the first to the second graph.
1964///
1965void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001966 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1967 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001968 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1969 if (N1 == 0 || N2 == 0) return;
1970
1971 DSNodeHandle &Entry = NodeMap[N1];
1972 if (Entry.getNode()) {
1973 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00001974 if (StrictChecking) {
1975 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
1976 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
1977 Entry.getNode()->isNodeCompletelyFolded()) &&
1978 "Inconsistent mapping detected!");
1979 }
Chris Lattner400433d2003-11-11 05:08:59 +00001980 return;
1981 }
1982
1983 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001984 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001985
1986 // Loop over all of the fields that N1 and N2 have in common, recursively
1987 // mapping the edges together now.
1988 int N2Idx = NH2.getOffset()-NH1.getOffset();
1989 unsigned N2Size = N2->getSize();
1990 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1991 if (unsigned(N2Idx)+i < N2Size)
1992 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
Chris Lattnerb1aaeee2004-03-03 05:34:31 +00001993 else
1994 computeNodeMapping(N1->getLink(i),
1995 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
Chris Lattner400433d2003-11-11 05:08:59 +00001996}