blob: 2f8b2b447dd9469bd2a146035657704b6274ed53 [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
39
40
Chris Lattnerb1060432002-11-07 05:20:53 +000041using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000042
Chris Lattner731b2d72003-02-13 19:09:00 +000043DSNode *DSNodeHandle::HandleForwarding() const {
44 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
45
46 // Handle node forwarding here!
47 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
48 Offset += N->ForwardNH.getOffset();
49
50 if (--N->NumReferrers == 0) {
51 // Removing the last referrer to the node, sever the forwarding link
52 N->stopForwarding();
53 }
54
55 N = Next;
56 N->NumReferrers++;
57 if (N->Size <= Offset) {
58 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
59 Offset = 0;
60 }
61 return N;
62}
63
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000064//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000065// DSNode Implementation
66//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000067
Chris Lattnerbd92b732003-06-19 21:15:11 +000068DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000069 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000070 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000071 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000072 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000073}
74
Chris Lattner0d9bab82002-07-18 00:12:30 +000075// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000076DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000077 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000078 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000079 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000080}
81
Chris Lattner15869aa2003-11-02 22:27:28 +000082/// getTargetData - Get the target data object used to construct this node.
83///
84const TargetData &DSNode::getTargetData() const {
85 return ParentGraph->getTargetData();
86}
87
Chris Lattner72d29a42003-02-11 23:11:51 +000088void DSNode::assertOK() const {
89 assert((Ty != Type::VoidTy ||
90 Ty == Type::VoidTy && (Size == 0 ||
91 (NodeType & DSNode::Array))) &&
92 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +000093
94 assert(ParentGraph && "Node has no parent?");
95 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
96 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
97 assert(SM.find(Globals[i]) != SM.end());
98 assert(SM.find(Globals[i])->second.getNode() == this);
99 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000100}
101
102/// forwardNode - Mark this node as being obsolete, and all references to it
103/// should be forwarded to the specified node and offset.
104///
105void DSNode::forwardNode(DSNode *To, unsigned Offset) {
106 assert(this != To && "Cannot forward a node to itself!");
107 assert(ForwardNH.isNull() && "Already forwarding from this node!");
108 if (To->Size <= 1) Offset = 0;
109 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
110 "Forwarded offset is wrong!");
111 ForwardNH.setNode(To);
112 ForwardNH.setOffset(Offset);
113 NodeType = DEAD;
114 Size = 0;
115 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000116}
117
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000118// addGlobal - Add an entry for a global value to the Globals list. This also
119// marks the node with the 'G' flag if it does not already have it.
120//
121void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000122 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000123 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000124 std::lower_bound(Globals.begin(), Globals.end(), GV);
125
126 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000127 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000128 Globals.insert(I, GV);
129 NodeType |= GlobalNode;
130 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000131}
132
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000133/// foldNodeCompletely - If we determine that this node has some funny
134/// behavior happening to it that we cannot represent, we fold it down to a
135/// single, completely pessimistic, node. This node is represented as a
136/// single byte with a single TypeEntry of "void".
137///
138void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000139 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000140
Chris Lattner08db7192002-11-06 06:20:27 +0000141 ++NumFolds;
142
Chris Lattner72d29a42003-02-11 23:11:51 +0000143 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000144 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000145 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000146 DestNode->Ty = Type::VoidTy;
147 DestNode->Size = 1;
148 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000149
Chris Lattner72d29a42003-02-11 23:11:51 +0000150 // Start forwarding to the destination node...
151 forwardNode(DestNode, 0);
152
153 if (Links.size()) {
154 DestNode->Links.push_back(Links[0]);
155 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000156
Chris Lattner72d29a42003-02-11 23:11:51 +0000157 // If we have links, merge all of our outgoing links together...
158 for (unsigned i = Links.size()-1; i != 0; --i)
159 NH.getNode()->Links[0].mergeWith(Links[i]);
160 Links.clear();
161 } else {
162 DestNode->Links.resize(1);
163 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000164}
Chris Lattner076c1f92002-11-07 06:31:54 +0000165
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000166/// isNodeCompletelyFolded - Return true if this node has been completely
167/// folded down to something that can never be expanded, effectively losing
168/// all of the field sensitivity that may be present in the node.
169///
170bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000171 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000172}
173
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000174namespace {
175 /// TypeElementWalker Class - Used for implementation of physical subtyping...
176 ///
177 class TypeElementWalker {
178 struct StackState {
179 const Type *Ty;
180 unsigned Offset;
181 unsigned Idx;
182 StackState(const Type *T, unsigned Off = 0)
183 : Ty(T), Offset(Off), Idx(0) {}
184 };
185
186 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000187 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000188 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000189 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000190 Stack.push_back(T);
191 StepToLeaf();
192 }
193
194 bool isDone() const { return Stack.empty(); }
195 const Type *getCurrentType() const { return Stack.back().Ty; }
196 unsigned getCurrentOffset() const { return Stack.back().Offset; }
197
198 void StepToNextType() {
199 PopStackAndAdvance();
200 StepToLeaf();
201 }
202
203 private:
204 /// PopStackAndAdvance - Pop the current element off of the stack and
205 /// advance the underlying element to the next contained member.
206 void PopStackAndAdvance() {
207 assert(!Stack.empty() && "Cannot pop an empty stack!");
208 Stack.pop_back();
209 while (!Stack.empty()) {
210 StackState &SS = Stack.back();
211 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
212 ++SS.Idx;
213 if (SS.Idx != ST->getElementTypes().size()) {
214 const StructLayout *SL = TD.getStructLayout(ST);
215 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
216 return;
217 }
218 Stack.pop_back(); // At the end of the structure
219 } else {
220 const ArrayType *AT = cast<ArrayType>(SS.Ty);
221 ++SS.Idx;
222 if (SS.Idx != AT->getNumElements()) {
223 SS.Offset += TD.getTypeSize(AT->getElementType());
224 return;
225 }
226 Stack.pop_back(); // At the end of the array
227 }
228 }
229 }
230
231 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
232 /// on the type stack.
233 void StepToLeaf() {
234 if (Stack.empty()) return;
235 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
236 StackState &SS = Stack.back();
237 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
238 if (ST->getElementTypes().empty()) {
239 assert(SS.Idx == 0);
240 PopStackAndAdvance();
241 } else {
242 // Step into the structure...
243 assert(SS.Idx < ST->getElementTypes().size());
244 const StructLayout *SL = TD.getStructLayout(ST);
245 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
246 SS.Offset+SL->MemberOffsets[SS.Idx]));
247 }
248 } else {
249 const ArrayType *AT = cast<ArrayType>(SS.Ty);
250 if (AT->getNumElements() == 0) {
251 assert(SS.Idx == 0);
252 PopStackAndAdvance();
253 } else {
254 // Step into the array...
255 assert(SS.Idx < AT->getNumElements());
256 Stack.push_back(StackState(AT->getElementType(),
257 SS.Offset+SS.Idx*
258 TD.getTypeSize(AT->getElementType())));
259 }
260 }
261 }
262 }
263 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000264} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000265
266/// ElementTypesAreCompatible - Check to see if the specified types are
267/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000268/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
269/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000270///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000271static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000272 bool AllowLargerT1, const TargetData &TD){
273 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000274
275 while (!T1W.isDone() && !T2W.isDone()) {
276 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
277 return false;
278
279 const Type *T1 = T1W.getCurrentType();
280 const Type *T2 = T2W.getCurrentType();
281 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
282 return false;
283
284 T1W.StepToNextType();
285 T2W.StepToNextType();
286 }
287
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000288 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000289}
290
291
Chris Lattner08db7192002-11-06 06:20:27 +0000292/// mergeTypeInfo - This method merges the specified type into the current node
293/// at the specified offset. This may update the current node's type record if
294/// this gives more information to the node, it may do nothing to the node if
295/// this information is already known, or it may merge the node completely (and
296/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000297///
Chris Lattner08db7192002-11-06 06:20:27 +0000298/// This method returns true if the node is completely folded, otherwise false.
299///
Chris Lattner088b6392003-03-03 17:13:31 +0000300bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
301 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000302 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000303 // Check to make sure the Size member is up-to-date. Size can be one of the
304 // following:
305 // Size = 0, Ty = Void: Nothing is known about this node.
306 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
307 // Size = 1, Ty = Void, Array = 1: The node is collapsed
308 // Otherwise, sizeof(Ty) = Size
309 //
Chris Lattner18552922002-11-18 21:44:46 +0000310 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
311 (Size == 0 && !Ty->isSized() && !isArray()) ||
312 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
313 (Size == 0 && !Ty->isSized() && !isArray()) ||
314 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000315 "Size member of DSNode doesn't match the type structure!");
316 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000317
Chris Lattner18552922002-11-18 21:44:46 +0000318 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000319 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000320
Chris Lattner08db7192002-11-06 06:20:27 +0000321 // Return true immediately if the node is completely folded.
322 if (isNodeCompletelyFolded()) return true;
323
Chris Lattner23f83dc2002-11-08 22:49:57 +0000324 // If this is an array type, eliminate the outside arrays because they won't
325 // be used anyway. This greatly reduces the size of large static arrays used
326 // as global variables, for example.
327 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000328 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000329 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
330 // FIXME: we might want to keep small arrays, but must be careful about
331 // things like: [2 x [10000 x int*]]
332 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000333 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000334 }
335
Chris Lattner08db7192002-11-06 06:20:27 +0000336 // Figure out how big the new type we're merging in is...
337 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
338
339 // Otherwise check to see if we can fold this type into the current node. If
340 // we can't, we fold the node completely, if we can, we potentially update our
341 // internal state.
342 //
Chris Lattner18552922002-11-18 21:44:46 +0000343 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000344 // If this is the first type that this node has seen, just accept it without
345 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000346 assert(Offset == 0 && !isArray() &&
347 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000348 Ty = NewTy;
349 NodeType &= ~Array;
350 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000351 Size = NewTySize;
352
353 // Calculate the number of outgoing links from this node.
354 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
355 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000356 }
Chris Lattner08db7192002-11-06 06:20:27 +0000357
358 // Handle node expansion case here...
359 if (Offset+NewTySize > Size) {
360 // It is illegal to grow this node if we have treated it as an array of
361 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000362 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000363 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000364 return true;
365 }
366
367 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000368 std::cerr << "UNIMP: Trying to merge a growth type into "
369 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000370 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000371 return true;
372 }
373
374 // Okay, the situation is nice and simple, we are trying to merge a type in
375 // at offset 0 that is bigger than our current type. Implement this by
376 // switching to the new type and then merge in the smaller one, which should
377 // hit the other code path here. If the other code path decides it's not
378 // ok, it will collapse the node as appropriate.
379 //
Chris Lattner18552922002-11-18 21:44:46 +0000380 const Type *OldTy = Ty;
381 Ty = NewTy;
382 NodeType &= ~Array;
383 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000384 Size = NewTySize;
385
386 // Must grow links to be the appropriate size...
387 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
388
389 // Merge in the old type now... which is guaranteed to be smaller than the
390 // "current" type.
391 return mergeTypeInfo(OldTy, 0);
392 }
393
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000394 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000395 "Cannot merge something into a part of our type that doesn't exist!");
396
Chris Lattner18552922002-11-18 21:44:46 +0000397 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000398 // type that starts at offset Offset.
399 //
400 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000401 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000402 while (O < Offset) {
403 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
404
405 switch (SubType->getPrimitiveID()) {
406 case Type::StructTyID: {
407 const StructType *STy = cast<StructType>(SubType);
408 const StructLayout &SL = *TD.getStructLayout(STy);
409
410 unsigned i = 0, e = SL.MemberOffsets.size();
411 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
412 /* empty */;
413
414 // The offset we are looking for must be in the i'th element...
415 SubType = STy->getElementTypes()[i];
416 O += SL.MemberOffsets[i];
417 break;
418 }
419 case Type::ArrayTyID: {
420 SubType = cast<ArrayType>(SubType)->getElementType();
421 unsigned ElSize = TD.getTypeSize(SubType);
422 unsigned Remainder = (Offset-O) % ElSize;
423 O = Offset-Remainder;
424 break;
425 }
426 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000427 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000428 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000429 }
430 }
431
432 assert(O == Offset && "Could not achieve the correct offset!");
433
434 // If we found our type exactly, early exit
435 if (SubType == NewTy) return false;
436
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000437 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
438
439 // Ok, we are getting desperate now. Check for physical subtyping, where we
440 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000441 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000442 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000443 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000444 return false;
445
Chris Lattner08db7192002-11-06 06:20:27 +0000446 // Okay, so we found the leader type at the offset requested. Search the list
447 // of types that starts at this offset. If SubType is currently an array or
448 // structure, the type desired may actually be the first element of the
449 // composite type...
450 //
Chris Lattner18552922002-11-18 21:44:46 +0000451 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000452 while (SubType != NewTy) {
453 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000454 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000455 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000456 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000457 case Type::StructTyID: {
458 const StructType *STy = cast<StructType>(SubType);
459 const StructLayout &SL = *TD.getStructLayout(STy);
460 if (SL.MemberOffsets.size() > 1)
461 NextPadSize = SL.MemberOffsets[1];
462 else
463 NextPadSize = SubTypeSize;
464 NextSubType = STy->getElementTypes()[0];
465 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000466 break;
Chris Lattner18552922002-11-18 21:44:46 +0000467 }
Chris Lattner08db7192002-11-06 06:20:27 +0000468 case Type::ArrayTyID:
469 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000470 NextSubTypeSize = TD.getTypeSize(NextSubType);
471 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000472 break;
473 default: ;
474 // fall out
475 }
476
477 if (NextSubType == 0)
478 break; // In the default case, break out of the loop
479
Chris Lattner18552922002-11-18 21:44:46 +0000480 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000481 break; // Don't allow shrinking to a smaller type than NewTySize
482 SubType = NextSubType;
483 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000484 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000485 }
486
487 // If we found the type exactly, return it...
488 if (SubType == NewTy)
489 return false;
490
491 // Check to see if we have a compatible, but different type...
492 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000493 // Check to see if this type is obviously convertible... int -> uint f.e.
494 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000495 return false;
496
497 // Check to see if we have a pointer & integer mismatch going on here,
498 // loading a pointer as a long, for example.
499 //
500 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
501 NewTy->isInteger() && isa<PointerType>(SubType))
502 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000503 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
504 // We are accessing the field, plus some structure padding. Ignore the
505 // structure padding.
506 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000507 }
508
Chris Lattner58f98d02003-07-02 04:38:49 +0000509 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000510 if (getParentGraph()->getReturnNodes().size())
511 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000512 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
513 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
514 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
515 << "SubType: ";
516 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000517
Chris Lattner088b6392003-03-03 17:13:31 +0000518 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000519 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000520}
521
Chris Lattner08db7192002-11-06 06:20:27 +0000522
523
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000524// addEdgeTo - Add an edge from the current node to the specified node. This
525// can cause merging of nodes in the graph.
526//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000527void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000528 if (NH.getNode() == 0) return; // Nothing to do
529
Chris Lattner08db7192002-11-06 06:20:27 +0000530 DSNodeHandle &ExistingEdge = getLink(Offset);
531 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000532 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000533 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000534 } else { // No merging to perform...
535 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000536 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000537}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000538
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000539
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000540// MergeSortedVectors - Efficiently merge a vector into another vector where
541// duplicates are not allowed and both are sorted. This assumes that 'T's are
542// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000543//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000544static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
545 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000546 // By far, the most common cases will be the simple ones. In these cases,
547 // avoid having to allocate a temporary vector...
548 //
549 if (Src.empty()) { // Nothing to merge in...
550 return;
551 } else if (Dest.empty()) { // Just copy the result in...
552 Dest = Src;
553 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000554 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000555 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000556 std::lower_bound(Dest.begin(), Dest.end(), V);
557 if (I == Dest.end() || *I != Src[0]) // If not already contained...
558 Dest.insert(I, Src[0]);
559 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000560 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000561 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000562 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000563 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
564 if (I == Dest.end() || *I != Tmp) // If not already contained...
565 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000566
567 } else {
568 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000569 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000570
571 // Make space for all of the type entries now...
572 Dest.resize(Dest.size()+Src.size());
573
574 // Merge the two sorted ranges together... into Dest.
575 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
576
577 // Now erase any duplicate entries that may have accumulated into the
578 // vectors (because they were in both of the input sets)
579 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
580 }
581}
582
583
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000584// MergeNodes() - Helper function for DSNode::mergeWith().
585// This function does the hard work of merging two nodes, CurNodeH
586// and NH after filtering out trivial cases and making sure that
587// CurNodeH.offset >= NH.offset.
588//
589// ***WARNING***
590// Since merging may cause either node to go away, we must always
591// use the node-handles to refer to the nodes. These node handles are
592// automatically updated during merging, so will always provide access
593// to the correct node after a merge.
594//
595void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
596 assert(CurNodeH.getOffset() >= NH.getOffset() &&
597 "This should have been enforced in the caller.");
598
599 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
600 // respect to NH.Offset) is now zero. NOffset is the distance from the base
601 // of our object that N starts from.
602 //
603 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
604 unsigned NSize = NH.getNode()->getSize();
605
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000606 // If the two nodes are of different size, and the smaller node has the array
607 // bit set, collapse!
608 if (NSize != CurNodeH.getNode()->getSize()) {
609 if (NSize < CurNodeH.getNode()->getSize()) {
610 if (NH.getNode()->isArray())
611 NH.getNode()->foldNodeCompletely();
612 } else if (CurNodeH.getNode()->isArray()) {
613 NH.getNode()->foldNodeCompletely();
614 }
615 }
616
617 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000618 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000619 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000620 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000621
622 // If we are merging a node with a completely folded node, then both nodes are
623 // now completely folded.
624 //
625 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
626 if (!NH.getNode()->isNodeCompletelyFolded()) {
627 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000628 assert(NH.getNode() && NH.getOffset() == 0 &&
629 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000630 NOffset = NH.getOffset();
631 NSize = NH.getNode()->getSize();
632 assert(NOffset == 0 && NSize == 1);
633 }
634 } else if (NH.getNode()->isNodeCompletelyFolded()) {
635 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000636 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
637 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000638 NOffset = NH.getOffset();
639 NSize = NH.getNode()->getSize();
640 assert(NOffset == 0 && NSize == 1);
641 }
642
Chris Lattner72d29a42003-02-11 23:11:51 +0000643 DSNode *N = NH.getNode();
644 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000645 assert(!CurNodeH.getNode()->isDeadNode());
646
647 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000648 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000649
Chris Lattner72d29a42003-02-11 23:11:51 +0000650 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000651 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000652 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000653
Chris Lattner72d29a42003-02-11 23:11:51 +0000654 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
655 //
656 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
657 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000658 if (Link.getNode()) {
659 // Compute the offset into the current node at which to
660 // merge this link. In the common case, this is a linear
661 // relation to the offset in the original node (with
662 // wrapping), but if the current node gets collapsed due to
663 // recursive merging, we must make sure to merge in all remaining
664 // links at offset zero.
665 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000666 DSNode *CN = CurNodeH.getNode();
667 if (CN->Size != 1)
668 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
669 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000670 }
671 }
672
673 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000674 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000675
676 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000677 if (!N->Globals.empty()) {
678 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000679
680 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000681 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000682 }
683}
684
685
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000686// mergeWith - Merge this node and the specified node, moving all links to and
687// from the argument node into the current node, deleting the node argument.
688// Offset indicates what offset the specified node is to be merged into the
689// current node.
690//
Chris Lattner5254a8d2004-01-22 16:31:08 +0000691// The specified node may be a null pointer (in which case, we update it to
692// point to this node).
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000693//
694void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
695 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000696 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000697 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000698
Chris Lattner5254a8d2004-01-22 16:31:08 +0000699 // If the RHS is a null node, make it point to this node!
700 if (N == 0) {
701 NH.mergeWith(DSNodeHandle(this, Offset));
702 return;
703 }
704
Chris Lattnerbd92b732003-06-19 21:15:11 +0000705 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000706 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
707
Chris Lattner02606632002-11-04 06:48:26 +0000708 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000709 // We cannot merge two pieces of the same node together, collapse the node
710 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000711 DEBUG(std::cerr << "Attempting to merge two chunks of"
712 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000713 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000714 return;
715 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000716
Chris Lattner5190ce82002-11-12 07:20:45 +0000717 // If both nodes are not at offset 0, make sure that we are merging the node
718 // at an later offset into the node with the zero offset.
719 //
720 if (Offset < NH.getOffset()) {
721 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
722 return;
723 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
724 // If the offsets are the same, merge the smaller node into the bigger node
725 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
726 return;
727 }
728
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000729 // Ok, now we can merge the two nodes. Use a static helper that works with
730 // two node handles, since "this" may get merged away at intermediate steps.
731 DSNodeHandle CurNodeH(this, Offset);
732 DSNodeHandle NHCopy(NH);
733 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000734}
735
Chris Lattner9de906c2002-10-20 22:11:44 +0000736//===----------------------------------------------------------------------===//
737// DSCallSite Implementation
738//===----------------------------------------------------------------------===//
739
Vikram S. Adve26b98262002-10-20 21:41:02 +0000740// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000741Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000742 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000743}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000744
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000745
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000746//===----------------------------------------------------------------------===//
747// DSGraph Implementation
748//===----------------------------------------------------------------------===//
749
Chris Lattnera9d65662003-06-30 05:57:30 +0000750/// getFunctionNames - Return a space separated list of the name of the
751/// functions in this graph (if any)
752std::string DSGraph::getFunctionNames() const {
753 switch (getReturnNodes().size()) {
754 case 0: return "Globals graph";
755 case 1: return getReturnNodes().begin()->first->getName();
756 default:
757 std::string Return;
758 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
759 I != getReturnNodes().end(); ++I)
760 Return += I->first->getName() + " ";
761 Return.erase(Return.end()-1, Return.end()); // Remove last space character
762 return Return;
763 }
764}
765
766
Chris Lattner15869aa2003-11-02 22:27:28 +0000767DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000768 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000769 NodeMapTy NodeMap;
770 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000771 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattner0d9bab82002-07-18 00:12:30 +0000772}
773
Chris Lattner5a540632003-06-30 03:15:25 +0000774DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +0000775 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000776 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000777 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000778 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattnereff0da92002-10-21 15:32:34 +0000779}
780
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000781DSGraph::~DSGraph() {
782 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000783 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000784 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000785 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000786 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000787
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000788 // Drop all intra-node references, so that assertions don't fail...
789 std::for_each(Nodes.begin(), Nodes.end(),
790 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000791
792 // Delete all of the nodes themselves...
793 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
794}
795
Chris Lattner0d9bab82002-07-18 00:12:30 +0000796// dump - Allow inspection of graph in a debugger.
797void DSGraph::dump() const { print(std::cerr); }
798
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000799
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000800/// remapLinks - Change all of the Links in the current node according to the
801/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000802///
Chris Lattner8d327672003-06-30 03:36:09 +0000803void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +0000804 for (unsigned i = 0, e = Links.size(); i != e; ++i)
805 if (DSNode *N = Links[i].getNode()) {
806 DSNodeHandle &H = OldNodeMap[N];
807 Links[i].setNode(H.getNode());
808 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
809 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000810}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000811
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000812
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000813/// cloneReachableNodes - Clone all reachable nodes from *Node into the
814/// current graph. This is a recursive function. The map OldNodeMap is a
815/// map from the original nodes to their clones.
816///
Chris Lattner2f561382004-01-22 16:56:13 +0000817void DSGraph::cloneReachableNodes(const DSNode* Node, unsigned BitsToClear,
818 NodeMapTy& OldNodeMap) {
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000819 DSNodeHandle& NH = OldNodeMap[Node];
820 if (NH.getNode() != NULL)
821 return;
822
823 // else Node has not yet been cloned: clone it and clear the specified bits
824 NH = new DSNode(*Node, this); // enters in OldNodeMap
825 NH.getNode()->maskNodeTypes(~BitsToClear);
826
827 // now recursively clone nodes pointed to by this node
828 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
829 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
830 if (const DSNode* nextNode = Link.getNode())
Chris Lattner2f561382004-01-22 16:56:13 +0000831 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000832 }
833}
834
835void DSGraph::cloneReachableSubgraph(const DSGraph& G,
836 const hash_set<const DSNode*>& RootNodes,
837 NodeMapTy& OldNodeMap,
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000838 unsigned CloneFlags) {
839 if (RootNodes.empty())
840 return;
841
842 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
843 assert(&G != this && "Cannot clone graph into itself!");
844 assert((*RootNodes.begin())->getParentGraph() == &G &&
845 "Root nodes do not belong to this graph!");
846
847 // Remove alloca or mod/ref bits as specified...
848 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
849 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
850 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
851 BitsToClear |= DSNode::DEAD; // Clear dead flag...
852
853 // Clone all nodes reachable from each root node, using a recursive helper
854 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
855 E = RootNodes.end(); I != E; ++I)
Chris Lattner2f561382004-01-22 16:56:13 +0000856 cloneReachableNodes(*I, BitsToClear, OldNodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000857
858 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
Chris Lattner2f561382004-01-22 16:56:13 +0000859 // to point into the current graph.
860 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I) {
861 assert(I->first && "Null node pointer?");
862 I->second.getNode()->remapLinks(OldNodeMap);
863 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000864
865 // Now merge cloned global nodes with their copies in the current graph
866 // Just look through OldNodeMap to find such nodes!
867 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
868 if (I->first->isGlobalNode()) {
869 DSNodeHandle &GClone = I->second;
870 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
871 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
872 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
873 DSNodeHandle &GH = ScalarMap[Globals[gi]];
874 GH.mergeWith(GClone);
875 }
876 }
877}
878
879
880/// updateFromGlobalGraph - This function rematerializes global nodes and
881/// nodes reachable from them from the globals graph into the current graph.
882/// It invokes cloneReachableSubgraph, using the globals in the current graph
883/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
884/// merging globals that are already up-to-date in the current graph. In
885/// practice, in the TD pass, this is likely to be a large fraction of the
886/// live global nodes in each function (since most live nodes are likely to
887/// have been brought up-to-date in at _some_ caller or callee).
888///
889void DSGraph::updateFromGlobalGraph() {
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000890 // Put the live, non-up-to-date global nodes into a set and the up-to-date
891 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
892 hash_set<const DSNode*> GlobalNodeSet;
893 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
894 E = getScalarMap().end(); I != E; ++I)
895 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
896 DSNode* GNode = I->second.getNode();
897 assert(GNode && "No node for live global in current Graph?");
898 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
899 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
900 GlobalNodeSet.insert(GGNode);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000901 }
902
903 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
904 // and merge the cloned global nodes with the corresponding ones, if any.
Chris Lattner2f561382004-01-22 16:56:13 +0000905 {
906 NodeMapTy OldNodeMap; // Scope ensures these is deleted promptly
907 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap);
908 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000909
910 // Merging global nodes leaves behind unused nodes: get rid of them now.
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000911 removeTriviallyDeadNodes();
912}
913
Chris Lattner5a540632003-06-30 03:15:25 +0000914/// cloneInto - Clone the specified DSGraph into the current graph. The
915/// translated ScalarMap for the old function is filled into the OldValMap
916/// member, and the translated ReturnNodes map is returned into ReturnNodes.
917///
918/// The CloneFlags member controls various aspects of the cloning process.
919///
920void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
921 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
922 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000923 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000924 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000925 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000926
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000927 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000928
929 // Duplicate all of the nodes, populating the node map...
930 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000931
932 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000933 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
934 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
935 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000936 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000937 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000938 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000939 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000940 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000941 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000942 }
Chris Lattner18552922002-11-18 21:44:46 +0000943#ifndef NDEBUG
944 Timer::addPeakMemoryMeasurement();
945#endif
946
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000947 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000948 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000949 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000950
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000951 { TIME_REGION(X, "cloneInto:scalars");
952
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000953 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000954 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000955 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000956 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000957 DSNodeHandle &H = OldValMap[I->first];
958 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
959 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000960
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000961 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000962 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
963 ScalarMap[GV].mergeWith(H);
964 InlinedGlobals.insert(GV);
965 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000966 }
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000967 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000968
Chris Lattner679e8e12002-11-08 21:27:12 +0000969 if (!(CloneFlags & DontCloneCallNodes)) {
970 // Copy the function calls list...
971 unsigned FC = FunctionCalls.size(); // FirstCall
972 FunctionCalls.reserve(FC+G.FunctionCalls.size());
973 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
974 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000975 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000976
Chris Lattneracf491f2002-11-08 22:27:09 +0000977 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000978 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000979 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000980 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
981 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
982 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
983 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000984
Chris Lattner5a540632003-06-30 03:15:25 +0000985 // Map the return node pointers over...
986 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
987 E = G.getReturnNodes().end(); I != E; ++I) {
988 const DSNodeHandle &Ret = I->second;
989 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
990 OldReturnNodes.insert(std::make_pair(I->first,
991 DSNodeHandle(MappedRet.getNode(),
992 MappedRet.getOffset()+Ret.getOffset())));
993 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000994}
995
Chris Lattner4c6cb7a2004-01-22 15:30:58 +0000996/// clonePartiallyInto - Clone the reachable subset of the specified DSGraph
997/// into the current graph, for the specified function.
998///
999/// This differs from cloneInto in that it only clones nodes reachable from
1000/// globals, call nodes, the scalars specified in ValBindings, and the return
1001/// value of the specified function. This method merges the the cloned
1002/// version of the scalars and return value with the specified DSNodeHandles.
1003///
1004/// On return, OldNodeMap contains a mapping from the original nodes to the
1005/// newly cloned nodes, for the subset of nodes that were actually cloned.
1006///
1007/// The CloneFlags member controls various aspects of the cloning process.
1008///
1009void DSGraph::clonePartiallyInto(const DSGraph &G, Function &F,
1010 const DSNodeHandle &RetVal,
1011 const ScalarMapTy &ValBindings,
1012 NodeMapTy &OldNodeMap,
1013 unsigned CloneFlags) {
1014
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001015 TIME_REGION(X, "clonePartiallyInto");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001016 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1017 assert(&G != this && "Cannot clone graph into itself!");
1018
1019 unsigned FN = Nodes.size(); // First new node...
1020
1021 /// FIXME: This currently clones the whole graph over, instead of doing it
1022 /// incrementally. This could be sped up quite a bit further!
1023
1024 // Duplicate all of the nodes, populating the node map...
1025 Nodes.reserve(FN+G.Nodes.size());
1026
1027 // Remove alloca or mod/ref bits as specified...
1028 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1029 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1030 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1031 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1032
1033 GlobalSetTy ClonedGlobals;
1034 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
1035 DSNode *Old = G.Nodes[i];
1036 DSNode *New = new DSNode(*Old, this);
1037 New->maskNodeTypes(~BitsToClear);
1038 OldNodeMap[Old] = New;
1039
1040 ClonedGlobals.insert(New->getGlobals().begin(), New->getGlobals().end());
1041 }
1042#ifndef NDEBUG
1043 Timer::addPeakMemoryMeasurement();
1044#endif
1045
1046 // Rewrite the links in the new nodes to point into the current graph now.
1047 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
1048 Nodes[i]->remapLinks(OldNodeMap);
1049
1050 // Ensure that all global nodes end up in the scalar map, as appropriate.
1051 for (GlobalSetTy::iterator CI = ClonedGlobals.begin(),
1052 E = ClonedGlobals.end(); CI != E; ++CI) {
1053 const DSNodeHandle &NGH = G.ScalarMap.find(*CI)->second;
1054
1055 DSNodeHandle &MappedNode = OldNodeMap[NGH.getNode()];
1056 DSNodeHandle H(MappedNode.getNode(),NGH.getOffset()+MappedNode.getOffset());
1057 ScalarMap[*CI].mergeWith(H);
1058 InlinedGlobals.insert(*CI);
1059 }
1060
1061 // Merge the requested portion of the scalar map with the values specified.
1062 for (ScalarMapTy::const_iterator I = ValBindings.begin(),
1063 E = ValBindings.end(); I != E; ++I) {
1064 ScalarMapTy::const_iterator SMI = G.ScalarMap.find(I->first);
1065 assert(SMI != G.ScalarMap.end() && "Cannot map non-existant scalar!");
1066
1067 DSNodeHandle &MappedNode = OldNodeMap[SMI->second.getNode()];
1068 DSNodeHandle H(MappedNode.getNode(),
1069 SMI->second.getOffset()+MappedNode.getOffset());
1070 H.mergeWith(I->second);
1071 }
1072
1073 // Map the return node pointer over.
1074 if (RetVal.getNode()) {
1075 const DSNodeHandle &Ret = G.getReturnNodeFor(F);
1076 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1077 DSNodeHandle H(MappedRet.getNode(),
1078 MappedRet.getOffset()+Ret.getOffset());
1079 H.mergeWith(RetVal);
1080 }
1081
1082 // If requested, copy the calls or aux-calls lists.
1083 if (!(CloneFlags & DontCloneCallNodes)) {
1084 // Copy the function calls list...
1085 unsigned FC = FunctionCalls.size(); // FirstCall
1086 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1087 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1088 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1089 }
1090
1091 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1092 // Copy the auxiliary function calls list...
1093 unsigned FC = AuxFunctionCalls.size(); // FirstCall
1094 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1095 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1096 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1097 }
1098}
1099
1100
1101
1102
Chris Lattner076c1f92002-11-07 06:31:54 +00001103/// mergeInGraph - The method is used for merging graphs together. If the
1104/// argument graph is not *this, it makes a clone of the specified graph, then
1105/// merges the nodes specified in the call site with the formal arguments in the
1106/// graph.
1107///
Chris Lattner9f930552003-06-30 05:27:18 +00001108void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1109 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001110 // If this is not a recursive call, clone the graph into this graph...
1111 if (&Graph != this) {
1112 // Clone the callee's graph into the current graph, keeping
1113 // track of where scalars in the old graph _used_ to point,
1114 // and of the new nodes matching nodes of the old graph.
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001115 ScalarMapTy ValueBindings;
Chris Lattner58f98d02003-07-02 04:38:49 +00001116
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001117 // Set up argument bindings
1118 Function::aiterator AI = F.abegin();
1119 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1120 // Advance the argument iterator to the first pointer argument...
1121 while (AI != F.aend() && !isPointerType(AI->getType())) {
1122 ++AI;
Chris Lattner076c1f92002-11-07 06:31:54 +00001123#ifndef NDEBUG
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001124 if (AI == F.aend())
1125 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001126#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001127 }
1128 if (AI == F.aend()) break;
1129
1130 // Add the link from the argument scalar to the provided value.
1131 ValueBindings[AI] = CS.getPtrArg(i);
Chris Lattner076c1f92002-11-07 06:31:54 +00001132 }
1133
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001134 NodeMapTy OldNodeMap;
1135 clonePartiallyInto(Graph, F, CS.getRetVal(), ValueBindings, OldNodeMap,
1136 CloneFlags);
1137
1138 } else {
1139 DSNodeHandle RetVal = getReturnNodeFor(F);
1140 ScalarMapTy &ScalarMap = getScalarMap();
1141
1142 // Merge the return value with the return value of the context...
1143 RetVal.mergeWith(CS.getRetVal());
1144
1145 // Resolve all of the function arguments...
1146 Function::aiterator AI = F.abegin();
1147
1148 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1149 // Advance the argument iterator to the first pointer argument...
1150 while (AI != F.aend() && !isPointerType(AI->getType())) {
1151 ++AI;
1152#ifndef NDEBUG
1153 if (AI == F.aend())
1154 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1155#endif
1156 }
1157 if (AI == F.aend()) break;
1158
1159 // Add the link from the argument scalar to the provided value
1160 assert(ScalarMap.count(AI) && "Argument not in scalar map?");
1161 DSNodeHandle &NH = ScalarMap[AI];
1162 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1163 NH.mergeWith(CS.getPtrArg(i));
1164 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001165 }
1166}
1167
Chris Lattner58f98d02003-07-02 04:38:49 +00001168/// getCallSiteForArguments - Get the arguments and return value bindings for
1169/// the specified function in the current graph.
1170///
1171DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1172 std::vector<DSNodeHandle> Args;
1173
1174 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1175 if (isPointerType(I->getType()))
1176 Args.push_back(getScalarMap().find(I)->second);
1177
Chris Lattner808a7ae2003-09-20 16:34:13 +00001178 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001179}
1180
1181
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001182
Chris Lattner0d9bab82002-07-18 00:12:30 +00001183// markIncompleteNodes - Mark the specified node as having contents that are not
1184// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001185// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001186// must recursively traverse the data structure graph, marking all reachable
1187// nodes as incomplete.
1188//
1189static void markIncompleteNode(DSNode *N) {
1190 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001191 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001192
1193 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001194 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001195
Misha Brukman2f2d0652003-09-11 18:14:24 +00001196 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001197 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1198 if (DSNode *DSN = N->getLink(i).getNode())
1199 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001200}
1201
Chris Lattnere71ffc22002-11-11 03:36:55 +00001202static void markIncomplete(DSCallSite &Call) {
1203 // Then the return value is certainly incomplete!
1204 markIncompleteNode(Call.getRetVal().getNode());
1205
1206 // All objects pointed to by function arguments are incomplete!
1207 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1208 markIncompleteNode(Call.getPtrArg(i).getNode());
1209}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001210
1211// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1212// modified by other functions that have not been resolved yet. This marks
1213// nodes that are reachable through three sources of "unknownness":
1214//
1215// Global Variables, Function Calls, and Incoming Arguments
1216//
1217// For any node that may have unknown components (because something outside the
1218// scope of current analysis may have modified it), the 'Incomplete' flag is
1219// added to the NodeType.
1220//
Chris Lattner394471f2003-01-23 22:05:33 +00001221void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001222 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001223 if (Flags & DSGraph::MarkFormalArgs)
1224 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1225 FI != E; ++FI) {
1226 Function &F = *FI->first;
1227 if (F.getName() != "main")
1228 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1229 if (isPointerType(I->getType()) &&
1230 ScalarMap.find(I) != ScalarMap.end())
1231 markIncompleteNode(ScalarMap[I].getNode());
1232 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001233
1234 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001235 if (!shouldPrintAuxCalls())
1236 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1237 markIncomplete(FunctionCalls[i]);
1238 else
1239 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1240 markIncomplete(AuxFunctionCalls[i]);
1241
Chris Lattner0d9bab82002-07-18 00:12:30 +00001242
Chris Lattner93d7a212003-02-09 18:41:49 +00001243 // Mark all global nodes as incomplete...
1244 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1245 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001246 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001247 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001248}
1249
Chris Lattneraa8146f2002-11-10 06:59:55 +00001250static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1251 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001252 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001253 // No interesting info?
1254 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001255 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001256 Edge.setNode(0); // Kill the edge!
1257}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001258
Chris Lattneraa8146f2002-11-10 06:59:55 +00001259static inline bool nodeContainsExternalFunction(const DSNode *N) {
1260 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1261 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1262 if (Globals[i]->isExternal())
1263 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001264 return false;
1265}
1266
Chris Lattner5a540632003-06-30 03:15:25 +00001267static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001268
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001269 // Remove trivially identical function calls
1270 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001271 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1272
1273 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001274 DSNode *LastCalleeNode = 0;
1275 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001276 unsigned NumDuplicateCalls = 0;
1277 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001278 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001279 DSCallSite &CS = Calls[i];
1280
Chris Lattnere4258442002-11-11 21:35:38 +00001281 // If the Callee is a useless edge, this must be an unreachable call site,
1282 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001283 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001284 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001285 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001286 CS.swap(Calls.back());
1287 Calls.pop_back();
1288 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001289 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001290 // If the return value or any arguments point to a void node with no
1291 // information at all in it, and the call node is the only node to point
1292 // to it, remove the edge to the node (killing the node).
1293 //
1294 killIfUselessEdge(CS.getRetVal());
1295 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1296 killIfUselessEdge(CS.getPtrArg(a));
1297
1298 // If this call site calls the same function as the last call site, and if
1299 // the function pointer contains an external function, this node will
1300 // never be resolved. Merge the arguments of the call node because no
1301 // information will be lost.
1302 //
Chris Lattner923fc052003-02-05 21:59:58 +00001303 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1304 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001305 ++NumDuplicateCalls;
1306 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001307 if (LastCalleeNode)
1308 LastCalleeContainsExternalFunction =
1309 nodeContainsExternalFunction(LastCalleeNode);
1310 else
1311 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001312 }
1313
Chris Lattner58f98d02003-07-02 04:38:49 +00001314#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001315 if (LastCalleeContainsExternalFunction ||
1316 // This should be more than enough context sensitivity!
1317 // FIXME: Evaluate how many times this is tripped!
1318 NumDuplicateCalls > 20) {
1319 DSCallSite &OCS = Calls[i-1];
1320 OCS.mergeWith(CS);
1321
1322 // The node will now be eliminated as a duplicate!
1323 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1324 CS = OCS;
1325 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1326 OCS = CS;
1327 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001328#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001329 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001330 if (CS.isDirectCall()) {
1331 LastCalleeFunc = CS.getCalleeFunc();
1332 LastCalleeNode = 0;
1333 } else {
1334 LastCalleeNode = CS.getCalleeNode();
1335 LastCalleeFunc = 0;
1336 }
Chris Lattnere4258442002-11-11 21:35:38 +00001337 NumDuplicateCalls = 0;
1338 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001339 }
1340 }
1341
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001342 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001343
Chris Lattner33312f72002-11-08 01:21:07 +00001344 // Track the number of call nodes merged away...
1345 NumCallNodesMerged += NumFns-Calls.size();
1346
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001347 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001348 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001349}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001350
Chris Lattneraa8146f2002-11-10 06:59:55 +00001351
Chris Lattnere2219762002-07-18 18:22:40 +00001352// removeTriviallyDeadNodes - After the graph has been constructed, this method
1353// removes all unreachable nodes that are created because they got merged with
1354// other nodes in the graph. These nodes will all be trivially unreachable, so
1355// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001356//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001357void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001358 TIME_REGION(X, "removeTriviallyDeadNodes");
1359
Chris Lattner5a540632003-06-30 03:15:25 +00001360 removeIdenticalCalls(FunctionCalls);
1361 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001362
Chris Lattnerbab8c282003-09-20 21:34:07 +00001363 // Loop over all of the nodes in the graph, calling getNode on each field.
1364 // This will cause all nodes to update their forwarding edges, causing
1365 // forwarded nodes to be delete-able.
1366 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1367 DSNode *N = Nodes[i];
1368 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1369 N->getLink(l*N->getPointerSize()).getNode();
1370 }
1371
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001372 // Likewise, forward any edges from the scalar nodes. While we are at it,
1373 // clean house a bit.
1374 for (ScalarMapTy::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1375 // Check to see if this is a worthless node generated for non-pointer
1376 // values, such as integers. Consider an addition of long types: A+B.
1377 // Assuming we can track all uses of the value in this context, and it is
1378 // NOT used as a pointer, we can delete the node. We will be able to detect
1379 // this situation if the node pointed to ONLY has Unknown bit set in the
1380 // node. In this case, the node is not incomplete, does not point to any
1381 // other nodes (no mod/ref bits set), and is therefore uninteresting for
1382 // data structure analysis. If we run across one of these, prune the scalar
1383 // pointing to it.
1384 //
1385 DSNode *N = I->second.getNode();
1386 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1387 ScalarMap.erase(I++);
1388 else
1389 ++I;
1390 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001391
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001392 bool isGlobalsGraph = !GlobalsGraph;
1393
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001394 for (unsigned i = 0; i != Nodes.size(); ++i) {
1395 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001396
1397 // Do not remove *any* global nodes in the globals graph.
1398 // This is a special case because such nodes may not have I, M, R flags set.
1399 if (Node->isGlobalNode() && isGlobalsGraph)
1400 continue;
1401
Chris Lattner72d50a02003-06-28 21:58:28 +00001402 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001403 // This is a useless node if it has no mod/ref info (checked above),
1404 // outgoing edges (which it cannot, as it is not modified in this
1405 // context), and it has no incoming edges. If it is a global node it may
1406 // have all of these properties and still have incoming edges, due to the
1407 // scalar map, so we check those now.
1408 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001409 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001410 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001411
1412 // Loop through and make sure all of the globals are referring directly
1413 // to the node...
1414 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1415 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1416 assert(N == Node && "ScalarMap doesn't match globals list!");
1417 }
1418
Chris Lattnerbd92b732003-06-19 21:15:11 +00001419 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001420 if (Node->getNumReferrers() == Globals.size()) {
1421 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1422 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001423 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001424 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001425 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001426
1427#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1428 //
1429 // *** It seems to me that we should be able to simply check if
1430 // *** there are fewer or equal #referrers as #globals and make
1431 // *** sure that all those referrers are in the scalar map?
1432 //
1433 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1434 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1435
1436#ifndef NDEBUG
1437 // Loop through and make sure all of the globals are referring directly
1438 // to the node...
1439 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1440 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1441 assert(N == Node && "ScalarMap doesn't match globals list!");
1442 }
1443#endif
1444
1445 // Make sure NumReferrers still agrees. The node is truly dead.
1446 assert(Node->getNumReferrers() == Globals.size());
1447 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1448 ScalarMap.erase(Globals[j]);
1449 Node->makeNodeDead();
1450 }
1451#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001452 }
1453
Chris Lattnerbd92b732003-06-19 21:15:11 +00001454 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001455 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001456 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001457 Nodes[i--] = Nodes.back();
1458 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001459 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001460 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001461}
1462
1463
Chris Lattner5c7380e2003-01-29 21:10:20 +00001464/// markReachableNodes - This method recursively traverses the specified
1465/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1466/// to the set, which allows it to only traverse visited nodes once.
1467///
Chris Lattner41c04f72003-02-01 04:52:08 +00001468void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001469 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001470 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001471 if (ReachableNodes.insert(this).second) // Is newly reachable?
1472 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1473 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001474}
1475
Chris Lattner41c04f72003-02-01 04:52:08 +00001476void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001477 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001478 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001479
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001480 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1481 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001482}
1483
Chris Lattnera1220af2003-02-01 06:17:02 +00001484// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1485// looking for a node that is marked alive. If an alive node is found, return
1486// true, otherwise return false. If an alive node is reachable, this node is
1487// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001488//
Chris Lattnera1220af2003-02-01 06:17:02 +00001489static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001490 hash_set<DSNode*> &Visited,
1491 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001492 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001493 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001494
Chris Lattner85cfe012003-07-03 02:03:53 +00001495 // If this is a global node, it will end up in the globals graph anyway, so we
1496 // don't need to worry about it.
1497 if (IgnoreGlobals && N->isGlobalNode()) return false;
1498
Chris Lattneraa8146f2002-11-10 06:59:55 +00001499 // If we know that this node is alive, return so!
1500 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001501
Chris Lattneraa8146f2002-11-10 06:59:55 +00001502 // Otherwise, we don't think the node is alive yet, check for infinite
1503 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001504 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001505 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001506
Chris Lattner08db7192002-11-06 06:20:27 +00001507 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001508 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1509 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001510 N->markReachableNodes(Alive);
1511 return true;
1512 }
1513 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001514}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001515
Chris Lattnera1220af2003-02-01 06:17:02 +00001516// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1517// alive nodes.
1518//
Chris Lattner41c04f72003-02-01 04:52:08 +00001519static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001520 hash_set<DSNode*> &Visited,
1521 bool IgnoreGlobals) {
1522 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1523 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001524 return true;
1525 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001526 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001527 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001528 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001529 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1530 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001531 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001532 return false;
1533}
1534
Chris Lattnere2219762002-07-18 18:22:40 +00001535// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1536// subgraphs that are unreachable. This often occurs because the data
1537// structure doesn't "escape" into it's caller, and thus should be eliminated
1538// from the caller's graph entirely. This is only appropriate to use when
1539// inlining graphs.
1540//
Chris Lattner394471f2003-01-23 22:05:33 +00001541void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001542 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001543
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001544 // Reduce the amount of work we have to do... remove dummy nodes left over by
1545 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001546 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001547
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001548 TIME_REGION(X, "removeDeadNodes");
1549
Misha Brukman2f2d0652003-09-11 18:14:24 +00001550 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001551
1552 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001553 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001554 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001555
Chris Lattneraa8146f2002-11-10 06:59:55 +00001556 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001557 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I != E;
1558 ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001559 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001560 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001561 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001562 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001563 } else {
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001564 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001565 }
Chris Lattnere2219762002-07-18 18:22:40 +00001566
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001567 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001568 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1569 I != E; ++I)
1570 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001571
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001572 // Mark any nodes reachable by primary calls as alive...
1573 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1574 FunctionCalls[i].markReachableNodes(Alive);
1575
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001576 // Copy and merge all information about globals to the GlobalsGraph
1577 // if this is not a final pass (where unreachable globals are removed)
1578 NodeMapTy GlobalNodeMap;
1579 hash_set<const DSNode*> GlobalNodeSet;
1580
1581 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1582 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1583 GlobalNodeSet.insert(I->second); // put global nodes into a set
1584
1585 // Now find globals and aux call nodes that are already live or reach a live
1586 // value (which makes them live in turn), and continue till no more are found.
1587 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001588 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001589 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001590 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1591 do {
1592 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001593 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001594 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001595 // unreachable globals in the list.
1596 //
1597 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001598 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1599 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1600 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1601 Flags & DSGraph::RemoveUnreachableGlobals)) {
1602 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1603 GlobalNodes.pop_back(); // erase efficiently
1604 Iterate = true;
1605 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001606
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001607 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1608 // call nodes that get resolved will be difficult to remove from that graph.
1609 // The final unresolved call nodes must be handled specially at the end of
1610 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001611 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1612 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001613 (AuxFunctionCalls[i].isIndirectCall()
1614 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1615 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001616 AuxFunctionCalls[i].markReachableNodes(Alive);
1617 AuxFCallsAlive[i] = true;
1618 Iterate = true;
1619 }
1620 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001621
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001622 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001623 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001624 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1625 if (AuxFCallsAlive[i])
1626 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001627
1628 // Copy and merge all global nodes and dead aux call nodes into the
1629 // GlobalsGraph, and all nodes reachable from those nodes
1630 //
1631 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1632
1633 // First, add the dead aux call nodes to the set of root nodes for cloning
1634 // -- return value at this call site, if any
1635 // -- actual arguments passed at this call site
1636 // -- callee node at this call site, if this is an indirect call
1637 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1638 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1639 GlobalNodeSet.insert(RetNode);
1640 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1641 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1642 GlobalNodeSet.insert(ArgTarget);
1643 if (AuxFunctionCalls[i].isIndirectCall())
1644 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1645 }
1646
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001647 // Strip all alloca bits since the current function is only for the BU pass.
1648 // Strip all incomplete bits since they are short-lived properties and they
1649 // will be correctly computed when rematerializing nodes into the functions.
1650 //
Chris Lattner2f561382004-01-22 16:56:13 +00001651 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet, GlobalNodeMap,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001652 (DSGraph::StripAllocaBit |
1653 DSGraph::StripIncompleteBit));
1654 }
1655
1656 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001657 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001658 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001659
1660 // Copy the unreachable call nodes to the globals graph, updating
1661 // their target pointers using the GlobalNodeMap
1662 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1663 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1664 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001665 }
1666 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001667 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1668 AuxFunctionCalls.end());
1669
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001670 // We are finally done with the GlobalNodeMap so we can clear it and
1671 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1672 GlobalNodeMap.clear();
1673 GlobalsGraph->removeTriviallyDeadNodes();
1674
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001675 // At this point, any nodes which are visited, but not alive, are nodes
1676 // which can be removed. Loop over all nodes, eliminating completely
1677 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001678 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001679 std::vector<DSNode*> DeadNodes;
1680 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001681 for (unsigned i = 0; i != Nodes.size(); ++i)
1682 if (!Alive.count(Nodes[i])) {
1683 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001684 Nodes[i--] = Nodes.back(); // move node to end of vector
1685 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001686 DeadNodes.push_back(N);
1687 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001688 } else {
1689 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001690 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001691
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001692 // Remove all unreachable globals from the ScalarMap.
1693 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1694 // In either case, the dead nodes will not be in the set Alive.
1695 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1696 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1697 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1698 if (!Alive.count(GlobalNodes[i].second))
1699 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001700 }
1701
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001702 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001703 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1704 delete DeadNodes[i];
1705
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001706 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001707}
1708
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001709void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001710 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1711 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001712
Chris Lattner8d327672003-06-30 03:36:09 +00001713 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001714 E = ScalarMap.end(); I != E; ++I) {
1715 assert(I->second.getNode() && "Null node in scalarmap!");
1716 AssertNodeInGraph(I->second.getNode());
1717 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001718 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001719 "Global points to node, but node isn't global?");
1720 AssertNodeContainsGlobal(I->second.getNode(), GV);
1721 }
1722 }
1723 AssertCallNodesInGraph();
1724 AssertAuxCallNodesInGraph();
1725}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001726
Chris Lattner7ddb0132003-08-05 18:38:37 +00001727/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1728/// globals graph into the DS, BU or TD graph for a function. This code retains
1729/// all globals, i.e., does not delete unreachable globals after they are
1730/// inlined.
1731///
1732void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001733 NodeMapTy GlobalNodeMap;
1734 ScalarMapTy OldValMap;
1735 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001736 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1737 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1738 DSGraph::DontCloneAuxCallNodes);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001739
1740 // Now merge existing global nodes in the GlobalsGraph with their copies
1741 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1742 I != E; ++I)
1743 if (isa<GlobalValue>(I->first)) { // Found a global node
1744 DSNodeHandle &GH = I->second;
1745 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1746 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1747 }
1748
1749 // Merging leaves behind unused nodes: get rid of them now.
1750 GlobalNodeMap.clear();
1751 OldValMap.clear();
1752 OldRetNodes.clear();
1753 removeTriviallyDeadNodes();
1754}
Chris Lattner400433d2003-11-11 05:08:59 +00001755
Brian Gaeked0fde302003-11-11 22:41:34 +00001756
Chris Lattner400433d2003-11-11 05:08:59 +00001757/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1758/// nodes reachable from the two graphs, computing the mapping of nodes from
1759/// the first to the second graph.
1760///
1761void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001762 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1763 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001764 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1765 if (N1 == 0 || N2 == 0) return;
1766
1767 DSNodeHandle &Entry = NodeMap[N1];
1768 if (Entry.getNode()) {
1769 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001770 assert(!StrictChecking ||
1771 (Entry.getNode() == N2 &&
1772 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001773 "Inconsistent mapping detected!");
1774 return;
1775 }
1776
1777 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001778 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001779
1780 // Loop over all of the fields that N1 and N2 have in common, recursively
1781 // mapping the edges together now.
1782 int N2Idx = NH2.getOffset()-NH1.getOffset();
1783 unsigned N2Size = N2->getSize();
1784 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1785 if (unsigned(N2Idx)+i < N2Size)
1786 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1787}