blob: 9e00860365b205725efde5f6fa2a326363f6d265 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00002//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00003// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00004//
5//===----------------------------------------------------------------------===//
6
Chris Lattnerfccd06f2002-10-01 22:33:50 +00007#include "llvm/Analysis/DSGraph.h"
8#include "llvm/Function.h"
Vikram S. Adve26b98262002-10-20 21:41:02 +00009#include "llvm/iOther.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000011#include "llvm/Target/TargetData.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000012#include "Support/STLExtras.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000013#include "Support/Statistic.h"
Chris Lattner18552922002-11-18 21:44:46 +000014#include "Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000015#include <algorithm>
Chris Lattnerc68c31b2002-07-10 22:38:08 +000016
Chris Lattner08db7192002-11-06 06:20:27 +000017namespace {
Chris Lattner33312f72002-11-08 01:21:07 +000018 Statistic<> NumFolds ("dsnode", "Number of nodes completely folded");
19 Statistic<> NumCallNodesMerged("dsnode", "Number of call nodes merged");
Chris Lattner08db7192002-11-06 06:20:27 +000020};
21
Chris Lattnerb1060432002-11-07 05:20:53 +000022namespace DS { // TODO: FIXME
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023 extern TargetData TD;
24}
Chris Lattnerb1060432002-11-07 05:20:53 +000025using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000026
Chris Lattner731b2d72003-02-13 19:09:00 +000027DSNode *DSNodeHandle::HandleForwarding() const {
28 assert(!N->ForwardNH.isNull() && "Can only be invoked if forwarding!");
29
30 // Handle node forwarding here!
31 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
32 Offset += N->ForwardNH.getOffset();
33
34 if (--N->NumReferrers == 0) {
35 // Removing the last referrer to the node, sever the forwarding link
36 N->stopForwarding();
37 }
38
39 N = Next;
40 N->NumReferrers++;
41 if (N->Size <= Offset) {
42 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
43 Offset = 0;
44 }
45 return N;
46}
47
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000048//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000049// DSNode Implementation
50//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000051
Chris Lattnerbd92b732003-06-19 21:15:11 +000052DSNode::DSNode(const Type *T, DSGraph *G)
53 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000054 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000055 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000056 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000057}
58
Chris Lattner0d9bab82002-07-18 00:12:30 +000059// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000060DSNode::DSNode(const DSNode &N, DSGraph *G)
61 : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
62 Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
63 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000064}
65
Chris Lattner72d29a42003-02-11 23:11:51 +000066void DSNode::assertOK() const {
67 assert((Ty != Type::VoidTy ||
68 Ty == Type::VoidTy && (Size == 0 ||
69 (NodeType & DSNode::Array))) &&
70 "Node not OK!");
Chris Lattnerbd92b732003-06-19 21:15:11 +000071
72 // Check to ensure that the multiobject constraints are met...
73 unsigned Comp = NodeType & DSNode::Composition;
74 assert((NodeType & DSNode::MultiObject) ||
75 Comp == 0 || Comp == DSNode::AllocaNode || Comp == DSNode::HeapNode ||
76 Comp == DSNode::GlobalNode || Comp == DSNode::UnknownNode);
Chris Lattner72d29a42003-02-11 23:11:51 +000077}
78
79/// forwardNode - Mark this node as being obsolete, and all references to it
80/// should be forwarded to the specified node and offset.
81///
82void DSNode::forwardNode(DSNode *To, unsigned Offset) {
83 assert(this != To && "Cannot forward a node to itself!");
84 assert(ForwardNH.isNull() && "Already forwarding from this node!");
85 if (To->Size <= 1) Offset = 0;
86 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
87 "Forwarded offset is wrong!");
88 ForwardNH.setNode(To);
89 ForwardNH.setOffset(Offset);
90 NodeType = DEAD;
91 Size = 0;
92 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000093}
94
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000095// addGlobal - Add an entry for a global value to the Globals list. This also
96// marks the node with the 'G' flag if it does not already have it.
97//
98void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000099 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000100 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000101 std::lower_bound(Globals.begin(), Globals.end(), GV);
102
103 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000104 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000105 Globals.insert(I, GV);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000106 if (NodeType & DSNode::Composition)
107 NodeType |= DSNode::MultiObject;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000108 NodeType |= GlobalNode;
109 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000110}
111
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000112/// foldNodeCompletely - If we determine that this node has some funny
113/// behavior happening to it that we cannot represent, we fold it down to a
114/// single, completely pessimistic, node. This node is represented as a
115/// single byte with a single TypeEntry of "void".
116///
117void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000118 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000119
Chris Lattner08db7192002-11-06 06:20:27 +0000120 ++NumFolds;
121
Chris Lattner72d29a42003-02-11 23:11:51 +0000122 // Create the node we are going to forward to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000123 DSNode *DestNode = new DSNode(0, ParentGraph);
124 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000125 DestNode->Ty = Type::VoidTy;
126 DestNode->Size = 1;
127 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000128
Chris Lattner72d29a42003-02-11 23:11:51 +0000129 // Start forwarding to the destination node...
130 forwardNode(DestNode, 0);
131
132 if (Links.size()) {
133 DestNode->Links.push_back(Links[0]);
134 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000135
Chris Lattner72d29a42003-02-11 23:11:51 +0000136 // If we have links, merge all of our outgoing links together...
137 for (unsigned i = Links.size()-1; i != 0; --i)
138 NH.getNode()->Links[0].mergeWith(Links[i]);
139 Links.clear();
140 } else {
141 DestNode->Links.resize(1);
142 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000143}
Chris Lattner076c1f92002-11-07 06:31:54 +0000144
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000145/// isNodeCompletelyFolded - Return true if this node has been completely
146/// folded down to something that can never be expanded, effectively losing
147/// all of the field sensitivity that may be present in the node.
148///
149bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000150 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000151}
152
153
Chris Lattner08db7192002-11-06 06:20:27 +0000154/// mergeTypeInfo - This method merges the specified type into the current node
155/// at the specified offset. This may update the current node's type record if
156/// this gives more information to the node, it may do nothing to the node if
157/// this information is already known, or it may merge the node completely (and
158/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000159///
Chris Lattner08db7192002-11-06 06:20:27 +0000160/// This method returns true if the node is completely folded, otherwise false.
161///
Chris Lattner088b6392003-03-03 17:13:31 +0000162bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
163 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000164 // Check to make sure the Size member is up-to-date. Size can be one of the
165 // following:
166 // Size = 0, Ty = Void: Nothing is known about this node.
167 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
168 // Size = 1, Ty = Void, Array = 1: The node is collapsed
169 // Otherwise, sizeof(Ty) = Size
170 //
Chris Lattner18552922002-11-18 21:44:46 +0000171 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
172 (Size == 0 && !Ty->isSized() && !isArray()) ||
173 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
174 (Size == 0 && !Ty->isSized() && !isArray()) ||
175 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000176 "Size member of DSNode doesn't match the type structure!");
177 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000178
Chris Lattner18552922002-11-18 21:44:46 +0000179 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000180 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000181
Chris Lattner08db7192002-11-06 06:20:27 +0000182 // Return true immediately if the node is completely folded.
183 if (isNodeCompletelyFolded()) return true;
184
Chris Lattner23f83dc2002-11-08 22:49:57 +0000185 // If this is an array type, eliminate the outside arrays because they won't
186 // be used anyway. This greatly reduces the size of large static arrays used
187 // as global variables, for example.
188 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000189 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000190 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
191 // FIXME: we might want to keep small arrays, but must be careful about
192 // things like: [2 x [10000 x int*]]
193 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000194 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000195 }
196
Chris Lattner08db7192002-11-06 06:20:27 +0000197 // Figure out how big the new type we're merging in is...
198 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
199
200 // Otherwise check to see if we can fold this type into the current node. If
201 // we can't, we fold the node completely, if we can, we potentially update our
202 // internal state.
203 //
Chris Lattner18552922002-11-18 21:44:46 +0000204 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000205 // If this is the first type that this node has seen, just accept it without
206 // question....
207 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000208 assert(!isArray() && "This shouldn't happen!");
209 Ty = NewTy;
210 NodeType &= ~Array;
211 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000212 Size = NewTySize;
213
214 // Calculate the number of outgoing links from this node.
215 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
216 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000217 }
Chris Lattner08db7192002-11-06 06:20:27 +0000218
219 // Handle node expansion case here...
220 if (Offset+NewTySize > Size) {
221 // It is illegal to grow this node if we have treated it as an array of
222 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000223 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000224 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000225 return true;
226 }
227
228 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000229 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
230 << "offset != 0: Collapsing!\n");
Chris Lattner088b6392003-03-03 17:13:31 +0000231 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000232 return true;
233 }
234
235 // Okay, the situation is nice and simple, we are trying to merge a type in
236 // at offset 0 that is bigger than our current type. Implement this by
237 // switching to the new type and then merge in the smaller one, which should
238 // hit the other code path here. If the other code path decides it's not
239 // ok, it will collapse the node as appropriate.
240 //
Chris Lattner18552922002-11-18 21:44:46 +0000241 const Type *OldTy = Ty;
242 Ty = NewTy;
243 NodeType &= ~Array;
244 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000245 Size = NewTySize;
246
247 // Must grow links to be the appropriate size...
248 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
249
250 // Merge in the old type now... which is guaranteed to be smaller than the
251 // "current" type.
252 return mergeTypeInfo(OldTy, 0);
253 }
254
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000255 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000256 "Cannot merge something into a part of our type that doesn't exist!");
257
Chris Lattner18552922002-11-18 21:44:46 +0000258 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000259 // type that starts at offset Offset.
260 //
261 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000262 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000263 while (O < Offset) {
264 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
265
266 switch (SubType->getPrimitiveID()) {
267 case Type::StructTyID: {
268 const StructType *STy = cast<StructType>(SubType);
269 const StructLayout &SL = *TD.getStructLayout(STy);
270
271 unsigned i = 0, e = SL.MemberOffsets.size();
272 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
273 /* empty */;
274
275 // The offset we are looking for must be in the i'th element...
276 SubType = STy->getElementTypes()[i];
277 O += SL.MemberOffsets[i];
278 break;
279 }
280 case Type::ArrayTyID: {
281 SubType = cast<ArrayType>(SubType)->getElementType();
282 unsigned ElSize = TD.getTypeSize(SubType);
283 unsigned Remainder = (Offset-O) % ElSize;
284 O = Offset-Remainder;
285 break;
286 }
287 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000288 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000289 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000290 }
291 }
292
293 assert(O == Offset && "Could not achieve the correct offset!");
294
295 // If we found our type exactly, early exit
296 if (SubType == NewTy) return false;
297
298 // Okay, so we found the leader type at the offset requested. Search the list
299 // of types that starts at this offset. If SubType is currently an array or
300 // structure, the type desired may actually be the first element of the
301 // composite type...
302 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000303 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner18552922002-11-18 21:44:46 +0000304 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000305 while (SubType != NewTy) {
306 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000307 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000308 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000309 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000310 case Type::StructTyID: {
311 const StructType *STy = cast<StructType>(SubType);
312 const StructLayout &SL = *TD.getStructLayout(STy);
313 if (SL.MemberOffsets.size() > 1)
314 NextPadSize = SL.MemberOffsets[1];
315 else
316 NextPadSize = SubTypeSize;
317 NextSubType = STy->getElementTypes()[0];
318 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000319 break;
Chris Lattner18552922002-11-18 21:44:46 +0000320 }
Chris Lattner08db7192002-11-06 06:20:27 +0000321 case Type::ArrayTyID:
322 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000323 NextSubTypeSize = TD.getTypeSize(NextSubType);
324 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000325 break;
326 default: ;
327 // fall out
328 }
329
330 if (NextSubType == 0)
331 break; // In the default case, break out of the loop
332
Chris Lattner18552922002-11-18 21:44:46 +0000333 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000334 break; // Don't allow shrinking to a smaller type than NewTySize
335 SubType = NextSubType;
336 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000337 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000338 }
339
340 // If we found the type exactly, return it...
341 if (SubType == NewTy)
342 return false;
343
344 // Check to see if we have a compatible, but different type...
345 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000346 // Check to see if this type is obviously convertible... int -> uint f.e.
347 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000348 return false;
349
350 // Check to see if we have a pointer & integer mismatch going on here,
351 // loading a pointer as a long, for example.
352 //
353 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
354 NewTy->isInteger() && isa<PointerType>(SubType))
355 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000356 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
357 // We are accessing the field, plus some structure padding. Ignore the
358 // structure padding.
359 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000360 }
361
362
Chris Lattner18552922002-11-18 21:44:46 +0000363 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000364 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
365 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000366
Chris Lattner088b6392003-03-03 17:13:31 +0000367 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000368 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000369}
370
Chris Lattner08db7192002-11-06 06:20:27 +0000371
372
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000373// addEdgeTo - Add an edge from the current node to the specified node. This
374// can cause merging of nodes in the graph.
375//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000376void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000377 if (NH.getNode() == 0) return; // Nothing to do
378
Chris Lattner08db7192002-11-06 06:20:27 +0000379 DSNodeHandle &ExistingEdge = getLink(Offset);
380 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000381 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000382 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000383 } else { // No merging to perform...
384 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000385 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000386}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000387
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000388
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000389// MergeSortedVectors - Efficiently merge a vector into another vector where
390// duplicates are not allowed and both are sorted. This assumes that 'T's are
391// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000392//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000393static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
394 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000395 // By far, the most common cases will be the simple ones. In these cases,
396 // avoid having to allocate a temporary vector...
397 //
398 if (Src.empty()) { // Nothing to merge in...
399 return;
400 } else if (Dest.empty()) { // Just copy the result in...
401 Dest = Src;
402 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000403 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000404 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000405 std::lower_bound(Dest.begin(), Dest.end(), V);
406 if (I == Dest.end() || *I != Src[0]) // If not already contained...
407 Dest.insert(I, Src[0]);
408 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000409 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000410 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000411 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000412 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
413 if (I == Dest.end() || *I != Tmp) // If not already contained...
414 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000415
416 } else {
417 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000418 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000419
420 // Make space for all of the type entries now...
421 Dest.resize(Dest.size()+Src.size());
422
423 // Merge the two sorted ranges together... into Dest.
424 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
425
426 // Now erase any duplicate entries that may have accumulated into the
427 // vectors (because they were in both of the input sets)
428 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
429 }
430}
431
432
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000433// MergeNodes() - Helper function for DSNode::mergeWith().
434// This function does the hard work of merging two nodes, CurNodeH
435// and NH after filtering out trivial cases and making sure that
436// CurNodeH.offset >= NH.offset.
437//
438// ***WARNING***
439// Since merging may cause either node to go away, we must always
440// use the node-handles to refer to the nodes. These node handles are
441// automatically updated during merging, so will always provide access
442// to the correct node after a merge.
443//
444void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
445 assert(CurNodeH.getOffset() >= NH.getOffset() &&
446 "This should have been enforced in the caller.");
447
448 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
449 // respect to NH.Offset) is now zero. NOffset is the distance from the base
450 // of our object that N starts from.
451 //
452 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
453 unsigned NSize = NH.getNode()->getSize();
454
455 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000456 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000457 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000458 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000459
460 // If we are merging a node with a completely folded node, then both nodes are
461 // now completely folded.
462 //
463 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
464 if (!NH.getNode()->isNodeCompletelyFolded()) {
465 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000466 assert(NH.getNode() && NH.getOffset() == 0 &&
467 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000468 NOffset = NH.getOffset();
469 NSize = NH.getNode()->getSize();
470 assert(NOffset == 0 && NSize == 1);
471 }
472 } else if (NH.getNode()->isNodeCompletelyFolded()) {
473 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000474 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
475 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000476 NOffset = NH.getOffset();
477 NSize = NH.getNode()->getSize();
478 assert(NOffset == 0 && NSize == 1);
479 }
480
Chris Lattner72d29a42003-02-11 23:11:51 +0000481 DSNode *N = NH.getNode();
482 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000483 assert(!CurNodeH.getNode()->isDeadNode());
484
485 // Merge the NodeType information...
486 if ((CurNodeH.getNode()->NodeType & DSNode::Composition) != 0 &&
487 (N->NodeType & DSNode::Composition) != 0)
488 N->NodeType |= DSNode::MultiObject; // Multiple composition -> multiobject
489 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000490
Chris Lattner72d29a42003-02-11 23:11:51 +0000491 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000492 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000493 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000494
Chris Lattner72d29a42003-02-11 23:11:51 +0000495 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
496 //
497 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
498 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000499 if (Link.getNode()) {
500 // Compute the offset into the current node at which to
501 // merge this link. In the common case, this is a linear
502 // relation to the offset in the original node (with
503 // wrapping), but if the current node gets collapsed due to
504 // recursive merging, we must make sure to merge in all remaining
505 // links at offset zero.
506 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000507 DSNode *CN = CurNodeH.getNode();
508 if (CN->Size != 1)
509 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
510 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000511 }
512 }
513
514 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000515 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000516
517 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000518 if (!N->Globals.empty()) {
519 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000520
521 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000522 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000523 }
524}
525
526
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000527// mergeWith - Merge this node and the specified node, moving all links to and
528// from the argument node into the current node, deleting the node argument.
529// Offset indicates what offset the specified node is to be merged into the
530// current node.
531//
532// The specified node may be a null pointer (in which case, nothing happens).
533//
534void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
535 DSNode *N = NH.getNode();
536 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000537 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000538
Chris Lattnerbd92b732003-06-19 21:15:11 +0000539 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000540 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
541
Chris Lattner02606632002-11-04 06:48:26 +0000542 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000543 // We cannot merge two pieces of the same node together, collapse the node
544 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000545 DEBUG(std::cerr << "Attempting to merge two chunks of"
546 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000547 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000548 return;
549 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000550
Chris Lattner5190ce82002-11-12 07:20:45 +0000551 // If both nodes are not at offset 0, make sure that we are merging the node
552 // at an later offset into the node with the zero offset.
553 //
554 if (Offset < NH.getOffset()) {
555 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
556 return;
557 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
558 // If the offsets are the same, merge the smaller node into the bigger node
559 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
560 return;
561 }
562
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000563 // Ok, now we can merge the two nodes. Use a static helper that works with
564 // two node handles, since "this" may get merged away at intermediate steps.
565 DSNodeHandle CurNodeH(this, Offset);
566 DSNodeHandle NHCopy(NH);
567 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000568}
569
Chris Lattner9de906c2002-10-20 22:11:44 +0000570//===----------------------------------------------------------------------===//
571// DSCallSite Implementation
572//===----------------------------------------------------------------------===//
573
Vikram S. Adve26b98262002-10-20 21:41:02 +0000574// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000575Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000576 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000577}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000578
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000579
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000580//===----------------------------------------------------------------------===//
581// DSGraph Implementation
582//===----------------------------------------------------------------------===//
583
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000584DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000585 PrintAuxCalls = false;
Chris Lattner41c04f72003-02-01 04:52:08 +0000586 hash_map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000587 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000588}
589
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000590DSGraph::DSGraph(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000591 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000592 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000593 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000594 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000595}
596
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000597DSGraph::~DSGraph() {
598 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000599 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000600 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000601 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000602
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000603 // Drop all intra-node references, so that assertions don't fail...
604 std::for_each(Nodes.begin(), Nodes.end(),
605 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000606
607 // Delete all of the nodes themselves...
608 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
609}
610
Chris Lattner0d9bab82002-07-18 00:12:30 +0000611// dump - Allow inspection of graph in a debugger.
612void DSGraph::dump() const { print(std::cerr); }
613
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000614
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000615/// remapLinks - Change all of the Links in the current node according to the
616/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000617///
Chris Lattner41c04f72003-02-01 04:52:08 +0000618void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000619 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
620 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
621 Links[i].setNode(H.getNode());
622 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
623 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000624}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000625
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000626
Chris Lattner0d9bab82002-07-18 00:12:30 +0000627// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000628// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000629// filled into the OldValMap member. If StripAllocas is set to true, Alloca
630// markers are removed from the graph, as the graph is being cloned into a
631// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000632//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000633DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000634 hash_map<Value*, DSNodeHandle> &OldValMap,
635 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000636 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000637 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000638 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000639
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000640 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000641
642 // Duplicate all of the nodes, populating the node map...
643 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000644
645 // Remove alloca or mod/ref bits as specified...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000646 unsigned BitsToClear =((CloneFlags & StripAllocaBit) ? DSNode::AllocaNode : 0)
647 | ((CloneFlags & StripModRefBits) ? (DSNode::Modified | DSNode::Read) : 0);
648 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000649 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000650 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000651 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000652 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000653 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000654 }
655
Chris Lattner18552922002-11-18 21:44:46 +0000656#ifndef NDEBUG
657 Timer::addPeakMemoryMeasurement();
658#endif
659
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000660 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000661 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000662 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000663
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000664 // Copy the scalar map... merging all of the global nodes...
Chris Lattner41c04f72003-02-01 04:52:08 +0000665 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000666 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000667 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000668 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000669 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattner72d29a42003-02-11 23:11:51 +0000670 H.setNode(MappedNode.getNode());
Chris Lattnercf15db32002-10-17 20:09:52 +0000671
672 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattner41c04f72003-02-01 04:52:08 +0000673 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000674 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000675 GVI->second.mergeWith(H);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000676 else
Chris Lattnerc875f022002-11-03 21:27:48 +0000677 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000678 }
679 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000680
Chris Lattner679e8e12002-11-08 21:27:12 +0000681 if (!(CloneFlags & DontCloneCallNodes)) {
682 // Copy the function calls list...
683 unsigned FC = FunctionCalls.size(); // FirstCall
684 FunctionCalls.reserve(FC+G.FunctionCalls.size());
685 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
686 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000687 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000688
Chris Lattneracf491f2002-11-08 22:27:09 +0000689 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000690 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000691 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000692 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
693 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
694 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
695 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000696
Chris Lattner0d9bab82002-07-18 00:12:30 +0000697 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000698 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
699 return DSNodeHandle(MappedRet.getNode(),
700 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000701}
702
Chris Lattner076c1f92002-11-07 06:31:54 +0000703/// mergeInGraph - The method is used for merging graphs together. If the
704/// argument graph is not *this, it makes a clone of the specified graph, then
705/// merges the nodes specified in the call site with the formal arguments in the
706/// graph.
707///
708void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000709 unsigned CloneFlags) {
Chris Lattner41c04f72003-02-01 04:52:08 +0000710 hash_map<Value*, DSNodeHandle> OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000711 DSNodeHandle RetVal;
Chris Lattner41c04f72003-02-01 04:52:08 +0000712 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000713
714 // If this is not a recursive call, clone the graph into this graph...
715 if (&Graph != this) {
716 // Clone the callee's graph into the current graph, keeping
717 // track of where scalars in the old graph _used_ to point,
718 // and of the new nodes matching nodes of the old graph.
Chris Lattner41c04f72003-02-01 04:52:08 +0000719 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000720
721 // The clone call may invalidate any of the vectors in the data
722 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000723 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000724 ScalarMap = &OldValMap;
725 } else {
726 RetVal = getRetNode();
727 ScalarMap = &getScalarMap();
728 }
729
730 // Merge the return value with the return value of the context...
731 RetVal.mergeWith(CS.getRetVal());
732
733 // Resolve all of the function arguments...
734 Function &F = Graph.getFunction();
735 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000736
Chris Lattner076c1f92002-11-07 06:31:54 +0000737 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
738 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000739 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000740 ++AI;
741#ifndef NDEBUG
742 if (AI == F.aend())
743 std::cerr << "Bad call to Function: " << F.getName() << "\n";
744#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000745 }
Chris Lattner5d274582003-02-06 00:15:08 +0000746 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000747
748 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000749 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000750 DSNodeHandle &NH = (*ScalarMap)[AI];
751 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
752 NH.mergeWith(CS.getPtrArg(i));
753 }
754}
755
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000756
Chris Lattner0d9bab82002-07-18 00:12:30 +0000757// markIncompleteNodes - Mark the specified node as having contents that are not
758// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +0000759// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +0000760// must recursively traverse the data structure graph, marking all reachable
761// nodes as incomplete.
762//
763static void markIncompleteNode(DSNode *N) {
764 // Stop recursion if no node, or if node already marked...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000765 if (N == 0 || (N->isIncomplete())) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000766
767 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000768 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +0000769
770 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000771 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
772 if (DSNode *DSN = N->getLink(i).getNode())
773 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000774}
775
Chris Lattnere71ffc22002-11-11 03:36:55 +0000776static void markIncomplete(DSCallSite &Call) {
777 // Then the return value is certainly incomplete!
778 markIncompleteNode(Call.getRetVal().getNode());
779
780 // All objects pointed to by function arguments are incomplete!
781 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
782 markIncompleteNode(Call.getPtrArg(i).getNode());
783}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000784
785// markIncompleteNodes - Traverse the graph, identifying nodes that may be
786// modified by other functions that have not been resolved yet. This marks
787// nodes that are reachable through three sources of "unknownness":
788//
789// Global Variables, Function Calls, and Incoming Arguments
790//
791// For any node that may have unknown components (because something outside the
792// scope of current analysis may have modified it), the 'Incomplete' flag is
793// added to the NodeType.
794//
Chris Lattner394471f2003-01-23 22:05:33 +0000795void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000796 // Mark any incoming arguments as incomplete...
Chris Lattnere77f1452003-02-08 23:08:02 +0000797 if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000798 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000799 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
800 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000801
802 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000803 if (!shouldPrintAuxCalls())
804 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
805 markIncomplete(FunctionCalls[i]);
806 else
807 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
808 markIncomplete(AuxFunctionCalls[i]);
809
Chris Lattner0d9bab82002-07-18 00:12:30 +0000810
Chris Lattner93d7a212003-02-09 18:41:49 +0000811 // Mark all global nodes as incomplete...
812 if ((Flags & DSGraph::IgnoreGlobals) == 0)
813 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +0000814 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +0000815 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000816}
817
Chris Lattneraa8146f2002-11-10 06:59:55 +0000818static inline void killIfUselessEdge(DSNodeHandle &Edge) {
819 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +0000820 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +0000821 // No interesting info?
822 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +0000823 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000824 Edge.setNode(0); // Kill the edge!
825}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000826
Chris Lattneraa8146f2002-11-10 06:59:55 +0000827static inline bool nodeContainsExternalFunction(const DSNode *N) {
828 const std::vector<GlobalValue*> &Globals = N->getGlobals();
829 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
830 if (Globals[i]->isExternal())
831 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000832 return false;
833}
834
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000835static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000836 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000837 // Remove trivially identical function calls
838 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000839 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
840
841 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +0000842 DSNode *LastCalleeNode = 0;
843 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000844 unsigned NumDuplicateCalls = 0;
845 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000846 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000847 DSCallSite &CS = Calls[i];
848
Chris Lattnere4258442002-11-11 21:35:38 +0000849 // If the Callee is a useless edge, this must be an unreachable call site,
850 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +0000851 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +0000852 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +0000853 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +0000854 CS.swap(Calls.back());
855 Calls.pop_back();
856 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000857 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000858 // If the return value or any arguments point to a void node with no
859 // information at all in it, and the call node is the only node to point
860 // to it, remove the edge to the node (killing the node).
861 //
862 killIfUselessEdge(CS.getRetVal());
863 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
864 killIfUselessEdge(CS.getPtrArg(a));
865
866 // If this call site calls the same function as the last call site, and if
867 // the function pointer contains an external function, this node will
868 // never be resolved. Merge the arguments of the call node because no
869 // information will be lost.
870 //
Chris Lattner923fc052003-02-05 21:59:58 +0000871 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
872 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +0000873 ++NumDuplicateCalls;
874 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +0000875 if (LastCalleeNode)
876 LastCalleeContainsExternalFunction =
877 nodeContainsExternalFunction(LastCalleeNode);
878 else
879 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +0000880 }
881
882 if (LastCalleeContainsExternalFunction ||
883 // This should be more than enough context sensitivity!
884 // FIXME: Evaluate how many times this is tripped!
885 NumDuplicateCalls > 20) {
886 DSCallSite &OCS = Calls[i-1];
887 OCS.mergeWith(CS);
888
889 // The node will now be eliminated as a duplicate!
890 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
891 CS = OCS;
892 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
893 OCS = CS;
894 }
895 } else {
Chris Lattner923fc052003-02-05 21:59:58 +0000896 if (CS.isDirectCall()) {
897 LastCalleeFunc = CS.getCalleeFunc();
898 LastCalleeNode = 0;
899 } else {
900 LastCalleeNode = CS.getCalleeNode();
901 LastCalleeFunc = 0;
902 }
Chris Lattnere4258442002-11-11 21:35:38 +0000903 NumDuplicateCalls = 0;
904 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000905 }
906 }
907
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000908 Calls.erase(std::unique(Calls.begin(), Calls.end()),
909 Calls.end());
910
Chris Lattner33312f72002-11-08 01:21:07 +0000911 // Track the number of call nodes merged away...
912 NumCallNodesMerged += NumFns-Calls.size();
913
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000914 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000915 std::cerr << "Merged " << (NumFns-Calls.size())
916 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000917}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000918
Chris Lattneraa8146f2002-11-10 06:59:55 +0000919
Chris Lattnere2219762002-07-18 18:22:40 +0000920// removeTriviallyDeadNodes - After the graph has been constructed, this method
921// removes all unreachable nodes that are created because they got merged with
922// other nodes in the graph. These nodes will all be trivially unreachable, so
923// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000924//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000925void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000926 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000927 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
928
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000929 for (unsigned i = 0; i != Nodes.size(); ++i) {
930 DSNode *Node = Nodes[i];
Chris Lattnerbd92b732003-06-19 21:15:11 +0000931 if (!Node->isIncomplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000932 // This is a useless node if it has no mod/ref info (checked above),
933 // outgoing edges (which it cannot, as it is not modified in this
934 // context), and it has no incoming edges. If it is a global node it may
935 // have all of these properties and still have incoming edges, due to the
936 // scalar map, so we check those now.
937 //
Chris Lattner72d29a42003-02-11 23:11:51 +0000938 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +0000939 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +0000940
941 // Loop through and make sure all of the globals are referring directly
942 // to the node...
943 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
944 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
945 assert(N == Node && "ScalarMap doesn't match globals list!");
946 }
947
Chris Lattnerbd92b732003-06-19 21:15:11 +0000948 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000949 if (Node->getNumReferrers() == Globals.size()) {
950 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
951 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000952 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +0000953 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000954 }
955 }
956
Chris Lattnerbd92b732003-06-19 21:15:11 +0000957 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +0000958 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000959 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +0000960 Nodes[i--] = Nodes.back();
961 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000962 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000963 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000964}
965
966
Chris Lattner5c7380e2003-01-29 21:10:20 +0000967/// markReachableNodes - This method recursively traverses the specified
968/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
969/// to the set, which allows it to only traverse visited nodes once.
970///
Chris Lattner41c04f72003-02-01 04:52:08 +0000971void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000972 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +0000973 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +0000974 if (ReachableNodes.count(this)) return; // Already marked reachable
975 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +0000976
Chris Lattner5c7380e2003-01-29 21:10:20 +0000977 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
978 getLink(i).getNode()->markReachableNodes(ReachableNodes);
979}
980
Chris Lattner41c04f72003-02-01 04:52:08 +0000981void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000982 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +0000983 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +0000984
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000985 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
986 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +0000987}
988
Chris Lattnera1220af2003-02-01 06:17:02 +0000989// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
990// looking for a node that is marked alive. If an alive node is found, return
991// true, otherwise return false. If an alive node is reachable, this node is
992// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000993//
Chris Lattnera1220af2003-02-01 06:17:02 +0000994static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
995 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000996 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +0000997 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000998
Chris Lattneraa8146f2002-11-10 06:59:55 +0000999 // If we know that this node is alive, return so!
1000 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001001
Chris Lattneraa8146f2002-11-10 06:59:55 +00001002 // Otherwise, we don't think the node is alive yet, check for infinite
1003 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001004 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001005 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001006
Chris Lattner08db7192002-11-06 06:20:27 +00001007 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +00001008 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
1009 N->markReachableNodes(Alive);
1010 return true;
1011 }
1012 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001013}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001014
Chris Lattnera1220af2003-02-01 06:17:02 +00001015// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1016// alive nodes.
1017//
Chris Lattner41c04f72003-02-01 04:52:08 +00001018static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1019 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +00001020 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1021 return true;
1022 if (CS.isIndirectCall() &&
1023 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001024 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001025 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1026 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001027 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001028 return false;
1029}
1030
Chris Lattnere2219762002-07-18 18:22:40 +00001031// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1032// subgraphs that are unreachable. This often occurs because the data
1033// structure doesn't "escape" into it's caller, and thus should be eliminated
1034// from the caller's graph entirely. This is only appropriate to use when
1035// inlining graphs.
1036//
Chris Lattner394471f2003-01-23 22:05:33 +00001037void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001038 // Reduce the amount of work we have to do... remove dummy nodes left over by
1039 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001040 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001041
Chris Lattnere2219762002-07-18 18:22:40 +00001042 // FIXME: Merge nontrivially identical call nodes...
1043
1044 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001045 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001046 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001047
Chris Lattneraa8146f2002-11-10 06:59:55 +00001048 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner41c04f72003-02-01 04:52:08 +00001049 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001050 E = ScalarMap.end(); I != E; )
1051 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001052 assert(I->second.getNode() && "Null global node?");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001053 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1054 ++I;
1055 } else {
1056 // Check to see if this is a worthless node generated for non-pointer
1057 // values, such as integers. Consider an addition of long types: A+B.
1058 // Assuming we can track all uses of the value in this context, and it is
1059 // NOT used as a pointer, we can delete the node. We will be able to
1060 // detect this situation if the node pointed to ONLY has Unknown bit set
1061 // in the node. In this case, the node is not incomplete, does not point
1062 // to any other nodes (no mod/ref bits set), and is therefore
1063 // uninteresting for data structure analysis. If we run across one of
1064 // these, prune the scalar pointing to it.
1065 //
1066 DSNode *N = I->second.getNode();
Chris Lattnerbd92b732003-06-19 21:15:11 +00001067 if (N->isUnknownNode() && !isa<Argument>(I->first)) {
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001068 ScalarMap.erase(I++);
1069 } else {
1070 I->second.getNode()->markReachableNodes(Alive);
1071 ++I;
1072 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001073 }
Chris Lattnere2219762002-07-18 18:22:40 +00001074
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001075 // The return value is alive as well...
Chris Lattner5c7380e2003-01-29 21:10:20 +00001076 RetNode.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001077
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001078 // Mark any nodes reachable by primary calls as alive...
1079 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1080 FunctionCalls[i].markReachableNodes(Alive);
1081
1082 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001083 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001084 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1085 do {
1086 Visited.clear();
1087 // If any global nodes points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001088 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001089 // unreachable globals in the list.
1090 //
1091 Iterate = false;
1092 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1093 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1094 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1095 GlobalNodes.pop_back(); // Erase efficiently
1096 Iterate = true;
1097 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001098
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001099 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1100 if (!AuxFCallsAlive[i] &&
1101 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1102 AuxFunctionCalls[i].markReachableNodes(Alive);
1103 AuxFCallsAlive[i] = true;
1104 Iterate = true;
1105 }
1106 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001107
1108 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001109 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001110 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1111 if (AuxFCallsAlive[i])
1112 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001113 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001114 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001115 // Move the unreachable call nodes to the globals graph...
1116 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1117 AuxFunctionCalls.begin()+CurIdx,
1118 AuxFunctionCalls.end());
1119 }
1120 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001121 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1122 AuxFunctionCalls.end());
1123
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001124 // At this point, any nodes which are visited, but not alive, are nodes which
1125 // should be moved to the globals graph. Loop over all nodes, eliminating
1126 // completely unreachable nodes, and moving visited nodes to the globals graph
1127 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001128 std::vector<DSNode*> DeadNodes;
1129 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001130 for (unsigned i = 0; i != Nodes.size(); ++i)
1131 if (!Alive.count(Nodes[i])) {
1132 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001133 Nodes[i--] = Nodes.back(); // move node to end of vector
1134 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001135 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1136 Visited.count(N)) { // Visited but not alive?
1137 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner72d29a42003-02-11 23:11:51 +00001138 N->setParentGraph(GlobalsGraph);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001139 } else { // Otherwise, delete the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001140 assert((!N->isGlobalNode() ||
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001141 (Flags & DSGraph::RemoveUnreachableGlobals))
1142 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001143 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1144 // << "] Node is dead: "; N->dump();
1145 DeadNodes.push_back(N);
1146 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001147 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001148 } else {
1149 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001150 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001151
1152 // Now that the nodes have either been deleted or moved to the globals graph,
1153 // loop over the scalarmap, updating the entries for globals...
1154 //
1155 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1156 // In this array we start the remapping, which can cause merging. Because
1157 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1158 // must always go through the ScalarMap (which contains DSNodeHandles [which
1159 // cannot be invalidated by merging]).
1160 //
1161 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1162 Value *G = GlobalNodes[i].first;
1163 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1164 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1165 assert(I->second.getNode() && "Global not pointing to anything?");
1166 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1167 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1168 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1169 "Global not pointing to anything?");
1170 ScalarMap.erase(I);
1171 }
1172
1173 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1174 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001175 if (!GlobalNodes.empty())
1176 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001177 } else {
1178 // If we are in the top-down pass, remove all unreachable globals from the
1179 // ScalarMap...
1180 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1181 ScalarMap.erase(GlobalNodes[i].first);
1182 }
1183
Chris Lattner72d29a42003-02-11 23:11:51 +00001184 // Loop over all of the dead nodes now, deleting them since their referrer
1185 // count is zero.
1186 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1187 delete DeadNodes[i];
1188
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001189 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001190}
1191
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001192void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001193 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1194 Nodes[i]->assertOK();
1195 return; // FIXME: remove
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001196 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1197 E = ScalarMap.end(); I != E; ++I) {
1198 assert(I->second.getNode() && "Null node in scalarmap!");
1199 AssertNodeInGraph(I->second.getNode());
1200 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001201 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001202 "Global points to node, but node isn't global?");
1203 AssertNodeContainsGlobal(I->second.getNode(), GV);
1204 }
1205 }
1206 AssertCallNodesInGraph();
1207 AssertAuxCallNodesInGraph();
1208}