blob: 33c36c38e7069177d0e834e9b5ca38716d546795 [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!");
71}
72
73/// forwardNode - Mark this node as being obsolete, and all references to it
74/// should be forwarded to the specified node and offset.
75///
76void DSNode::forwardNode(DSNode *To, unsigned Offset) {
77 assert(this != To && "Cannot forward a node to itself!");
78 assert(ForwardNH.isNull() && "Already forwarding from this node!");
79 if (To->Size <= 1) Offset = 0;
80 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
81 "Forwarded offset is wrong!");
82 ForwardNH.setNode(To);
83 ForwardNH.setOffset(Offset);
84 NodeType = DEAD;
85 Size = 0;
86 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000087}
88
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000089// addGlobal - Add an entry for a global value to the Globals list. This also
90// marks the node with the 'G' flag if it does not already have it.
91//
92void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000093 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000094 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000095 std::lower_bound(Globals.begin(), Globals.end(), GV);
96
97 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000098 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000099 Globals.insert(I, GV);
100 NodeType |= GlobalNode;
101 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000102}
103
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000104/// foldNodeCompletely - If we determine that this node has some funny
105/// behavior happening to it that we cannot represent, we fold it down to a
106/// single, completely pessimistic, node. This node is represented as a
107/// single byte with a single TypeEntry of "void".
108///
109void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000110 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000111
Chris Lattner08db7192002-11-06 06:20:27 +0000112 ++NumFolds;
113
Chris Lattner72d29a42003-02-11 23:11:51 +0000114 // Create the node we are going to forward to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000115 DSNode *DestNode = new DSNode(0, ParentGraph);
116 DestNode->NodeType = NodeType|DSNode::Array;
Chris Lattner72d29a42003-02-11 23:11:51 +0000117 DestNode->Ty = Type::VoidTy;
118 DestNode->Size = 1;
119 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000120
Chris Lattner72d29a42003-02-11 23:11:51 +0000121 // Start forwarding to the destination node...
122 forwardNode(DestNode, 0);
123
124 if (Links.size()) {
125 DestNode->Links.push_back(Links[0]);
126 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000127
Chris Lattner72d29a42003-02-11 23:11:51 +0000128 // If we have links, merge all of our outgoing links together...
129 for (unsigned i = Links.size()-1; i != 0; --i)
130 NH.getNode()->Links[0].mergeWith(Links[i]);
131 Links.clear();
132 } else {
133 DestNode->Links.resize(1);
134 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000135}
Chris Lattner076c1f92002-11-07 06:31:54 +0000136
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000137/// isNodeCompletelyFolded - Return true if this node has been completely
138/// folded down to something that can never be expanded, effectively losing
139/// all of the field sensitivity that may be present in the node.
140///
141bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000142 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000143}
144
145
Chris Lattner08db7192002-11-06 06:20:27 +0000146/// mergeTypeInfo - This method merges the specified type into the current node
147/// at the specified offset. This may update the current node's type record if
148/// this gives more information to the node, it may do nothing to the node if
149/// this information is already known, or it may merge the node completely (and
150/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000151///
Chris Lattner08db7192002-11-06 06:20:27 +0000152/// This method returns true if the node is completely folded, otherwise false.
153///
Chris Lattner088b6392003-03-03 17:13:31 +0000154bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
155 bool FoldIfIncompatible) {
Chris Lattner08db7192002-11-06 06:20:27 +0000156 // Check to make sure the Size member is up-to-date. Size can be one of the
157 // following:
158 // Size = 0, Ty = Void: Nothing is known about this node.
159 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
160 // Size = 1, Ty = Void, Array = 1: The node is collapsed
161 // Otherwise, sizeof(Ty) = Size
162 //
Chris Lattner18552922002-11-18 21:44:46 +0000163 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
164 (Size == 0 && !Ty->isSized() && !isArray()) ||
165 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
166 (Size == 0 && !Ty->isSized() && !isArray()) ||
167 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000168 "Size member of DSNode doesn't match the type structure!");
169 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000170
Chris Lattner18552922002-11-18 21:44:46 +0000171 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000172 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000173
Chris Lattner08db7192002-11-06 06:20:27 +0000174 // Return true immediately if the node is completely folded.
175 if (isNodeCompletelyFolded()) return true;
176
Chris Lattner23f83dc2002-11-08 22:49:57 +0000177 // If this is an array type, eliminate the outside arrays because they won't
178 // be used anyway. This greatly reduces the size of large static arrays used
179 // as global variables, for example.
180 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000181 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000182 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
183 // FIXME: we might want to keep small arrays, but must be careful about
184 // things like: [2 x [10000 x int*]]
185 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000186 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000187 }
188
Chris Lattner08db7192002-11-06 06:20:27 +0000189 // Figure out how big the new type we're merging in is...
190 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
191
192 // Otherwise check to see if we can fold this type into the current node. If
193 // we can't, we fold the node completely, if we can, we potentially update our
194 // internal state.
195 //
Chris Lattner18552922002-11-18 21:44:46 +0000196 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000197 // If this is the first type that this node has seen, just accept it without
198 // question....
199 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000200 assert(!isArray() && "This shouldn't happen!");
201 Ty = NewTy;
202 NodeType &= ~Array;
203 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000204 Size = NewTySize;
205
206 // Calculate the number of outgoing links from this node.
207 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
208 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000209 }
Chris Lattner08db7192002-11-06 06:20:27 +0000210
211 // Handle node expansion case here...
212 if (Offset+NewTySize > Size) {
213 // It is illegal to grow this node if we have treated it as an array of
214 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000215 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000216 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000217 return true;
218 }
219
220 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000221 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
222 << "offset != 0: Collapsing!\n");
Chris Lattner088b6392003-03-03 17:13:31 +0000223 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000224 return true;
225 }
226
227 // Okay, the situation is nice and simple, we are trying to merge a type in
228 // at offset 0 that is bigger than our current type. Implement this by
229 // switching to the new type and then merge in the smaller one, which should
230 // hit the other code path here. If the other code path decides it's not
231 // ok, it will collapse the node as appropriate.
232 //
Chris Lattner18552922002-11-18 21:44:46 +0000233 const Type *OldTy = Ty;
234 Ty = NewTy;
235 NodeType &= ~Array;
236 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000237 Size = NewTySize;
238
239 // Must grow links to be the appropriate size...
240 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
241
242 // Merge in the old type now... which is guaranteed to be smaller than the
243 // "current" type.
244 return mergeTypeInfo(OldTy, 0);
245 }
246
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000247 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000248 "Cannot merge something into a part of our type that doesn't exist!");
249
Chris Lattner18552922002-11-18 21:44:46 +0000250 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000251 // type that starts at offset Offset.
252 //
253 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000254 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000255 while (O < Offset) {
256 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
257
258 switch (SubType->getPrimitiveID()) {
259 case Type::StructTyID: {
260 const StructType *STy = cast<StructType>(SubType);
261 const StructLayout &SL = *TD.getStructLayout(STy);
262
263 unsigned i = 0, e = SL.MemberOffsets.size();
264 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
265 /* empty */;
266
267 // The offset we are looking for must be in the i'th element...
268 SubType = STy->getElementTypes()[i];
269 O += SL.MemberOffsets[i];
270 break;
271 }
272 case Type::ArrayTyID: {
273 SubType = cast<ArrayType>(SubType)->getElementType();
274 unsigned ElSize = TD.getTypeSize(SubType);
275 unsigned Remainder = (Offset-O) % ElSize;
276 O = Offset-Remainder;
277 break;
278 }
279 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000280 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000281 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000282 }
283 }
284
285 assert(O == Offset && "Could not achieve the correct offset!");
286
287 // If we found our type exactly, early exit
288 if (SubType == NewTy) return false;
289
290 // Okay, so we found the leader type at the offset requested. Search the list
291 // of types that starts at this offset. If SubType is currently an array or
292 // structure, the type desired may actually be the first element of the
293 // composite type...
294 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000295 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner18552922002-11-18 21:44:46 +0000296 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000297 while (SubType != NewTy) {
298 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000299 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000300 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000301 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000302 case Type::StructTyID: {
303 const StructType *STy = cast<StructType>(SubType);
304 const StructLayout &SL = *TD.getStructLayout(STy);
305 if (SL.MemberOffsets.size() > 1)
306 NextPadSize = SL.MemberOffsets[1];
307 else
308 NextPadSize = SubTypeSize;
309 NextSubType = STy->getElementTypes()[0];
310 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000311 break;
Chris Lattner18552922002-11-18 21:44:46 +0000312 }
Chris Lattner08db7192002-11-06 06:20:27 +0000313 case Type::ArrayTyID:
314 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000315 NextSubTypeSize = TD.getTypeSize(NextSubType);
316 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000317 break;
318 default: ;
319 // fall out
320 }
321
322 if (NextSubType == 0)
323 break; // In the default case, break out of the loop
324
Chris Lattner18552922002-11-18 21:44:46 +0000325 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000326 break; // Don't allow shrinking to a smaller type than NewTySize
327 SubType = NextSubType;
328 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000329 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000330 }
331
332 // If we found the type exactly, return it...
333 if (SubType == NewTy)
334 return false;
335
336 // Check to see if we have a compatible, but different type...
337 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000338 // Check to see if this type is obviously convertible... int -> uint f.e.
339 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000340 return false;
341
342 // Check to see if we have a pointer & integer mismatch going on here,
343 // loading a pointer as a long, for example.
344 //
345 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
346 NewTy->isInteger() && isa<PointerType>(SubType))
347 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000348 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
349 // We are accessing the field, plus some structure padding. Ignore the
350 // structure padding.
351 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000352 }
353
354
Chris Lattner18552922002-11-18 21:44:46 +0000355 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000356 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
357 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000358
Chris Lattner088b6392003-03-03 17:13:31 +0000359 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000360 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000361}
362
Chris Lattner08db7192002-11-06 06:20:27 +0000363
364
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000365// addEdgeTo - Add an edge from the current node to the specified node. This
366// can cause merging of nodes in the graph.
367//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000368void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000369 if (NH.getNode() == 0) return; // Nothing to do
370
Chris Lattner08db7192002-11-06 06:20:27 +0000371 DSNodeHandle &ExistingEdge = getLink(Offset);
372 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000373 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000374 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000375 } else { // No merging to perform...
376 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000377 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000378}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000379
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000380
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000381// MergeSortedVectors - Efficiently merge a vector into another vector where
382// duplicates are not allowed and both are sorted. This assumes that 'T's are
383// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000384//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000385static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
386 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000387 // By far, the most common cases will be the simple ones. In these cases,
388 // avoid having to allocate a temporary vector...
389 //
390 if (Src.empty()) { // Nothing to merge in...
391 return;
392 } else if (Dest.empty()) { // Just copy the result in...
393 Dest = Src;
394 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000395 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000396 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000397 std::lower_bound(Dest.begin(), Dest.end(), V);
398 if (I == Dest.end() || *I != Src[0]) // If not already contained...
399 Dest.insert(I, Src[0]);
400 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000401 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000402 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000403 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000404 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
405 if (I == Dest.end() || *I != Tmp) // If not already contained...
406 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000407
408 } else {
409 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000410 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000411
412 // Make space for all of the type entries now...
413 Dest.resize(Dest.size()+Src.size());
414
415 // Merge the two sorted ranges together... into Dest.
416 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
417
418 // Now erase any duplicate entries that may have accumulated into the
419 // vectors (because they were in both of the input sets)
420 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
421 }
422}
423
424
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000425// MergeNodes() - Helper function for DSNode::mergeWith().
426// This function does the hard work of merging two nodes, CurNodeH
427// and NH after filtering out trivial cases and making sure that
428// CurNodeH.offset >= NH.offset.
429//
430// ***WARNING***
431// Since merging may cause either node to go away, we must always
432// use the node-handles to refer to the nodes. These node handles are
433// automatically updated during merging, so will always provide access
434// to the correct node after a merge.
435//
436void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
437 assert(CurNodeH.getOffset() >= NH.getOffset() &&
438 "This should have been enforced in the caller.");
439
440 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
441 // respect to NH.Offset) is now zero. NOffset is the distance from the base
442 // of our object that N starts from.
443 //
444 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
445 unsigned NSize = NH.getNode()->getSize();
446
447 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000448 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000449 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000450 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000451
452 // If we are merging a node with a completely folded node, then both nodes are
453 // now completely folded.
454 //
455 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
456 if (!NH.getNode()->isNodeCompletelyFolded()) {
457 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000458 assert(NH.getNode() && NH.getOffset() == 0 &&
459 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000460 NOffset = NH.getOffset();
461 NSize = NH.getNode()->getSize();
462 assert(NOffset == 0 && NSize == 1);
463 }
464 } else if (NH.getNode()->isNodeCompletelyFolded()) {
465 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000466 assert(CurNodeH.getNode() && CurNodeH.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
Chris Lattner72d29a42003-02-11 23:11:51 +0000473 DSNode *N = NH.getNode();
474 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000475 assert(!CurNodeH.getNode()->isDeadNode());
476
477 // Merge the NodeType information...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000478 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000479
Chris Lattner72d29a42003-02-11 23:11:51 +0000480 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000481 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000482 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000483
Chris Lattner72d29a42003-02-11 23:11:51 +0000484 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
485 //
486 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
487 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000488 if (Link.getNode()) {
489 // Compute the offset into the current node at which to
490 // merge this link. In the common case, this is a linear
491 // relation to the offset in the original node (with
492 // wrapping), but if the current node gets collapsed due to
493 // recursive merging, we must make sure to merge in all remaining
494 // links at offset zero.
495 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000496 DSNode *CN = CurNodeH.getNode();
497 if (CN->Size != 1)
498 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
499 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000500 }
501 }
502
503 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000504 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000505
506 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000507 if (!N->Globals.empty()) {
508 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000509
510 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000511 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000512 }
513}
514
515
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000516// mergeWith - Merge this node and the specified node, moving all links to and
517// from the argument node into the current node, deleting the node argument.
518// Offset indicates what offset the specified node is to be merged into the
519// current node.
520//
521// The specified node may be a null pointer (in which case, nothing happens).
522//
523void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
524 DSNode *N = NH.getNode();
525 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000526 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000527
Chris Lattnerbd92b732003-06-19 21:15:11 +0000528 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000529 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
530
Chris Lattner02606632002-11-04 06:48:26 +0000531 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000532 // We cannot merge two pieces of the same node together, collapse the node
533 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000534 DEBUG(std::cerr << "Attempting to merge two chunks of"
535 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000536 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000537 return;
538 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000539
Chris Lattner5190ce82002-11-12 07:20:45 +0000540 // If both nodes are not at offset 0, make sure that we are merging the node
541 // at an later offset into the node with the zero offset.
542 //
543 if (Offset < NH.getOffset()) {
544 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
545 return;
546 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
547 // If the offsets are the same, merge the smaller node into the bigger node
548 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
549 return;
550 }
551
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000552 // Ok, now we can merge the two nodes. Use a static helper that works with
553 // two node handles, since "this" may get merged away at intermediate steps.
554 DSNodeHandle CurNodeH(this, Offset);
555 DSNodeHandle NHCopy(NH);
556 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000557}
558
Chris Lattner9de906c2002-10-20 22:11:44 +0000559//===----------------------------------------------------------------------===//
560// DSCallSite Implementation
561//===----------------------------------------------------------------------===//
562
Vikram S. Adve26b98262002-10-20 21:41:02 +0000563// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000564Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000565 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000566}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000567
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000568
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000569//===----------------------------------------------------------------------===//
570// DSGraph Implementation
571//===----------------------------------------------------------------------===//
572
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000573DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000574 PrintAuxCalls = false;
Chris Lattner41c04f72003-02-01 04:52:08 +0000575 hash_map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000576 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000577}
578
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000579DSGraph::DSGraph(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000580 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000581 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000582 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000583 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000584}
585
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000586DSGraph::~DSGraph() {
587 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000588 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000589 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000590 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000591
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000592 // Drop all intra-node references, so that assertions don't fail...
593 std::for_each(Nodes.begin(), Nodes.end(),
594 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000595
596 // Delete all of the nodes themselves...
597 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
598}
599
Chris Lattner0d9bab82002-07-18 00:12:30 +0000600// dump - Allow inspection of graph in a debugger.
601void DSGraph::dump() const { print(std::cerr); }
602
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000603
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000604/// remapLinks - Change all of the Links in the current node according to the
605/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000606///
Chris Lattner41c04f72003-02-01 04:52:08 +0000607void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000608 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
609 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
610 Links[i].setNode(H.getNode());
611 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
612 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000613}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000614
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000615
Chris Lattner0d9bab82002-07-18 00:12:30 +0000616// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000617// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000618// filled into the OldValMap member. If StripAllocas is set to true, Alloca
619// markers are removed from the graph, as the graph is being cloned into a
620// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000621//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000622DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000623 hash_map<Value*, DSNodeHandle> &OldValMap,
624 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000625 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000626 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000627 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000628
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000629 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000630
631 // Duplicate all of the nodes, populating the node map...
632 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000633
634 // Remove alloca or mod/ref bits as specified...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000635 unsigned BitsToClear =((CloneFlags & StripAllocaBit) ? DSNode::AllocaNode : 0)
636 | ((CloneFlags & StripModRefBits) ? (DSNode::Modified | DSNode::Read) : 0);
637 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000638 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000639 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000640 DSNode *New = new DSNode(*Old, this);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000641 New->maskNodeTypes(~BitsToClear);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000642 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000643 }
644
Chris Lattner18552922002-11-18 21:44:46 +0000645#ifndef NDEBUG
646 Timer::addPeakMemoryMeasurement();
647#endif
648
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000649 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000650 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000651 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000652
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000653 // Copy the scalar map... merging all of the global nodes...
Chris Lattner41c04f72003-02-01 04:52:08 +0000654 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000655 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000656 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000657 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000658 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattner72d29a42003-02-11 23:11:51 +0000659 H.setNode(MappedNode.getNode());
Chris Lattnercf15db32002-10-17 20:09:52 +0000660
661 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattner41c04f72003-02-01 04:52:08 +0000662 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000663 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000664 GVI->second.mergeWith(H);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000665 else
Chris Lattnerc875f022002-11-03 21:27:48 +0000666 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000667 }
668 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000669
Chris Lattner679e8e12002-11-08 21:27:12 +0000670 if (!(CloneFlags & DontCloneCallNodes)) {
671 // Copy the function calls list...
672 unsigned FC = FunctionCalls.size(); // FirstCall
673 FunctionCalls.reserve(FC+G.FunctionCalls.size());
674 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
675 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000676 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000677
Chris Lattneracf491f2002-11-08 22:27:09 +0000678 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000679 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000680 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000681 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
682 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
683 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
684 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000685
Chris Lattner0d9bab82002-07-18 00:12:30 +0000686 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000687 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
688 return DSNodeHandle(MappedRet.getNode(),
689 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000690}
691
Chris Lattner076c1f92002-11-07 06:31:54 +0000692/// mergeInGraph - The method is used for merging graphs together. If the
693/// argument graph is not *this, it makes a clone of the specified graph, then
694/// merges the nodes specified in the call site with the formal arguments in the
695/// graph.
696///
697void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000698 unsigned CloneFlags) {
Chris Lattner41c04f72003-02-01 04:52:08 +0000699 hash_map<Value*, DSNodeHandle> OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000700 DSNodeHandle RetVal;
Chris Lattner41c04f72003-02-01 04:52:08 +0000701 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000702
703 // If this is not a recursive call, clone the graph into this graph...
704 if (&Graph != this) {
705 // Clone the callee's graph into the current graph, keeping
706 // track of where scalars in the old graph _used_ to point,
707 // and of the new nodes matching nodes of the old graph.
Chris Lattner41c04f72003-02-01 04:52:08 +0000708 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000709
710 // The clone call may invalidate any of the vectors in the data
711 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000712 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000713 ScalarMap = &OldValMap;
714 } else {
715 RetVal = getRetNode();
716 ScalarMap = &getScalarMap();
717 }
718
719 // Merge the return value with the return value of the context...
720 RetVal.mergeWith(CS.getRetVal());
721
722 // Resolve all of the function arguments...
723 Function &F = Graph.getFunction();
724 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000725
Chris Lattner076c1f92002-11-07 06:31:54 +0000726 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
727 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000728 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000729 ++AI;
730#ifndef NDEBUG
731 if (AI == F.aend())
732 std::cerr << "Bad call to Function: " << F.getName() << "\n";
733#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000734 }
Chris Lattner5d274582003-02-06 00:15:08 +0000735 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000736
737 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000738 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000739 DSNodeHandle &NH = (*ScalarMap)[AI];
740 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
741 NH.mergeWith(CS.getPtrArg(i));
742 }
743}
744
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000745
Chris Lattner0d9bab82002-07-18 00:12:30 +0000746// markIncompleteNodes - Mark the specified node as having contents that are not
747// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +0000748// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +0000749// must recursively traverse the data structure graph, marking all reachable
750// nodes as incomplete.
751//
752static void markIncompleteNode(DSNode *N) {
753 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +0000754 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000755
756 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000757 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +0000758
759 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000760 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
761 if (DSNode *DSN = N->getLink(i).getNode())
762 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000763}
764
Chris Lattnere71ffc22002-11-11 03:36:55 +0000765static void markIncomplete(DSCallSite &Call) {
766 // Then the return value is certainly incomplete!
767 markIncompleteNode(Call.getRetVal().getNode());
768
769 // All objects pointed to by function arguments are incomplete!
770 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
771 markIncompleteNode(Call.getPtrArg(i).getNode());
772}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000773
774// markIncompleteNodes - Traverse the graph, identifying nodes that may be
775// modified by other functions that have not been resolved yet. This marks
776// nodes that are reachable through three sources of "unknownness":
777//
778// Global Variables, Function Calls, and Incoming Arguments
779//
780// For any node that may have unknown components (because something outside the
781// scope of current analysis may have modified it), the 'Incomplete' flag is
782// added to the NodeType.
783//
Chris Lattner394471f2003-01-23 22:05:33 +0000784void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000785 // Mark any incoming arguments as incomplete...
Chris Lattnere77f1452003-02-08 23:08:02 +0000786 if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000787 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000788 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
789 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000790
791 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000792 if (!shouldPrintAuxCalls())
793 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
794 markIncomplete(FunctionCalls[i]);
795 else
796 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
797 markIncomplete(AuxFunctionCalls[i]);
798
Chris Lattner0d9bab82002-07-18 00:12:30 +0000799
Chris Lattner93d7a212003-02-09 18:41:49 +0000800 // Mark all global nodes as incomplete...
801 if ((Flags & DSGraph::IgnoreGlobals) == 0)
802 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerbd92b732003-06-19 21:15:11 +0000803 if (Nodes[i]->isGlobalNode() && Nodes[i]->getNumLinks())
Chris Lattner93d7a212003-02-09 18:41:49 +0000804 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000805}
806
Chris Lattneraa8146f2002-11-10 06:59:55 +0000807static inline void killIfUselessEdge(DSNodeHandle &Edge) {
808 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +0000809 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +0000810 // No interesting info?
811 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +0000812 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000813 Edge.setNode(0); // Kill the edge!
814}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000815
Chris Lattneraa8146f2002-11-10 06:59:55 +0000816static inline bool nodeContainsExternalFunction(const DSNode *N) {
817 const std::vector<GlobalValue*> &Globals = N->getGlobals();
818 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
819 if (Globals[i]->isExternal())
820 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000821 return false;
822}
823
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000824static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000825 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000826 // Remove trivially identical function calls
827 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000828 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
829
830 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +0000831 DSNode *LastCalleeNode = 0;
832 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000833 unsigned NumDuplicateCalls = 0;
834 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000835 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000836 DSCallSite &CS = Calls[i];
837
Chris Lattnere4258442002-11-11 21:35:38 +0000838 // If the Callee is a useless edge, this must be an unreachable call site,
839 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +0000840 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerbd92b732003-06-19 21:15:11 +0000841 CS.getCalleeNode()->getNodeFlags() == 0) { // No useful info?
Chris Lattner923fc052003-02-05 21:59:58 +0000842 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +0000843 CS.swap(Calls.back());
844 Calls.pop_back();
845 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000846 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000847 // If the return value or any arguments point to a void node with no
848 // information at all in it, and the call node is the only node to point
849 // to it, remove the edge to the node (killing the node).
850 //
851 killIfUselessEdge(CS.getRetVal());
852 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
853 killIfUselessEdge(CS.getPtrArg(a));
854
855 // If this call site calls the same function as the last call site, and if
856 // the function pointer contains an external function, this node will
857 // never be resolved. Merge the arguments of the call node because no
858 // information will be lost.
859 //
Chris Lattner923fc052003-02-05 21:59:58 +0000860 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
861 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +0000862 ++NumDuplicateCalls;
863 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +0000864 if (LastCalleeNode)
865 LastCalleeContainsExternalFunction =
866 nodeContainsExternalFunction(LastCalleeNode);
867 else
868 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +0000869 }
870
871 if (LastCalleeContainsExternalFunction ||
872 // This should be more than enough context sensitivity!
873 // FIXME: Evaluate how many times this is tripped!
874 NumDuplicateCalls > 20) {
875 DSCallSite &OCS = Calls[i-1];
876 OCS.mergeWith(CS);
877
878 // The node will now be eliminated as a duplicate!
879 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
880 CS = OCS;
881 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
882 OCS = CS;
883 }
884 } else {
Chris Lattner923fc052003-02-05 21:59:58 +0000885 if (CS.isDirectCall()) {
886 LastCalleeFunc = CS.getCalleeFunc();
887 LastCalleeNode = 0;
888 } else {
889 LastCalleeNode = CS.getCalleeNode();
890 LastCalleeFunc = 0;
891 }
Chris Lattnere4258442002-11-11 21:35:38 +0000892 NumDuplicateCalls = 0;
893 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000894 }
895 }
896
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000897 Calls.erase(std::unique(Calls.begin(), Calls.end()),
898 Calls.end());
899
Chris Lattner33312f72002-11-08 01:21:07 +0000900 // Track the number of call nodes merged away...
901 NumCallNodesMerged += NumFns-Calls.size();
902
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000903 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000904 std::cerr << "Merged " << (NumFns-Calls.size())
905 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000906}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000907
Chris Lattneraa8146f2002-11-10 06:59:55 +0000908
Chris Lattnere2219762002-07-18 18:22:40 +0000909// removeTriviallyDeadNodes - After the graph has been constructed, this method
910// removes all unreachable nodes that are created because they got merged with
911// other nodes in the graph. These nodes will all be trivially unreachable, so
912// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000913//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000914void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000915 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000916 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
917
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000918 for (unsigned i = 0; i != Nodes.size(); ++i) {
919 DSNode *Node = Nodes[i];
Chris Lattner72d50a02003-06-28 21:58:28 +0000920 if (Node->isComplete() && !Node->isModified() && !Node->isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000921 // This is a useless node if it has no mod/ref info (checked above),
922 // outgoing edges (which it cannot, as it is not modified in this
923 // context), and it has no incoming edges. If it is a global node it may
924 // have all of these properties and still have incoming edges, due to the
925 // scalar map, so we check those now.
926 //
Chris Lattner72d29a42003-02-11 23:11:51 +0000927 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattnerbd92b732003-06-19 21:15:11 +0000928 const std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +0000929
930 // Loop through and make sure all of the globals are referring directly
931 // to the node...
932 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
933 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
934 assert(N == Node && "ScalarMap doesn't match globals list!");
935 }
936
Chris Lattnerbd92b732003-06-19 21:15:11 +0000937 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000938 if (Node->getNumReferrers() == Globals.size()) {
939 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
940 ScalarMap.erase(Globals[j]);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000941 Node->makeNodeDead();
Chris Lattner72d29a42003-02-11 23:11:51 +0000942 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000943 }
944 }
945
Chris Lattnerbd92b732003-06-19 21:15:11 +0000946 if (Node->getNodeFlags() == 0 && Node->hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +0000947 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000948 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +0000949 Nodes[i--] = Nodes.back();
950 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000951 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000952 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000953}
954
955
Chris Lattner5c7380e2003-01-29 21:10:20 +0000956/// markReachableNodes - This method recursively traverses the specified
957/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
958/// to the set, which allows it to only traverse visited nodes once.
959///
Chris Lattner41c04f72003-02-01 04:52:08 +0000960void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000961 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +0000962 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +0000963 if (ReachableNodes.count(this)) return; // Already marked reachable
964 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +0000965
Chris Lattner5c7380e2003-01-29 21:10:20 +0000966 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
967 getLink(i).getNode()->markReachableNodes(ReachableNodes);
968}
969
Chris Lattner41c04f72003-02-01 04:52:08 +0000970void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000971 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +0000972 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +0000973
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000974 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
975 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +0000976}
977
Chris Lattnera1220af2003-02-01 06:17:02 +0000978// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
979// looking for a node that is marked alive. If an alive node is found, return
980// true, otherwise return false. If an alive node is reachable, this node is
981// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000982//
Chris Lattnera1220af2003-02-01 06:17:02 +0000983static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
984 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000985 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +0000986 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000987
Chris Lattneraa8146f2002-11-10 06:59:55 +0000988 // If we know that this node is alive, return so!
989 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000990
Chris Lattneraa8146f2002-11-10 06:59:55 +0000991 // Otherwise, we don't think the node is alive yet, check for infinite
992 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +0000993 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +0000994 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000995
Chris Lattner08db7192002-11-06 06:20:27 +0000996 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +0000997 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
998 N->markReachableNodes(Alive);
999 return true;
1000 }
1001 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001002}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001003
Chris Lattnera1220af2003-02-01 06:17:02 +00001004// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1005// alive nodes.
1006//
Chris Lattner41c04f72003-02-01 04:52:08 +00001007static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
1008 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +00001009 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
1010 return true;
1011 if (CS.isIndirectCall() &&
1012 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001013 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001014 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1015 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001016 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001017 return false;
1018}
1019
Chris Lattnere2219762002-07-18 18:22:40 +00001020// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1021// subgraphs that are unreachable. This often occurs because the data
1022// structure doesn't "escape" into it's caller, and thus should be eliminated
1023// from the caller's graph entirely. This is only appropriate to use when
1024// inlining graphs.
1025//
Chris Lattner394471f2003-01-23 22:05:33 +00001026void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001027 // Reduce the amount of work we have to do... remove dummy nodes left over by
1028 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001029 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001030
Chris Lattnere2219762002-07-18 18:22:40 +00001031 // FIXME: Merge nontrivially identical call nodes...
1032
1033 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001034 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001035 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001036
Chris Lattneraa8146f2002-11-10 06:59:55 +00001037 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner41c04f72003-02-01 04:52:08 +00001038 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001039 E = ScalarMap.end(); I != E; )
1040 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001041 assert(I->second.getNode() && "Null global node?");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001042 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
1043 ++I;
1044 } else {
1045 // Check to see if this is a worthless node generated for non-pointer
1046 // values, such as integers. Consider an addition of long types: A+B.
1047 // Assuming we can track all uses of the value in this context, and it is
1048 // NOT used as a pointer, we can delete the node. We will be able to
1049 // detect this situation if the node pointed to ONLY has Unknown bit set
1050 // in the node. In this case, the node is not incomplete, does not point
1051 // to any other nodes (no mod/ref bits set), and is therefore
1052 // uninteresting for data structure analysis. If we run across one of
1053 // these, prune the scalar pointing to it.
1054 //
1055 DSNode *N = I->second.getNode();
Chris Lattnerbd92b732003-06-19 21:15:11 +00001056 if (N->isUnknownNode() && !isa<Argument>(I->first)) {
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001057 ScalarMap.erase(I++);
1058 } else {
1059 I->second.getNode()->markReachableNodes(Alive);
1060 ++I;
1061 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001062 }
Chris Lattnere2219762002-07-18 18:22:40 +00001063
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001064 // The return value is alive as well...
Chris Lattner5c7380e2003-01-29 21:10:20 +00001065 RetNode.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001066
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001067 // Mark any nodes reachable by primary calls as alive...
1068 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1069 FunctionCalls[i].markReachableNodes(Alive);
1070
1071 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001072 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001073 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1074 do {
1075 Visited.clear();
1076 // If any global nodes points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001077 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001078 // unreachable globals in the list.
1079 //
1080 Iterate = false;
1081 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1082 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1083 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1084 GlobalNodes.pop_back(); // Erase efficiently
1085 Iterate = true;
1086 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001087
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001088 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1089 if (!AuxFCallsAlive[i] &&
1090 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1091 AuxFunctionCalls[i].markReachableNodes(Alive);
1092 AuxFCallsAlive[i] = true;
1093 Iterate = true;
1094 }
1095 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001096
1097 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001098 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001099 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1100 if (AuxFCallsAlive[i])
1101 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001102 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001103 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001104 // Move the unreachable call nodes to the globals graph...
1105 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1106 AuxFunctionCalls.begin()+CurIdx,
1107 AuxFunctionCalls.end());
1108 }
1109 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001110 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1111 AuxFunctionCalls.end());
1112
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001113 // At this point, any nodes which are visited, but not alive, are nodes which
1114 // should be moved to the globals graph. Loop over all nodes, eliminating
1115 // completely unreachable nodes, and moving visited nodes to the globals graph
1116 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001117 std::vector<DSNode*> DeadNodes;
1118 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001119 for (unsigned i = 0; i != Nodes.size(); ++i)
1120 if (!Alive.count(Nodes[i])) {
1121 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001122 Nodes[i--] = Nodes.back(); // move node to end of vector
1123 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001124 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1125 Visited.count(N)) { // Visited but not alive?
1126 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner72d29a42003-02-11 23:11:51 +00001127 N->setParentGraph(GlobalsGraph);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001128 } else { // Otherwise, delete the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001129 assert((!N->isGlobalNode() ||
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001130 (Flags & DSGraph::RemoveUnreachableGlobals))
1131 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001132 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1133 // << "] Node is dead: "; N->dump();
1134 DeadNodes.push_back(N);
1135 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001136 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001137 } else {
1138 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001139 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001140
1141 // Now that the nodes have either been deleted or moved to the globals graph,
1142 // loop over the scalarmap, updating the entries for globals...
1143 //
1144 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1145 // In this array we start the remapping, which can cause merging. Because
1146 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1147 // must always go through the ScalarMap (which contains DSNodeHandles [which
1148 // cannot be invalidated by merging]).
1149 //
1150 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1151 Value *G = GlobalNodes[i].first;
1152 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1153 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1154 assert(I->second.getNode() && "Global not pointing to anything?");
1155 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1156 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1157 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1158 "Global not pointing to anything?");
1159 ScalarMap.erase(I);
1160 }
1161
1162 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1163 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001164 if (!GlobalNodes.empty())
1165 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001166 } else {
1167 // If we are in the top-down pass, remove all unreachable globals from the
1168 // ScalarMap...
1169 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1170 ScalarMap.erase(GlobalNodes[i].first);
1171 }
1172
Chris Lattner72d29a42003-02-11 23:11:51 +00001173 // Loop over all of the dead nodes now, deleting them since their referrer
1174 // count is zero.
1175 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1176 delete DeadNodes[i];
1177
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001178 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001179}
1180
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001181void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001182 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1183 Nodes[i]->assertOK();
1184 return; // FIXME: remove
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001185 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1186 E = ScalarMap.end(); I != E; ++I) {
1187 assert(I->second.getNode() && "Null node in scalarmap!");
1188 AssertNodeInGraph(I->second.getNode());
1189 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00001190 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001191 "Global points to node, but node isn't global?");
1192 AssertNodeContainsGlobal(I->second.getNode(), GV);
1193 }
1194 }
1195 AssertCallNodesInGraph();
1196 AssertAuxCallNodesInGraph();
1197}