blob: 98fb07dff2d5d5b9eb47312e3d803630e5f06231 [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 Lattner4dabb2c2004-07-07 06:32:21 +000014#include "llvm/Analysis/DataStructure/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"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.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"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/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 Lattnerb29dd0f2004-12-08 21:03:56 +000030#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
31
Chris Lattner08db7192002-11-06 06:20:27 +000032namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000033 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
34 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
35 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
36 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000037 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
38 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000039};
40
Chris Lattnera88a55c2004-01-28 02:41:32 +000041#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000042#define TIME_REGION(VARNAME, DESC) \
43 NamedRegionTimer VARNAME(DESC)
44#else
45#define TIME_REGION(VARNAME, DESC)
46#endif
47
Chris Lattnerb1060432002-11-07 05:20:53 +000048using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000049
Chris Lattner6f967742004-10-30 04:05:01 +000050/// isForwarding - Return true if this NodeHandle is forwarding to another
51/// one.
52bool DSNodeHandle::isForwarding() const {
53 return N && N->isForwarding();
54}
55
Chris Lattner731b2d72003-02-13 19:09:00 +000056DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000057 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000058
59 // Handle node forwarding here!
60 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
61 Offset += N->ForwardNH.getOffset();
62
63 if (--N->NumReferrers == 0) {
64 // Removing the last referrer to the node, sever the forwarding link
65 N->stopForwarding();
66 }
67
68 N = Next;
69 N->NumReferrers++;
70 if (N->Size <= Offset) {
71 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
72 Offset = 0;
73 }
74 return N;
75}
76
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000077//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000078// DSNode Implementation
79//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000080
Chris Lattnerbd92b732003-06-19 21:15:11 +000081DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000082 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000083 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000084 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000085 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000086 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000087}
88
Chris Lattner0d9bab82002-07-18 00:12:30 +000089// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000090DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000091 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattnerf590ced2004-03-04 17:06:53 +000092 Ty(N.Ty), NodeType(N.NodeType) {
93 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +000094 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +000095 Globals = N.Globals;
96 } else
Chris Lattner0b144872004-01-27 22:03:40 +000097 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000098 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000099 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000100}
101
Chris Lattner15869aa2003-11-02 22:27:28 +0000102/// getTargetData - Get the target data object used to construct this node.
103///
104const TargetData &DSNode::getTargetData() const {
105 return ParentGraph->getTargetData();
106}
107
Chris Lattner72d29a42003-02-11 23:11:51 +0000108void DSNode::assertOK() const {
109 assert((Ty != Type::VoidTy ||
110 Ty == Type::VoidTy && (Size == 0 ||
111 (NodeType & DSNode::Array))) &&
112 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000113
114 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000115 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000116 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnera88a55c2004-01-28 02:41:32 +0000117 assert(SM.count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000118 assert(SM.find(Globals[i])->second.getNode() == this);
119 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000120}
121
122/// forwardNode - Mark this node as being obsolete, and all references to it
123/// should be forwarded to the specified node and offset.
124///
125void DSNode::forwardNode(DSNode *To, unsigned Offset) {
126 assert(this != To && "Cannot forward a node to itself!");
127 assert(ForwardNH.isNull() && "Already forwarding from this node!");
128 if (To->Size <= 1) Offset = 0;
129 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
130 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000131 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000132 NodeType = DEAD;
133 Size = 0;
134 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000135
136 // Remove this node from the parent graph's Nodes list.
137 ParentGraph->unlinkNode(this);
138 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000139}
140
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000141// addGlobal - Add an entry for a global value to the Globals list. This also
142// marks the node with the 'G' flag if it does not already have it.
143//
144void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000145 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000146 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000147 std::lower_bound(Globals.begin(), Globals.end(), GV);
148
149 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000150 Globals.insert(I, GV);
151 NodeType |= GlobalNode;
152 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000153}
154
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000155/// foldNodeCompletely - If we determine that this node has some funny
156/// behavior happening to it that we cannot represent, we fold it down to a
157/// single, completely pessimistic, node. This node is represented as a
158/// single byte with a single TypeEntry of "void".
159///
160void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000161 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000162
Chris Lattner08db7192002-11-06 06:20:27 +0000163 ++NumFolds;
164
Chris Lattner0b144872004-01-27 22:03:40 +0000165 // If this node has a size that is <= 1, we don't need to create a forwarding
166 // node.
167 if (getSize() <= 1) {
168 NodeType |= DSNode::Array;
169 Ty = Type::VoidTy;
170 Size = 1;
171 assert(Links.size() <= 1 && "Size is 1, but has more links?");
172 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000173 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000174 // Create the node we are going to forward to. This is required because
175 // some referrers may have an offset that is > 0. By forcing them to
176 // forward, the forwarder has the opportunity to correct the offset.
177 DSNode *DestNode = new DSNode(0, ParentGraph);
178 DestNode->NodeType = NodeType|DSNode::Array;
179 DestNode->Ty = Type::VoidTy;
180 DestNode->Size = 1;
181 DestNode->Globals.swap(Globals);
182
183 // Start forwarding to the destination node...
184 forwardNode(DestNode, 0);
185
186 if (!Links.empty()) {
187 DestNode->Links.reserve(1);
188
189 DSNodeHandle NH(DestNode);
190 DestNode->Links.push_back(Links[0]);
191
192 // If we have links, merge all of our outgoing links together...
193 for (unsigned i = Links.size()-1; i != 0; --i)
194 NH.getNode()->Links[0].mergeWith(Links[i]);
195 Links.clear();
196 } else {
197 DestNode->Links.resize(1);
198 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000199 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000200}
Chris Lattner076c1f92002-11-07 06:31:54 +0000201
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000202/// isNodeCompletelyFolded - Return true if this node has been completely
203/// folded down to something that can never be expanded, effectively losing
204/// all of the field sensitivity that may be present in the node.
205///
206bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000207 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000208}
209
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000210namespace {
211 /// TypeElementWalker Class - Used for implementation of physical subtyping...
212 ///
213 class TypeElementWalker {
214 struct StackState {
215 const Type *Ty;
216 unsigned Offset;
217 unsigned Idx;
218 StackState(const Type *T, unsigned Off = 0)
219 : Ty(T), Offset(Off), Idx(0) {}
220 };
221
222 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000223 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000224 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000225 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000226 Stack.push_back(T);
227 StepToLeaf();
228 }
229
230 bool isDone() const { return Stack.empty(); }
231 const Type *getCurrentType() const { return Stack.back().Ty; }
232 unsigned getCurrentOffset() const { return Stack.back().Offset; }
233
234 void StepToNextType() {
235 PopStackAndAdvance();
236 StepToLeaf();
237 }
238
239 private:
240 /// PopStackAndAdvance - Pop the current element off of the stack and
241 /// advance the underlying element to the next contained member.
242 void PopStackAndAdvance() {
243 assert(!Stack.empty() && "Cannot pop an empty stack!");
244 Stack.pop_back();
245 while (!Stack.empty()) {
246 StackState &SS = Stack.back();
247 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
248 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000249 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000250 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattner507bdf92005-01-12 04:51:37 +0000251 SS.Offset +=
252 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000253 return;
254 }
255 Stack.pop_back(); // At the end of the structure
256 } else {
257 const ArrayType *AT = cast<ArrayType>(SS.Ty);
258 ++SS.Idx;
259 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000260 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000261 return;
262 }
263 Stack.pop_back(); // At the end of the array
264 }
265 }
266 }
267
268 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
269 /// on the type stack.
270 void StepToLeaf() {
271 if (Stack.empty()) return;
272 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
273 StackState &SS = Stack.back();
274 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000275 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000276 assert(SS.Idx == 0);
277 PopStackAndAdvance();
278 } else {
279 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000280 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000281 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000282 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000283 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000284 }
285 } else {
286 const ArrayType *AT = cast<ArrayType>(SS.Ty);
287 if (AT->getNumElements() == 0) {
288 assert(SS.Idx == 0);
289 PopStackAndAdvance();
290 } else {
291 // Step into the array...
292 assert(SS.Idx < AT->getNumElements());
293 Stack.push_back(StackState(AT->getElementType(),
294 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000295 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000296 }
297 }
298 }
299 }
300 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000301} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000302
303/// ElementTypesAreCompatible - Check to see if the specified types are
304/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000305/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
306/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000307///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000308static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000309 bool AllowLargerT1, const TargetData &TD){
310 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000311
312 while (!T1W.isDone() && !T2W.isDone()) {
313 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
314 return false;
315
316 const Type *T1 = T1W.getCurrentType();
317 const Type *T2 = T2W.getCurrentType();
318 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
319 return false;
320
321 T1W.StepToNextType();
322 T2W.StepToNextType();
323 }
324
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000325 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000326}
327
328
Chris Lattner08db7192002-11-06 06:20:27 +0000329/// mergeTypeInfo - This method merges the specified type into the current node
330/// at the specified offset. This may update the current node's type record if
331/// this gives more information to the node, it may do nothing to the node if
332/// this information is already known, or it may merge the node completely (and
333/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000334///
Chris Lattner08db7192002-11-06 06:20:27 +0000335/// This method returns true if the node is completely folded, otherwise false.
336///
Chris Lattner088b6392003-03-03 17:13:31 +0000337bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
338 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000339 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000340 // Check to make sure the Size member is up-to-date. Size can be one of the
341 // following:
342 // Size = 0, Ty = Void: Nothing is known about this node.
343 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
344 // Size = 1, Ty = Void, Array = 1: The node is collapsed
345 // Otherwise, sizeof(Ty) = Size
346 //
Chris Lattner18552922002-11-18 21:44:46 +0000347 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
348 (Size == 0 && !Ty->isSized() && !isArray()) ||
349 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
350 (Size == 0 && !Ty->isSized() && !isArray()) ||
351 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000352 "Size member of DSNode doesn't match the type structure!");
353 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000354
Chris Lattner18552922002-11-18 21:44:46 +0000355 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000356 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000357
Chris Lattner08db7192002-11-06 06:20:27 +0000358 // Return true immediately if the node is completely folded.
359 if (isNodeCompletelyFolded()) return true;
360
Chris Lattner23f83dc2002-11-08 22:49:57 +0000361 // If this is an array type, eliminate the outside arrays because they won't
362 // be used anyway. This greatly reduces the size of large static arrays used
363 // as global variables, for example.
364 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000365 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000366 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
367 // FIXME: we might want to keep small arrays, but must be careful about
368 // things like: [2 x [10000 x int*]]
369 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000370 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000371 }
372
Chris Lattner08db7192002-11-06 06:20:27 +0000373 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000374 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000375
376 // Otherwise check to see if we can fold this type into the current node. If
377 // we can't, we fold the node completely, if we can, we potentially update our
378 // internal state.
379 //
Chris Lattner18552922002-11-18 21:44:46 +0000380 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000381 // If this is the first type that this node has seen, just accept it without
382 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000383 assert(Offset == 0 && !isArray() &&
384 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000385 Ty = NewTy;
386 NodeType &= ~Array;
387 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000388 Size = NewTySize;
389
390 // Calculate the number of outgoing links from this node.
391 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
392 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000393 }
Chris Lattner08db7192002-11-06 06:20:27 +0000394
395 // Handle node expansion case here...
396 if (Offset+NewTySize > Size) {
397 // It is illegal to grow this node if we have treated it as an array of
398 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000399 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000400 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000401 return true;
402 }
403
404 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000405 std::cerr << "UNIMP: Trying to merge a growth type into "
406 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000407 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000408 return true;
409 }
410
411 // Okay, the situation is nice and simple, we are trying to merge a type in
412 // at offset 0 that is bigger than our current type. Implement this by
413 // switching to the new type and then merge in the smaller one, which should
414 // hit the other code path here. If the other code path decides it's not
415 // ok, it will collapse the node as appropriate.
416 //
Chris Lattner18552922002-11-18 21:44:46 +0000417 const Type *OldTy = Ty;
418 Ty = NewTy;
419 NodeType &= ~Array;
420 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000421 Size = NewTySize;
422
423 // Must grow links to be the appropriate size...
424 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
425
426 // Merge in the old type now... which is guaranteed to be smaller than the
427 // "current" type.
428 return mergeTypeInfo(OldTy, 0);
429 }
430
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000431 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000432 "Cannot merge something into a part of our type that doesn't exist!");
433
Chris Lattner18552922002-11-18 21:44:46 +0000434 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000435 // type that starts at offset Offset.
436 //
437 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000438 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000439 while (O < Offset) {
440 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
441
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000442 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000443 case Type::StructTyID: {
444 const StructType *STy = cast<StructType>(SubType);
445 const StructLayout &SL = *TD.getStructLayout(STy);
446
447 unsigned i = 0, e = SL.MemberOffsets.size();
448 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
449 /* empty */;
450
451 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000452 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000453 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000454 break;
455 }
456 case Type::ArrayTyID: {
457 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000458 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000459 unsigned Remainder = (Offset-O) % ElSize;
460 O = Offset-Remainder;
461 break;
462 }
463 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000464 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000465 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000466 }
467 }
468
469 assert(O == Offset && "Could not achieve the correct offset!");
470
471 // If we found our type exactly, early exit
472 if (SubType == NewTy) return false;
473
Misha Brukman96a8bd72004-04-29 04:05:30 +0000474 // Differing function types don't require us to merge. They are not values
475 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000476 if (isa<FunctionType>(SubType) &&
477 isa<FunctionType>(NewTy)) return false;
478
Chris Lattner507bdf92005-01-12 04:51:37 +0000479 unsigned SubTypeSize = SubType->isSized() ?
480 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000481
482 // Ok, we are getting desperate now. Check for physical subtyping, where we
483 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000484 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000485 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000486 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000487 return false;
488
Chris Lattner08db7192002-11-06 06:20:27 +0000489 // Okay, so we found the leader type at the offset requested. Search the list
490 // of types that starts at this offset. If SubType is currently an array or
491 // structure, the type desired may actually be the first element of the
492 // composite type...
493 //
Chris Lattner18552922002-11-18 21:44:46 +0000494 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000495 while (SubType != NewTy) {
496 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000497 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000498 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000499 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000500 case Type::StructTyID: {
501 const StructType *STy = cast<StructType>(SubType);
502 const StructLayout &SL = *TD.getStructLayout(STy);
503 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000504 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000505 else
506 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000507 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000508 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000509 break;
Chris Lattner18552922002-11-18 21:44:46 +0000510 }
Chris Lattner08db7192002-11-06 06:20:27 +0000511 case Type::ArrayTyID:
512 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000513 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000514 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000515 break;
516 default: ;
517 // fall out
518 }
519
520 if (NextSubType == 0)
521 break; // In the default case, break out of the loop
522
Chris Lattner18552922002-11-18 21:44:46 +0000523 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000524 break; // Don't allow shrinking to a smaller type than NewTySize
525 SubType = NextSubType;
526 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000527 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000528 }
529
530 // If we found the type exactly, return it...
531 if (SubType == NewTy)
532 return false;
533
534 // Check to see if we have a compatible, but different type...
535 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000536 // Check to see if this type is obviously convertible... int -> uint f.e.
537 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000538 return false;
539
540 // Check to see if we have a pointer & integer mismatch going on here,
541 // loading a pointer as a long, for example.
542 //
543 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
544 NewTy->isInteger() && isa<PointerType>(SubType))
545 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000546 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
547 // We are accessing the field, plus some structure padding. Ignore the
548 // structure padding.
549 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000550 }
551
Chris Lattner58f98d02003-07-02 04:38:49 +0000552 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000553 if (getParentGraph()->getReturnNodes().size())
554 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000555 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
556 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
557 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
558 << "SubType: ";
559 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000560
Chris Lattner088b6392003-03-03 17:13:31 +0000561 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000562 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000563}
564
Chris Lattner08db7192002-11-06 06:20:27 +0000565
566
Misha Brukman96a8bd72004-04-29 04:05:30 +0000567/// addEdgeTo - Add an edge from the current node to the specified node. This
568/// can cause merging of nodes in the graph.
569///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000570void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000571 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000572
Chris Lattner08db7192002-11-06 06:20:27 +0000573 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000574 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000575 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000576 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000577 } else { // No merging to perform...
578 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000579 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000580}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000581
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000582
Misha Brukman96a8bd72004-04-29 04:05:30 +0000583/// MergeSortedVectors - Efficiently merge a vector into another vector where
584/// duplicates are not allowed and both are sorted. This assumes that 'T's are
585/// efficiently copyable and have sane comparison semantics.
586///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000587static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
588 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000589 // By far, the most common cases will be the simple ones. In these cases,
590 // avoid having to allocate a temporary vector...
591 //
592 if (Src.empty()) { // Nothing to merge in...
593 return;
594 } else if (Dest.empty()) { // Just copy the result in...
595 Dest = Src;
596 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000597 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000598 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000599 std::lower_bound(Dest.begin(), Dest.end(), V);
600 if (I == Dest.end() || *I != Src[0]) // If not already contained...
601 Dest.insert(I, Src[0]);
602 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000603 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000604 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000605 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000606 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
607 if (I == Dest.end() || *I != Tmp) // If not already contained...
608 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000609
610 } else {
611 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000612 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000613
614 // Make space for all of the type entries now...
615 Dest.resize(Dest.size()+Src.size());
616
617 // Merge the two sorted ranges together... into Dest.
618 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
619
620 // Now erase any duplicate entries that may have accumulated into the
621 // vectors (because they were in both of the input sets)
622 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
623 }
624}
625
Chris Lattner0b144872004-01-27 22:03:40 +0000626void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
627 MergeSortedVectors(Globals, RHS);
628}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000629
Chris Lattner0b144872004-01-27 22:03:40 +0000630// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000631// This function does the hard work of merging two nodes, CurNodeH
632// and NH after filtering out trivial cases and making sure that
633// CurNodeH.offset >= NH.offset.
634//
635// ***WARNING***
636// Since merging may cause either node to go away, we must always
637// use the node-handles to refer to the nodes. These node handles are
638// automatically updated during merging, so will always provide access
639// to the correct node after a merge.
640//
641void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
642 assert(CurNodeH.getOffset() >= NH.getOffset() &&
643 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000644 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
645 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000646
647 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
648 // respect to NH.Offset) is now zero. NOffset is the distance from the base
649 // of our object that N starts from.
650 //
651 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
652 unsigned NSize = NH.getNode()->getSize();
653
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000654 // If the two nodes are of different size, and the smaller node has the array
655 // bit set, collapse!
656 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000657#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000658 if (NSize < CurNodeH.getNode()->getSize()) {
659 if (NH.getNode()->isArray())
660 NH.getNode()->foldNodeCompletely();
661 } else if (CurNodeH.getNode()->isArray()) {
662 NH.getNode()->foldNodeCompletely();
663 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000664#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000665 }
666
667 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000668 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000669 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000670 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000671
672 // If we are merging a node with a completely folded node, then both nodes are
673 // now completely folded.
674 //
675 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
676 if (!NH.getNode()->isNodeCompletelyFolded()) {
677 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000678 assert(NH.getNode() && NH.getOffset() == 0 &&
679 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000680 NOffset = NH.getOffset();
681 NSize = NH.getNode()->getSize();
682 assert(NOffset == 0 && NSize == 1);
683 }
684 } else if (NH.getNode()->isNodeCompletelyFolded()) {
685 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000686 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
687 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000688 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000689 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000690 assert(NOffset == 0 && NSize == 1);
691 }
692
Chris Lattner72d29a42003-02-11 23:11:51 +0000693 DSNode *N = NH.getNode();
694 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000695 assert(!CurNodeH.getNode()->isDeadNode());
696
Chris Lattner0b144872004-01-27 22:03:40 +0000697 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000698 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000699
Chris Lattner72d29a42003-02-11 23:11:51 +0000700 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000701 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000702 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000703
Chris Lattner72d29a42003-02-11 23:11:51 +0000704 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
705 //
706 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
707 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000708 if (Link.getNode()) {
709 // Compute the offset into the current node at which to
710 // merge this link. In the common case, this is a linear
711 // relation to the offset in the original node (with
712 // wrapping), but if the current node gets collapsed due to
713 // recursive merging, we must make sure to merge in all remaining
714 // links at offset zero.
715 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000716 DSNode *CN = CurNodeH.getNode();
717 if (CN->Size != 1)
718 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
719 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000720 }
721 }
722
723 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000724 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000725
726 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000727 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000728 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000729
730 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000731 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000732 }
733}
734
735
Misha Brukman96a8bd72004-04-29 04:05:30 +0000736/// mergeWith - Merge this node and the specified node, moving all links to and
737/// from the argument node into the current node, deleting the node argument.
738/// Offset indicates what offset the specified node is to be merged into the
739/// current node.
740///
741/// The specified node may be a null pointer (in which case, we update it to
742/// point to this node).
743///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000744void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
745 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000746 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000747 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000748
Chris Lattner5254a8d2004-01-22 16:31:08 +0000749 // If the RHS is a null node, make it point to this node!
750 if (N == 0) {
751 NH.mergeWith(DSNodeHandle(this, Offset));
752 return;
753 }
754
Chris Lattnerbd92b732003-06-19 21:15:11 +0000755 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000756 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
757
Chris Lattner02606632002-11-04 06:48:26 +0000758 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000759 // We cannot merge two pieces of the same node together, collapse the node
760 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000761 DEBUG(std::cerr << "Attempting to merge two chunks of"
762 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000763 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000764 return;
765 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000766
Chris Lattner5190ce82002-11-12 07:20:45 +0000767 // If both nodes are not at offset 0, make sure that we are merging the node
768 // at an later offset into the node with the zero offset.
769 //
770 if (Offset < NH.getOffset()) {
771 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
772 return;
773 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
774 // If the offsets are the same, merge the smaller node into the bigger node
775 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
776 return;
777 }
778
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000779 // Ok, now we can merge the two nodes. Use a static helper that works with
780 // two node handles, since "this" may get merged away at intermediate steps.
781 DSNodeHandle CurNodeH(this, Offset);
782 DSNodeHandle NHCopy(NH);
783 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000784}
785
Chris Lattner0b144872004-01-27 22:03:40 +0000786
787//===----------------------------------------------------------------------===//
788// ReachabilityCloner Implementation
789//===----------------------------------------------------------------------===//
790
791DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
792 if (SrcNH.isNull()) return DSNodeHandle();
793 const DSNode *SN = SrcNH.getNode();
794
795 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000796 if (!NH.isNull()) { // Node already mapped?
797 DSNode *NHN = NH.getNode();
798 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
799 }
Chris Lattner0b144872004-01-27 22:03:40 +0000800
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000801 // If SrcNH has globals and the destination graph has one of the same globals,
802 // merge this node with the destination node, which is much more efficient.
803 if (SN->global_begin() != SN->global_end()) {
804 DSScalarMap &DestSM = Dest.getScalarMap();
805 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
806 I != E; ++I) {
807 GlobalValue *GV = *I;
808 DSScalarMap::iterator GI = DestSM.find(GV);
809 if (GI != DestSM.end() && !GI->second.isNull()) {
810 // We found one, use merge instead!
811 merge(GI->second, Src.getNodeForValue(GV));
812 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000813 DSNode *NHN = NH.getNode();
814 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000815 }
816 }
817 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000818
Chris Lattner0b144872004-01-27 22:03:40 +0000819 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
820 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000821 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000822
823 // Next, recursively clone all outgoing links as necessary. Note that
824 // adding these links can cause the node to collapse itself at any time, and
825 // the current node may be merged with arbitrary other nodes. For this
826 // reason, we must always go through NH.
827 DN = 0;
828 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
829 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
830 if (!SrcEdge.isNull()) {
831 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
832 // Compute the offset into the current node at which to
833 // merge this link. In the common case, this is a linear
834 // relation to the offset in the original node (with
835 // wrapping), but if the current node gets collapsed due to
836 // recursive merging, we must make sure to merge in all remaining
837 // links at offset zero.
838 unsigned MergeOffset = 0;
839 DSNode *CN = NH.getNode();
840 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000841 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000842 CN->addEdgeTo(MergeOffset, DestEdge);
843 }
844 }
845
846 // If this node contains any globals, make sure they end up in the scalar
847 // map with the correct offset.
848 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
849 I != E; ++I) {
850 GlobalValue *GV = *I;
851 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
852 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
853 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
854 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000855 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000856
857 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
858 Dest.getInlinedGlobals().insert(GV);
859 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000860 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000861
862 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
863}
864
865void ReachabilityCloner::merge(const DSNodeHandle &NH,
866 const DSNodeHandle &SrcNH) {
867 if (SrcNH.isNull()) return; // Noop
868 if (NH.isNull()) {
869 // If there is no destination node, just clone the source and assign the
870 // destination node to be it.
871 NH.mergeWith(getClonedNH(SrcNH));
872 return;
873 }
874
875 // Okay, at this point, we know that we have both a destination and a source
876 // node that need to be merged. Check to see if the source node has already
877 // been cloned.
878 const DSNode *SN = SrcNH.getNode();
879 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000880 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000881 DSNode *SCNHN = SCNH.getNode();
882 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000883 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000884 return; // Nothing to do!
885 }
Chris Lattner6f967742004-10-30 04:05:01 +0000886
Chris Lattner0b144872004-01-27 22:03:40 +0000887 // Okay, so the source node has not already been cloned. Instead of creating
888 // a new DSNode, only to merge it into the one we already have, try to perform
889 // the merge in-place. The only case we cannot handle here is when the offset
890 // into the existing node is less than the offset into the virtual node we are
891 // merging in. In this case, we have to extend the existing node, which
892 // requires an allocation anyway.
893 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
894 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000895 if (!DN->isNodeCompletelyFolded()) {
896 // Make sure the destination node is folded if the source node is folded.
897 if (SN->isNodeCompletelyFolded()) {
898 DN->foldNodeCompletely();
899 DN = NH.getNode();
900 } else if (SN->getSize() != DN->getSize()) {
901 // If the two nodes are of different size, and the smaller node has the
902 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000903#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000904 if (SN->getSize() < DN->getSize()) {
905 if (SN->isArray()) {
906 DN->foldNodeCompletely();
907 DN = NH.getNode();
908 }
909 } else if (DN->isArray()) {
910 DN->foldNodeCompletely();
911 DN = NH.getNode();
912 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000913#endif
Chris Lattner0b144872004-01-27 22:03:40 +0000914 }
915
916 // Merge the type entries of the two nodes together...
917 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
918 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
919 DN = NH.getNode();
920 }
921 }
922
923 assert(!DN->isDeadNode());
924
925 // Merge the NodeType information.
926 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
927
928 // Before we start merging outgoing links and updating the scalar map, make
929 // sure it is known that this is the representative node for the src node.
930 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
931
932 // If the source node contains any globals, make sure they end up in the
933 // scalar map with the correct offset.
934 if (SN->global_begin() != SN->global_end()) {
935 // Update the globals in the destination node itself.
936 DN->mergeGlobals(SN->getGlobals());
937
938 // Update the scalar map for the graph we are merging the source node
939 // into.
940 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
941 I != E; ++I) {
942 GlobalValue *GV = *I;
943 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
944 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
945 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
946 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +0000947 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000948
949 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
950 Dest.getInlinedGlobals().insert(GV);
951 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000952 NH.getNode()->mergeGlobals(SN->getGlobals());
Chris Lattner0b144872004-01-27 22:03:40 +0000953 }
954 } else {
955 // We cannot handle this case without allocating a temporary node. Fall
956 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +0000957 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
958 NewDN->maskNodeTypes(BitsToKeep);
959
960 unsigned NHOffset = NH.getOffset();
961 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +0000962
Chris Lattner0b144872004-01-27 22:03:40 +0000963 assert(NH.getNode() &&
964 (NH.getOffset() > NHOffset ||
965 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
966 "Merging did not adjust the offset!");
967
968 // Before we start merging outgoing links and updating the scalar map, make
969 // sure it is known that this is the representative node for the src node.
970 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +0000971
972 // If the source node contained any globals, make sure to create entries
973 // in the scalar map for them!
974 for (DSNode::global_iterator I = SN->global_begin(), E = SN->global_end();
975 I != E; ++I) {
976 GlobalValue *GV = *I;
977 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
978 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
979 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
980 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
981 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
982 DestGNH.getOffset()+SrcGNH.getOffset()));
983
984 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
985 Dest.getInlinedGlobals().insert(GV);
986 }
Chris Lattner0b144872004-01-27 22:03:40 +0000987 }
988
989
990 // Next, recursively merge all outgoing links as necessary. Note that
991 // adding these links can cause the destination node to collapse itself at
992 // any time, and the current node may be merged with arbitrary other nodes.
993 // For this reason, we must always go through NH.
994 DN = 0;
995 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
996 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
997 if (!SrcEdge.isNull()) {
998 // Compute the offset into the current node at which to
999 // merge this link. In the common case, this is a linear
1000 // relation to the offset in the original node (with
1001 // wrapping), but if the current node gets collapsed due to
1002 // recursive merging, we must make sure to merge in all remaining
1003 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001004 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001005 unsigned MergeOffset =
1006 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001007
Chris Lattnerf590ced2004-03-04 17:06:53 +00001008 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1009 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001010 // Perform the recursive merging. Make sure to create a temporary NH,
1011 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001012 merge(Tmp, SrcEdge);
1013 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001014 Tmp.mergeWith(getClonedNH(SrcEdge));
1015 // Merging this could cause all kinds of recursive things to happen,
1016 // culminating in the current node being eliminated. Since this is
1017 // possible, make sure to reaquire the link from 'CN'.
1018
1019 unsigned MergeOffset = 0;
1020 CN = SCNH.getNode();
1021 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1022 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001023 }
Chris Lattner0b144872004-01-27 22:03:40 +00001024 }
1025 }
1026}
1027
1028/// mergeCallSite - Merge the nodes reachable from the specified src call
1029/// site into the nodes reachable from DestCS.
1030void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1031 const DSCallSite &SrcCS) {
1032 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1033 unsigned MinArgs = DestCS.getNumPtrArgs();
1034 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1035
1036 for (unsigned a = 0; a != MinArgs; ++a)
1037 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1038}
1039
1040
Chris Lattner9de906c2002-10-20 22:11:44 +00001041//===----------------------------------------------------------------------===//
1042// DSCallSite Implementation
1043//===----------------------------------------------------------------------===//
1044
Vikram S. Adve26b98262002-10-20 21:41:02 +00001045// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001046Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001047 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001048}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001049
Chris Lattner0b144872004-01-27 22:03:40 +00001050void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1051 ReachabilityCloner &RC) {
1052 NH = RC.getClonedNH(Src);
1053}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001054
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001055//===----------------------------------------------------------------------===//
1056// DSGraph Implementation
1057//===----------------------------------------------------------------------===//
1058
Chris Lattnera9d65662003-06-30 05:57:30 +00001059/// getFunctionNames - Return a space separated list of the name of the
1060/// functions in this graph (if any)
1061std::string DSGraph::getFunctionNames() const {
1062 switch (getReturnNodes().size()) {
1063 case 0: return "Globals graph";
1064 case 1: return getReturnNodes().begin()->first->getName();
1065 default:
1066 std::string Return;
1067 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
1068 I != getReturnNodes().end(); ++I)
1069 Return += I->first->getName() + " ";
1070 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1071 return Return;
1072 }
1073}
1074
1075
Chris Lattner15869aa2003-11-02 22:27:28 +00001076DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001077 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001078 NodeMapTy NodeMap;
1079 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001080}
1081
Chris Lattner5a540632003-06-30 03:15:25 +00001082DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +00001083 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001084 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001085 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001086}
1087
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001088DSGraph::~DSGraph() {
1089 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001090 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001091 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001092 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001093 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001094
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001095 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001096 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
1097 (*NI)->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001098
Chris Lattner28897e12004-02-08 00:53:26 +00001099 // Free all of the nodes.
1100 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001101}
1102
Chris Lattner0d9bab82002-07-18 00:12:30 +00001103// dump - Allow inspection of graph in a debugger.
1104void DSGraph::dump() const { print(std::cerr); }
1105
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001106
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001107/// remapLinks - Change all of the Links in the current node according to the
1108/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001109///
Chris Lattner8d327672003-06-30 03:36:09 +00001110void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001111 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1112 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001113 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001114 if (ONMI != OldNodeMap.end()) {
1115 DSNode *ONMIN = ONMI->second.getNode();
1116 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1117 }
Chris Lattner2f561382004-01-22 16:56:13 +00001118 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001119}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001120
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001121/// updateFromGlobalGraph - This function rematerializes global nodes and
1122/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001123/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1124/// are already up-to-date in the current graph. In practice, in the TD pass,
1125/// this is likely to be a large fraction of the live global nodes in each
1126/// function (since most live nodes are likely to have been brought up-to-date
1127/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001128///
1129void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001130 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001131 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1132
1133 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001134 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1135 E = getScalarMap().global_end(); I != E; ++I)
1136 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001137 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001138 if (It != GlobalsGraph->ScalarMap.end())
1139 RC.merge(getNodeForValue(*I), It->second);
1140 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001141}
1142
Chris Lattnerd672ab92005-02-15 18:40:55 +00001143/// addObjectToGraph - This method can be used to add global, stack, and heap
1144/// objects to the graph. This can be used when updating DSGraphs due to the
1145/// introduction of new temporary objects. The new object is not pointed to
1146/// and does not point to any other objects in the graph.
1147DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1148 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1149 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1150 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001151 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001152 ScalarMap[Ptr] = N;
1153
1154 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1155 N->addGlobal(GV);
1156 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1157 N->setHeapNodeMarker();
1158 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1159 N->setAllocaNodeMarker();
1160 } else {
1161 assert(0 && "Illegal memory object input!");
1162 }
1163 return N;
1164}
1165
1166
Chris Lattner5a540632003-06-30 03:15:25 +00001167/// cloneInto - Clone the specified DSGraph into the current graph. The
1168/// translated ScalarMap for the old function is filled into the OldValMap
1169/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1170///
1171/// The CloneFlags member controls various aspects of the cloning process.
1172///
Chris Lattner62482e52004-01-28 09:15:42 +00001173void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001174 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1175 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001176 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001177 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001178 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001179
Chris Lattner1e883692003-02-03 20:08:51 +00001180 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001181 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1182 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1183 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001184 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001185
Chris Lattnerd85645f2004-02-21 22:28:26 +00001186 for (node_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1187 assert(!(*I)->isForwarding() &&
1188 "Forward nodes shouldn't be in node list!");
1189 DSNode *New = new DSNode(**I, this);
1190 New->maskNodeTypes(~BitsToClear);
1191 OldNodeMap[*I] = New;
1192 }
1193
Chris Lattner18552922002-11-18 21:44:46 +00001194#ifndef NDEBUG
1195 Timer::addPeakMemoryMeasurement();
1196#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001197
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001198 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001199 // Note that we don't loop over the node's list to do this. The problem is
1200 // that remaping links can cause recursive merging to happen, which means
1201 // that node_iterator's can get easily invalidated! Because of this, we
1202 // loop over the OldNodeMap, which contains all of the new nodes as the
1203 // .second element of the map elements. Also note that if we remap a node
1204 // more than once, we won't break anything.
1205 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1206 I != E; ++I)
1207 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001208
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001209 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001210 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001211 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001212 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001213 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner6f967742004-10-30 04:05:01 +00001214 DSNode *MappedNodeN = MappedNode.getNode();
1215 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001216 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001217
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001218 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001219 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1220 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001221 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1222 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001223 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001224 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001225
Chris Lattner679e8e12002-11-08 21:27:12 +00001226 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001227 // Copy the function calls list.
1228 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1229 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001230 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001231
Chris Lattneracf491f2002-11-08 22:27:09 +00001232 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001233 // Copy the auxiliary function calls list.
1234 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1235 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001236 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001237
Chris Lattner5a540632003-06-30 03:15:25 +00001238 // Map the return node pointers over...
1239 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1240 E = G.getReturnNodes().end(); I != E; ++I) {
1241 const DSNodeHandle &Ret = I->second;
1242 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001243 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattner5a540632003-06-30 03:15:25 +00001244 OldReturnNodes.insert(std::make_pair(I->first,
Chris Lattner6f967742004-10-30 04:05:01 +00001245 DSNodeHandle(MappedRetN,
Chris Lattner5a540632003-06-30 03:15:25 +00001246 MappedRet.getOffset()+Ret.getOffset())));
1247 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001248}
1249
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001250static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001251 if (N)
1252 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1253 if (RC.hasClonedNode(*I))
1254 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001255 return false;
1256}
1257
Chris Lattner2f346902004-03-04 03:57:53 +00001258static bool PathExistsToClonedNode(const DSCallSite &CS,
1259 ReachabilityCloner &RC) {
1260 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1261 return true;
1262 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1263 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1264 return true;
1265 return false;
1266}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001267
Chris Lattnerbb753c42005-02-03 18:40:25 +00001268/// getFunctionArgumentsForCall - Given a function that is currently in this
1269/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1270/// function arguments. The vector is filled in with the return value (or
1271/// null if it is not pointer compatible), followed by all of the
1272/// pointer-compatible arguments.
1273void DSGraph::getFunctionArgumentsForCall(Function *F,
1274 std::vector<DSNodeHandle> &Args) const {
1275 Args.push_back(getReturnNodeFor(*F));
1276 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1277 if (isPointerType(AI->getType())) {
1278 Args.push_back(getNodeForValue(AI));
1279 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1280 }
1281}
1282
Chris Lattnere8594442005-02-04 19:58:28 +00001283/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1284/// nodes from G2 into 'this' graph, merging the bindings specified by the
1285/// call site (in this graph) with the bindings specified by the vector in G2.
1286/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001287///
Chris Lattnere8594442005-02-04 19:58:28 +00001288void DSGraph::mergeInGraph(const DSCallSite &CS,
1289 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001290 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001291 TIME_REGION(X, "mergeInGraph");
1292
Chris Lattner076c1f92002-11-07 06:31:54 +00001293 // If this is not a recursive call, clone the graph into this graph...
1294 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001295 // Clone the callee's graph into the current graph, keeping track of where
1296 // scalars in the old graph _used_ to point, and of the new nodes matching
1297 // nodes of the old graph.
1298 ReachabilityCloner RC(*this, Graph, CloneFlags);
1299
Chris Lattner0b144872004-01-27 22:03:40 +00001300 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001301 if (!CS.getRetVal().isNull())
Chris Lattnerbb753c42005-02-03 18:40:25 +00001302 RC.merge(CS.getRetVal(), Args[0]);
Chris Lattnerf590ced2004-03-04 17:06:53 +00001303
Chris Lattnerbb753c42005-02-03 18:40:25 +00001304 // Map over all of the arguments.
1305 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001306 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001307 break;
Chris Lattnerbb753c42005-02-03 18:40:25 +00001308
1309 // Add the link from the argument scalar to the provided value.
1310 RC.merge(CS.getPtrArg(i), Args[i+1]);
1311 }
1312
Chris Lattner2f346902004-03-04 03:57:53 +00001313 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001314 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001315 // Copy the function calls list.
1316 for (fc_iterator I = Graph.fc_begin(), E = Graph.fc_end(); I != E; ++I)
1317 FunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner0b144872004-01-27 22:03:40 +00001318 }
Chris Lattner2f346902004-03-04 03:57:53 +00001319
1320 // If the user has us copying aux calls (the normal case), set up a data
1321 // structure to keep track of which ones we've copied over.
Chris Lattnera9548d92005-01-30 23:51:02 +00001322 std::set<const DSCallSite*> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001323
Chris Lattner0321b682004-02-27 20:05:15 +00001324 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001325 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001326 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1327 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1328 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1329 if (ScalarMap.count(GV))
1330 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001331 else
1332 NonCopiedGlobals.insert(GV);
1333
1334 // If the global does not appear in the callers graph we generally don't
1335 // want to copy the node. However, if there is a path from the node global
1336 // node to a node that we did copy in the graph, we *must* copy it to
1337 // maintain the connection information. Every time we decide to include a
1338 // new global, this might make other globals live, so we must iterate
1339 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001340 bool MadeChange = true;
1341 while (MadeChange) {
1342 MadeChange = false;
1343 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1344 I != NonCopiedGlobals.end();) {
1345 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1346 if (RC.hasClonedNode(GlobalNode)) {
1347 // Already cloned it, remove from set.
1348 NonCopiedGlobals.erase(I++);
1349 MadeChange = true;
1350 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1351 RC.getClonedNH(Graph.getNodeForValue(*I));
1352 NonCopiedGlobals.erase(I++);
1353 MadeChange = true;
1354 } else {
1355 ++I;
1356 }
1357 }
1358
1359 // If requested, copy any aux calls that can reach copied nodes.
1360 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001361 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1362 if (CopiedAuxCall.insert(&*I).second &&
1363 PathExistsToClonedNode(*I, RC)) {
1364 AuxFunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner2f346902004-03-04 03:57:53 +00001365 MadeChange = true;
1366 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001367 }
1368 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001369
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001370 } else {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001371 // Merge the return value with the return value of the context.
1372 Args[0].mergeWith(CS.getRetVal());
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001373
Chris Lattnerbb753c42005-02-03 18:40:25 +00001374 // Resolve all of the function arguments.
1375 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001376 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001377 break;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001378
Chris Lattnerbb753c42005-02-03 18:40:25 +00001379 // Add the link from the argument scalar to the provided value.
1380 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001381 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001382 }
1383}
1384
Chris Lattnere8594442005-02-04 19:58:28 +00001385
1386
1387/// mergeInGraph - The method is used for merging graphs together. If the
1388/// argument graph is not *this, it makes a clone of the specified graph, then
1389/// merges the nodes specified in the call site with the formal arguments in the
1390/// graph.
1391///
1392void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1393 const DSGraph &Graph, unsigned CloneFlags) {
1394 // Fastpath for a noop inline.
1395 if (CS.getNumPtrArgs() == 0 && CS.getRetVal().isNull())
1396 return;
1397
1398 // Set up argument bindings.
1399 std::vector<DSNodeHandle> Args;
1400 Graph.getFunctionArgumentsForCall(&F, Args);
1401
1402 mergeInGraph(CS, Args, Graph, CloneFlags);
1403}
1404
Chris Lattner58f98d02003-07-02 04:38:49 +00001405/// getCallSiteForArguments - Get the arguments and return value bindings for
1406/// the specified function in the current graph.
1407///
1408DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1409 std::vector<DSNodeHandle> Args;
1410
1411 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1412 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001413 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001414
Chris Lattner808a7ae2003-09-20 16:34:13 +00001415 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001416}
1417
Chris Lattner85fb1be2004-03-09 19:37:06 +00001418/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1419/// the context of this graph, return the DSCallSite for it.
1420DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1421 DSNodeHandle RetVal;
1422 Instruction *I = CS.getInstruction();
1423 if (isPointerType(I->getType()))
1424 RetVal = getNodeForValue(I);
1425
1426 std::vector<DSNodeHandle> Args;
1427 Args.reserve(CS.arg_end()-CS.arg_begin());
1428
1429 // Calculate the arguments vector...
1430 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1431 if (isPointerType((*I)->getType()))
1432 Args.push_back(getNodeForValue(*I));
1433
1434 // Add a new function call entry...
1435 if (Function *F = CS.getCalledFunction())
1436 return DSCallSite(CS, RetVal, F, Args);
1437 else
1438 return DSCallSite(CS, RetVal,
1439 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1440}
1441
Chris Lattner58f98d02003-07-02 04:38:49 +00001442
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001443
Chris Lattner0d9bab82002-07-18 00:12:30 +00001444// markIncompleteNodes - Mark the specified node as having contents that are not
1445// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001446// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001447// must recursively traverse the data structure graph, marking all reachable
1448// nodes as incomplete.
1449//
1450static void markIncompleteNode(DSNode *N) {
1451 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001452 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001453
1454 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001455 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001456
Misha Brukman2f2d0652003-09-11 18:14:24 +00001457 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001458 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1459 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001460 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001461}
1462
Chris Lattnere71ffc22002-11-11 03:36:55 +00001463static void markIncomplete(DSCallSite &Call) {
1464 // Then the return value is certainly incomplete!
1465 markIncompleteNode(Call.getRetVal().getNode());
1466
1467 // All objects pointed to by function arguments are incomplete!
1468 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1469 markIncompleteNode(Call.getPtrArg(i).getNode());
1470}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001471
1472// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1473// modified by other functions that have not been resolved yet. This marks
1474// nodes that are reachable through three sources of "unknownness":
1475//
1476// Global Variables, Function Calls, and Incoming Arguments
1477//
1478// For any node that may have unknown components (because something outside the
1479// scope of current analysis may have modified it), the 'Incomplete' flag is
1480// added to the NodeType.
1481//
Chris Lattner394471f2003-01-23 22:05:33 +00001482void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001483 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001484 if (Flags & DSGraph::MarkFormalArgs)
1485 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1486 FI != E; ++FI) {
1487 Function &F = *FI->first;
1488 if (F.getName() != "main")
1489 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
Chris Lattner0b144872004-01-27 22:03:40 +00001490 if (isPointerType(I->getType()))
1491 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001492 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001493
Chris Lattnera9548d92005-01-30 23:51:02 +00001494 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001495 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001496 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1497 E = FunctionCalls.end(); I != E; ++I)
1498 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001499 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001500 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1501 E = AuxFunctionCalls.end(); I != E; ++I)
1502 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001503
Chris Lattner93d7a212003-02-09 18:41:49 +00001504 // Mark all global nodes as incomplete...
1505 if ((Flags & DSGraph::IgnoreGlobals) == 0)
Chris Lattner51c06ab2004-02-25 23:08:00 +00001506 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1507 E = ScalarMap.global_end(); I != E; ++I)
Chris Lattnercf14e712004-02-25 23:36:08 +00001508 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattnerd84d3502004-03-08 03:52:24 +00001509 if (!GV->isConstant() || !GV->hasInitializer())
Chris Lattnercf14e712004-02-25 23:36:08 +00001510 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001511}
1512
Chris Lattneraa8146f2002-11-10 06:59:55 +00001513static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1514 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001515 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001516 // No interesting info?
1517 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001518 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001519 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001520}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001521
Chris Lattneraa8146f2002-11-10 06:59:55 +00001522static inline bool nodeContainsExternalFunction(const DSNode *N) {
1523 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1524 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
Chris Lattner857eb062004-10-30 05:41:23 +00001525 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001526 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001527 return false;
1528}
1529
Chris Lattnera9548d92005-01-30 23:51:02 +00001530static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001531 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001532 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001533
1534 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001535 DSNode *LastCalleeNode = 0;
1536 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001537 unsigned NumDuplicateCalls = 0;
1538 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001539
Chris Lattnera9548d92005-01-30 23:51:02 +00001540 unsigned NumDeleted = 0;
1541 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1542 I != E;) {
1543 DSCallSite &CS = *I;
1544 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001545
Chris Lattnere4258442002-11-11 21:35:38 +00001546 // If the Callee is a useless edge, this must be an unreachable call site,
1547 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001548 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001549 CS.getCalleeNode()->isComplete() &&
Chris Lattneraf6926a2004-02-26 03:45:03 +00001550 CS.getCalleeNode()->getGlobals().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001551#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001552 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001553#endif
Chris Lattnera9548d92005-01-30 23:51:02 +00001554 Calls.erase(OldIt);
1555 ++NumDeleted;
1556 continue;
1557 }
1558
1559 // If the return value or any arguments point to a void node with no
1560 // information at all in it, and the call node is the only node to point
1561 // to it, remove the edge to the node (killing the node).
1562 //
1563 killIfUselessEdge(CS.getRetVal());
1564 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1565 killIfUselessEdge(CS.getPtrArg(a));
1566
Chris Lattner0b144872004-01-27 22:03:40 +00001567#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001568 // If this call site calls the same function as the last call site, and if
1569 // the function pointer contains an external function, this node will
1570 // never be resolved. Merge the arguments of the call node because no
1571 // information will be lost.
1572 //
1573 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1574 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1575 ++NumDuplicateCalls;
1576 if (NumDuplicateCalls == 1) {
1577 if (LastCalleeNode)
1578 LastCalleeContainsExternalFunction =
1579 nodeContainsExternalFunction(LastCalleeNode);
1580 else
1581 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001582 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001583
1584 // It is not clear why, but enabling this code makes DSA really
1585 // sensitive to node forwarding. Basically, with this enabled, DSA
1586 // performs different number of inlinings based on which nodes are
1587 // forwarding or not. This is clearly a problem, so this code is
1588 // disabled until this can be resolved.
1589#if 1
1590 if (LastCalleeContainsExternalFunction
1591#if 0
1592 ||
1593 // This should be more than enough context sensitivity!
1594 // FIXME: Evaluate how many times this is tripped!
1595 NumDuplicateCalls > 20
1596#endif
1597 ) {
1598
1599 std::list<DSCallSite>::iterator PrevIt = OldIt;
1600 --PrevIt;
1601 PrevIt->mergeWith(CS);
1602
1603 // No need to keep this call anymore.
1604 Calls.erase(OldIt);
1605 ++NumDeleted;
1606 continue;
1607 }
1608#endif
1609 } else {
1610 if (CS.isDirectCall()) {
1611 LastCalleeFunc = CS.getCalleeFunc();
1612 LastCalleeNode = 0;
1613 } else {
1614 LastCalleeNode = CS.getCalleeNode();
1615 LastCalleeFunc = 0;
1616 }
1617 NumDuplicateCalls = 0;
1618 }
1619#endif
1620
1621 if (I != Calls.end() && CS == *I) {
1622 Calls.erase(OldIt);
1623 ++NumDeleted;
1624 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001625 }
1626 }
Chris Lattner857eb062004-10-30 05:41:23 +00001627
Chris Lattnera9548d92005-01-30 23:51:02 +00001628 // Resort now that we simplified things.
1629 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001630
Chris Lattnera9548d92005-01-30 23:51:02 +00001631 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001632 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1633 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001634 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001635 std::list<DSCallSite>::iterator OldIt = CI++;
1636 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001637
1638 // If this call site is now the same as the previous one, we can delete it
1639 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001640 if (*OldIt == *CI) {
1641 Calls.erase(CI);
1642 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001643 ++NumDeleted;
1644 }
1645 }
1646
1647 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001648
Chris Lattner33312f72002-11-08 01:21:07 +00001649 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001650 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001651
Chris Lattnera9548d92005-01-30 23:51:02 +00001652 DEBUG(if (NumDeleted)
1653 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001654}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001655
Chris Lattneraa8146f2002-11-10 06:59:55 +00001656
Chris Lattnere2219762002-07-18 18:22:40 +00001657// removeTriviallyDeadNodes - After the graph has been constructed, this method
1658// removes all unreachable nodes that are created because they got merged with
1659// other nodes in the graph. These nodes will all be trivially unreachable, so
1660// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001661//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001662void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001663 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001664
Chris Lattner5ace1e42004-07-08 07:25:51 +00001665#if 0
1666 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1667 /// substantially!
1668
Chris Lattnerbab8c282003-09-20 21:34:07 +00001669 // Loop over all of the nodes in the graph, calling getNode on each field.
1670 // This will cause all nodes to update their forwarding edges, causing
1671 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001672 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001673 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
1674 DSNode *N = *NI;
Chris Lattnerbab8c282003-09-20 21:34:07 +00001675 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1676 N->getLink(l*N->getPointerSize()).getNode();
1677 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001678 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001679
Chris Lattner0b144872004-01-27 22:03:40 +00001680 // NOTE: This code is disabled. Though it should, in theory, allow us to
1681 // remove more nodes down below, the scan of the scalar map is incredibly
1682 // expensive for certain programs (with large SCCs). In the future, if we can
1683 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001684 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1685
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001686 // Likewise, forward any edges from the scalar nodes. While we are at it,
1687 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001688 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001689 I->second.getNode();
1690 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001691 }
Chris Lattner0b144872004-01-27 22:03:40 +00001692 }
1693#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001694 bool isGlobalsGraph = !GlobalsGraph;
1695
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001696 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001697 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001698
1699 // Do not remove *any* global nodes in the globals graph.
1700 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001701 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001702 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001703 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001704 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001705
Chris Lattner28897e12004-02-08 00:53:26 +00001706 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001707 // This is a useless node if it has no mod/ref info (checked above),
1708 // outgoing edges (which it cannot, as it is not modified in this
1709 // context), and it has no incoming edges. If it is a global node it may
1710 // have all of these properties and still have incoming edges, due to the
1711 // scalar map, so we check those now.
1712 //
Chris Lattner28897e12004-02-08 00:53:26 +00001713 if (Node.getNumReferrers() == Node.getGlobals().size()) {
1714 const std::vector<GlobalValue*> &Globals = Node.getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001715
Chris Lattner17a93e22004-01-29 03:32:15 +00001716 // Loop through and make sure all of the globals are referring directly
1717 // to the node...
1718 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1719 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001720 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001721 }
1722
Chris Lattnerbd92b732003-06-19 21:15:11 +00001723 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001724 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001725 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1726 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001727 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001728 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001729 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001730 }
1731 }
1732
Chris Lattner28897e12004-02-08 00:53:26 +00001733 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001734 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001735 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001736 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001737 } else {
1738 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001739 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001740 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001741
1742 removeIdenticalCalls(FunctionCalls);
1743 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001744}
1745
1746
Chris Lattner5c7380e2003-01-29 21:10:20 +00001747/// markReachableNodes - This method recursively traverses the specified
1748/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1749/// to the set, which allows it to only traverse visited nodes once.
1750///
Chris Lattnera9548d92005-01-30 23:51:02 +00001751void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001752 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001753 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001754 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001755 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1756 I != E; ++I)
1757 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001758}
1759
Chris Lattnera9548d92005-01-30 23:51:02 +00001760void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001761 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001762 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001763
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001764 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1765 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001766}
1767
Chris Lattnera1220af2003-02-01 06:17:02 +00001768// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1769// looking for a node that is marked alive. If an alive node is found, return
1770// true, otherwise return false. If an alive node is reachable, this node is
1771// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001772//
Chris Lattnera9548d92005-01-30 23:51:02 +00001773static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1774 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001775 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001776 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001777 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001778
Chris Lattner85cfe012003-07-03 02:03:53 +00001779 // If this is a global node, it will end up in the globals graph anyway, so we
1780 // don't need to worry about it.
1781 if (IgnoreGlobals && N->isGlobalNode()) return false;
1782
Chris Lattneraa8146f2002-11-10 06:59:55 +00001783 // If we know that this node is alive, return so!
1784 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001785
Chris Lattneraa8146f2002-11-10 06:59:55 +00001786 // Otherwise, we don't think the node is alive yet, check for infinite
1787 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001788 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001789 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001790
Chris Lattner6be07942005-02-09 03:20:43 +00001791 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1792 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001793 N->markReachableNodes(Alive);
1794 return true;
1795 }
1796 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001797}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001798
Chris Lattnera1220af2003-02-01 06:17:02 +00001799// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1800// alive nodes.
1801//
Chris Lattnera9548d92005-01-30 23:51:02 +00001802static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1803 hash_set<const DSNode*> &Alive,
1804 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001805 bool IgnoreGlobals) {
1806 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1807 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001808 return true;
1809 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001810 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001811 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001812 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001813 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1814 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001815 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001816 return false;
1817}
1818
Chris Lattnere2219762002-07-18 18:22:40 +00001819// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1820// subgraphs that are unreachable. This often occurs because the data
1821// structure doesn't "escape" into it's caller, and thus should be eliminated
1822// from the caller's graph entirely. This is only appropriate to use when
1823// inlining graphs.
1824//
Chris Lattner394471f2003-01-23 22:05:33 +00001825void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001826 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001827
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001828 // Reduce the amount of work we have to do... remove dummy nodes left over by
1829 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001830 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001831
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001832 TIME_REGION(X, "removeDeadNodes");
1833
Misha Brukman2f2d0652003-09-11 18:14:24 +00001834 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001835
1836 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00001837 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001838 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001839
Chris Lattner0b144872004-01-27 22:03:40 +00001840 // Copy and merge all information about globals to the GlobalsGraph if this is
1841 // not a final pass (where unreachable globals are removed).
1842 //
1843 // Strip all alloca bits since the current function is only for the BU pass.
1844 // Strip all incomplete bits since they are short-lived properties and they
1845 // will be correctly computed when rematerializing nodes into the functions.
1846 //
1847 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1848 DSGraph::StripIncompleteBit);
1849
Chris Lattneraa8146f2002-11-10 06:59:55 +00001850 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner00948c02004-01-28 02:05:05 +00001851 { TIME_REGION(Y, "removeDeadNodes:scalarscan");
Chris Lattner62482e52004-01-28 09:15:42 +00001852 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001853 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00001854 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001855 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001856 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001857
1858 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001859 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1860 DSGraph::ScalarMapTy::iterator SMI =
1861 GlobalsGraph->getScalarMap().find(I->first);
1862 if (SMI != GlobalsGraph->getScalarMap().end())
1863 GGCloner.merge(SMI->second, I->second);
1864 else
1865 GGCloner.getClonedNH(I->second);
1866 }
Chris Lattner0b144872004-01-27 22:03:40 +00001867 ++I;
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001868 } else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001869 DSNode *N = I->second.getNode();
1870#if 0
Chris Lattner0b144872004-01-27 22:03:40 +00001871 // Check to see if this is a worthless node generated for non-pointer
1872 // values, such as integers. Consider an addition of long types: A+B.
1873 // Assuming we can track all uses of the value in this context, and it is
1874 // NOT used as a pointer, we can delete the node. We will be able to
1875 // detect this situation if the node pointed to ONLY has Unknown bit set
1876 // in the node. In this case, the node is not incomplete, does not point
1877 // to any other nodes (no mod/ref bits set), and is therefore
1878 // uninteresting for data structure analysis. If we run across one of
1879 // these, prune the scalar pointing to it.
1880 //
Chris Lattner0b144872004-01-27 22:03:40 +00001881 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1882 ScalarMap.erase(I++);
1883 else {
Chris Lattnera88a55c2004-01-28 02:41:32 +00001884#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001885 N->markReachableNodes(Alive);
1886 ++I;
Chris Lattnera88a55c2004-01-28 02:41:32 +00001887 //}
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001888 }
Chris Lattner00948c02004-01-28 02:05:05 +00001889 }
Chris Lattnere2219762002-07-18 18:22:40 +00001890
Chris Lattner0b144872004-01-27 22:03:40 +00001891 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001892 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1893 I != E; ++I)
1894 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001895
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001896 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00001897 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1898 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001899
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001900
1901 // Now find globals and aux call nodes that are already live or reach a live
1902 // value (which makes them live in turn), and continue till no more are found.
1903 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001904 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00001905 hash_set<const DSNode*> Visited;
1906 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001907 do {
1908 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001909 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001910 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001911 // unreachable globals in the list.
1912 //
1913 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001914 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001915 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1916 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1917 Flags & DSGraph::RemoveUnreachableGlobals)) {
1918 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1919 GlobalNodes.pop_back(); // erase efficiently
1920 Iterate = true;
1921 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001922
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001923 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1924 // call nodes that get resolved will be difficult to remove from that graph.
1925 // The final unresolved call nodes must be handled specially at the end of
1926 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00001927 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
1928 if (AuxFCallsAlive.insert(&*CI).second &&
1929 (CI->isIndirectCall()
1930 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001931 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001932 CI->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001933 Iterate = true;
1934 }
1935 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001936
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001937 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001938 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001939 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
1940 E = AuxFunctionCalls.end(); CI != E; )
1941 if (AuxFCallsAlive.count(&*CI))
1942 ++CI;
1943 else {
1944 // Copy and merge global nodes and dead aux call nodes into the
1945 // GlobalsGraph, and all nodes reachable from those nodes. Update their
1946 // target pointers using the GGCloner.
1947 //
1948 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1949 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001950
Chris Lattnera9548d92005-01-30 23:51:02 +00001951 AuxFunctionCalls.erase(CI++);
1952 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001953
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001954 // We are finally done with the GGCloner so we can destroy it.
1955 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001956
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001957 // At this point, any nodes which are visited, but not alive, are nodes
1958 // which can be removed. Loop over all nodes, eliminating completely
1959 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001960 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001961 std::vector<DSNode*> DeadNodes;
1962 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00001963 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
1964 DSNode *N = NI++;
1965 assert(!N->isForwarding() && "Forwarded node in nodes list?");
1966
1967 if (!Alive.count(N)) {
1968 Nodes.remove(N);
1969 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001970 DeadNodes.push_back(N);
1971 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00001972 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00001973 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00001974 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001975
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001976 // Remove all unreachable globals from the ScalarMap.
1977 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1978 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00001979 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001980 if (!Alive.count(GlobalNodes[i].second))
1981 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00001982 else
1983 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001984
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001985 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001986 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1987 delete DeadNodes[i];
1988
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001989 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001990}
1991
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001992void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
1993 assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
1994 N->getGlobals().end() && "Global value not in node!");
1995}
1996
Chris Lattner2c7725a2004-03-03 20:55:27 +00001997void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
1998 if (CS.isIndirectCall()) {
1999 AssertNodeInGraph(CS.getCalleeNode());
2000#if 0
2001 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2002 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
2003 std::cerr << "WARNING: WIERD CALL SITE FOUND!\n";
2004#endif
2005 }
2006 AssertNodeInGraph(CS.getRetVal().getNode());
2007 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2008 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2009}
2010
2011void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002012 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2013 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002014}
2015void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002016 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2017 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002018}
2019
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002020void DSGraph::AssertGraphOK() const {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00002021 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2022 (*NI)->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002023
Chris Lattner8d327672003-06-30 03:36:09 +00002024 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002025 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002026 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002027 AssertNodeInGraph(I->second.getNode());
2028 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002029 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002030 "Global points to node, but node isn't global?");
2031 AssertNodeContainsGlobal(I->second.getNode(), GV);
2032 }
2033 }
2034 AssertCallNodesInGraph();
2035 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002036
2037 // Check that all pointer arguments to any functions in this graph have
2038 // destinations.
2039 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2040 E = ReturnNodes.end();
2041 RI != E; ++RI) {
2042 Function &F = *RI->first;
2043 for (Function::aiterator AI = F.abegin(); AI != F.aend(); ++AI)
2044 if (isPointerType(AI->getType()))
2045 assert(!getNodeForValue(AI).isNull() &&
2046 "Pointer argument must be in the scalar map!");
2047 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002048}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002049
Chris Lattner400433d2003-11-11 05:08:59 +00002050/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002051/// nodes reachable from the two graphs, computing the mapping of nodes from the
2052/// first to the second graph. This mapping may be many-to-one (i.e. the first
2053/// graph may have multiple nodes representing one node in the second graph),
2054/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002055///
2056void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002057 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2058 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002059 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2060 if (N1 == 0 || N2 == 0) return;
2061
2062 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002063 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002064 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002065 if (StrictChecking) {
2066 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2067 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2068 Entry.getNode()->isNodeCompletelyFolded()) &&
2069 "Inconsistent mapping detected!");
2070 }
Chris Lattner400433d2003-11-11 05:08:59 +00002071 return;
2072 }
2073
Chris Lattnerefffdc92004-07-07 06:12:52 +00002074 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002075
2076 // Loop over all of the fields that N1 and N2 have in common, recursively
2077 // mapping the edges together now.
2078 int N2Idx = NH2.getOffset()-NH1.getOffset();
2079 unsigned N2Size = N2->getSize();
2080 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
2081 if (unsigned(N2Idx)+i < N2Size)
2082 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
Chris Lattnerb1aaeee2004-03-03 05:34:31 +00002083 else
2084 computeNodeMapping(N1->getLink(i),
2085 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
Chris Lattner400433d2003-11-11 05:08:59 +00002086}