blob: 81e6db3d758dd27a88c60d114cd9cd4cf3d4d60d [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerfccd06f2002-10-01 22:33:50 +000014#include "llvm/Analysis/DSGraph.h"
15#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +000016#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000018#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000019#include "llvm/Assembly/Writer.h"
Chris Lattner6806f562003-08-01 22:15:03 +000020#include "Support/Debug.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000021#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000022#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000023#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000024#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner08db7192002-11-06 06:20:27 +000027namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000028 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
29 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000030};
31
Chris Lattner93ddd7e2004-01-22 16:36:28 +000032#if 0
33#define TIME_REGION(VARNAME, DESC) \
34 NamedRegionTimer VARNAME(DESC)
35#else
36#define TIME_REGION(VARNAME, DESC)
37#endif
38
Chris Lattnerb1060432002-11-07 05:20:53 +000039using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000040
Chris Lattner731b2d72003-02-13 19:09:00 +000041DSNode *DSNodeHandle::HandleForwarding() const {
42 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
43
44 // Handle node forwarding here!
45 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
46 Offset += N->ForwardNH.getOffset();
47
48 if (--N->NumReferrers == 0) {
49 // Removing the last referrer to the node, sever the forwarding link
50 N->stopForwarding();
51 }
52
53 N = Next;
54 N->NumReferrers++;
55 if (N->Size <= Offset) {
56 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
57 Offset = 0;
58 }
59 return N;
60}
61
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000062//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000063// DSNode Implementation
64//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000065
Chris Lattnerbd92b732003-06-19 21:15:11 +000066DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000067 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000068 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000069 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000070 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000071}
72
Chris Lattner0d9bab82002-07-18 00:12:30 +000073// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000074DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000075 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000076 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000077 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000078}
79
Chris Lattner15869aa2003-11-02 22:27:28 +000080/// getTargetData - Get the target data object used to construct this node.
81///
82const TargetData &DSNode::getTargetData() const {
83 return ParentGraph->getTargetData();
84}
85
Chris Lattner72d29a42003-02-11 23:11:51 +000086void DSNode::assertOK() const {
87 assert((Ty != Type::VoidTy ||
88 Ty == Type::VoidTy && (Size == 0 ||
89 (NodeType & DSNode::Array))) &&
90 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +000091
92 assert(ParentGraph && "Node has no parent?");
93 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
94 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
95 assert(SM.find(Globals[i]) != SM.end());
96 assert(SM.find(Globals[i])->second.getNode() == this);
97 }
Chris Lattner72d29a42003-02-11 23:11:51 +000098}
99
100/// forwardNode - Mark this node as being obsolete, and all references to it
101/// should be forwarded to the specified node and offset.
102///
103void DSNode::forwardNode(DSNode *To, unsigned Offset) {
104 assert(this != To && "Cannot forward a node to itself!");
105 assert(ForwardNH.isNull() && "Already forwarding from this node!");
106 if (To->Size <= 1) Offset = 0;
107 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
108 "Forwarded offset is wrong!");
109 ForwardNH.setNode(To);
110 ForwardNH.setOffset(Offset);
111 NodeType = DEAD;
112 Size = 0;
113 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000114}
115
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000116// addGlobal - Add an entry for a global value to the Globals list. This also
117// marks the node with the 'G' flag if it does not already have it.
118//
119void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000120 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000121 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000122 std::lower_bound(Globals.begin(), Globals.end(), GV);
123
124 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000125 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000126 Globals.insert(I, GV);
127 NodeType |= GlobalNode;
128 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000129}
130
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000131/// foldNodeCompletely - If we determine that this node has some funny
132/// behavior happening to it that we cannot represent, we fold it down to a
133/// single, completely pessimistic, node. This node is represented as a
134/// single byte with a single TypeEntry of "void".
135///
136void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000137 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000138
Chris Lattner08db7192002-11-06 06:20:27 +0000139 ++NumFolds;
140
Chris Lattner72d29a42003-02-11 23:11:51 +0000141 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000142 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000143 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000144 DestNode->Ty = Type::VoidTy;
145 DestNode->Size = 1;
146 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000147
Chris Lattner72d29a42003-02-11 23:11:51 +0000148 // Start forwarding to the destination node...
149 forwardNode(DestNode, 0);
150
151 if (Links.size()) {
152 DestNode->Links.push_back(Links[0]);
153 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000154
Chris Lattner72d29a42003-02-11 23:11:51 +0000155 // If we have links, merge all of our outgoing links together...
156 for (unsigned i = Links.size()-1; i != 0; --i)
157 NH.getNode()->Links[0].mergeWith(Links[i]);
158 Links.clear();
159 } else {
160 DestNode->Links.resize(1);
161 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000162}
Chris Lattner076c1f92002-11-07 06:31:54 +0000163
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000164/// isNodeCompletelyFolded - Return true if this node has been completely
165/// folded down to something that can never be expanded, effectively losing
166/// all of the field sensitivity that may be present in the node.
167///
168bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000169 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000170}
171
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000172namespace {
173 /// TypeElementWalker Class - Used for implementation of physical subtyping...
174 ///
175 class TypeElementWalker {
176 struct StackState {
177 const Type *Ty;
178 unsigned Offset;
179 unsigned Idx;
180 StackState(const Type *T, unsigned Off = 0)
181 : Ty(T), Offset(Off), Idx(0) {}
182 };
183
184 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000185 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000186 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000187 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000188 Stack.push_back(T);
189 StepToLeaf();
190 }
191
192 bool isDone() const { return Stack.empty(); }
193 const Type *getCurrentType() const { return Stack.back().Ty; }
194 unsigned getCurrentOffset() const { return Stack.back().Offset; }
195
196 void StepToNextType() {
197 PopStackAndAdvance();
198 StepToLeaf();
199 }
200
201 private:
202 /// PopStackAndAdvance - Pop the current element off of the stack and
203 /// advance the underlying element to the next contained member.
204 void PopStackAndAdvance() {
205 assert(!Stack.empty() && "Cannot pop an empty stack!");
206 Stack.pop_back();
207 while (!Stack.empty()) {
208 StackState &SS = Stack.back();
209 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
210 ++SS.Idx;
211 if (SS.Idx != ST->getElementTypes().size()) {
212 const StructLayout *SL = TD.getStructLayout(ST);
213 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
214 return;
215 }
216 Stack.pop_back(); // At the end of the structure
217 } else {
218 const ArrayType *AT = cast<ArrayType>(SS.Ty);
219 ++SS.Idx;
220 if (SS.Idx != AT->getNumElements()) {
221 SS.Offset += TD.getTypeSize(AT->getElementType());
222 return;
223 }
224 Stack.pop_back(); // At the end of the array
225 }
226 }
227 }
228
229 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
230 /// on the type stack.
231 void StepToLeaf() {
232 if (Stack.empty()) return;
233 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
234 StackState &SS = Stack.back();
235 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
236 if (ST->getElementTypes().empty()) {
237 assert(SS.Idx == 0);
238 PopStackAndAdvance();
239 } else {
240 // Step into the structure...
241 assert(SS.Idx < ST->getElementTypes().size());
242 const StructLayout *SL = TD.getStructLayout(ST);
243 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
244 SS.Offset+SL->MemberOffsets[SS.Idx]));
245 }
246 } else {
247 const ArrayType *AT = cast<ArrayType>(SS.Ty);
248 if (AT->getNumElements() == 0) {
249 assert(SS.Idx == 0);
250 PopStackAndAdvance();
251 } else {
252 // Step into the array...
253 assert(SS.Idx < AT->getNumElements());
254 Stack.push_back(StackState(AT->getElementType(),
255 SS.Offset+SS.Idx*
256 TD.getTypeSize(AT->getElementType())));
257 }
258 }
259 }
260 }
261 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000262} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000263
264/// ElementTypesAreCompatible - Check to see if the specified types are
265/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000266/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
267/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000268///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000269static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000270 bool AllowLargerT1, const TargetData &TD){
271 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000272
273 while (!T1W.isDone() && !T2W.isDone()) {
274 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
275 return false;
276
277 const Type *T1 = T1W.getCurrentType();
278 const Type *T2 = T2W.getCurrentType();
279 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
280 return false;
281
282 T1W.StepToNextType();
283 T2W.StepToNextType();
284 }
285
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000286 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000287}
288
289
Chris Lattner08db7192002-11-06 06:20:27 +0000290/// mergeTypeInfo - This method merges the specified type into the current node
291/// at the specified offset. This may update the current node's type record if
292/// this gives more information to the node, it may do nothing to the node if
293/// this information is already known, or it may merge the node completely (and
294/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000295///
Chris Lattner08db7192002-11-06 06:20:27 +0000296/// This method returns true if the node is completely folded, otherwise false.
297///
Chris Lattner088b6392003-03-03 17:13:31 +0000298bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
299 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000300 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000301 // Check to make sure the Size member is up-to-date. Size can be one of the
302 // following:
303 // Size = 0, Ty = Void: Nothing is known about this node.
304 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
305 // Size = 1, Ty = Void, Array = 1: The node is collapsed
306 // Otherwise, sizeof(Ty) = Size
307 //
Chris Lattner18552922002-11-18 21:44:46 +0000308 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
309 (Size == 0 && !Ty->isSized() && !isArray()) ||
310 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
311 (Size == 0 && !Ty->isSized() && !isArray()) ||
312 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000313 "Size member of DSNode doesn't match the type structure!");
314 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000315
Chris Lattner18552922002-11-18 21:44:46 +0000316 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000317 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000318
Chris Lattner08db7192002-11-06 06:20:27 +0000319 // Return true immediately if the node is completely folded.
320 if (isNodeCompletelyFolded()) return true;
321
Chris Lattner23f83dc2002-11-08 22:49:57 +0000322 // If this is an array type, eliminate the outside arrays because they won't
323 // be used anyway. This greatly reduces the size of large static arrays used
324 // as global variables, for example.
325 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000326 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000327 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
328 // FIXME: we might want to keep small arrays, but must be careful about
329 // things like: [2 x [10000 x int*]]
330 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000331 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000332 }
333
Chris Lattner08db7192002-11-06 06:20:27 +0000334 // Figure out how big the new type we're merging in is...
335 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
336
337 // Otherwise check to see if we can fold this type into the current node. If
338 // we can't, we fold the node completely, if we can, we potentially update our
339 // internal state.
340 //
Chris Lattner18552922002-11-18 21:44:46 +0000341 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000342 // If this is the first type that this node has seen, just accept it without
343 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000344 assert(Offset == 0 && !isArray() &&
345 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000346 Ty = NewTy;
347 NodeType &= ~Array;
348 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000349 Size = NewTySize;
350
351 // Calculate the number of outgoing links from this node.
352 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
353 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000354 }
Chris Lattner08db7192002-11-06 06:20:27 +0000355
356 // Handle node expansion case here...
357 if (Offset+NewTySize > Size) {
358 // It is illegal to grow this node if we have treated it as an array of
359 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000360 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000361 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000362 return true;
363 }
364
365 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000366 std::cerr << "UNIMP: Trying to merge a growth type into "
367 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000368 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000369 return true;
370 }
371
372 // Okay, the situation is nice and simple, we are trying to merge a type in
373 // at offset 0 that is bigger than our current type. Implement this by
374 // switching to the new type and then merge in the smaller one, which should
375 // hit the other code path here. If the other code path decides it's not
376 // ok, it will collapse the node as appropriate.
377 //
Chris Lattner18552922002-11-18 21:44:46 +0000378 const Type *OldTy = Ty;
379 Ty = NewTy;
380 NodeType &= ~Array;
381 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000382 Size = NewTySize;
383
384 // Must grow links to be the appropriate size...
385 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
386
387 // Merge in the old type now... which is guaranteed to be smaller than the
388 // "current" type.
389 return mergeTypeInfo(OldTy, 0);
390 }
391
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000392 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000393 "Cannot merge something into a part of our type that doesn't exist!");
394
Chris Lattner18552922002-11-18 21:44:46 +0000395 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000396 // type that starts at offset Offset.
397 //
398 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000399 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000400 while (O < Offset) {
401 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
402
403 switch (SubType->getPrimitiveID()) {
404 case Type::StructTyID: {
405 const StructType *STy = cast<StructType>(SubType);
406 const StructLayout &SL = *TD.getStructLayout(STy);
407
408 unsigned i = 0, e = SL.MemberOffsets.size();
409 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
410 /* empty */;
411
412 // The offset we are looking for must be in the i'th element...
413 SubType = STy->getElementTypes()[i];
414 O += SL.MemberOffsets[i];
415 break;
416 }
417 case Type::ArrayTyID: {
418 SubType = cast<ArrayType>(SubType)->getElementType();
419 unsigned ElSize = TD.getTypeSize(SubType);
420 unsigned Remainder = (Offset-O) % ElSize;
421 O = Offset-Remainder;
422 break;
423 }
424 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000425 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000426 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000427 }
428 }
429
430 assert(O == Offset && "Could not achieve the correct offset!");
431
432 // If we found our type exactly, early exit
433 if (SubType == NewTy) return false;
434
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000435 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
436
437 // Ok, we are getting desperate now. Check for physical subtyping, where we
438 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000439 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000440 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000441 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000442 return false;
443
Chris Lattner08db7192002-11-06 06:20:27 +0000444 // Okay, so we found the leader type at the offset requested. Search the list
445 // of types that starts at this offset. If SubType is currently an array or
446 // structure, the type desired may actually be the first element of the
447 // composite type...
448 //
Chris Lattner18552922002-11-18 21:44:46 +0000449 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000450 while (SubType != NewTy) {
451 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000452 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000453 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000454 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000455 case Type::StructTyID: {
456 const StructType *STy = cast<StructType>(SubType);
457 const StructLayout &SL = *TD.getStructLayout(STy);
458 if (SL.MemberOffsets.size() > 1)
459 NextPadSize = SL.MemberOffsets[1];
460 else
461 NextPadSize = SubTypeSize;
462 NextSubType = STy->getElementTypes()[0];
463 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000464 break;
Chris Lattner18552922002-11-18 21:44:46 +0000465 }
Chris Lattner08db7192002-11-06 06:20:27 +0000466 case Type::ArrayTyID:
467 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000468 NextSubTypeSize = TD.getTypeSize(NextSubType);
469 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000470 break;
471 default: ;
472 // fall out
473 }
474
475 if (NextSubType == 0)
476 break; // In the default case, break out of the loop
477
Chris Lattner18552922002-11-18 21:44:46 +0000478 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000479 break; // Don't allow shrinking to a smaller type than NewTySize
480 SubType = NextSubType;
481 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000482 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000483 }
484
485 // If we found the type exactly, return it...
486 if (SubType == NewTy)
487 return false;
488
489 // Check to see if we have a compatible, but different type...
490 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000491 // Check to see if this type is obviously convertible... int -> uint f.e.
492 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000493 return false;
494
495 // Check to see if we have a pointer & integer mismatch going on here,
496 // loading a pointer as a long, for example.
497 //
498 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
499 NewTy->isInteger() && isa<PointerType>(SubType))
500 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000501 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
502 // We are accessing the field, plus some structure padding. Ignore the
503 // structure padding.
504 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000505 }
506
Chris Lattner58f98d02003-07-02 04:38:49 +0000507 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000508 if (getParentGraph()->getReturnNodes().size())
509 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000510 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
511 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
512 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
513 << "SubType: ";
514 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000515
Chris Lattner088b6392003-03-03 17:13:31 +0000516 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000517 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000518}
519
Chris Lattner08db7192002-11-06 06:20:27 +0000520
521
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000522// addEdgeTo - Add an edge from the current node to the specified node. This
523// can cause merging of nodes in the graph.
524//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000525void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000526 if (NH.getNode() == 0) return; // Nothing to do
527
Chris Lattner08db7192002-11-06 06:20:27 +0000528 DSNodeHandle &ExistingEdge = getLink(Offset);
529 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000530 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000531 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000532 } else { // No merging to perform...
533 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000534 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000535}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000536
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000537
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000538// MergeSortedVectors - Efficiently merge a vector into another vector where
539// duplicates are not allowed and both are sorted. This assumes that 'T's are
540// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000541//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000542static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
543 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000544 // By far, the most common cases will be the simple ones. In these cases,
545 // avoid having to allocate a temporary vector...
546 //
547 if (Src.empty()) { // Nothing to merge in...
548 return;
549 } else if (Dest.empty()) { // Just copy the result in...
550 Dest = Src;
551 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000552 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000553 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000554 std::lower_bound(Dest.begin(), Dest.end(), V);
555 if (I == Dest.end() || *I != Src[0]) // If not already contained...
556 Dest.insert(I, Src[0]);
557 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000558 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000559 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000560 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000561 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
562 if (I == Dest.end() || *I != Tmp) // If not already contained...
563 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000564
565 } else {
566 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000567 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000568
569 // Make space for all of the type entries now...
570 Dest.resize(Dest.size()+Src.size());
571
572 // Merge the two sorted ranges together... into Dest.
573 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
574
575 // Now erase any duplicate entries that may have accumulated into the
576 // vectors (because they were in both of the input sets)
577 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
578 }
579}
580
581
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000582// MergeNodes() - Helper function for DSNode::mergeWith().
583// This function does the hard work of merging two nodes, CurNodeH
584// and NH after filtering out trivial cases and making sure that
585// CurNodeH.offset >= NH.offset.
586//
587// ***WARNING***
588// Since merging may cause either node to go away, we must always
589// use the node-handles to refer to the nodes. These node handles are
590// automatically updated during merging, so will always provide access
591// to the correct node after a merge.
592//
593void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
594 assert(CurNodeH.getOffset() >= NH.getOffset() &&
595 "This should have been enforced in the caller.");
596
597 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
598 // respect to NH.Offset) is now zero. NOffset is the distance from the base
599 // of our object that N starts from.
600 //
601 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
602 unsigned NSize = NH.getNode()->getSize();
603
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000604 // If the two nodes are of different size, and the smaller node has the array
605 // bit set, collapse!
606 if (NSize != CurNodeH.getNode()->getSize()) {
607 if (NSize < CurNodeH.getNode()->getSize()) {
608 if (NH.getNode()->isArray())
609 NH.getNode()->foldNodeCompletely();
610 } else if (CurNodeH.getNode()->isArray()) {
611 NH.getNode()->foldNodeCompletely();
612 }
613 }
614
615 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000616 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000617 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000618 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000619
620 // If we are merging a node with a completely folded node, then both nodes are
621 // now completely folded.
622 //
623 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
624 if (!NH.getNode()->isNodeCompletelyFolded()) {
625 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000626 assert(NH.getNode() && NH.getOffset() == 0 &&
627 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000628 NOffset = NH.getOffset();
629 NSize = NH.getNode()->getSize();
630 assert(NOffset == 0 && NSize == 1);
631 }
632 } else if (NH.getNode()->isNodeCompletelyFolded()) {
633 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000634 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
635 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000636 NOffset = NH.getOffset();
637 NSize = NH.getNode()->getSize();
638 assert(NOffset == 0 && NSize == 1);
639 }
640
Chris Lattner72d29a42003-02-11 23:11:51 +0000641 DSNode *N = NH.getNode();
642 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000643 assert(!CurNodeH.getNode()->isDeadNode());
644
645 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000646 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000647
Chris Lattner72d29a42003-02-11 23:11:51 +0000648 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000649 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000650 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000651
Chris Lattner72d29a42003-02-11 23:11:51 +0000652 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
653 //
654 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
655 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000656 if (Link.getNode()) {
657 // Compute the offset into the current node at which to
658 // merge this link. In the common case, this is a linear
659 // relation to the offset in the original node (with
660 // wrapping), but if the current node gets collapsed due to
661 // recursive merging, we must make sure to merge in all remaining
662 // links at offset zero.
663 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000664 DSNode *CN = CurNodeH.getNode();
665 if (CN->Size != 1)
666 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
667 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000668 }
669 }
670
671 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000672 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000673
674 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000675 if (!N->Globals.empty()) {
676 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000677
678 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000679 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000680 }
681}
682
683
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000684// mergeWith - Merge this node and the specified node, moving all links to and
685// from the argument node into the current node, deleting the node argument.
686// Offset indicates what offset the specified node is to be merged into the
687// current node.
688//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000689// The specified node may be a null pointer (in which case, we update it to
690// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000691//
692void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
693 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000694 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000695 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000696
Chris Lattner5254a8d2004-01-22 16:31:08 +0000697 // If the RHS is a null node, make it point to this node!
698 if (N == 0) {
699 NH.mergeWith(DSNodeHandle(this, Offset));
700 return;
701 }
702
Chris Lattnerbd92b732003-06-19 21:15:11 +0000703 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000704 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
705
Chris Lattner02606632002-11-04 06:48:26 +0000706 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000707 // We cannot merge two pieces of the same node together, collapse the node
708 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000709 DEBUG(std::cerr << "Attempting to merge two chunks of"
710 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000711 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000712 return;
713 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000714
Chris Lattner5190ce82002-11-12 07:20:45 +0000715 // If both nodes are not at offset 0, make sure that we are merging the node
716 // at an later offset into the node with the zero offset.
717 //
718 if (Offset < NH.getOffset()) {
719 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
720 return;
721 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
722 // If the offsets are the same, merge the smaller node into the bigger node
723 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
724 return;
725 }
726
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000727 // Ok, now we can merge the two nodes. Use a static helper that works with
728 // two node handles, since "this" may get merged away at intermediate steps.
729 DSNodeHandle CurNodeH(this, Offset);
730 DSNodeHandle NHCopy(NH);
731 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000732}
733
Chris Lattner9de906c2002-10-20 22:11:44 +0000734//===----------------------------------------------------------------------===//
735// DSCallSite Implementation
736//===----------------------------------------------------------------------===//
737
Vikram S. Adve26b98262002-10-20 21:41:02 +0000738// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000739Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000740 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000741}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000742
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000743
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000744//===----------------------------------------------------------------------===//
745// DSGraph Implementation
746//===----------------------------------------------------------------------===//
747
Chris Lattnera9d65662003-06-30 05:57:30 +0000748/// getFunctionNames - Return a space separated list of the name of the
749/// functions in this graph (if any)
750std::string DSGraph::getFunctionNames() const {
751 switch (getReturnNodes().size()) {
752 case 0: return "Globals graph";
753 case 1: return getReturnNodes().begin()->first->getName();
754 default:
755 std::string Return;
756 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
757 I != getReturnNodes().end(); ++I)
758 Return += I->first->getName() + " ";
759 Return.erase(Return.end()-1, Return.end()); // Remove last space character
760 return Return;
761 }
762}
763
764
Chris Lattner15869aa2003-11-02 22:27:28 +0000765DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000766 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000767 NodeMapTy NodeMap;
768 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000769}
770
Chris Lattner5a540632003-06-30 03:15:25 +0000771DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +0000772 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000773 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000774 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000775}
776
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000777DSGraph::~DSGraph() {
778 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000779 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000780 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000781 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000782 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000783
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000784 // Drop all intra-node references, so that assertions don't fail...
785 std::for_each(Nodes.begin(), Nodes.end(),
786 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000787
788 // Delete all of the nodes themselves...
789 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
790}
791
Chris Lattner0d9bab82002-07-18 00:12:30 +0000792// dump - Allow inspection of graph in a debugger.
793void DSGraph::dump() const { print(std::cerr); }
794
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000795
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000796/// remapLinks - Change all of the Links in the current node according to the
797/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000798///
Chris Lattner8d327672003-06-30 03:36:09 +0000799void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +0000800 for (unsigned i = 0, e = Links.size(); i != e; ++i)
801 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +0000802 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
803 if (ONMI != OldNodeMap.end()) {
804 Links[i].setNode(ONMI->second.getNode());
805 Links[i].setOffset(Links[i].getOffset()+ONMI->second.getOffset());
806 }
Chris Lattner2f561382004-01-22 16:56:13 +0000807 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000808}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000809
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000810
Chris Lattner091f7762004-01-23 01:44:53 +0000811/// cloneReachableNodes - Clone all reachable nodes from *Node into the current
812/// graph. This is a recursive function. The map OldNodeMap is a map from the
813/// original nodes to their clones. This populates the Globals set with all of
814/// the global values that are cloned in.
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000815///
Chris Lattner091f7762004-01-23 01:44:53 +0000816void DSGraph::cloneReachableNodes(const DSNode *Node, unsigned BitsToClear,
817 NodeMapTy &OldNodeMap, GlobalSetTy &Globals) {
818 DSNodeHandle &NH = OldNodeMap[Node];
819 if (NH.getNode()) return; // Already cloned this node?
820
821 // FIXME: eliminate eventually!
822 Globals.insert(Node->getGlobals().begin(), Node->getGlobals().end());
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000823
824 // else Node has not yet been cloned: clone it and clear the specified bits
Chris Lattner091f7762004-01-23 01:44:53 +0000825 DSNode *New = new DSNode(*Node, this);
826 New->maskNodeTypes(~BitsToClear);
827 NH = New; // enters in OldNodeMap
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000828
829 // now recursively clone nodes pointed to by this node
Chris Lattner091f7762004-01-23 01:44:53 +0000830 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i)
831 if (const DSNode *N = Node->getLink(i << DS::PointerShift).getNode())
832 cloneReachableNodes(N, BitsToClear, OldNodeMap, Globals);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000833}
834
Chris Lattner091f7762004-01-23 01:44:53 +0000835void DSGraph::cloneReachableSubgraph(const DSGraph &G,
836 hash_set<const DSNode*> &RootNodes,
837 NodeMapTy &OldNodeMap,
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000838 unsigned CloneFlags) {
Chris Lattner091f7762004-01-23 01:44:53 +0000839 RootNodes.erase(0); // Null is not a root node
840 if (RootNodes.empty()) return;
841 TIME_REGION(X, "cloneReachableSubgraph");
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000842
843 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
844 assert(&G != this && "Cannot clone graph into itself!");
845 assert((*RootNodes.begin())->getParentGraph() == &G &&
846 "Root nodes do not belong to this graph!");
847
848 // Remove alloca or mod/ref bits as specified...
849 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
850 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
851 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
852 BitsToClear |= DSNode::DEAD; // Clear dead flag...
853
Chris Lattner091f7762004-01-23 01:44:53 +0000854 GlobalSetTy Globals;
855
856 // Clone all nodes reachable from each root node, using a recursive helper.
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000857 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
858 E = RootNodes.end(); I != E; ++I)
Chris Lattner091f7762004-01-23 01:44:53 +0000859 cloneReachableNodes(*I, BitsToClear, OldNodeMap, Globals);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000860
861 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
Chris Lattner2f561382004-01-22 16:56:13 +0000862 // to point into the current graph.
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000863 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
Chris Lattner091f7762004-01-23 01:44:53 +0000864 I->second.getNode()->remapLinks(OldNodeMap);
865
866 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
867 InlinedGlobals.insert(Globals.begin(), Globals.end());
868
869 // Make sure to set up the scalar map entries for all of the globals.
870 //
871 // FIXME: when cloneReachableNodes is improved to not require 'remapLinks',
872 // this should not be needed!
873 for (GlobalSetTy::iterator I = Globals.begin(), E = Globals.end(); I!=E; ++I){
874 const DSNodeHandle &GOrig = G.getNodeForValue(*I);
875 DSNodeHandle &GClone = OldNodeMap[GOrig.getNode()];
876 GClone.setOffset(GClone.getOffset()+GOrig.getOffset());
877 ScalarMap[*I].mergeWith(GClone);
878 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000879}
880
881
882/// updateFromGlobalGraph - This function rematerializes global nodes and
883/// nodes reachable from them from the globals graph into the current graph.
884/// It invokes cloneReachableSubgraph, using the globals in the current graph
885/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
886/// merging globals that are already up-to-date in the current graph. In
887/// practice, in the TD pass, this is likely to be a large fraction of the
888/// live global nodes in each function (since most live nodes are likely to
889/// have been brought up-to-date in at _some_ caller or callee).
890///
891void DSGraph::updateFromGlobalGraph() {
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000892 // Put the live, non-up-to-date global nodes into a set and the up-to-date
893 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
894 hash_set<const DSNode*> GlobalNodeSet;
895 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
896 E = getScalarMap().end(); I != E; ++I)
897 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
898 DSNode* GNode = I->second.getNode();
899 assert(GNode && "No node for live global in current Graph?");
900 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
901 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
902 GlobalNodeSet.insert(GGNode);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000903 }
904
905 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
906 // and merge the cloned global nodes with the corresponding ones, if any.
Chris Lattner2f561382004-01-22 16:56:13 +0000907 {
908 NodeMapTy OldNodeMap; // Scope ensures these is deleted promptly
909 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap);
910 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000911
912 // Merging global nodes leaves behind unused nodes: get rid of them now.
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000913 removeTriviallyDeadNodes();
914}
915
Chris Lattner5a540632003-06-30 03:15:25 +0000916/// cloneInto - Clone the specified DSGraph into the current graph. The
917/// translated ScalarMap for the old function is filled into the OldValMap
918/// member, and the translated ReturnNodes map is returned into ReturnNodes.
919///
920/// The CloneFlags member controls various aspects of the cloning process.
921///
922void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
923 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
924 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000925 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000926 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000927 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000928
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000929 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000930
931 // Duplicate all of the nodes, populating the node map...
932 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000933
934 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000935 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
936 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
937 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000938 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000939 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000940 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000941 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000942 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000943 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000944 }
Chris Lattner18552922002-11-18 21:44:46 +0000945#ifndef NDEBUG
946 Timer::addPeakMemoryMeasurement();
947#endif
948
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000949 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000950 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000951 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000952
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000953 { TIME_REGION(X, "cloneInto:scalars");
954
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000955 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000956 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000957 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000958 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000959 DSNodeHandle &H = OldValMap[I->first];
960 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
961 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000962
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000963 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000964 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
965 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +0000966 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
967 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000968 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000969 }
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000970 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000971
Chris Lattner679e8e12002-11-08 21:27:12 +0000972 if (!(CloneFlags & DontCloneCallNodes)) {
973 // Copy the function calls list...
974 unsigned FC = FunctionCalls.size(); // FirstCall
975 FunctionCalls.reserve(FC+G.FunctionCalls.size());
976 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
977 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000978 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000979
Chris Lattneracf491f2002-11-08 22:27:09 +0000980 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000981 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000982 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000983 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
984 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
985 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
986 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000987
Chris Lattner5a540632003-06-30 03:15:25 +0000988 // Map the return node pointers over...
989 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
990 E = G.getReturnNodes().end(); I != E; ++I) {
991 const DSNodeHandle &Ret = I->second;
992 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
993 OldReturnNodes.insert(std::make_pair(I->first,
994 DSNodeHandle(MappedRet.getNode(),
995 MappedRet.getOffset()+Ret.getOffset())));
996 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000997}
998
Chris Lattner4c6cb7a2004-01-22 15:30:58 +0000999/// clonePartiallyInto - Clone the reachable subset of the specified DSGraph
1000/// into the current graph, for the specified function.
1001///
1002/// This differs from cloneInto in that it only clones nodes reachable from
1003/// globals, call nodes, the scalars specified in ValBindings, and the return
1004/// value of the specified function. This method merges the the cloned
1005/// version of the scalars and return value with the specified DSNodeHandles.
1006///
1007/// On return, OldNodeMap contains a mapping from the original nodes to the
1008/// newly cloned nodes, for the subset of nodes that were actually cloned.
1009///
1010/// The CloneFlags member controls various aspects of the cloning process.
1011///
1012void DSGraph::clonePartiallyInto(const DSGraph &G, Function &F,
1013 const DSNodeHandle &RetVal,
1014 const ScalarMapTy &ValBindings,
1015 NodeMapTy &OldNodeMap,
1016 unsigned CloneFlags) {
1017
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001018 TIME_REGION(X, "clonePartiallyInto");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001019 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1020 assert(&G != this && "Cannot clone graph into itself!");
1021
Chris Lattner091f7762004-01-23 01:44:53 +00001022#if 0 // ENABLE THIS to get the cloneReachableSubGraph code path
1023 hash_set<const DSNode*> RootNodes;
1024
1025#if 0
1026 // THIS IS A HACK that sanity checks the cloner. This is inefficient, and
1027 // causes all nodes to be cloned.
1028
1029 // Add the nodes that we need to clone to the RootNodes set.
1030 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i)
1031 RootNodes.insert(G.Nodes[i]);
1032
1033#else
1034 // We need the return value nodes...
1035 if (RetVal.getNode())
1036 RootNodes.insert(G.getReturnNodeFor(F).getNode());
1037
1038 // We need the nodes whose bindings are specified by the ValBindings map.
1039 for (ScalarMapTy::const_iterator I = ValBindings.begin(),
1040 E = ValBindings.end(); I != E; ++I)
1041 RootNodes.insert(G.getNodeForValue(I->first).getNode());
1042
1043 // If requested, we need the nodes from the calls list...
1044 if (!(CloneFlags & DontCloneCallNodes)) {
1045 for (unsigned i = 0, e = G.FunctionCalls.size(); i != e; ++i) {
1046 const DSCallSite &CS = G.FunctionCalls[i];
1047 RootNodes.insert(CS.getRetVal().getNode());
1048 if (CS.isIndirectCall())
1049 RootNodes.insert(CS.getCalleeNode());
1050 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1051 RootNodes.insert(CS.getPtrArg(a).getNode());
1052 }
1053 }
1054
1055 // If requested, we need the nodes from the aux calls list...
1056 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1057 for (unsigned i = 0, e = G.AuxFunctionCalls.size(); i != e; ++i) {
1058 const DSCallSite &CS = G.AuxFunctionCalls[i];
1059 RootNodes.insert(CS.getRetVal().getNode());
1060 if (CS.isIndirectCall())
1061 RootNodes.insert(CS.getCalleeNode());
1062 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1063 RootNodes.insert(CS.getPtrArg(a).getNode());
1064 }
1065 }
1066
1067
1068 /// FIXME: This is another hack, which adds all global nodes to the roots,
1069 /// this is necessary for correctness for some reason???
1070
1071 // Add the nodes that we need to clone to the RootNodes set.
1072 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i)
1073 if (!G.Nodes[i]->getGlobals().empty())
1074 RootNodes.insert(G.Nodes[i]);
1075
1076
1077#endif
1078
1079 // Finally, clone the subgraph reachable from these roots.
1080 cloneReachableSubgraph(G, RootNodes, OldNodeMap, CloneFlags);
1081#else
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001082 unsigned FN = Nodes.size(); // First new node...
1083
1084 /// FIXME: This currently clones the whole graph over, instead of doing it
1085 /// incrementally. This could be sped up quite a bit further!
1086
1087 // Duplicate all of the nodes, populating the node map...
1088 Nodes.reserve(FN+G.Nodes.size());
1089
1090 // Remove alloca or mod/ref bits as specified...
1091 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1092 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1093 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1094 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1095
1096 GlobalSetTy ClonedGlobals;
1097 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
1098 DSNode *Old = G.Nodes[i];
1099 DSNode *New = new DSNode(*Old, this);
1100 New->maskNodeTypes(~BitsToClear);
1101 OldNodeMap[Old] = New;
1102
1103 ClonedGlobals.insert(New->getGlobals().begin(), New->getGlobals().end());
1104 }
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001105
1106 // Rewrite the links in the new nodes to point into the current graph now.
1107 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
1108 Nodes[i]->remapLinks(OldNodeMap);
1109
1110 // Ensure that all global nodes end up in the scalar map, as appropriate.
1111 for (GlobalSetTy::iterator CI = ClonedGlobals.begin(),
1112 E = ClonedGlobals.end(); CI != E; ++CI) {
Chris Lattner091f7762004-01-23 01:44:53 +00001113 const DSNodeHandle &NGH = G.getNodeForValue(*CI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001114
1115 DSNodeHandle &MappedNode = OldNodeMap[NGH.getNode()];
1116 DSNodeHandle H(MappedNode.getNode(),NGH.getOffset()+MappedNode.getOffset());
1117 ScalarMap[*CI].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001118
1119 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1120 InlinedGlobals.insert(*CI);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001121 }
Chris Lattner091f7762004-01-23 01:44:53 +00001122#endif
1123
1124#ifndef NDEBUG
1125 Timer::addPeakMemoryMeasurement();
1126#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001127
1128 // Merge the requested portion of the scalar map with the values specified.
1129 for (ScalarMapTy::const_iterator I = ValBindings.begin(),
1130 E = ValBindings.end(); I != E; ++I) {
Chris Lattner091f7762004-01-23 01:44:53 +00001131 const DSNodeHandle &SNH = G.getNodeForValue(I->first);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001132
Chris Lattner091f7762004-01-23 01:44:53 +00001133 DSNodeHandle &MappedNode = OldNodeMap[SNH.getNode()];
1134 DSNodeHandle H(MappedNode.getNode(),SNH.getOffset()+MappedNode.getOffset());
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001135 H.mergeWith(I->second);
1136 }
1137
1138 // Map the return node pointer over.
1139 if (RetVal.getNode()) {
1140 const DSNodeHandle &Ret = G.getReturnNodeFor(F);
1141 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1142 DSNodeHandle H(MappedRet.getNode(),
1143 MappedRet.getOffset()+Ret.getOffset());
1144 H.mergeWith(RetVal);
1145 }
1146
1147 // If requested, copy the calls or aux-calls lists.
1148 if (!(CloneFlags & DontCloneCallNodes)) {
1149 // Copy the function calls list...
1150 unsigned FC = FunctionCalls.size(); // FirstCall
1151 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1152 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1153 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1154 }
1155
1156 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1157 // Copy the auxiliary function calls list...
1158 unsigned FC = AuxFunctionCalls.size(); // FirstCall
1159 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1160 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1161 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1162 }
1163}
1164
1165
1166
1167
Chris Lattner076c1f92002-11-07 06:31:54 +00001168/// mergeInGraph - The method is used for merging graphs together. If the
1169/// argument graph is not *this, it makes a clone of the specified graph, then
1170/// merges the nodes specified in the call site with the formal arguments in the
1171/// graph.
1172///
Chris Lattner9f930552003-06-30 05:27:18 +00001173void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1174 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001175 // If this is not a recursive call, clone the graph into this graph...
1176 if (&Graph != this) {
1177 // Clone the callee's graph into the current graph, keeping
1178 // track of where scalars in the old graph _used_ to point,
1179 // and of the new nodes matching nodes of the old graph.
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001180 ScalarMapTy ValueBindings;
Chris Lattner58f98d02003-07-02 04:38:49 +00001181
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001182 // Set up argument bindings
1183 Function::aiterator AI = F.abegin();
1184 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1185 // Advance the argument iterator to the first pointer argument...
1186 while (AI != F.aend() && !isPointerType(AI->getType())) {
1187 ++AI;
Chris Lattner076c1f92002-11-07 06:31:54 +00001188#ifndef NDEBUG
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001189 if (AI == F.aend())
1190 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001191#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001192 }
1193 if (AI == F.aend()) break;
1194
1195 // Add the link from the argument scalar to the provided value.
1196 ValueBindings[AI] = CS.getPtrArg(i);
Chris Lattner076c1f92002-11-07 06:31:54 +00001197 }
1198
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001199 NodeMapTy OldNodeMap;
1200 clonePartiallyInto(Graph, F, CS.getRetVal(), ValueBindings, OldNodeMap,
Chris Lattner091f7762004-01-23 01:44:53 +00001201 CloneFlags | DSGraph::UpdateInlinedGlobals);
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001202
1203 } else {
1204 DSNodeHandle RetVal = getReturnNodeFor(F);
1205 ScalarMapTy &ScalarMap = getScalarMap();
1206
1207 // Merge the return value with the return value of the context...
1208 RetVal.mergeWith(CS.getRetVal());
1209
1210 // Resolve all of the function arguments...
1211 Function::aiterator AI = F.abegin();
1212
1213 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1214 // Advance the argument iterator to the first pointer argument...
1215 while (AI != F.aend() && !isPointerType(AI->getType())) {
1216 ++AI;
1217#ifndef NDEBUG
1218 if (AI == F.aend())
1219 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1220#endif
1221 }
1222 if (AI == F.aend()) break;
1223
1224 // Add the link from the argument scalar to the provided value
1225 assert(ScalarMap.count(AI) && "Argument not in scalar map?");
1226 DSNodeHandle &NH = ScalarMap[AI];
1227 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1228 NH.mergeWith(CS.getPtrArg(i));
1229 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001230 }
1231}
1232
Chris Lattner58f98d02003-07-02 04:38:49 +00001233/// getCallSiteForArguments - Get the arguments and return value bindings for
1234/// the specified function in the current graph.
1235///
1236DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1237 std::vector<DSNodeHandle> Args;
1238
1239 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1240 if (isPointerType(I->getType()))
1241 Args.push_back(getScalarMap().find(I)->second);
1242
Chris Lattner808a7ae2003-09-20 16:34:13 +00001243 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001244}
1245
1246
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001247
Chris Lattner0d9bab82002-07-18 00:12:30 +00001248// markIncompleteNodes - Mark the specified node as having contents that are not
1249// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001250// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001251// must recursively traverse the data structure graph, marking all reachable
1252// nodes as incomplete.
1253//
1254static void markIncompleteNode(DSNode *N) {
1255 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001256 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001257
1258 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001259 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001260
Misha Brukman2f2d0652003-09-11 18:14:24 +00001261 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001262 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1263 if (DSNode *DSN = N->getLink(i).getNode())
1264 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001265}
1266
Chris Lattnere71ffc22002-11-11 03:36:55 +00001267static void markIncomplete(DSCallSite &Call) {
1268 // Then the return value is certainly incomplete!
1269 markIncompleteNode(Call.getRetVal().getNode());
1270
1271 // All objects pointed to by function arguments are incomplete!
1272 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1273 markIncompleteNode(Call.getPtrArg(i).getNode());
1274}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001275
1276// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1277// modified by other functions that have not been resolved yet. This marks
1278// nodes that are reachable through three sources of "unknownness":
1279//
1280// Global Variables, Function Calls, and Incoming Arguments
1281//
1282// For any node that may have unknown components (because something outside the
1283// scope of current analysis may have modified it), the 'Incomplete' flag is
1284// added to the NodeType.
1285//
Chris Lattner394471f2003-01-23 22:05:33 +00001286void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001287 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001288 if (Flags & DSGraph::MarkFormalArgs)
1289 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1290 FI != E; ++FI) {
1291 Function &F = *FI->first;
1292 if (F.getName() != "main")
1293 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1294 if (isPointerType(I->getType()) &&
1295 ScalarMap.find(I) != ScalarMap.end())
1296 markIncompleteNode(ScalarMap[I].getNode());
1297 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001298
1299 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001300 if (!shouldPrintAuxCalls())
1301 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1302 markIncomplete(FunctionCalls[i]);
1303 else
1304 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1305 markIncomplete(AuxFunctionCalls[i]);
1306
Chris Lattner0d9bab82002-07-18 00:12:30 +00001307
Chris Lattner93d7a212003-02-09 18:41:49 +00001308 // Mark all global nodes as incomplete...
1309 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1310 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001311 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001312 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001313}
1314
Chris Lattneraa8146f2002-11-10 06:59:55 +00001315static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1316 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001317 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001318 // No interesting info?
1319 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001320 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001321 Edge.setNode(0); // Kill the edge!
1322}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001323
Chris Lattneraa8146f2002-11-10 06:59:55 +00001324static inline bool nodeContainsExternalFunction(const DSNode *N) {
1325 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1326 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1327 if (Globals[i]->isExternal())
1328 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001329 return false;
1330}
1331
Chris Lattner5a540632003-06-30 03:15:25 +00001332static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001333
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001334 // Remove trivially identical function calls
1335 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001336 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1337
1338 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001339 DSNode *LastCalleeNode = 0;
1340 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001341 unsigned NumDuplicateCalls = 0;
1342 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001343 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001344 DSCallSite &CS = Calls[i];
1345
Chris Lattnere4258442002-11-11 21:35:38 +00001346 // If the Callee is a useless edge, this must be an unreachable call site,
1347 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001348 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001349 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001350 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001351 CS.swap(Calls.back());
1352 Calls.pop_back();
1353 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001354 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001355 // If the return value or any arguments point to a void node with no
1356 // information at all in it, and the call node is the only node to point
1357 // to it, remove the edge to the node (killing the node).
1358 //
1359 killIfUselessEdge(CS.getRetVal());
1360 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1361 killIfUselessEdge(CS.getPtrArg(a));
1362
1363 // If this call site calls the same function as the last call site, and if
1364 // the function pointer contains an external function, this node will
1365 // never be resolved. Merge the arguments of the call node because no
1366 // information will be lost.
1367 //
Chris Lattner923fc052003-02-05 21:59:58 +00001368 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1369 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001370 ++NumDuplicateCalls;
1371 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001372 if (LastCalleeNode)
1373 LastCalleeContainsExternalFunction =
1374 nodeContainsExternalFunction(LastCalleeNode);
1375 else
1376 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001377 }
1378
Chris Lattner58f98d02003-07-02 04:38:49 +00001379#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001380 if (LastCalleeContainsExternalFunction ||
1381 // This should be more than enough context sensitivity!
1382 // FIXME: Evaluate how many times this is tripped!
1383 NumDuplicateCalls > 20) {
1384 DSCallSite &OCS = Calls[i-1];
1385 OCS.mergeWith(CS);
1386
1387 // The node will now be eliminated as a duplicate!
1388 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1389 CS = OCS;
1390 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1391 OCS = CS;
1392 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001393#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001394 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001395 if (CS.isDirectCall()) {
1396 LastCalleeFunc = CS.getCalleeFunc();
1397 LastCalleeNode = 0;
1398 } else {
1399 LastCalleeNode = CS.getCalleeNode();
1400 LastCalleeFunc = 0;
1401 }
Chris Lattnere4258442002-11-11 21:35:38 +00001402 NumDuplicateCalls = 0;
1403 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001404 }
1405 }
1406
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001407 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001408
Chris Lattner33312f72002-11-08 01:21:07 +00001409 // Track the number of call nodes merged away...
1410 NumCallNodesMerged += NumFns-Calls.size();
1411
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001412 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001413 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001414}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001415
Chris Lattneraa8146f2002-11-10 06:59:55 +00001416
Chris Lattnere2219762002-07-18 18:22:40 +00001417// removeTriviallyDeadNodes - After the graph has been constructed, this method
1418// removes all unreachable nodes that are created because they got merged with
1419// other nodes in the graph. These nodes will all be trivially unreachable, so
1420// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001421//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001422void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001423 TIME_REGION(X, "removeTriviallyDeadNodes");
1424
Chris Lattner5a540632003-06-30 03:15:25 +00001425 removeIdenticalCalls(FunctionCalls);
1426 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001427
Chris Lattnerbab8c282003-09-20 21:34:07 +00001428 // Loop over all of the nodes in the graph, calling getNode on each field.
1429 // This will cause all nodes to update their forwarding edges, causing
1430 // forwarded nodes to be delete-able.
1431 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1432 DSNode *N = Nodes[i];
1433 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1434 N->getLink(l*N->getPointerSize()).getNode();
1435 }
1436
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001437 // Likewise, forward any edges from the scalar nodes. While we are at it,
1438 // clean house a bit.
1439 for (ScalarMapTy::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1440 // Check to see if this is a worthless node generated for non-pointer
1441 // values, such as integers. Consider an addition of long types: A+B.
1442 // Assuming we can track all uses of the value in this context, and it is
1443 // NOT used as a pointer, we can delete the node. We will be able to detect
1444 // this situation if the node pointed to ONLY has Unknown bit set in the
1445 // node. In this case, the node is not incomplete, does not point to any
1446 // other nodes (no mod/ref bits set), and is therefore uninteresting for
1447 // data structure analysis. If we run across one of these, prune the scalar
1448 // pointing to it.
1449 //
1450 DSNode *N = I->second.getNode();
1451 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1452 ScalarMap.erase(I++);
1453 else
1454 ++I;
1455 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001456
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001457 bool isGlobalsGraph = !GlobalsGraph;
1458
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001459 for (unsigned i = 0; i != Nodes.size(); ++i) {
1460 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001461
1462 // Do not remove *any* global nodes in the globals graph.
1463 // This is a special case because such nodes may not have I, M, R flags set.
1464 if (Node->isGlobalNode() && isGlobalsGraph)
1465 continue;
1466
Chris Lattner72d50a02003-06-28 21:58:28 +00001467 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001468 // This is a useless node if it has no mod/ref info (checked above),
1469 // outgoing edges (which it cannot, as it is not modified in this
1470 // context), and it has no incoming edges. If it is a global node it may
1471 // have all of these properties and still have incoming edges, due to the
1472 // scalar map, so we check those now.
1473 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001474 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001475 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001476
1477 // Loop through and make sure all of the globals are referring directly
1478 // to the node...
1479 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1480 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1481 assert(N == Node && "ScalarMap doesn't match globals list!");
1482 }
1483
Chris Lattnerbd92b732003-06-19 21:15:11 +00001484 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001485 if (Node->getNumReferrers() == Globals.size()) {
1486 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1487 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001488 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001489 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001490 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001491
1492#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1493 //
1494 // *** It seems to me that we should be able to simply check if
1495 // *** there are fewer or equal #referrers as #globals and make
1496 // *** sure that all those referrers are in the scalar map?
1497 //
1498 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1499 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1500
1501#ifndef NDEBUG
1502 // Loop through and make sure all of the globals are referring directly
1503 // to the node...
1504 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1505 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1506 assert(N == Node && "ScalarMap doesn't match globals list!");
1507 }
1508#endif
1509
1510 // Make sure NumReferrers still agrees. The node is truly dead.
1511 assert(Node->getNumReferrers() == Globals.size());
1512 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1513 ScalarMap.erase(Globals[j]);
1514 Node->makeNodeDead();
1515 }
1516#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001517 }
1518
Chris Lattnerbd92b732003-06-19 21:15:11 +00001519 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001520 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001521 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001522 Nodes[i--] = Nodes.back();
1523 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001524 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001525 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001526}
1527
1528
Chris Lattner5c7380e2003-01-29 21:10:20 +00001529/// markReachableNodes - This method recursively traverses the specified
1530/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1531/// to the set, which allows it to only traverse visited nodes once.
1532///
Chris Lattner41c04f72003-02-01 04:52:08 +00001533void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001534 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001535 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001536 if (ReachableNodes.insert(this).second) // Is newly reachable?
1537 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1538 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001539}
1540
Chris Lattner41c04f72003-02-01 04:52:08 +00001541void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001542 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001543 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001544
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001545 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1546 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001547}
1548
Chris Lattnera1220af2003-02-01 06:17:02 +00001549// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1550// looking for a node that is marked alive. If an alive node is found, return
1551// true, otherwise return false. If an alive node is reachable, this node is
1552// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001553//
Chris Lattnera1220af2003-02-01 06:17:02 +00001554static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001555 hash_set<DSNode*> &Visited,
1556 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001557 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001558 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001559
Chris Lattner85cfe012003-07-03 02:03:53 +00001560 // If this is a global node, it will end up in the globals graph anyway, so we
1561 // don't need to worry about it.
1562 if (IgnoreGlobals && N->isGlobalNode()) return false;
1563
Chris Lattneraa8146f2002-11-10 06:59:55 +00001564 // If we know that this node is alive, return so!
1565 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001566
Chris Lattneraa8146f2002-11-10 06:59:55 +00001567 // Otherwise, we don't think the node is alive yet, check for infinite
1568 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001569 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001570 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001571
Chris Lattner08db7192002-11-06 06:20:27 +00001572 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001573 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1574 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001575 N->markReachableNodes(Alive);
1576 return true;
1577 }
1578 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001579}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001580
Chris Lattnera1220af2003-02-01 06:17:02 +00001581// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1582// alive nodes.
1583//
Chris Lattner41c04f72003-02-01 04:52:08 +00001584static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001585 hash_set<DSNode*> &Visited,
1586 bool IgnoreGlobals) {
1587 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1588 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001589 return true;
1590 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001591 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001592 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001593 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001594 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1595 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001596 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001597 return false;
1598}
1599
Chris Lattnere2219762002-07-18 18:22:40 +00001600// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1601// subgraphs that are unreachable. This often occurs because the data
1602// structure doesn't "escape" into it's caller, and thus should be eliminated
1603// from the caller's graph entirely. This is only appropriate to use when
1604// inlining graphs.
1605//
Chris Lattner394471f2003-01-23 22:05:33 +00001606void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001607 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001608
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001609 // Reduce the amount of work we have to do... remove dummy nodes left over by
1610 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001611 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001612
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001613 TIME_REGION(X, "removeDeadNodes");
1614
Misha Brukman2f2d0652003-09-11 18:14:24 +00001615 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001616
1617 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001618 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001619 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001620
Chris Lattneraa8146f2002-11-10 06:59:55 +00001621 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001622 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I != E;
1623 ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001624 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001625 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001626 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001627 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001628 } else {
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001629 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001630 }
Chris Lattnere2219762002-07-18 18:22:40 +00001631
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001632 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001633 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1634 I != E; ++I)
1635 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001636
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001637 // Mark any nodes reachable by primary calls as alive...
1638 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1639 FunctionCalls[i].markReachableNodes(Alive);
1640
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001641 // Copy and merge all information about globals to the GlobalsGraph
1642 // if this is not a final pass (where unreachable globals are removed)
1643 NodeMapTy GlobalNodeMap;
1644 hash_set<const DSNode*> GlobalNodeSet;
1645
1646 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1647 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1648 GlobalNodeSet.insert(I->second); // put global nodes into a set
1649
1650 // Now find globals and aux call nodes that are already live or reach a live
1651 // value (which makes them live in turn), and continue till no more are found.
1652 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001653 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001654 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001655 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1656 do {
1657 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001658 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001659 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001660 // unreachable globals in the list.
1661 //
1662 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001663 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1664 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1665 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1666 Flags & DSGraph::RemoveUnreachableGlobals)) {
1667 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1668 GlobalNodes.pop_back(); // erase efficiently
1669 Iterate = true;
1670 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001671
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001672 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1673 // call nodes that get resolved will be difficult to remove from that graph.
1674 // The final unresolved call nodes must be handled specially at the end of
1675 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001676 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1677 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001678 (AuxFunctionCalls[i].isIndirectCall()
1679 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1680 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001681 AuxFunctionCalls[i].markReachableNodes(Alive);
1682 AuxFCallsAlive[i] = true;
1683 Iterate = true;
1684 }
1685 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001686
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001687 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001688 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001689 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1690 if (AuxFCallsAlive[i])
1691 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001692
1693 // Copy and merge all global nodes and dead aux call nodes into the
1694 // GlobalsGraph, and all nodes reachable from those nodes
1695 //
1696 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1697
1698 // First, add the dead aux call nodes to the set of root nodes for cloning
1699 // -- return value at this call site, if any
1700 // -- actual arguments passed at this call site
1701 // -- callee node at this call site, if this is an indirect call
1702 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1703 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1704 GlobalNodeSet.insert(RetNode);
1705 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1706 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1707 GlobalNodeSet.insert(ArgTarget);
1708 if (AuxFunctionCalls[i].isIndirectCall())
1709 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1710 }
1711
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001712 // Strip all alloca bits since the current function is only for the BU pass.
1713 // Strip all incomplete bits since they are short-lived properties and they
1714 // will be correctly computed when rematerializing nodes into the functions.
1715 //
Chris Lattner2f561382004-01-22 16:56:13 +00001716 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet, GlobalNodeMap,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001717 (DSGraph::StripAllocaBit |
1718 DSGraph::StripIncompleteBit));
1719 }
1720
1721 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001722 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001723 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001724
1725 // Copy the unreachable call nodes to the globals graph, updating
1726 // their target pointers using the GlobalNodeMap
1727 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1728 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1729 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001730 }
1731 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001732 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1733 AuxFunctionCalls.end());
1734
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001735 // We are finally done with the GlobalNodeMap so we can clear it and
1736 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1737 GlobalNodeMap.clear();
1738 GlobalsGraph->removeTriviallyDeadNodes();
1739
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001740 // At this point, any nodes which are visited, but not alive, are nodes
1741 // which can be removed. Loop over all nodes, eliminating completely
1742 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001743 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001744 std::vector<DSNode*> DeadNodes;
1745 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001746 for (unsigned i = 0; i != Nodes.size(); ++i)
1747 if (!Alive.count(Nodes[i])) {
1748 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001749 Nodes[i--] = Nodes.back(); // move node to end of vector
1750 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001751 DeadNodes.push_back(N);
1752 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001753 } else {
1754 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001755 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001756
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001757 // Remove all unreachable globals from the ScalarMap.
1758 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1759 // In either case, the dead nodes will not be in the set Alive.
1760 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1761 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1762 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1763 if (!Alive.count(GlobalNodes[i].second))
1764 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001765 }
1766
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001767 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001768 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1769 delete DeadNodes[i];
1770
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001771 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001772}
1773
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001774void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001775 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1776 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001777
Chris Lattner8d327672003-06-30 03:36:09 +00001778 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001779 E = ScalarMap.end(); I != E; ++I) {
1780 assert(I->second.getNode() && "Null node in scalarmap!");
1781 AssertNodeInGraph(I->second.getNode());
1782 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001783 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001784 "Global points to node, but node isn't global?");
1785 AssertNodeContainsGlobal(I->second.getNode(), GV);
1786 }
1787 }
1788 AssertCallNodesInGraph();
1789 AssertAuxCallNodesInGraph();
1790}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001791
Chris Lattner7ddb0132003-08-05 18:38:37 +00001792/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1793/// globals graph into the DS, BU or TD graph for a function. This code retains
1794/// all globals, i.e., does not delete unreachable globals after they are
1795/// inlined.
1796///
1797void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001798 NodeMapTy GlobalNodeMap;
1799 ScalarMapTy OldValMap;
1800 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001801 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1802 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
Chris Lattner091f7762004-01-23 01:44:53 +00001803 DSGraph::DontCloneAuxCallNodes | DSGraph::UpdateInlinedGlobals);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001804
1805 // Now merge existing global nodes in the GlobalsGraph with their copies
1806 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1807 I != E; ++I)
1808 if (isa<GlobalValue>(I->first)) { // Found a global node
1809 DSNodeHandle &GH = I->second;
1810 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1811 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1812 }
1813
1814 // Merging leaves behind unused nodes: get rid of them now.
1815 GlobalNodeMap.clear();
1816 OldValMap.clear();
1817 OldRetNodes.clear();
1818 removeTriviallyDeadNodes();
1819}
Chris Lattner400433d2003-11-11 05:08:59 +00001820
Brian Gaeked0fde302003-11-11 22:41:34 +00001821
Chris Lattner400433d2003-11-11 05:08:59 +00001822/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1823/// nodes reachable from the two graphs, computing the mapping of nodes from
1824/// the first to the second graph.
1825///
1826void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001827 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1828 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001829 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1830 if (N1 == 0 || N2 == 0) return;
1831
1832 DSNodeHandle &Entry = NodeMap[N1];
1833 if (Entry.getNode()) {
1834 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001835 assert(!StrictChecking ||
1836 (Entry.getNode() == N2 &&
1837 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001838 "Inconsistent mapping detected!");
1839 return;
1840 }
1841
1842 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001843 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001844
1845 // Loop over all of the fields that N1 and N2 have in common, recursively
1846 // mapping the edges together now.
1847 int N2Idx = NH2.getOffset()-NH1.getOffset();
1848 unsigned N2Size = N2->getSize();
1849 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1850 if (unsigned(N2Idx)+i < N2Size)
1851 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1852}