blob: 9d9813cd7cbbede340e0696e8f946bdf328a6d85 [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 Lattnerc68c31b2002-07-10 22:38:08 +000025
Brian Gaeked0fde302003-11-11 22:41:34 +000026namespace llvm {
27
Chris Lattner08db7192002-11-06 06:20:27 +000028namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000029 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
30 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000031};
32
Chris Lattnerb1060432002-11-07 05:20:53 +000033using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000034
Chris Lattner731b2d72003-02-13 19:09:00 +000035DSNode *DSNodeHandle::HandleForwarding() const {
36 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
37
38 // Handle node forwarding here!
39 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
40 Offset += N->ForwardNH.getOffset();
41
42 if (--N->NumReferrers == 0) {
43 // Removing the last referrer to the node, sever the forwarding link
44 N->stopForwarding();
45 }
46
47 N = Next;
48 N->NumReferrers++;
49 if (N->Size <= Offset) {
50 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
51 Offset = 0;
52 }
53 return N;
54}
55
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000056//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000057// DSNode Implementation
58//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000059
Chris Lattnerbd92b732003-06-19 21:15:11 +000060DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000061 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000062 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000063 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000064 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000065}
66
Chris Lattner0d9bab82002-07-18 00:12:30 +000067// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000068DSNode::DSNode(const DSNode &N, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000069 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattner58f98d02003-07-02 04:38:49 +000070 Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattner72d29a42003-02-11 23:11:51 +000071 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000072}
73
Chris Lattner15869aa2003-11-02 22:27:28 +000074/// getTargetData - Get the target data object used to construct this node.
75///
76const TargetData &DSNode::getTargetData() const {
77 return ParentGraph->getTargetData();
78}
79
Chris Lattner72d29a42003-02-11 23:11:51 +000080void DSNode::assertOK() const {
81 assert((Ty != Type::VoidTy ||
82 Ty == Type::VoidTy && (Size == 0 ||
83 (NodeType & DSNode::Array))) &&
84 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +000085
86 assert(ParentGraph && "Node has no parent?");
87 const DSGraph::ScalarMapTy &SM = ParentGraph->getScalarMap();
88 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
89 assert(SM.find(Globals[i]) != SM.end());
90 assert(SM.find(Globals[i])->second.getNode() == this);
91 }
Chris Lattner72d29a42003-02-11 23:11:51 +000092}
93
94/// forwardNode - Mark this node as being obsolete, and all references to it
95/// should be forwarded to the specified node and offset.
96///
97void DSNode::forwardNode(DSNode *To, unsigned Offset) {
98 assert(this != To && "Cannot forward a node to itself!");
99 assert(ForwardNH.isNull() && "Already forwarding from this node!");
100 if (To->Size <= 1) Offset = 0;
101 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
102 "Forwarded offset is wrong!");
103 ForwardNH.setNode(To);
104 ForwardNH.setOffset(Offset);
105 NodeType = DEAD;
106 Size = 0;
107 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000108}
109
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000110// addGlobal - Add an entry for a global value to the Globals list. This also
111// marks the node with the 'G' flag if it does not already have it.
112//
113void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000114 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000115 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000116 std::lower_bound(Globals.begin(), Globals.end(), GV);
117
118 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000119 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000120 Globals.insert(I, GV);
121 NodeType |= GlobalNode;
122 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000123}
124
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000125/// foldNodeCompletely - If we determine that this node has some funny
126/// behavior happening to it that we cannot represent, we fold it down to a
127/// single, completely pessimistic, node. This node is represented as a
128/// single byte with a single TypeEntry of "void".
129///
130void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000131 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000132
Chris Lattner08db7192002-11-06 06:20:27 +0000133 ++NumFolds;
134
Chris Lattner72d29a42003-02-11 23:11:51 +0000135 // Create the node we are going to forward to...
Chris Lattner70793862003-07-02 23:57:05 +0000136 DSNode *DestNode = new DSNode(0, ParentGraph);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000137 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000138 DestNode->Ty = Type::VoidTy;
139 DestNode->Size = 1;
140 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000141
Chris Lattner72d29a42003-02-11 23:11:51 +0000142 // Start forwarding to the destination node...
143 forwardNode(DestNode, 0);
144
145 if (Links.size()) {
146 DestNode->Links.push_back(Links[0]);
147 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000148
Chris Lattner72d29a42003-02-11 23:11:51 +0000149 // If we have links, merge all of our outgoing links together...
150 for (unsigned i = Links.size()-1; i != 0; --i)
151 NH.getNode()->Links[0].mergeWith(Links[i]);
152 Links.clear();
153 } else {
154 DestNode->Links.resize(1);
155 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000156}
Chris Lattner076c1f92002-11-07 06:31:54 +0000157
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000158/// isNodeCompletelyFolded - Return true if this node has been completely
159/// folded down to something that can never be expanded, effectively losing
160/// all of the field sensitivity that may be present in the node.
161///
162bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000163 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000164}
165
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000166namespace {
167 /// TypeElementWalker Class - Used for implementation of physical subtyping...
168 ///
169 class TypeElementWalker {
170 struct StackState {
171 const Type *Ty;
172 unsigned Offset;
173 unsigned Idx;
174 StackState(const Type *T, unsigned Off = 0)
175 : Ty(T), Offset(Off), Idx(0) {}
176 };
177
178 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000179 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000180 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000181 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000182 Stack.push_back(T);
183 StepToLeaf();
184 }
185
186 bool isDone() const { return Stack.empty(); }
187 const Type *getCurrentType() const { return Stack.back().Ty; }
188 unsigned getCurrentOffset() const { return Stack.back().Offset; }
189
190 void StepToNextType() {
191 PopStackAndAdvance();
192 StepToLeaf();
193 }
194
195 private:
196 /// PopStackAndAdvance - Pop the current element off of the stack and
197 /// advance the underlying element to the next contained member.
198 void PopStackAndAdvance() {
199 assert(!Stack.empty() && "Cannot pop an empty stack!");
200 Stack.pop_back();
201 while (!Stack.empty()) {
202 StackState &SS = Stack.back();
203 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
204 ++SS.Idx;
205 if (SS.Idx != ST->getElementTypes().size()) {
206 const StructLayout *SL = TD.getStructLayout(ST);
207 SS.Offset += SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1];
208 return;
209 }
210 Stack.pop_back(); // At the end of the structure
211 } else {
212 const ArrayType *AT = cast<ArrayType>(SS.Ty);
213 ++SS.Idx;
214 if (SS.Idx != AT->getNumElements()) {
215 SS.Offset += TD.getTypeSize(AT->getElementType());
216 return;
217 }
218 Stack.pop_back(); // At the end of the array
219 }
220 }
221 }
222
223 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
224 /// on the type stack.
225 void StepToLeaf() {
226 if (Stack.empty()) return;
227 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
228 StackState &SS = Stack.back();
229 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
230 if (ST->getElementTypes().empty()) {
231 assert(SS.Idx == 0);
232 PopStackAndAdvance();
233 } else {
234 // Step into the structure...
235 assert(SS.Idx < ST->getElementTypes().size());
236 const StructLayout *SL = TD.getStructLayout(ST);
237 Stack.push_back(StackState(ST->getElementTypes()[SS.Idx],
238 SS.Offset+SL->MemberOffsets[SS.Idx]));
239 }
240 } else {
241 const ArrayType *AT = cast<ArrayType>(SS.Ty);
242 if (AT->getNumElements() == 0) {
243 assert(SS.Idx == 0);
244 PopStackAndAdvance();
245 } else {
246 // Step into the array...
247 assert(SS.Idx < AT->getNumElements());
248 Stack.push_back(StackState(AT->getElementType(),
249 SS.Offset+SS.Idx*
250 TD.getTypeSize(AT->getElementType())));
251 }
252 }
253 }
254 }
255 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000256} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000257
258/// ElementTypesAreCompatible - Check to see if the specified types are
259/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000260/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
261/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000262///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000263static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000264 bool AllowLargerT1, const TargetData &TD){
265 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000266
267 while (!T1W.isDone() && !T2W.isDone()) {
268 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
269 return false;
270
271 const Type *T1 = T1W.getCurrentType();
272 const Type *T2 = T2W.getCurrentType();
273 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
274 return false;
275
276 T1W.StepToNextType();
277 T2W.StepToNextType();
278 }
279
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000280 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000281}
282
283
Chris Lattner08db7192002-11-06 06:20:27 +0000284/// mergeTypeInfo - This method merges the specified type into the current node
285/// at the specified offset. This may update the current node's type record if
286/// this gives more information to the node, it may do nothing to the node if
287/// this information is already known, or it may merge the node completely (and
288/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000289///
Chris Lattner08db7192002-11-06 06:20:27 +0000290/// This method returns true if the node is completely folded, otherwise false.
291///
Chris Lattner088b6392003-03-03 17:13:31 +0000292bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
293 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000294 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000295 // Check to make sure the Size member is up-to-date. Size can be one of the
296 // following:
297 // Size = 0, Ty = Void: Nothing is known about this node.
298 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
299 // Size = 1, Ty = Void, Array = 1: The node is collapsed
300 // Otherwise, sizeof(Ty) = Size
301 //
Chris Lattner18552922002-11-18 21:44:46 +0000302 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
303 (Size == 0 && !Ty->isSized() && !isArray()) ||
304 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
305 (Size == 0 && !Ty->isSized() && !isArray()) ||
306 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000307 "Size member of DSNode doesn't match the type structure!");
308 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000309
Chris Lattner18552922002-11-18 21:44:46 +0000310 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000311 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000312
Chris Lattner08db7192002-11-06 06:20:27 +0000313 // Return true immediately if the node is completely folded.
314 if (isNodeCompletelyFolded()) return true;
315
Chris Lattner23f83dc2002-11-08 22:49:57 +0000316 // If this is an array type, eliminate the outside arrays because they won't
317 // be used anyway. This greatly reduces the size of large static arrays used
318 // as global variables, for example.
319 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000320 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000321 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
322 // FIXME: we might want to keep small arrays, but must be careful about
323 // things like: [2 x [10000 x int*]]
324 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000325 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000326 }
327
Chris Lattner08db7192002-11-06 06:20:27 +0000328 // Figure out how big the new type we're merging in is...
329 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
330
331 // Otherwise check to see if we can fold this type into the current node. If
332 // we can't, we fold the node completely, if we can, we potentially update our
333 // internal state.
334 //
Chris Lattner18552922002-11-18 21:44:46 +0000335 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000336 // If this is the first type that this node has seen, just accept it without
337 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000338 assert(Offset == 0 && !isArray() &&
339 "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000340 Ty = NewTy;
341 NodeType &= ~Array;
342 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000343 Size = NewTySize;
344
345 // Calculate the number of outgoing links from this node.
346 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
347 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000348 }
Chris Lattner08db7192002-11-06 06:20:27 +0000349
350 // Handle node expansion case here...
351 if (Offset+NewTySize > Size) {
352 // It is illegal to grow this node if we have treated it as an array of
353 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000354 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000355 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000356 return true;
357 }
358
359 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000360 std::cerr << "UNIMP: Trying to merge a growth type into "
361 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000362 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000363 return true;
364 }
365
366 // Okay, the situation is nice and simple, we are trying to merge a type in
367 // at offset 0 that is bigger than our current type. Implement this by
368 // switching to the new type and then merge in the smaller one, which should
369 // hit the other code path here. If the other code path decides it's not
370 // ok, it will collapse the node as appropriate.
371 //
Chris Lattner18552922002-11-18 21:44:46 +0000372 const Type *OldTy = Ty;
373 Ty = NewTy;
374 NodeType &= ~Array;
375 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000376 Size = NewTySize;
377
378 // Must grow links to be the appropriate size...
379 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
380
381 // Merge in the old type now... which is guaranteed to be smaller than the
382 // "current" type.
383 return mergeTypeInfo(OldTy, 0);
384 }
385
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000386 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000387 "Cannot merge something into a part of our type that doesn't exist!");
388
Chris Lattner18552922002-11-18 21:44:46 +0000389 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000390 // type that starts at offset Offset.
391 //
392 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000393 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000394 while (O < Offset) {
395 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
396
397 switch (SubType->getPrimitiveID()) {
398 case Type::StructTyID: {
399 const StructType *STy = cast<StructType>(SubType);
400 const StructLayout &SL = *TD.getStructLayout(STy);
401
402 unsigned i = 0, e = SL.MemberOffsets.size();
403 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
404 /* empty */;
405
406 // The offset we are looking for must be in the i'th element...
407 SubType = STy->getElementTypes()[i];
408 O += SL.MemberOffsets[i];
409 break;
410 }
411 case Type::ArrayTyID: {
412 SubType = cast<ArrayType>(SubType)->getElementType();
413 unsigned ElSize = TD.getTypeSize(SubType);
414 unsigned Remainder = (Offset-O) % ElSize;
415 O = Offset-Remainder;
416 break;
417 }
418 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000419 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000420 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000421 }
422 }
423
424 assert(O == Offset && "Could not achieve the correct offset!");
425
426 // If we found our type exactly, early exit
427 if (SubType == NewTy) return false;
428
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000429 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
430
431 // Ok, we are getting desperate now. Check for physical subtyping, where we
432 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000433 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000434 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000435 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000436 return false;
437
Chris Lattner08db7192002-11-06 06:20:27 +0000438 // Okay, so we found the leader type at the offset requested. Search the list
439 // of types that starts at this offset. If SubType is currently an array or
440 // structure, the type desired may actually be the first element of the
441 // composite type...
442 //
Chris Lattner18552922002-11-18 21:44:46 +0000443 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000444 while (SubType != NewTy) {
445 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000446 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000447 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000448 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000449 case Type::StructTyID: {
450 const StructType *STy = cast<StructType>(SubType);
451 const StructLayout &SL = *TD.getStructLayout(STy);
452 if (SL.MemberOffsets.size() > 1)
453 NextPadSize = SL.MemberOffsets[1];
454 else
455 NextPadSize = SubTypeSize;
456 NextSubType = STy->getElementTypes()[0];
457 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000458 break;
Chris Lattner18552922002-11-18 21:44:46 +0000459 }
Chris Lattner08db7192002-11-06 06:20:27 +0000460 case Type::ArrayTyID:
461 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000462 NextSubTypeSize = TD.getTypeSize(NextSubType);
463 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000464 break;
465 default: ;
466 // fall out
467 }
468
469 if (NextSubType == 0)
470 break; // In the default case, break out of the loop
471
Chris Lattner18552922002-11-18 21:44:46 +0000472 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000473 break; // Don't allow shrinking to a smaller type than NewTySize
474 SubType = NextSubType;
475 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000476 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000477 }
478
479 // If we found the type exactly, return it...
480 if (SubType == NewTy)
481 return false;
482
483 // Check to see if we have a compatible, but different type...
484 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000485 // Check to see if this type is obviously convertible... int -> uint f.e.
486 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000487 return false;
488
489 // Check to see if we have a pointer & integer mismatch going on here,
490 // loading a pointer as a long, for example.
491 //
492 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
493 NewTy->isInteger() && isa<PointerType>(SubType))
494 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000495 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
496 // We are accessing the field, plus some structure padding. Ignore the
497 // structure padding.
498 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000499 }
500
Chris Lattner58f98d02003-07-02 04:38:49 +0000501 Module *M = 0;
Chris Lattner58f98d02003-07-02 04:38:49 +0000502 if (getParentGraph()->getReturnNodes().size())
503 M = getParentGraph()->getReturnNodes().begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000504 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
505 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
506 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
507 << "SubType: ";
508 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000509
Chris Lattner088b6392003-03-03 17:13:31 +0000510 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000511 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000512}
513
Chris Lattner08db7192002-11-06 06:20:27 +0000514
515
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000516// addEdgeTo - Add an edge from the current node to the specified node. This
517// can cause merging of nodes in the graph.
518//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000519void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000520 if (NH.getNode() == 0) return; // Nothing to do
521
Chris Lattner08db7192002-11-06 06:20:27 +0000522 DSNodeHandle &ExistingEdge = getLink(Offset);
523 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000524 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000525 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000526 } else { // No merging to perform...
527 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000528 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000529}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000530
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000531
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000532// MergeSortedVectors - Efficiently merge a vector into another vector where
533// duplicates are not allowed and both are sorted. This assumes that 'T's are
534// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000535//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000536static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
537 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000538 // By far, the most common cases will be the simple ones. In these cases,
539 // avoid having to allocate a temporary vector...
540 //
541 if (Src.empty()) { // Nothing to merge in...
542 return;
543 } else if (Dest.empty()) { // Just copy the result in...
544 Dest = Src;
545 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000546 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000547 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000548 std::lower_bound(Dest.begin(), Dest.end(), V);
549 if (I == Dest.end() || *I != Src[0]) // If not already contained...
550 Dest.insert(I, Src[0]);
551 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000552 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000553 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000554 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000555 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
556 if (I == Dest.end() || *I != Tmp) // If not already contained...
557 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000558
559 } else {
560 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000561 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000562
563 // Make space for all of the type entries now...
564 Dest.resize(Dest.size()+Src.size());
565
566 // Merge the two sorted ranges together... into Dest.
567 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
568
569 // Now erase any duplicate entries that may have accumulated into the
570 // vectors (because they were in both of the input sets)
571 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
572 }
573}
574
575
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000576// MergeNodes() - Helper function for DSNode::mergeWith().
577// This function does the hard work of merging two nodes, CurNodeH
578// and NH after filtering out trivial cases and making sure that
579// CurNodeH.offset >= NH.offset.
580//
581// ***WARNING***
582// Since merging may cause either node to go away, we must always
583// use the node-handles to refer to the nodes. These node handles are
584// automatically updated during merging, so will always provide access
585// to the correct node after a merge.
586//
587void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
588 assert(CurNodeH.getOffset() >= NH.getOffset() &&
589 "This should have been enforced in the caller.");
590
591 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
592 // respect to NH.Offset) is now zero. NOffset is the distance from the base
593 // of our object that N starts from.
594 //
595 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
596 unsigned NSize = NH.getNode()->getSize();
597
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000598 // If the two nodes are of different size, and the smaller node has the array
599 // bit set, collapse!
600 if (NSize != CurNodeH.getNode()->getSize()) {
601 if (NSize < CurNodeH.getNode()->getSize()) {
602 if (NH.getNode()->isArray())
603 NH.getNode()->foldNodeCompletely();
604 } else if (CurNodeH.getNode()->isArray()) {
605 NH.getNode()->foldNodeCompletely();
606 }
607 }
608
609 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000610 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000611 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000612 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000613
614 // If we are merging a node with a completely folded node, then both nodes are
615 // now completely folded.
616 //
617 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
618 if (!NH.getNode()->isNodeCompletelyFolded()) {
619 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000620 assert(NH.getNode() && NH.getOffset() == 0 &&
621 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000622 NOffset = NH.getOffset();
623 NSize = NH.getNode()->getSize();
624 assert(NOffset == 0 && NSize == 1);
625 }
626 } else if (NH.getNode()->isNodeCompletelyFolded()) {
627 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000628 assert(CurNodeH.getNode() && CurNodeH.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
Chris Lattner72d29a42003-02-11 23:11:51 +0000635 DSNode *N = NH.getNode();
636 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000637 assert(!CurNodeH.getNode()->isDeadNode());
638
639 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000640 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000641
Chris Lattner72d29a42003-02-11 23:11:51 +0000642 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000643 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000644 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000645
Chris Lattner72d29a42003-02-11 23:11:51 +0000646 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
647 //
648 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
649 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000650 if (Link.getNode()) {
651 // Compute the offset into the current node at which to
652 // merge this link. In the common case, this is a linear
653 // relation to the offset in the original node (with
654 // wrapping), but if the current node gets collapsed due to
655 // recursive merging, we must make sure to merge in all remaining
656 // links at offset zero.
657 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000658 DSNode *CN = CurNodeH.getNode();
659 if (CN->Size != 1)
660 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
661 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000662 }
663 }
664
665 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000666 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000667
668 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000669 if (!N->Globals.empty()) {
670 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000671
672 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000673 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000674 }
675}
676
677
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000678// mergeWith - Merge this node and the specified node, moving all links to and
679// from the argument node into the current node, deleting the node argument.
680// Offset indicates what offset the specified node is to be merged into the
681// current node.
682//
683// The specified node may be a null pointer (in which case, nothing happens).
684//
685void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
686 DSNode *N = NH.getNode();
687 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000688 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000689
Chris Lattnerbd92b732003-06-19 21:15:11 +0000690 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000691 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
692
Chris Lattner02606632002-11-04 06:48:26 +0000693 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000694 // We cannot merge two pieces of the same node together, collapse the node
695 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000696 DEBUG(std::cerr << "Attempting to merge two chunks of"
697 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000698 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000699 return;
700 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000701
Chris Lattner5190ce82002-11-12 07:20:45 +0000702 // If both nodes are not at offset 0, make sure that we are merging the node
703 // at an later offset into the node with the zero offset.
704 //
705 if (Offset < NH.getOffset()) {
706 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
707 return;
708 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
709 // If the offsets are the same, merge the smaller node into the bigger node
710 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
711 return;
712 }
713
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000714 // Ok, now we can merge the two nodes. Use a static helper that works with
715 // two node handles, since "this" may get merged away at intermediate steps.
716 DSNodeHandle CurNodeH(this, Offset);
717 DSNodeHandle NHCopy(NH);
718 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000719}
720
Chris Lattner9de906c2002-10-20 22:11:44 +0000721//===----------------------------------------------------------------------===//
722// DSCallSite Implementation
723//===----------------------------------------------------------------------===//
724
Vikram S. Adve26b98262002-10-20 21:41:02 +0000725// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000726Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000727 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000728}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000729
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000730
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000731//===----------------------------------------------------------------------===//
732// DSGraph Implementation
733//===----------------------------------------------------------------------===//
734
Chris Lattnera9d65662003-06-30 05:57:30 +0000735/// getFunctionNames - Return a space separated list of the name of the
736/// functions in this graph (if any)
737std::string DSGraph::getFunctionNames() const {
738 switch (getReturnNodes().size()) {
739 case 0: return "Globals graph";
740 case 1: return getReturnNodes().begin()->first->getName();
741 default:
742 std::string Return;
743 for (DSGraph::ReturnNodesTy::const_iterator I = getReturnNodes().begin();
744 I != getReturnNodes().end(); ++I)
745 Return += I->first->getName() + " ";
746 Return.erase(Return.end()-1, Return.end()); // Remove last space character
747 return Return;
748 }
749}
750
751
Chris Lattner15869aa2003-11-02 22:27:28 +0000752DSGraph::DSGraph(const DSGraph &G) : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000753 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000754 NodeMapTy NodeMap;
755 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000756 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattner0d9bab82002-07-18 00:12:30 +0000757}
758
Chris Lattner5a540632003-06-30 03:15:25 +0000759DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap)
Chris Lattner15869aa2003-11-02 22:27:28 +0000760 : GlobalsGraph(0), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000761 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +0000762 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000763 InlinedGlobals.clear(); // clear set of "up-to-date" globals
Chris Lattnereff0da92002-10-21 15:32:34 +0000764}
765
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000766DSGraph::~DSGraph() {
767 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000768 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000769 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000770 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +0000771 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000772
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000773 // Drop all intra-node references, so that assertions don't fail...
774 std::for_each(Nodes.begin(), Nodes.end(),
775 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000776
777 // Delete all of the nodes themselves...
778 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
779}
780
Chris Lattner0d9bab82002-07-18 00:12:30 +0000781// dump - Allow inspection of graph in a debugger.
782void DSGraph::dump() const { print(std::cerr); }
783
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000784
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000785/// remapLinks - Change all of the Links in the current node according to the
786/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000787///
Chris Lattner8d327672003-06-30 03:36:09 +0000788void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000789 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
790 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
791 Links[i].setNode(H.getNode());
792 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
793 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000794}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000795
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000796
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000797/// cloneReachableNodes - Clone all reachable nodes from *Node into the
798/// current graph. This is a recursive function. The map OldNodeMap is a
799/// map from the original nodes to their clones.
800///
801void DSGraph::cloneReachableNodes(const DSNode* Node,
802 unsigned BitsToClear,
803 NodeMapTy& OldNodeMap,
804 NodeMapTy& CompletedNodeMap) {
805 if (CompletedNodeMap.find(Node) != CompletedNodeMap.end())
806 return;
807
808 DSNodeHandle& NH = OldNodeMap[Node];
809 if (NH.getNode() != NULL)
810 return;
811
812 // else Node has not yet been cloned: clone it and clear the specified bits
813 NH = new DSNode(*Node, this); // enters in OldNodeMap
814 NH.getNode()->maskNodeTypes(~BitsToClear);
815
816 // now recursively clone nodes pointed to by this node
817 for (unsigned i = 0, e = Node->getNumLinks(); i != e; ++i) {
818 const DSNodeHandle &Link = Node->getLink(i << DS::PointerShift);
819 if (const DSNode* nextNode = Link.getNode())
820 cloneReachableNodes(nextNode, BitsToClear, OldNodeMap, CompletedNodeMap);
821 }
822}
823
824void DSGraph::cloneReachableSubgraph(const DSGraph& G,
825 const hash_set<const DSNode*>& RootNodes,
826 NodeMapTy& OldNodeMap,
827 NodeMapTy& CompletedNodeMap,
828 unsigned CloneFlags) {
829 if (RootNodes.empty())
830 return;
831
832 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
833 assert(&G != this && "Cannot clone graph into itself!");
834 assert((*RootNodes.begin())->getParentGraph() == &G &&
835 "Root nodes do not belong to this graph!");
836
837 // Remove alloca or mod/ref bits as specified...
838 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
839 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
840 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
841 BitsToClear |= DSNode::DEAD; // Clear dead flag...
842
843 // Clone all nodes reachable from each root node, using a recursive helper
844 for (hash_set<const DSNode*>::const_iterator I = RootNodes.begin(),
845 E = RootNodes.end(); I != E; ++I)
846 cloneReachableNodes(*I, BitsToClear, OldNodeMap, CompletedNodeMap);
847
848 // Merge the map entries in OldNodeMap and CompletedNodeMap to remap links
849 NodeMapTy MergedMap(OldNodeMap);
850 MergedMap.insert(CompletedNodeMap.begin(), CompletedNodeMap.end());
851
852 // Rewrite the links in the newly created nodes (the nodes in OldNodeMap)
853 // to point into the current graph. MergedMap gives the full mapping.
854 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
855 I->second.getNode()->remapLinks(MergedMap);
856
857 // Now merge cloned global nodes with their copies in the current graph
858 // Just look through OldNodeMap to find such nodes!
859 for (NodeMapTy::iterator I=OldNodeMap.begin(), E=OldNodeMap.end(); I!= E; ++I)
860 if (I->first->isGlobalNode()) {
861 DSNodeHandle &GClone = I->second;
862 assert(GClone.getNode() != NULL && "NULL node in OldNodeMap?");
863 const std::vector<GlobalValue*> &Globals = I->first->getGlobals();
864 for (unsigned gi = 0, ge = Globals.size(); gi != ge; ++gi) {
865 DSNodeHandle &GH = ScalarMap[Globals[gi]];
866 GH.mergeWith(GClone);
867 }
868 }
869}
870
871
872/// updateFromGlobalGraph - This function rematerializes global nodes and
873/// nodes reachable from them from the globals graph into the current graph.
874/// It invokes cloneReachableSubgraph, using the globals in the current graph
875/// as the roots. It also uses the vector InlinedGlobals to avoid cloning and
876/// merging globals that are already up-to-date in the current graph. In
877/// practice, in the TD pass, this is likely to be a large fraction of the
878/// live global nodes in each function (since most live nodes are likely to
879/// have been brought up-to-date in at _some_ caller or callee).
880///
881void DSGraph::updateFromGlobalGraph() {
882
883 // Use a map to keep track of the mapping between nodes in the globals graph
884 // and this graph for up-to-date global nodes, which do not need to be cloned.
885 NodeMapTy CompletedMap;
886
887 // Put the live, non-up-to-date global nodes into a set and the up-to-date
888 // ones in the map above, mapping node in GlobalsGraph to the up-to-date node.
889 hash_set<const DSNode*> GlobalNodeSet;
890 for (ScalarMapTy::const_iterator I = getScalarMap().begin(),
891 E = getScalarMap().end(); I != E; ++I)
892 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
893 DSNode* GNode = I->second.getNode();
894 assert(GNode && "No node for live global in current Graph?");
895 if (const DSNode* GGNode = GlobalsGraph->ScalarMap[GV].getNode())
896 if (InlinedGlobals.count(GV) == 0) // GNode is not up-to-date
897 GlobalNodeSet.insert(GGNode);
898 else { // GNode is up-to-date
899 CompletedMap[GGNode] = I->second;
900 assert(GGNode->getNumLinks() == GNode->getNumLinks() &&
901 "Links dont match in a node that is supposed to be up-to-date?"
902 "\nremapLinks() will not work if the links don't match!");
903 }
904 }
905
906 // Clone the subgraph reachable from the vector of nodes in GlobalNodes
907 // and merge the cloned global nodes with the corresponding ones, if any.
908 NodeMapTy OldNodeMap;
909 cloneReachableSubgraph(*GlobalsGraph, GlobalNodeSet, OldNodeMap,CompletedMap);
910
911 // Merging global nodes leaves behind unused nodes: get rid of them now.
912 OldNodeMap.clear(); // remove references before dead node cleanup
913 CompletedMap.clear(); // remove references before dead node cleanup
914 removeTriviallyDeadNodes();
915}
916
Chris Lattner5a540632003-06-30 03:15:25 +0000917/// cloneInto - Clone the specified DSGraph into the current graph. The
918/// translated ScalarMap for the old function is filled into the OldValMap
919/// member, and the translated ReturnNodes map is returned into ReturnNodes.
920///
921/// The CloneFlags member controls various aspects of the cloning process.
922///
923void DSGraph::cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
924 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
925 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000926 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000927 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000928
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000929 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000930
931 // Duplicate all of the nodes, populating the node map...
932 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000933
934 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000935 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
936 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
937 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000938 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000939 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000940 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000941 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000942 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000943 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000944 }
945
Chris Lattner18552922002-11-18 21:44:46 +0000946#ifndef NDEBUG
947 Timer::addPeakMemoryMeasurement();
948#endif
949
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000950 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000951 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000952 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000953
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000954 // Copy the scalar map... merging all of the global nodes...
Chris Lattner8d327672003-06-30 03:36:09 +0000955 for (ScalarMapTy::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000956 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000957 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000958 DSNodeHandle &H = OldValMap[I->first];
959 H.mergeWith(DSNodeHandle(MappedNode.getNode(),
960 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +0000961
Chris Lattner2cb9acd2003-06-30 05:09:29 +0000962 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +0000963 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
964 ScalarMap[GV].mergeWith(H);
965 InlinedGlobals.insert(GV);
966 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000967 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000968
Chris Lattner679e8e12002-11-08 21:27:12 +0000969 if (!(CloneFlags & DontCloneCallNodes)) {
970 // Copy the function calls list...
971 unsigned FC = FunctionCalls.size(); // FirstCall
972 FunctionCalls.reserve(FC+G.FunctionCalls.size());
973 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
974 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000975 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000976
Chris Lattneracf491f2002-11-08 22:27:09 +0000977 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Misha Brukman2f2d0652003-09-11 18:14:24 +0000978 // Copy the auxiliary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000979 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000980 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
981 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
982 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
983 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000984
Chris Lattner5a540632003-06-30 03:15:25 +0000985 // Map the return node pointers over...
986 for (ReturnNodesTy::const_iterator I = G.getReturnNodes().begin(),
987 E = G.getReturnNodes().end(); I != E; ++I) {
988 const DSNodeHandle &Ret = I->second;
989 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
990 OldReturnNodes.insert(std::make_pair(I->first,
991 DSNodeHandle(MappedRet.getNode(),
992 MappedRet.getOffset()+Ret.getOffset())));
993 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000994}
995
Chris Lattner076c1f92002-11-07 06:31:54 +0000996/// mergeInGraph - The method is used for merging graphs together. If the
997/// argument graph is not *this, it makes a clone of the specified graph, then
998/// merges the nodes specified in the call site with the formal arguments in the
999/// graph.
1000///
Chris Lattner9f930552003-06-30 05:27:18 +00001001void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1002 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001003 ScalarMapTy OldValMap, *ScalarMap;
Chris Lattner076c1f92002-11-07 06:31:54 +00001004 DSNodeHandle RetVal;
Chris Lattner076c1f92002-11-07 06:31:54 +00001005
1006 // If this is not a recursive call, clone the graph into this graph...
1007 if (&Graph != this) {
1008 // Clone the callee's graph into the current graph, keeping
1009 // track of where scalars in the old graph _used_ to point,
1010 // and of the new nodes matching nodes of the old graph.
Chris Lattner5a540632003-06-30 03:15:25 +00001011 NodeMapTy OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +00001012
1013 // The clone call may invalidate any of the vectors in the data
1014 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner5a540632003-06-30 03:15:25 +00001015 ReturnNodesTy OldRetNodes;
1016 cloneInto(Graph, OldValMap, OldRetNodes, OldNodeMap, CloneFlags);
Chris Lattner58f98d02003-07-02 04:38:49 +00001017
1018 // We need to map the arguments for the function to the cloned nodes old
1019 // argument values. Do this now.
Chris Lattner5a540632003-06-30 03:15:25 +00001020 RetVal = OldRetNodes[&F];
Chris Lattner076c1f92002-11-07 06:31:54 +00001021 ScalarMap = &OldValMap;
1022 } else {
Chris Lattner5a540632003-06-30 03:15:25 +00001023 RetVal = getReturnNodeFor(F);
Chris Lattner076c1f92002-11-07 06:31:54 +00001024 ScalarMap = &getScalarMap();
1025 }
1026
1027 // Merge the return value with the return value of the context...
1028 RetVal.mergeWith(CS.getRetVal());
1029
1030 // Resolve all of the function arguments...
Chris Lattner076c1f92002-11-07 06:31:54 +00001031 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +00001032
Chris Lattner076c1f92002-11-07 06:31:54 +00001033 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
1034 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +00001035 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +00001036 ++AI;
1037#ifndef NDEBUG
1038 if (AI == F.aend())
1039 std::cerr << "Bad call to Function: " << F.getName() << "\n";
1040#endif
Chris Lattner076c1f92002-11-07 06:31:54 +00001041 }
Chris Lattner5d274582003-02-06 00:15:08 +00001042 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +00001043
1044 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +00001045 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +00001046 DSNodeHandle &NH = (*ScalarMap)[AI];
1047 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
1048 NH.mergeWith(CS.getPtrArg(i));
1049 }
1050}
1051
Chris Lattner58f98d02003-07-02 04:38:49 +00001052/// getCallSiteForArguments - Get the arguments and return value bindings for
1053/// the specified function in the current graph.
1054///
1055DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1056 std::vector<DSNodeHandle> Args;
1057
1058 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1059 if (isPointerType(I->getType()))
1060 Args.push_back(getScalarMap().find(I)->second);
1061
Chris Lattner808a7ae2003-09-20 16:34:13 +00001062 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001063}
1064
1065
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001066
Chris Lattner0d9bab82002-07-18 00:12:30 +00001067// markIncompleteNodes - Mark the specified node as having contents that are not
1068// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001069// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001070// must recursively traverse the data structure graph, marking all reachable
1071// nodes as incomplete.
1072//
1073static void markIncompleteNode(DSNode *N) {
1074 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001075 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001076
1077 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001078 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001079
Misha Brukman2f2d0652003-09-11 18:14:24 +00001080 // Recursively process children...
Chris Lattner08db7192002-11-06 06:20:27 +00001081 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
1082 if (DSNode *DSN = N->getLink(i).getNode())
1083 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001084}
1085
Chris Lattnere71ffc22002-11-11 03:36:55 +00001086static void markIncomplete(DSCallSite &Call) {
1087 // Then the return value is certainly incomplete!
1088 markIncompleteNode(Call.getRetVal().getNode());
1089
1090 // All objects pointed to by function arguments are incomplete!
1091 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1092 markIncompleteNode(Call.getPtrArg(i).getNode());
1093}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001094
1095// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1096// modified by other functions that have not been resolved yet. This marks
1097// nodes that are reachable through three sources of "unknownness":
1098//
1099// Global Variables, Function Calls, and Incoming Arguments
1100//
1101// For any node that may have unknown components (because something outside the
1102// scope of current analysis may have modified it), the 'Incomplete' flag is
1103// added to the NodeType.
1104//
Chris Lattner394471f2003-01-23 22:05:33 +00001105void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +00001106 // Mark any incoming arguments as incomplete...
Chris Lattner5a540632003-06-30 03:15:25 +00001107 if (Flags & DSGraph::MarkFormalArgs)
1108 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1109 FI != E; ++FI) {
1110 Function &F = *FI->first;
1111 if (F.getName() != "main")
1112 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
1113 if (isPointerType(I->getType()) &&
1114 ScalarMap.find(I) != ScalarMap.end())
1115 markIncompleteNode(ScalarMap[I].getNode());
1116 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001117
1118 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +00001119 if (!shouldPrintAuxCalls())
1120 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1121 markIncomplete(FunctionCalls[i]);
1122 else
1123 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1124 markIncomplete(AuxFunctionCalls[i]);
1125
Chris Lattner0d9bab82002-07-18 00:12:30 +00001126
Chris Lattner93d7a212003-02-09 18:41:49 +00001127 // Mark all global nodes as incomplete...
1128 if ((Flags & DSGraph::IgnoreGlobals) == 0)
1129 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +00001130 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +00001131 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001132}
1133
Chris Lattneraa8146f2002-11-10 06:59:55 +00001134static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1135 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001136 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001137 // No interesting info?
1138 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001139 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +00001140 Edge.setNode(0); // Kill the edge!
1141}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001142
Chris Lattneraa8146f2002-11-10 06:59:55 +00001143static inline bool nodeContainsExternalFunction(const DSNode *N) {
1144 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1145 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1146 if (Globals[i]->isExternal())
1147 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001148 return false;
1149}
1150
Chris Lattner5a540632003-06-30 03:15:25 +00001151static void removeIdenticalCalls(std::vector<DSCallSite> &Calls) {
Chris Lattner18f07a12003-07-01 16:28:11 +00001152
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001153 // Remove trivially identical function calls
1154 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +00001155 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
1156
1157 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001158 DSNode *LastCalleeNode = 0;
1159 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001160 unsigned NumDuplicateCalls = 0;
1161 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +00001162 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001163 DSCallSite &CS = Calls[i];
1164
Chris Lattnere4258442002-11-11 21:35:38 +00001165 // If the Callee is a useless edge, this must be an unreachable call site,
1166 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001167 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +00001168 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +00001169 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +00001170 CS.swap(Calls.back());
1171 Calls.pop_back();
1172 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001173 } else {
Chris Lattnere4258442002-11-11 21:35:38 +00001174 // If the return value or any arguments point to a void node with no
1175 // information at all in it, and the call node is the only node to point
1176 // to it, remove the edge to the node (killing the node).
1177 //
1178 killIfUselessEdge(CS.getRetVal());
1179 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1180 killIfUselessEdge(CS.getPtrArg(a));
1181
1182 // If this call site calls the same function as the last call site, and if
1183 // the function pointer contains an external function, this node will
1184 // never be resolved. Merge the arguments of the call node because no
1185 // information will be lost.
1186 //
Chris Lattner923fc052003-02-05 21:59:58 +00001187 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1188 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +00001189 ++NumDuplicateCalls;
1190 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +00001191 if (LastCalleeNode)
1192 LastCalleeContainsExternalFunction =
1193 nodeContainsExternalFunction(LastCalleeNode);
1194 else
1195 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001196 }
1197
Chris Lattner58f98d02003-07-02 04:38:49 +00001198#if 1
Chris Lattnere4258442002-11-11 21:35:38 +00001199 if (LastCalleeContainsExternalFunction ||
1200 // This should be more than enough context sensitivity!
1201 // FIXME: Evaluate how many times this is tripped!
1202 NumDuplicateCalls > 20) {
1203 DSCallSite &OCS = Calls[i-1];
1204 OCS.mergeWith(CS);
1205
1206 // The node will now be eliminated as a duplicate!
1207 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
1208 CS = OCS;
1209 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
1210 OCS = CS;
1211 }
Chris Lattner18f07a12003-07-01 16:28:11 +00001212#endif
Chris Lattnere4258442002-11-11 21:35:38 +00001213 } else {
Chris Lattner923fc052003-02-05 21:59:58 +00001214 if (CS.isDirectCall()) {
1215 LastCalleeFunc = CS.getCalleeFunc();
1216 LastCalleeNode = 0;
1217 } else {
1218 LastCalleeNode = CS.getCalleeNode();
1219 LastCalleeFunc = 0;
1220 }
Chris Lattnere4258442002-11-11 21:35:38 +00001221 NumDuplicateCalls = 0;
1222 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001223 }
1224 }
1225
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001226 Calls.erase(std::unique(Calls.begin(), Calls.end()),
1227 Calls.end());
1228
Chris Lattner33312f72002-11-08 01:21:07 +00001229 // Track the number of call nodes merged away...
1230 NumCallNodesMerged += NumFns-Calls.size();
1231
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001232 DEBUG(if (NumFns != Calls.size())
Chris Lattner5a540632003-06-30 03:15:25 +00001233 std::cerr << "Merged " << (NumFns-Calls.size()) << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001234}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001235
Chris Lattneraa8146f2002-11-10 06:59:55 +00001236
Chris Lattnere2219762002-07-18 18:22:40 +00001237// removeTriviallyDeadNodes - After the graph has been constructed, this method
1238// removes all unreachable nodes that are created because they got merged with
1239// other nodes in the graph. These nodes will all be trivially unreachable, so
1240// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001241//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001242void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner5a540632003-06-30 03:15:25 +00001243 removeIdenticalCalls(FunctionCalls);
1244 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001245
Chris Lattnerbab8c282003-09-20 21:34:07 +00001246 // Loop over all of the nodes in the graph, calling getNode on each field.
1247 // This will cause all nodes to update their forwarding edges, causing
1248 // forwarded nodes to be delete-able.
1249 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1250 DSNode *N = Nodes[i];
1251 for (unsigned l = 0, e = N->getNumLinks(); l != e; ++l)
1252 N->getLink(l*N->getPointerSize()).getNode();
1253 }
1254
1255 // Likewise, forward any edges from the scalar nodes...
1256 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1257 I != E; ++I)
1258 I->second.getNode();
1259
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001260 bool isGlobalsGraph = !GlobalsGraph;
1261
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001262 for (unsigned i = 0; i != Nodes.size(); ++i) {
1263 DSNode *Node = Nodes[i];
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001264
1265 // Do not remove *any* global nodes in the globals graph.
1266 // This is a special case because such nodes may not have I, M, R flags set.
1267 if (Node->isGlobalNode() && isGlobalsGraph)
1268 continue;
1269
Chris Lattner72d50a02003-06-28 21:58:28 +00001270 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001271 // This is a useless node if it has no mod/ref info (checked above),
1272 // outgoing edges (which it cannot, as it is not modified in this
1273 // context), and it has no incoming edges. If it is a global node it may
1274 // have all of these properties and still have incoming edges, due to the
1275 // scalar map, so we check those now.
1276 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001277 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001278 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +00001279
1280 // Loop through and make sure all of the globals are referring directly
1281 // to the node...
1282 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1283 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1284 assert(N == Node && "ScalarMap doesn't match globals list!");
1285 }
1286
Chris Lattnerbd92b732003-06-19 21:15:11 +00001287 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +00001288 if (Node->getNumReferrers() == Globals.size()) {
1289 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1290 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001291 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +00001292 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001293 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001294
1295#ifdef SANER_CODE_FOR_CHECKING_IF_ALL_REFERRERS_ARE_FROM_SCALARMAP
1296 //
1297 // *** It seems to me that we should be able to simply check if
1298 // *** there are fewer or equal #referrers as #globals and make
1299 // *** sure that all those referrers are in the scalar map?
1300 //
1301 if (Node->getNumReferrers() <= Node->getGlobals().size()) {
1302 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
1303
1304#ifndef NDEBUG
1305 // Loop through and make sure all of the globals are referring directly
1306 // to the node...
1307 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1308 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
1309 assert(N == Node && "ScalarMap doesn't match globals list!");
1310 }
1311#endif
1312
1313 // Make sure NumReferrers still agrees. The node is truly dead.
1314 assert(Node->getNumReferrers() == Globals.size());
1315 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1316 ScalarMap.erase(Globals[j]);
1317 Node->makeNodeDead();
1318 }
1319#endif
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001320 }
1321
Chris Lattnerbd92b732003-06-19 21:15:11 +00001322 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001323 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001324 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +00001325 Nodes[i--] = Nodes.back();
1326 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001327 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001328 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001329}
1330
1331
Chris Lattner5c7380e2003-01-29 21:10:20 +00001332/// markReachableNodes - This method recursively traverses the specified
1333/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1334/// to the set, which allows it to only traverse visited nodes once.
1335///
Chris Lattner41c04f72003-02-01 04:52:08 +00001336void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001337 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001338 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +00001339 if (ReachableNodes.count(this)) return; // Already marked reachable
1340 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +00001341
Chris Lattner5c7380e2003-01-29 21:10:20 +00001342 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
1343 getLink(i).getNode()->markReachableNodes(ReachableNodes);
1344}
1345
Chris Lattner41c04f72003-02-01 04:52:08 +00001346void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001347 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001348 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001349
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001350 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1351 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001352}
1353
Chris Lattnera1220af2003-02-01 06:17:02 +00001354// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1355// looking for a node that is marked alive. If an alive node is found, return
1356// true, otherwise return false. If an alive node is reachable, this node is
1357// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001358//
Chris Lattnera1220af2003-02-01 06:17:02 +00001359static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001360 hash_set<DSNode*> &Visited,
1361 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001362 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001363 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001364
Chris Lattner85cfe012003-07-03 02:03:53 +00001365 // If this is a global node, it will end up in the globals graph anyway, so we
1366 // don't need to worry about it.
1367 if (IgnoreGlobals && N->isGlobalNode()) return false;
1368
Chris Lattneraa8146f2002-11-10 06:59:55 +00001369 // If we know that this node is alive, return so!
1370 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001371
Chris Lattneraa8146f2002-11-10 06:59:55 +00001372 // Otherwise, we don't think the node is alive yet, check for infinite
1373 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001374 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001375 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001376
Chris Lattner08db7192002-11-06 06:20:27 +00001377 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattner85cfe012003-07-03 02:03:53 +00001378 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited,
1379 IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001380 N->markReachableNodes(Alive);
1381 return true;
1382 }
1383 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001384}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001385
Chris Lattnera1220af2003-02-01 06:17:02 +00001386// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1387// alive nodes.
1388//
Chris Lattner41c04f72003-02-01 04:52:08 +00001389static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
Chris Lattner85cfe012003-07-03 02:03:53 +00001390 hash_set<DSNode*> &Visited,
1391 bool IgnoreGlobals) {
1392 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1393 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001394 return true;
1395 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001396 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001397 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001398 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001399 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1400 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001401 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001402 return false;
1403}
1404
Chris Lattnere2219762002-07-18 18:22:40 +00001405// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1406// subgraphs that are unreachable. This often occurs because the data
1407// structure doesn't "escape" into it's caller, and thus should be eliminated
1408// from the caller's graph entirely. This is only appropriate to use when
1409// inlining graphs.
1410//
Chris Lattner394471f2003-01-23 22:05:33 +00001411void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001412 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001413
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001414 // Reduce the amount of work we have to do... remove dummy nodes left over by
1415 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001416 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001417
Misha Brukman2f2d0652003-09-11 18:14:24 +00001418 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001419
1420 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001421 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001422 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001423
Chris Lattneraa8146f2002-11-10 06:59:55 +00001424 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner8d327672003-06-30 03:36:09 +00001425 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end(); I !=E;)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001426 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001427 assert(I->second.getNode() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001428 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001429 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1430 ++I;
1431 } else {
1432 // Check to see if this is a worthless node generated for non-pointer
1433 // values, such as integers. Consider an addition of long types: A+B.
1434 // Assuming we can track all uses of the value in this context, and it is
1435 // NOT used as a pointer, we can delete the node. We will be able to
1436 // detect this situation if the node pointed to ONLY has Unknown bit set
1437 // in the node. In this case, the node is not incomplete, does not point
1438 // to any other nodes (no mod/ref bits set), and is therefore
1439 // uninteresting for data structure analysis. If we run across one of
1440 // these, prune the scalar pointing to it.
1441 //
1442 DSNode *N = I->second.getNode();
Chris Lattner85cfe012003-07-03 02:03:53 +00001443 if (N->getNodeFlags() == DSNode::UnknownNode && !isa<Argument>(I->first)){
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001444 ScalarMap.erase(I++);
1445 } else {
1446 I->second.getNode()->markReachableNodes(Alive);
1447 ++I;
1448 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001449 }
Chris Lattnere2219762002-07-18 18:22:40 +00001450
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001451 // The return value is alive as well...
Chris Lattner5a540632003-06-30 03:15:25 +00001452 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1453 I != E; ++I)
1454 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001455
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001456 // Mark any nodes reachable by primary calls as alive...
1457 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1458 FunctionCalls[i].markReachableNodes(Alive);
1459
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001460 // Copy and merge all information about globals to the GlobalsGraph
1461 // if this is not a final pass (where unreachable globals are removed)
1462 NodeMapTy GlobalNodeMap;
1463 hash_set<const DSNode*> GlobalNodeSet;
1464
1465 for (std::vector<std::pair<Value*, DSNode*> >::const_iterator
1466 I = GlobalNodes.begin(), E = GlobalNodes.end(); I != E; ++I)
1467 GlobalNodeSet.insert(I->second); // put global nodes into a set
1468
1469 // Now find globals and aux call nodes that are already live or reach a live
1470 // value (which makes them live in turn), and continue till no more are found.
1471 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001472 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001473 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001474 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1475 do {
1476 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001477 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001478 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001479 // unreachable globals in the list.
1480 //
1481 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001482 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
1483 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1484 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1485 Flags & DSGraph::RemoveUnreachableGlobals)) {
1486 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1487 GlobalNodes.pop_back(); // erase efficiently
1488 Iterate = true;
1489 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001490
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001491 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1492 // call nodes that get resolved will be difficult to remove from that graph.
1493 // The final unresolved call nodes must be handled specially at the end of
1494 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001495 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1496 if (!AuxFCallsAlive[i] &&
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001497 (AuxFunctionCalls[i].isIndirectCall()
1498 || CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited,
1499 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001500 AuxFunctionCalls[i].markReachableNodes(Alive);
1501 AuxFCallsAlive[i] = true;
1502 Iterate = true;
1503 }
1504 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001505
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001506 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001507 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001508 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1509 if (AuxFCallsAlive[i])
1510 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001511
1512 // Copy and merge all global nodes and dead aux call nodes into the
1513 // GlobalsGraph, and all nodes reachable from those nodes
1514 //
1515 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1516
1517 // First, add the dead aux call nodes to the set of root nodes for cloning
1518 // -- return value at this call site, if any
1519 // -- actual arguments passed at this call site
1520 // -- callee node at this call site, if this is an indirect call
1521 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i) {
1522 if (const DSNode* RetNode = AuxFunctionCalls[i].getRetVal().getNode())
1523 GlobalNodeSet.insert(RetNode);
1524 for (unsigned j=0, N=AuxFunctionCalls[i].getNumPtrArgs(); j < N; ++j)
1525 if (const DSNode* ArgTarget=AuxFunctionCalls[i].getPtrArg(j).getNode())
1526 GlobalNodeSet.insert(ArgTarget);
1527 if (AuxFunctionCalls[i].isIndirectCall())
1528 GlobalNodeSet.insert(AuxFunctionCalls[i].getCalleeNode());
1529 }
1530
1531 // There are no "pre-completed" nodes so use any empty map for those.
1532 // Strip all alloca bits since the current function is only for the BU pass.
1533 // Strip all incomplete bits since they are short-lived properties and they
1534 // will be correctly computed when rematerializing nodes into the functions.
1535 //
1536 NodeMapTy CompletedMap;
1537 GlobalsGraph->cloneReachableSubgraph(*this, GlobalNodeSet,
1538 GlobalNodeMap, CompletedMap,
1539 (DSGraph::StripAllocaBit |
1540 DSGraph::StripIncompleteBit));
1541 }
1542
1543 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001544 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001545 assert(GlobalsGraph && "No globals graph available??");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001546
1547 // Copy the unreachable call nodes to the globals graph, updating
1548 // their target pointers using the GlobalNodeMap
1549 for (unsigned i = CurIdx, e = AuxFunctionCalls.size(); i != e; ++i)
1550 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(AuxFunctionCalls[i],
1551 GlobalNodeMap));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001552 }
1553 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001554 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1555 AuxFunctionCalls.end());
1556
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001557 // We are finally done with the GlobalNodeMap so we can clear it and
1558 // then get rid of unused nodes in the GlobalsGraph produced by merging.
1559 GlobalNodeMap.clear();
1560 GlobalsGraph->removeTriviallyDeadNodes();
1561
Vikram S. Adve40c600e2003-07-22 12:08:58 +00001562 // At this point, any nodes which are visited, but not alive, are nodes
1563 // which can be removed. Loop over all nodes, eliminating completely
1564 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001565 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001566 std::vector<DSNode*> DeadNodes;
1567 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001568 for (unsigned i = 0; i != Nodes.size(); ++i)
1569 if (!Alive.count(Nodes[i])) {
1570 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001571 Nodes[i--] = Nodes.back(); // move node to end of vector
1572 Nodes.pop_back(); // Erase node from alive list.
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001573 DeadNodes.push_back(N);
1574 N->dropAllReferences();
Chris Lattner72d29a42003-02-11 23:11:51 +00001575 } else {
1576 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001577 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001578
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001579 // Remove all unreachable globals from the ScalarMap.
1580 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
1581 // In either case, the dead nodes will not be in the set Alive.
1582 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1583 assert(((Flags & DSGraph::RemoveUnreachableGlobals) ||
1584 !Alive.count(GlobalNodes[i].second)) && "huh? non-dead global");
1585 if (!Alive.count(GlobalNodes[i].second))
1586 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001587 }
1588
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001589 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00001590 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1591 delete DeadNodes[i];
1592
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001593 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001594}
1595
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001596void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001597 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1598 Nodes[i]->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00001599
Chris Lattner8d327672003-06-30 03:36:09 +00001600 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001601 E = ScalarMap.end(); I != E; ++I) {
1602 assert(I->second.getNode() && "Null node in scalarmap!");
1603 AssertNodeInGraph(I->second.getNode());
1604 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001605 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001606 "Global points to node, but node isn't global?");
1607 AssertNodeContainsGlobal(I->second.getNode(), GV);
1608 }
1609 }
1610 AssertCallNodesInGraph();
1611 AssertAuxCallNodesInGraph();
1612}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001613
Chris Lattner7ddb0132003-08-05 18:38:37 +00001614/// mergeInGlobalsGraph - This method is useful for clients to incorporate the
1615/// globals graph into the DS, BU or TD graph for a function. This code retains
1616/// all globals, i.e., does not delete unreachable globals after they are
1617/// inlined.
1618///
1619void DSGraph::mergeInGlobalsGraph() {
Sumant Kowshik108421a2003-08-05 17:04:41 +00001620 NodeMapTy GlobalNodeMap;
1621 ScalarMapTy OldValMap;
1622 ReturnNodesTy OldRetNodes;
Chris Lattner7ddb0132003-08-05 18:38:37 +00001623 cloneInto(*GlobalsGraph, OldValMap, OldRetNodes, GlobalNodeMap,
1624 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
1625 DSGraph::DontCloneAuxCallNodes);
Sumant Kowshik108421a2003-08-05 17:04:41 +00001626
1627 // Now merge existing global nodes in the GlobalsGraph with their copies
1628 for (ScalarMapTy::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1629 I != E; ++I)
1630 if (isa<GlobalValue>(I->first)) { // Found a global node
1631 DSNodeHandle &GH = I->second;
1632 DSNodeHandle &GGNodeH = GlobalsGraph->getScalarMap()[I->first];
1633 GH.mergeWith(GlobalNodeMap[GGNodeH.getNode()]);
1634 }
1635
1636 // Merging leaves behind unused nodes: get rid of them now.
1637 GlobalNodeMap.clear();
1638 OldValMap.clear();
1639 OldRetNodes.clear();
1640 removeTriviallyDeadNodes();
1641}
Chris Lattner400433d2003-11-11 05:08:59 +00001642
Brian Gaeked0fde302003-11-11 22:41:34 +00001643
Chris Lattner400433d2003-11-11 05:08:59 +00001644/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
1645/// nodes reachable from the two graphs, computing the mapping of nodes from
1646/// the first to the second graph.
1647///
1648void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
1649 const DSNodeHandle &NH2, NodeMapTy &NodeMap) {
1650 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
1651 if (N1 == 0 || N2 == 0) return;
1652
1653 DSNodeHandle &Entry = NodeMap[N1];
1654 if (Entry.getNode()) {
1655 // Termination of recursion!
1656 assert(Entry.getNode() == N2 &&
Chris Lattner413406c2003-11-11 20:12:32 +00001657 Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) &&
Chris Lattner400433d2003-11-11 05:08:59 +00001658 "Inconsistent mapping detected!");
1659 return;
1660 }
1661
1662 Entry.setNode(N2);
Chris Lattner413406c2003-11-11 20:12:32 +00001663 Entry.setOffset(NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00001664
1665 // Loop over all of the fields that N1 and N2 have in common, recursively
1666 // mapping the edges together now.
1667 int N2Idx = NH2.getOffset()-NH1.getOffset();
1668 unsigned N2Size = N2->getSize();
1669 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize)
1670 if (unsigned(N2Idx)+i < N2Size)
1671 computeNodeMapping(N1->getLink(i), N2->getLink(N2Idx+i), NodeMap);
1672}
1673
Brian Gaeked0fde302003-11-11 22:41:34 +00001674} // End llvm namespace