blob: 9673043ee613194029fa5adf597d241ae5e71866 [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 Lattnerf8c6aab2002-11-08 05:01:14 +0000804 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
805 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
806 Links[i].setNode(H.getNode());
807 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
808 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000809}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000810
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000811
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000812/// cloneReachableNodes - Clone all reachable nodes from *Node into the
813/// current graph. This is a recursive function. The map OldNodeMap is a
814/// map from the original nodes to their clones.
815///
816void DSGraph::cloneReachableNodes(const DSNode* Node,
817 unsigned BitsToClear,
818 NodeMapTy& OldNodeMap,
819 NodeMapTy& CompletedNodeMap) {
820 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
821 return;
822
823 DSNodeHandle& NH = OldNodeMap[Node];
824 if (NH.getNode() != NULL)
825 return;
826
827 // else Node has not yet been cloned: clone it and clear the specified bits
828 NH = new DSNode(*Node, this); // enters in OldNodeMap
829 NH.getNode()->maskNodeTypes(~BitsToClear);
830
831 // now recursively clone nodes pointed to by this node
832 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
833 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
834 if (const DSNode* nextNode = Link.getNode())
835 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
836 }
837}
838
839void DSGraph::cloneReachableSubgraph(const DSGraph& G,
840 const hash_set<const DSNode*>& RootNodes,
841 NodeMapTy& OldNodeMap,
842 NodeMapTy& CompletedNodeMap,
843 unsigned CloneFlags) {
844 if (RootNodes.empty())
845 return;
846
847 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
848 assert(&G != this && "Cannot clone graph into itself!");
849 assert((*RootNodes.begin())->getParentGraph() == &G &&
850 "Root nodes do not belong to this graph!");
851
852 // Remove alloca or mod/ref bits as specified...
853 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
854 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
855 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
856 BitsToClear |= DSNode::DEAD; // Clear dead flag...
857
858 // Clone all nodes reachable from each root node, using a recursive helper
859 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
860 E = RootNodes.end(); I != E; ++I)
861 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
862
863 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
864 NodeMapTy MergedMap(OldNodeMap);
865 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
866
867 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
868 // to point into the current graph. MergedMap gives the full mapping.
869 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
870 I->second.getNode()->remapLinks(MergedMap);
871
872 // Now merge cloned global nodes with their copies in the current graph
873 // Just look through OldNodeMap to find such nodes!
874 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
875 if (I->first->isGlobalNode()) {
876 DSNodeHandle &GClone = I->second;
877 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
878 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
879 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
880 DSNodeHandle &GH = ScalarMap[Globals[gi]];
881 GH.mergeWith(GClone);
882 }
883 }
884}
885
886
887/// updateFromGlobalGraph - This function rematerializes global nodes and
888/// nodes reachable from them from the globals graph into the current graph.
889/// It invokes cloneReachableSubgraph, using the globals in the current graph
890/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
891/// merging globals that are already up-to-date in the current graph. In
892/// practice, in the TD pass, this is likely to be a large fraction of the
893/// live global nodes in each function (since most live nodes are likely to
894/// have been brought up-to-date in at _some_ caller or callee).
895///
896void DSGraph::updateFromGlobalGraph() {
897
898 // Use a map to keep track of the mapping between nodes in the globals graph
899 // and this graph for up-to-date global nodes, which do not need to be cloned.
900 NodeMapTy CompletedMap;
901
902 // Put the live, non-up-to-date global nodes into a set and the up-to-date
903 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
904 hash_set<const DSNode*> GlobalNodeSet;
905 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
906 E = getScalarMap().end(); I != E; ++I)
907 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
908 DSNode* GNode = I->second.getNode();
909 assert(GNode && "No node for live global in current Graph?");
910 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
911 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
912 GlobalNodeSet.insert(GGNode);
913 else { // GNode is up-to-date
914 CompletedMap[GGNode] = I->second;
915 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
916 "Links dont match in a node that is supposed to be up-to-date?"
917 "\nremapLinks() will not work if the links don't match!");
918 }
919 }
920
921 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
922 // and merge the cloned global nodes with the corresponding ones, if any.
923 NodeMapTy OldNodeMap;
924 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
925
926 // Merging global nodes leaves behind unused nodes: get rid of them now.
927 OldNodeMap.clear(); // remove references before dead node cleanup
928 CompletedMap.clear(); // remove references before dead node cleanup
929 removeTriviallyDeadNodes();
930}
931
Chris Lattner5a540632003-06-30 03:15:25 +0000932/// cloneInto - Clone the specified DSGraph into the current graph. The
933/// translated ScalarMap for the old function is filled into the OldValMap
934/// member, and the translated ReturnNodes map is returned into ReturnNodes.
935///
936/// The CloneFlags member controls various aspects of the cloning process.
937///
938void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
939 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
940 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000941 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000942 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000943 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000944
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000945 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000946
947 // Duplicate all of the nodes, populating the node map...
948 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000949
950 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000951 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
952 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
953 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000954 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000955 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000956 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000957 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000958 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000959 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000960 }
Chris Lattner18552922002-11-18 21:44:46 +0000961#ifndef NDEBUG
962 Timer::addPeakMemoryMeasurement();
963#endif
964
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000965 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000966 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000967 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000968
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000969 { TIME_REGION(X, "cloneInto:scalars");
970
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000971 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000972 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000973 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000974 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000975 DSNodeHandle &H = OldValMap[I->first];
976 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
977 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000978
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000979 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000980 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
981 ScalarMap[GV].mergeWith(H);
982 InlinedGlobals.insert(GV);
983 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000984 }
Chris Lattner93ddd7e2004-01-22 16:36:28 +0000985 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000986
Chris Lattner679e8e12002-11-08 21:27:12 +0000987 if (!(CloneFlags & DontCloneCallNodes)) {
988 // Copy the function calls list...
989 unsigned FC = FunctionCalls.size(); // FirstCall
990 FunctionCalls.reserve(FC+G.FunctionCalls.size());
991 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
992 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000993 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000994
Chris Lattneracf491f2002-11-08 22:27:09 +0000995 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000996 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000997 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000998 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
999 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1000 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1001 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001002
Chris Lattner5a540632003-06-30 03:15:25 +00001003 // Map the return node pointers over...
1004 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
1005 E = G.getReturnNodes().end(); I != E; ++I) {
1006 const DSNodeHandle &Ret = I->second;
1007 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1008 OldReturnNodes.insert(std::make_pair(I->first,
1009 DSNodeHandle(MappedRet.getNode(),
1010 MappedRet.getOffset()+Ret.getOffset())));
1011 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001012}
1013
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001014/// clonePartiallyInto - Clone the reachable subset of the specified DSGraph
1015/// into the current graph, for the specified function.
1016///
1017/// This differs from cloneInto in that it only clones nodes reachable from
1018/// globals, call nodes, the scalars specified in ValBindings, and the return
1019/// value of the specified function. This method merges the the cloned
1020/// version of the scalars and return value with the specified DSNodeHandles.
1021///
1022/// On return, OldNodeMap contains a mapping from the original nodes to the
1023/// newly cloned nodes, for the subset of nodes that were actually cloned.
1024///
1025/// The CloneFlags member controls various aspects of the cloning process.
1026///
1027void DSGraph::clonePartiallyInto(const DSGraph &G, Function &F,
1028 const DSNodeHandle &RetVal,
1029 const ScalarMapTy &ValBindings,
1030 NodeMapTy &OldNodeMap,
1031 unsigned CloneFlags) {
1032
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001033 TIME_REGION(X, "clonePartiallyInto");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001034 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
1035 assert(&G != this && "Cannot clone graph into itself!");
1036
1037 unsigned FN = Nodes.size(); // First new node...
1038
1039 /// FIXME: This currently clones the whole graph over, instead of doing it
1040 /// incrementally. This could be sped up quite a bit further!
1041
1042 // Duplicate all of the nodes, populating the node map...
1043 Nodes.reserve(FN+G.Nodes.size());
1044
1045 // Remove alloca or mod/ref bits as specified...
1046 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1047 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1048 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
1049 BitsToClear |= DSNode::DEAD; // Clear dead flag...
1050
1051 GlobalSetTy ClonedGlobals;
1052 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
1053 DSNode *Old = G.Nodes[i];
1054 DSNode *New = new DSNode(*Old, this);
1055 New->maskNodeTypes(~BitsToClear);
1056 OldNodeMap[Old] = New;
1057
1058 ClonedGlobals.insert(New->getGlobals().begin(), New->getGlobals().end());
1059 }
1060#ifndef NDEBUG
1061 Timer::addPeakMemoryMeasurement();
1062#endif
1063
1064 // Rewrite the links in the new nodes to point into the current graph now.
1065 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
1066 Nodes[i]->remapLinks(OldNodeMap);
1067
1068 // Ensure that all global nodes end up in the scalar map, as appropriate.
1069 for (GlobalSetTy::iterator CI = ClonedGlobals.begin(),
1070 E = ClonedGlobals.end(); CI != E; ++CI) {
1071 const DSNodeHandle &NGH = G.ScalarMap.find(*CI)->second;
1072
1073 DSNodeHandle &MappedNode = OldNodeMap[NGH.getNode()];
1074 DSNodeHandle H(MappedNode.getNode(),NGH.getOffset()+MappedNode.getOffset());
1075 ScalarMap[*CI].mergeWith(H);
1076 InlinedGlobals.insert(*CI);
1077 }
1078
1079 // Merge the requested portion of the scalar map with the values specified.
1080 for (ScalarMapTy::const_iterator I = ValBindings.begin(),
1081 E = ValBindings.end(); I != E; ++I) {
1082 ScalarMapTy::const_iterator SMI = G.ScalarMap.find(I->first);
1083 assert(SMI != G.ScalarMap.end() && "Cannot map non-existant scalar!");
1084
1085 DSNodeHandle &MappedNode = OldNodeMap[SMI->second.getNode()];
1086 DSNodeHandle H(MappedNode.getNode(),
1087 SMI->second.getOffset()+MappedNode.getOffset());
1088 H.mergeWith(I->second);
1089 }
1090
1091 // Map the return node pointer over.
1092 if (RetVal.getNode()) {
1093 const DSNodeHandle &Ret = G.getReturnNodeFor(F);
1094 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
1095 DSNodeHandle H(MappedRet.getNode(),
1096 MappedRet.getOffset()+Ret.getOffset());
1097 H.mergeWith(RetVal);
1098 }
1099
1100 // If requested, copy the calls or aux-calls lists.
1101 if (!(CloneFlags & DontCloneCallNodes)) {
1102 // Copy the function calls list...
1103 unsigned FC = FunctionCalls.size(); // FirstCall
1104 FunctionCalls.reserve(FC+G.FunctionCalls.size());
1105 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
1106 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
1107 }
1108
1109 if (!(CloneFlags & DontCloneAuxCallNodes)) {
1110 // Copy the auxiliary function calls list...
1111 unsigned FC = AuxFunctionCalls.size(); // FirstCall
1112 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
1113 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
1114 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
1115 }
1116}
1117
1118
1119
1120
Chris Lattner076c1f92002-11-07 06:31:54 +00001121/// mergeInGraph - The method is used for merging graphs together. If the
1122/// argument graph is not *this, it makes a clone of the specified graph, then
1123/// merges the nodes specified in the call site with the formal arguments in the
1124/// graph.
1125///
Chris Lattner9f930552003-06-30 05:27:18 +00001126void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1127 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001128 // If this is not a recursive call, clone the graph into this graph...
1129 if (&Graph != this) {
1130 // Clone the callee's graph into the current graph, keeping
1131 // track of where scalars in the old graph _used_ to point,
1132 // and of the new nodes matching nodes of the old graph.
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001133 ScalarMapTy ValueBindings;
Chris Lattner58f98d02003-07-02 04:38:49 +00001134
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001135 // Set up argument bindings
1136 Function::aiterator AI = F.abegin();
1137 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1138 // Advance the argument iterator to the first pointer argument...
1139 while (AI != F.aend() && !isPointerType(AI->getType())) {
1140 ++AI;
Chris Lattner076c1f92002-11-07 06:31:54 +00001141#ifndef NDEBUG
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001142 if (AI == F.aend())
1143 std::cerr << "Bad call to Function: " << F.getName() << "\n";
Chris Lattner076c1f92002-11-07 06:31:54 +00001144#endif
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001145 }
1146 if (AI == F.aend()) break;
1147
1148 // Add the link from the argument scalar to the provided value.
1149 ValueBindings[AI] = CS.getPtrArg(i);
Chris Lattner076c1f92002-11-07 06:31:54 +00001150 }
1151
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001152 NodeMapTy OldNodeMap;
1153 clonePartiallyInto(Graph, F, CS.getRetVal(), ValueBindings, OldNodeMap,
1154 CloneFlags);
1155
1156 } else {
1157 DSNodeHandle RetVal = getReturnNodeFor(F);
1158 ScalarMapTy &ScalarMap = getScalarMap();
1159
1160 // Merge the return value with the return value of the context...
1161 RetVal.mergeWith(CS.getRetVal());
1162
1163 // Resolve all of the function arguments...
1164 Function::aiterator AI = F.abegin();
1165
1166 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1167 // Advance the argument iterator to the first pointer argument...
1168 while (AI != F.aend() && !isPointerType(AI->getType())) {
1169 ++AI;
1170#ifndef NDEBUG
1171 if (AI == F.aend())
1172 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1173#endif
1174 }
1175 if (AI == F.aend()) break;
1176
1177 // Add the link from the argument scalar to the provided value
1178 assert(ScalarMap.count(AI) && "Argument not in scalar map?");
1179 DSNodeHandle &NH = ScalarMap[AI];
1180 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1181 NH.mergeWith(CS.getPtrArg(i));
1182 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001183 }
1184}
1185
Chris Lattner58f98d02003-07-02 04:38:49 +00001186/// getCallSiteForArguments - Get the arguments and return value bindings for
1187/// the specified function in the current graph.
1188///
1189DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1190 std::vector<DSNodeHandle> Args;
1191
1192 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1193 if (isPointerType(I->getType()))
1194 Args.push_back(getScalarMap().find(I)->second);
1195
Chris Lattner808a7ae2003-09-20 16:34:13 +00001196 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001197}
1198
1199
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001200
Chris Lattner0d9bab82002-07-18 00:12:30 +00001201// markIncompleteNodes - Mark the specified node as having contents that are not
1202// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001203// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001204// must recursively traverse the data structure graph, marking all reachable
1205// nodes as incomplete.
1206//
1207static void markIncompleteNode(DSNode *N) {
1208 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001209 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001210
1211 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001212 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001213
Misha Brukman2f2d0652003-09-11 18:14:24 +00001214 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001215 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1216 if (DSNode *DSN = N->getLink(i).getNode())
1217 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001218}
1219
Chris Lattnere71ffc22002-11-11 03:36:55 +00001220static void markIncomplete(DSCallSite &Call) {
1221 // Then the return value is certainly incomplete!
1222 markIncompleteNode(Call.getRetVal().getNode());
1223
1224 // All objects pointed to by function arguments are incomplete!
1225 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1226 markIncompleteNode(Call.getPtrArg(i).getNode());
1227}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001228
1229// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1230// modified by other functions that have not been resolved yet. This marks
1231// nodes that are reachable through three sources of "unknownness":
1232//
1233// Global Variables, Function Calls, and Incoming Arguments
1234//
1235// For any node that may have unknown components (because something outside the
1236// scope of current analysis may have modified it), the 'Incomplete' flag is
1237// added to the NodeType.
1238//
Chris Lattner394471f2003-01-23 22:05:33 +00001239void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001240 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001241 if (Flags & DSGraph::MarkFormalArgs)
1242 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1243 FI != E; ++FI) {
1244 Function &F = *FI->first;
1245 if (F.getName() != "main")
1246 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1247 if (isPointerType(I->getType()) &&
1248 ScalarMap.find(I) != ScalarMap.end())
1249 markIncompleteNode(ScalarMap[I].getNode());
1250 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001251
1252 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001253 if (!shouldPrintAuxCalls())
1254 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1255 markIncomplete(FunctionCalls[i]);
1256 else
1257 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1258 markIncomplete(AuxFunctionCalls[i]);
1259
Chris Lattner0d9bab82002-07-18 00:12:30 +00001260
Chris Lattner93d7a212003-02-09 18:41:49 +00001261 // Mark all global nodes as incomplete...
1262 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1263 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001264 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001265 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001266}
1267
Chris Lattneraa8146f2002-11-10 06:59:55 +00001268static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1269 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001270 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001271 // No interesting info?
1272 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001273 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001274 Edge.setNode(0); // Kill the edge!
1275}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001276
Chris Lattneraa8146f2002-11-10 06:59:55 +00001277static inline bool nodeContainsExternalFunction(const DSNode *N) {
1278 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1279 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1280 if (Globals[i]->isExternal())
1281 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001282 return false;
1283}
1284
Chris Lattner5a540632003-06-30 03:15:25 +00001285static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001286
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001287 // Remove trivially identical function calls
1288 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001289 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1290
1291 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001292 DSNode *LastCalleeNode = 0;
1293 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001294 unsigned NumDuplicateCalls = 0;
1295 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001296 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001297 DSCallSite &CS = Calls[i];
1298
Chris Lattnere4258442002-11-11 21:35:38 +00001299 // If the Callee is a useless edge, this must be an unreachable call site,
1300 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001301 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001302 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001303 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001304 CS.swap(Calls.back());
1305 Calls.pop_back();
1306 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001307 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001308 // If the return value or any arguments point to a void node with no
1309 // information at all in it, and the call node is the only node to point
1310 // to it, remove the edge to the node (killing the node).
1311 //
1312 killIfUselessEdge(CS.getRetVal());
1313 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1314 killIfUselessEdge(CS.getPtrArg(a));
1315
1316 // If this call site calls the same function as the last call site, and if
1317 // the function pointer contains an external function, this node will
1318 // never be resolved. Merge the arguments of the call node because no
1319 // information will be lost.
1320 //
Chris Lattner923fc052003-02-05 21:59:58 +00001321 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1322 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001323 ++NumDuplicateCalls;
1324 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001325 if (LastCalleeNode)
1326 LastCalleeContainsExternalFunction =
1327 nodeContainsExternalFunction(LastCalleeNode);
1328 else
1329 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001330 }
1331
Chris Lattner58f98d02003-07-02 04:38:49 +00001332#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001333 if (LastCalleeContainsExternalFunction ||
1334 // This should be more than enough context sensitivity!
1335 // FIXME: Evaluate how many times this is tripped!
1336 NumDuplicateCalls > 20) {
1337 DSCallSite &OCS = Calls[i-1];
1338 OCS.mergeWith(CS);
1339
1340 // The node will now be eliminated as a duplicate!
1341 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1342 CS = OCS;
1343 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1344 OCS = CS;
1345 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001346#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001347 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001348 if (CS.isDirectCall()) {
1349 LastCalleeFunc = CS.getCalleeFunc();
1350 LastCalleeNode = 0;
1351 } else {
1352 LastCalleeNode = CS.getCalleeNode();
1353 LastCalleeFunc = 0;
1354 }
Chris Lattnere4258442002-11-11 21:35:38 +00001355 NumDuplicateCalls = 0;
1356 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001357 }
1358 }
1359
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001360 Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001361
Chris Lattner33312f72002-11-08 01:21:07 +00001362 // Track the number of call nodes merged away...
1363 NumCallNodesMerged += NumFns-Calls.size();
1364
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001365 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001366 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001367}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001368
Chris Lattneraa8146f2002-11-10 06:59:55 +00001369
Chris Lattnere2219762002-07-18 18:22:40 +00001370// removeTriviallyDeadNodes - After the graph has been constructed, this method
1371// removes all unreachable nodes that are created because they got merged with
1372// other nodes in the graph. These nodes will all be trivially unreachable, so
1373// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001374//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001375void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001376 TIME_REGION(X, "removeTriviallyDeadNodes");
1377
Chris Lattner5a540632003-06-30 03:15:25 +00001378 removeIdenticalCalls(FunctionCalls);
1379 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001380
Chris Lattnerbab8c282003-09-20 21:34:07 +00001381 // Loop over all of the nodes in the graph, calling getNode on each field.
1382 // This will cause all nodes to update their forwarding edges, causing
1383 // forwarded nodes to be delete-able.
1384 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1385 DSNode *N = Nodes[i];
1386 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1387 N->getLink(l*N->getPointerSize()).getNode();
1388 }
1389
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001390 // Likewise, forward any edges from the scalar nodes. While we are at it,
1391 // clean house a bit.
1392 for (ScalarMapTy::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
1393 // Check to see if this is a worthless node generated for non-pointer
1394 // values, such as integers. Consider an addition of long types: A+B.
1395 // Assuming we can track all uses of the value in this context, and it is
1396 // NOT used as a pointer, we can delete the node. We will be able to detect
1397 // this situation if the node pointed to ONLY has Unknown bit set in the
1398 // node. In this case, the node is not incomplete, does not point to any
1399 // other nodes (no mod/ref bits set), and is therefore uninteresting for
1400 // data structure analysis. If we run across one of these, prune the scalar
1401 // pointing to it.
1402 //
1403 DSNode *N = I->second.getNode();
1404 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first))
1405 ScalarMap.erase(I++);
1406 else
1407 ++I;
1408 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001409
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001410 bool isGlobalsGraph = !GlobalsGraph;
1411
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001412 for (unsigned i = 0; i != Nodes.size(); ++i) {
1413 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001414
1415 // Do not remove *any* global nodes in the globals graph.
1416 // This is a special case because such nodes may not have I, M, R flags set.
1417 if (Node->isGlobalNode() && isGlobalsGraph)
1418 continue;
1419
Chris Lattner72d50a02003-06-28 21:58:28 +00001420 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001421 // This is a useless node if it has no mod/ref info (checked above),
1422 // outgoing edges (which it cannot, as it is not modified in this
1423 // context), and it has no incoming edges. If it is a global node it may
1424 // have all of these properties and still have incoming edges, due to the
1425 // scalar map, so we check those now.
1426 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001427 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001428 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001429
1430 // Loop through and make sure all of the globals are referring directly
1431 // to the node...
1432 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1433 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1434 assert(N == Node && "ScalarMap doesn't match globals list!");
1435 }
1436
Chris Lattnerbd92b732003-06-19 21:15:11 +00001437 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001438 if (Node->getNumReferrers() == Globals.size()) {
1439 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1440 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001441 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001442 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001443 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001444
1445#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1446 //
1447 // *** It seems to me that we should be able to simply check if
1448 // *** there are fewer or equal #referrers as #globals and make
1449 // *** sure that all those referrers are in the scalar map?
1450 //
1451 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1452 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1453
1454#ifndef NDEBUG
1455 // Loop through and make sure all of the globals are referring directly
1456 // to the node...
1457 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1458 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1459 assert(N == Node && "ScalarMap doesn't match globals list!");
1460 }
1461#endif
1462
1463 // Make sure NumReferrers still agrees. The node is truly dead.
1464 assert(Node->getNumReferrers() == Globals.size());
1465 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1466 ScalarMap.erase(Globals[j]);
1467 Node->makeNodeDead();
1468 }
1469#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001470 }
1471
Chris Lattnerbd92b732003-06-19 21:15:11 +00001472 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001473 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001474 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001475 Nodes[i--] = Nodes.back();
1476 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001477 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001478 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001479}
1480
1481
Chris Lattner5c7380e2003-01-29 21:10:20 +00001482/// markReachableNodes - This method recursively traverses the specified
1483/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1484/// to the set, which allows it to only traverse visited nodes once.
1485///
Chris Lattner41c04f72003-02-01 04:52:08 +00001486void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001487 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001488 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001489 if (ReachableNodes.insert(this).second) // Is newly reachable?
1490 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1491 getLink(i).getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001492}
1493
Chris Lattner41c04f72003-02-01 04:52:08 +00001494void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001495 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001496 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001497
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001498 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1499 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001500}
1501
Chris Lattnera1220af2003-02-01 06:17:02 +00001502// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1503// looking for a node that is marked alive. If an alive node is found, return
1504// true, otherwise return false. If an alive node is reachable, this node is
1505// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001506//
Chris Lattnera1220af2003-02-01 06:17:02 +00001507static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001508 hash_set<DSNode*> &Visited,
1509 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001510 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001511 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001512
Chris Lattner85cfe012003-07-03 02:03:53 +00001513 // If this is a global node, it will end up in the globals graph anyway, so we
1514 // don't need to worry about it.
1515 if (IgnoreGlobals && N->isGlobalNode()) return false;
1516
Chris Lattneraa8146f2002-11-10 06:59:55 +00001517 // If we know that this node is alive, return so!
1518 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001519
Chris Lattneraa8146f2002-11-10 06:59:55 +00001520 // Otherwise, we don't think the node is alive yet, check for infinite
1521 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001522 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001523 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001524
Chris Lattner08db7192002-11-06 06:20:27 +00001525 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001526 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1527 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001528 N->markReachableNodes(Alive);
1529 return true;
1530 }
1531 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001532}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001533
Chris Lattnera1220af2003-02-01 06:17:02 +00001534// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1535// alive nodes.
1536//
Chris Lattner41c04f72003-02-01 04:52:08 +00001537static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001538 hash_set<DSNode*> &Visited,
1539 bool IgnoreGlobals) {
1540 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1541 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001542 return true;
1543 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001544 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001545 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001546 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001547 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1548 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001549 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001550 return false;
1551}
1552
Chris Lattnere2219762002-07-18 18:22:40 +00001553// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1554// subgraphs that are unreachable. This often occurs because the data
1555// structure doesn't "escape" into it's caller, and thus should be eliminated
1556// from the caller's graph entirely. This is only appropriate to use when
1557// inlining graphs.
1558//
Chris Lattner394471f2003-01-23 22:05:33 +00001559void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001560 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001561
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001562 // Reduce the amount of work we have to do... remove dummy nodes left over by
1563 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001564 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001565
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001566 TIME_REGION(X, "removeDeadNodes");
1567
Misha Brukman2f2d0652003-09-11 18:14:24 +00001568 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001569
1570 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001571 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001572 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001573
Chris Lattneraa8146f2002-11-10 06:59:55 +00001574 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001575 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I != E;
1576 ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001577 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001578 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001579 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001580 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001581 } else {
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001582 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001583 }
Chris Lattnere2219762002-07-18 18:22:40 +00001584
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001585 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001586 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1587 I != E; ++I)
1588 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001589
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001590 // Mark any nodes reachable by primary calls as alive...
1591 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1592 FunctionCalls[i].markReachableNodes(Alive);
1593
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001594 // Copy and merge all information about globals to the GlobalsGraph
1595 // if this is not a final pass (where unreachable globals are removed)
1596 NodeMapTy GlobalNodeMap;
1597 hash_set<const DSNode*> GlobalNodeSet;
1598
1599 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1600 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1601 GlobalNodeSet.insert(I->second); // put global nodes into a set
1602
1603 // Now find globals and aux call nodes that are already live or reach a live
1604 // value (which makes them live in turn), and continue till no more are found.
1605 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001606 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001607 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001608 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1609 do {
1610 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001611 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001612 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001613 // unreachable globals in the list.
1614 //
1615 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001616 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1617 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1618 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1619 Flags & DSGraph::RemoveUnreachableGlobals)) {
1620 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1621 GlobalNodes.pop_back(); // erase efficiently
1622 Iterate = true;
1623 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001624
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001625 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1626 // call nodes that get resolved will be difficult to remove from that graph.
1627 // The final unresolved call nodes must be handled specially at the end of
1628 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001629 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1630 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001631 (AuxFunctionCalls[i].isIndirectCall()
1632 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1633 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001634 AuxFunctionCalls[i].markReachableNodes(Alive);
1635 AuxFCallsAlive[i] = true;
1636 Iterate = true;
1637 }
1638 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001639
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001640 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001641 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001642 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1643 if (AuxFCallsAlive[i])
1644 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001645
1646 // Copy and merge all global nodes and dead aux call nodes into the
1647 // GlobalsGraph, and all nodes reachable from those nodes
1648 //
1649 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1650
1651 // First, add the dead aux call nodes to the set of root nodes for cloning
1652 // -- return value at this call site, if any
1653 // -- actual arguments passed at this call site
1654 // -- callee node at this call site, if this is an indirect call
1655 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1656 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1657 GlobalNodeSet.insert(RetNode);
1658 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1659 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1660 GlobalNodeSet.insert(ArgTarget);
1661 if (AuxFunctionCalls[i].isIndirectCall())
1662 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1663 }
1664
1665 // There are no "pre-completed" nodes so use any empty map for those.
1666 // Strip all alloca bits since the current function is only for the BU pass.
1667 // Strip all incomplete bits since they are short-lived properties and they
1668 // will be correctly computed when rematerializing nodes into the functions.
1669 //
1670 NodeMapTy CompletedMap;
1671 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1672 GlobalNodeMap, CompletedMap,
1673 (DSGraph::StripAllocaBit |
1674 DSGraph::StripIncompleteBit));
1675 }
1676
1677 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001678 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001679 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001680
1681 // Copy the unreachable call nodes to the globals graph, updating
1682 // their target pointers using the GlobalNodeMap
1683 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1684 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1685 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001686 }
1687 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001688 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1689 AuxFunctionCalls.end());
1690
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001691 // We are finally done with the GlobalNodeMap so we can clear it and
1692 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1693 GlobalNodeMap.clear();
1694 GlobalsGraph->removeTriviallyDeadNodes();
1695
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001696 // At this point, any nodes which are visited, but not alive, are nodes
1697 // which can be removed. Loop over all nodes, eliminating completely
1698 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001699 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001700 std::vector<DSNode*> DeadNodes;
1701 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001702 for (unsigned i = 0; i != Nodes.size(); ++i)
1703 if (!Alive.count(Nodes[i])) {
1704 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001705 Nodes[i--] = Nodes.back(); // move node to end of vector
1706 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001707 DeadNodes.push_back(N);
1708 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001709 } else {
1710 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001711 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001712
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001713 // Remove all unreachable globals from the ScalarMap.
1714 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1715 // In either case, the dead nodes will not be in the set Alive.
1716 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1717 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1718 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1719 if (!Alive.count(GlobalNodes[i].second))
1720 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001721 }
1722
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001723 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001724 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1725 delete DeadNodes[i];
1726
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001727 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001728}
1729
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001730void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001731 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1732 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001733
Chris Lattner8d327672003-06-30 03:36:09 +00001734 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001735 E = ScalarMap.end(); I != E; ++I) {
1736 assert(I->second.getNode() && "Null node in scalarmap!");
1737 AssertNodeInGraph(I->second.getNode());
1738 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001739 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001740 "Global points to node, but node isn't global?");
1741 AssertNodeContainsGlobal(I->second.getNode(), GV);
1742 }
1743 }
1744 AssertCallNodesInGraph();
1745 AssertAuxCallNodesInGraph();
1746}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001747
Chris Lattner7ddb0132003-08-05 18:38:37 +00001748/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1749/// globals graph into the DS, BU or TD graph for a function. This code retains
1750/// all globals, i.e., does not delete unreachable globals after they are
1751/// inlined.
1752///
1753void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001754 NodeMapTy GlobalNodeMap;
1755 ScalarMapTy OldValMap;
1756 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001757 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1758 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1759 DSGraph::DontCloneAuxCallNodes);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001760
1761 // Now merge existing global nodes in the GlobalsGraph with their copies
1762 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1763 I != E; ++I)
1764 if (isa<GlobalValue>(I->first)) { // Found a global node
1765 DSNodeHandle &GH = I->second;
1766 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1767 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1768 }
1769
1770 // Merging leaves behind unused nodes: get rid of them now.
1771 GlobalNodeMap.clear();
1772 OldValMap.clear();
1773 OldRetNodes.clear();
1774 removeTriviallyDeadNodes();
1775}
Chris Lattner400433d2003-11-11 05:08:59 +00001776
Brian Gaeked0fde302003-11-11 22:41:34 +00001777
Chris Lattner400433d2003-11-11 05:08:59 +00001778/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1779/// nodes reachable from the two graphs, computing the mapping of nodes from
1780/// the first to the second graph.
1781///
1782void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001783 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
1784 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00001785 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1786 if (N1 == 0 || N2 == 0) return;
1787
1788 DSNodeHandle &Entry = NodeMap[N1];
1789 if (Entry.getNode()) {
1790 // Termination of recursion!
Chris Lattnerafc1dba2003-11-12 17:58:22 +00001791 assert(!StrictChecking ||
1792 (Entry.getNode() == N2 &&
1793 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset())) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001794 "Inconsistent mapping detected!");
1795 return;
1796 }
1797
1798 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001799 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001800
1801 // Loop over all of the fields that N1 and N2 have in common, recursively
1802 // mapping the edges together now.
1803 int N2Idx = NH2.getOffset()-NH1.getOffset();
1804 unsigned N2Size = N2->getSize();
1805 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1806 if (unsigned(N2Idx)+i < N2Size)
1807 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1808}