blob: 80586de2f141a8911c0fc34afa0cd5d5111c1a52 [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 Lattnerbb2a28f2002-03-26 22:39:06 +000027//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000028// DSNode Implementation
29//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000030
Chris Lattner72d29a42003-02-11 23:11:51 +000031DSNode::DSNode(unsigned NT, const Type *T, DSGraph *G)
32 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(NT) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000033 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000034 if (T) mergeTypeInfo(T, 0);
Chris Lattner72d29a42003-02-11 23:11:51 +000035 G->getNodes().push_back(this);
Chris Lattnerc68c31b2002-07-10 22:38:08 +000036}
37
Chris Lattner0d9bab82002-07-18 00:12:30 +000038// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner72d29a42003-02-11 23:11:51 +000039DSNode::DSNode(const DSNode &N, DSGraph *G)
40 : NumReferrers(0), Size(N.Size), ParentGraph(G), Ty(N.Ty),
41 Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
42 G->getNodes().push_back(this);
Chris Lattner0d9bab82002-07-18 00:12:30 +000043}
44
Chris Lattner72d29a42003-02-11 23:11:51 +000045void DSNode::assertOK() const {
46 assert((Ty != Type::VoidTy ||
47 Ty == Type::VoidTy && (Size == 0 ||
48 (NodeType & DSNode::Array))) &&
49 "Node not OK!");
50}
51
52/// forwardNode - Mark this node as being obsolete, and all references to it
53/// should be forwarded to the specified node and offset.
54///
55void DSNode::forwardNode(DSNode *To, unsigned Offset) {
56 assert(this != To && "Cannot forward a node to itself!");
57 assert(ForwardNH.isNull() && "Already forwarding from this node!");
58 if (To->Size <= 1) Offset = 0;
59 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
60 "Forwarded offset is wrong!");
61 ForwardNH.setNode(To);
62 ForwardNH.setOffset(Offset);
63 NodeType = DEAD;
64 Size = 0;
65 Ty = Type::VoidTy;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000066}
67
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000068// addGlobal - Add an entry for a global value to the Globals list. This also
69// marks the node with the 'G' flag if it does not already have it.
70//
71void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000072 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000073 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000074 std::lower_bound(Globals.begin(), Globals.end(), GV);
75
76 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000077 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000078 Globals.insert(I, GV);
79 NodeType |= GlobalNode;
80 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000081}
82
Chris Lattner8f0a16e2002-10-31 05:45:02 +000083/// foldNodeCompletely - If we determine that this node has some funny
84/// behavior happening to it that we cannot represent, we fold it down to a
85/// single, completely pessimistic, node. This node is represented as a
86/// single byte with a single TypeEntry of "void".
87///
88void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +000089 assert(!hasNoReferrers() &&
90 "Why would we collapse a node with no referrers?");
91 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +000092
Chris Lattner08db7192002-11-06 06:20:27 +000093 ++NumFolds;
94
Chris Lattner72d29a42003-02-11 23:11:51 +000095 // Create the node we are going to forward to...
96 DSNode *DestNode = new DSNode(NodeType|DSNode::Array, 0, ParentGraph);
97 DestNode->Ty = Type::VoidTy;
98 DestNode->Size = 1;
99 DestNode->Globals.swap(Globals);
Chris Lattner08db7192002-11-06 06:20:27 +0000100
Chris Lattner72d29a42003-02-11 23:11:51 +0000101 // Start forwarding to the destination node...
102 forwardNode(DestNode, 0);
103
104 if (Links.size()) {
105 DestNode->Links.push_back(Links[0]);
106 DSNodeHandle NH(DestNode);
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000107
Chris Lattner72d29a42003-02-11 23:11:51 +0000108 // If we have links, merge all of our outgoing links together...
109 for (unsigned i = Links.size()-1; i != 0; --i)
110 NH.getNode()->Links[0].mergeWith(Links[i]);
111 Links.clear();
112 } else {
113 DestNode->Links.resize(1);
114 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000115}
Chris Lattner076c1f92002-11-07 06:31:54 +0000116
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000117/// isNodeCompletelyFolded - Return true if this node has been completely
118/// folded down to something that can never be expanded, effectively losing
119/// all of the field sensitivity that may be present in the node.
120///
121bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000122 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000123}
124
125
Chris Lattner08db7192002-11-06 06:20:27 +0000126/// mergeTypeInfo - This method merges the specified type into the current node
127/// at the specified offset. This may update the current node's type record if
128/// this gives more information to the node, it may do nothing to the node if
129/// this information is already known, or it may merge the node completely (and
130/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000131///
Chris Lattner08db7192002-11-06 06:20:27 +0000132/// This method returns true if the node is completely folded, otherwise false.
133///
134bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
135 // Check to make sure the Size member is up-to-date. Size can be one of the
136 // following:
137 // Size = 0, Ty = Void: Nothing is known about this node.
138 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
139 // Size = 1, Ty = Void, Array = 1: The node is collapsed
140 // Otherwise, sizeof(Ty) = Size
141 //
Chris Lattner18552922002-11-18 21:44:46 +0000142 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
143 (Size == 0 && !Ty->isSized() && !isArray()) ||
144 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
145 (Size == 0 && !Ty->isSized() && !isArray()) ||
146 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000147 "Size member of DSNode doesn't match the type structure!");
148 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000149
Chris Lattner18552922002-11-18 21:44:46 +0000150 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000151 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000152
Chris Lattner08db7192002-11-06 06:20:27 +0000153 // Return true immediately if the node is completely folded.
154 if (isNodeCompletelyFolded()) return true;
155
Chris Lattner23f83dc2002-11-08 22:49:57 +0000156 // If this is an array type, eliminate the outside arrays because they won't
157 // be used anyway. This greatly reduces the size of large static arrays used
158 // as global variables, for example.
159 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000160 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000161 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
162 // FIXME: we might want to keep small arrays, but must be careful about
163 // things like: [2 x [10000 x int*]]
164 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000165 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000166 }
167
Chris Lattner08db7192002-11-06 06:20:27 +0000168 // Figure out how big the new type we're merging in is...
169 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
170
171 // Otherwise check to see if we can fold this type into the current node. If
172 // we can't, we fold the node completely, if we can, we potentially update our
173 // internal state.
174 //
Chris Lattner18552922002-11-18 21:44:46 +0000175 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000176 // If this is the first type that this node has seen, just accept it without
177 // question....
178 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000179 assert(!isArray() && "This shouldn't happen!");
180 Ty = NewTy;
181 NodeType &= ~Array;
182 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000183 Size = NewTySize;
184
185 // Calculate the number of outgoing links from this node.
186 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
187 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000188 }
Chris Lattner08db7192002-11-06 06:20:27 +0000189
190 // Handle node expansion case here...
191 if (Offset+NewTySize > Size) {
192 // It is illegal to grow this node if we have treated it as an array of
193 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000194 if (isArray()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000195 foldNodeCompletely();
196 return true;
197 }
198
199 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000200 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
201 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000202 foldNodeCompletely();
203 return true;
204 }
205
206 // Okay, the situation is nice and simple, we are trying to merge a type in
207 // at offset 0 that is bigger than our current type. Implement this by
208 // switching to the new type and then merge in the smaller one, which should
209 // hit the other code path here. If the other code path decides it's not
210 // ok, it will collapse the node as appropriate.
211 //
Chris Lattner18552922002-11-18 21:44:46 +0000212 const Type *OldTy = Ty;
213 Ty = NewTy;
214 NodeType &= ~Array;
215 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000216 Size = NewTySize;
217
218 // Must grow links to be the appropriate size...
219 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
220
221 // Merge in the old type now... which is guaranteed to be smaller than the
222 // "current" type.
223 return mergeTypeInfo(OldTy, 0);
224 }
225
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000226 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000227 "Cannot merge something into a part of our type that doesn't exist!");
228
Chris Lattner18552922002-11-18 21:44:46 +0000229 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000230 // type that starts at offset Offset.
231 //
232 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000233 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000234 while (O < Offset) {
235 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
236
237 switch (SubType->getPrimitiveID()) {
238 case Type::StructTyID: {
239 const StructType *STy = cast<StructType>(SubType);
240 const StructLayout &SL = *TD.getStructLayout(STy);
241
242 unsigned i = 0, e = SL.MemberOffsets.size();
243 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
244 /* empty */;
245
246 // The offset we are looking for must be in the i'th element...
247 SubType = STy->getElementTypes()[i];
248 O += SL.MemberOffsets[i];
249 break;
250 }
251 case Type::ArrayTyID: {
252 SubType = cast<ArrayType>(SubType)->getElementType();
253 unsigned ElSize = TD.getTypeSize(SubType);
254 unsigned Remainder = (Offset-O) % ElSize;
255 O = Offset-Remainder;
256 break;
257 }
258 default:
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000259 foldNodeCompletely();
260 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000261 }
262 }
263
264 assert(O == Offset && "Could not achieve the correct offset!");
265
266 // If we found our type exactly, early exit
267 if (SubType == NewTy) return false;
268
269 // Okay, so we found the leader type at the offset requested. Search the list
270 // of types that starts at this offset. If SubType is currently an array or
271 // structure, the type desired may actually be the first element of the
272 // composite type...
273 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000274 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner18552922002-11-18 21:44:46 +0000275 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000276 while (SubType != NewTy) {
277 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000278 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000279 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000280 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000281 case Type::StructTyID: {
282 const StructType *STy = cast<StructType>(SubType);
283 const StructLayout &SL = *TD.getStructLayout(STy);
284 if (SL.MemberOffsets.size() > 1)
285 NextPadSize = SL.MemberOffsets[1];
286 else
287 NextPadSize = SubTypeSize;
288 NextSubType = STy->getElementTypes()[0];
289 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000290 break;
Chris Lattner18552922002-11-18 21:44:46 +0000291 }
Chris Lattner08db7192002-11-06 06:20:27 +0000292 case Type::ArrayTyID:
293 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000294 NextSubTypeSize = TD.getTypeSize(NextSubType);
295 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000296 break;
297 default: ;
298 // fall out
299 }
300
301 if (NextSubType == 0)
302 break; // In the default case, break out of the loop
303
Chris Lattner18552922002-11-18 21:44:46 +0000304 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000305 break; // Don't allow shrinking to a smaller type than NewTySize
306 SubType = NextSubType;
307 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000308 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000309 }
310
311 // If we found the type exactly, return it...
312 if (SubType == NewTy)
313 return false;
314
315 // Check to see if we have a compatible, but different type...
316 if (NewTySize == SubTypeSize) {
317 // Check to see if this type is obviously convertable... int -> uint f.e.
318 if (NewTy->isLosslesslyConvertableTo(SubType))
319 return false;
320
321 // Check to see if we have a pointer & integer mismatch going on here,
322 // loading a pointer as a long, for example.
323 //
324 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
325 NewTy->isInteger() && isa<PointerType>(SubType))
326 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000327 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
328 // We are accessing the field, plus some structure padding. Ignore the
329 // structure padding.
330 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000331 }
332
333
Chris Lattner18552922002-11-18 21:44:46 +0000334 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000335 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
336 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000337
338 foldNodeCompletely();
339 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000340}
341
Chris Lattner08db7192002-11-06 06:20:27 +0000342
343
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000344// addEdgeTo - Add an edge from the current node to the specified node. This
345// can cause merging of nodes in the graph.
346//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000347void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000348 if (NH.getNode() == 0) return; // Nothing to do
349
Chris Lattner08db7192002-11-06 06:20:27 +0000350 DSNodeHandle &ExistingEdge = getLink(Offset);
351 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000352 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000353 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000354 } else { // No merging to perform...
355 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000356 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000357}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000358
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000359
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000360// MergeSortedVectors - Efficiently merge a vector into another vector where
361// duplicates are not allowed and both are sorted. This assumes that 'T's are
362// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000363//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000364static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
365 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000366 // By far, the most common cases will be the simple ones. In these cases,
367 // avoid having to allocate a temporary vector...
368 //
369 if (Src.empty()) { // Nothing to merge in...
370 return;
371 } else if (Dest.empty()) { // Just copy the result in...
372 Dest = Src;
373 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000374 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000375 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000376 std::lower_bound(Dest.begin(), Dest.end(), V);
377 if (I == Dest.end() || *I != Src[0]) // If not already contained...
378 Dest.insert(I, Src[0]);
379 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000380 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000381 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000382 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000383 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
384 if (I == Dest.end() || *I != Tmp) // If not already contained...
385 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000386
387 } else {
388 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000389 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000390
391 // Make space for all of the type entries now...
392 Dest.resize(Dest.size()+Src.size());
393
394 // Merge the two sorted ranges together... into Dest.
395 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
396
397 // Now erase any duplicate entries that may have accumulated into the
398 // vectors (because they were in both of the input sets)
399 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
400 }
401}
402
403
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000404// MergeNodes() - Helper function for DSNode::mergeWith().
405// This function does the hard work of merging two nodes, CurNodeH
406// and NH after filtering out trivial cases and making sure that
407// CurNodeH.offset >= NH.offset.
408//
409// ***WARNING***
410// Since merging may cause either node to go away, we must always
411// use the node-handles to refer to the nodes. These node handles are
412// automatically updated during merging, so will always provide access
413// to the correct node after a merge.
414//
415void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
416 assert(CurNodeH.getOffset() >= NH.getOffset() &&
417 "This should have been enforced in the caller.");
418
419 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
420 // respect to NH.Offset) is now zero. NOffset is the distance from the base
421 // of our object that N starts from.
422 //
423 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
424 unsigned NSize = NH.getNode()->getSize();
425
426 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000427 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000428 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000429 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
430
431 // If we are merging a node with a completely folded node, then both nodes are
432 // now completely folded.
433 //
434 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
435 if (!NH.getNode()->isNodeCompletelyFolded()) {
436 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000437 assert(NH.getNode() && NH.getOffset() == 0 &&
438 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000439 NOffset = NH.getOffset();
440 NSize = NH.getNode()->getSize();
441 assert(NOffset == 0 && NSize == 1);
442 }
443 } else if (NH.getNode()->isNodeCompletelyFolded()) {
444 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000445 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
446 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000447 NOffset = NH.getOffset();
448 NSize = NH.getNode()->getSize();
449 assert(NOffset == 0 && NSize == 1);
450 }
451
Chris Lattner72d29a42003-02-11 23:11:51 +0000452 DSNode *N = NH.getNode();
453 if (CurNodeH.getNode() == N || N == 0) return;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000454 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
455
Chris Lattner72d29a42003-02-11 23:11:51 +0000456 // Start forwarding to the new node!
457 CurNodeH.getNode()->NodeType |= N->NodeType;
458 N->forwardNode(CurNodeH.getNode(), NOffset);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000459 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
460
Chris Lattner72d29a42003-02-11 23:11:51 +0000461 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
462 //
463 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
464 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000465 if (Link.getNode()) {
466 // Compute the offset into the current node at which to
467 // merge this link. In the common case, this is a linear
468 // relation to the offset in the original node (with
469 // wrapping), but if the current node gets collapsed due to
470 // recursive merging, we must make sure to merge in all remaining
471 // links at offset zero.
472 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000473 DSNode *CN = CurNodeH.getNode();
474 if (CN->Size != 1)
475 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
476 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000477 }
478 }
479
480 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000481 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000482
483 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000484 if (!N->Globals.empty()) {
485 MergeSortedVectors(CurNodeH.getNode()->Globals, N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000486
487 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000488 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000489 }
490}
491
492
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000493// mergeWith - Merge this node and the specified node, moving all links to and
494// from the argument node into the current node, deleting the node argument.
495// Offset indicates what offset the specified node is to be merged into the
496// current node.
497//
498// The specified node may be a null pointer (in which case, nothing happens).
499//
500void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
501 DSNode *N = NH.getNode();
502 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000503 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000504
Chris Lattner679e8e12002-11-08 21:27:12 +0000505 assert((N->NodeType & DSNode::DEAD) == 0);
506 assert((NodeType & DSNode::DEAD) == 0);
507 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
508
Chris Lattner02606632002-11-04 06:48:26 +0000509 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000510 // We cannot merge two pieces of the same node together, collapse the node
511 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000512 DEBUG(std::cerr << "Attempting to merge two chunks of"
513 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000514 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000515 return;
516 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000517
Chris Lattner5190ce82002-11-12 07:20:45 +0000518 // If both nodes are not at offset 0, make sure that we are merging the node
519 // at an later offset into the node with the zero offset.
520 //
521 if (Offset < NH.getOffset()) {
522 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
523 return;
524 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
525 // If the offsets are the same, merge the smaller node into the bigger node
526 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
527 return;
528 }
529
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000530 // Ok, now we can merge the two nodes. Use a static helper that works with
531 // two node handles, since "this" may get merged away at intermediate steps.
532 DSNodeHandle CurNodeH(this, Offset);
533 DSNodeHandle NHCopy(NH);
534 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000535}
536
Chris Lattner9de906c2002-10-20 22:11:44 +0000537//===----------------------------------------------------------------------===//
538// DSCallSite Implementation
539//===----------------------------------------------------------------------===//
540
Vikram S. Adve26b98262002-10-20 21:41:02 +0000541// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000542Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000543 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000544}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000545
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000546
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000547//===----------------------------------------------------------------------===//
548// DSGraph Implementation
549//===----------------------------------------------------------------------===//
550
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000551DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000552 PrintAuxCalls = false;
Chris Lattner41c04f72003-02-01 04:52:08 +0000553 hash_map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000554 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000555}
556
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000557DSGraph::DSGraph(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000558 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000559 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000560 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000561 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000562}
563
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000564DSGraph::~DSGraph() {
565 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000566 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000567 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000568 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000569
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000570 // Drop all intra-node references, so that assertions don't fail...
571 std::for_each(Nodes.begin(), Nodes.end(),
572 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000573
574 // Delete all of the nodes themselves...
575 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
576}
577
Chris Lattner0d9bab82002-07-18 00:12:30 +0000578// dump - Allow inspection of graph in a debugger.
579void DSGraph::dump() const { print(std::cerr); }
580
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000581
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000582/// remapLinks - Change all of the Links in the current node according to the
583/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000584///
Chris Lattner41c04f72003-02-01 04:52:08 +0000585void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000586 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
587 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
588 Links[i].setNode(H.getNode());
589 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
590 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000591}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000592
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000593
Chris Lattner0d9bab82002-07-18 00:12:30 +0000594// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000595// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000596// filled into the OldValMap member. If StripAllocas is set to true, Alloca
597// markers are removed from the graph, as the graph is being cloned into a
598// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000599//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000600DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000601 hash_map<Value*, DSNodeHandle> &OldValMap,
602 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000603 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000604 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000605 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000606
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000607 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000608
609 // Duplicate all of the nodes, populating the node map...
610 Nodes.reserve(FN+G.Nodes.size());
Chris Lattner1e883692003-02-03 20:08:51 +0000611
612 // Remove alloca or mod/ref bits as specified...
613 unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
614 | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
615 clearBits |= DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000616 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000617 DSNode *Old = G.Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +0000618 DSNode *New = new DSNode(*Old, this);
Chris Lattner1e883692003-02-03 20:08:51 +0000619 New->NodeType &= ~clearBits;
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000620 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000621 }
622
Chris Lattner18552922002-11-18 21:44:46 +0000623#ifndef NDEBUG
624 Timer::addPeakMemoryMeasurement();
625#endif
626
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000627 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000628 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000629 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000630
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000631 // Copy the scalar map... merging all of the global nodes...
Chris Lattner41c04f72003-02-01 04:52:08 +0000632 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000633 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000634 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000635 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000636 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattner72d29a42003-02-11 23:11:51 +0000637 H.setNode(MappedNode.getNode());
Chris Lattnercf15db32002-10-17 20:09:52 +0000638
639 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattner41c04f72003-02-01 04:52:08 +0000640 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000641 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000642 GVI->second.mergeWith(H);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000643 else
Chris Lattnerc875f022002-11-03 21:27:48 +0000644 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000645 }
646 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000647
Chris Lattner679e8e12002-11-08 21:27:12 +0000648 if (!(CloneFlags & DontCloneCallNodes)) {
649 // Copy the function calls list...
650 unsigned FC = FunctionCalls.size(); // FirstCall
651 FunctionCalls.reserve(FC+G.FunctionCalls.size());
652 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
653 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000654 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000655
Chris Lattneracf491f2002-11-08 22:27:09 +0000656 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000657 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000658 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000659 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
660 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
661 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
662 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000663
Chris Lattner0d9bab82002-07-18 00:12:30 +0000664 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000665 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
666 return DSNodeHandle(MappedRet.getNode(),
667 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000668}
669
Chris Lattner076c1f92002-11-07 06:31:54 +0000670/// mergeInGraph - The method is used for merging graphs together. If the
671/// argument graph is not *this, it makes a clone of the specified graph, then
672/// merges the nodes specified in the call site with the formal arguments in the
673/// graph.
674///
675void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000676 unsigned CloneFlags) {
Chris Lattner41c04f72003-02-01 04:52:08 +0000677 hash_map<Value*, DSNodeHandle> OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000678 DSNodeHandle RetVal;
Chris Lattner41c04f72003-02-01 04:52:08 +0000679 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000680
681 // If this is not a recursive call, clone the graph into this graph...
682 if (&Graph != this) {
683 // Clone the callee's graph into the current graph, keeping
684 // track of where scalars in the old graph _used_ to point,
685 // and of the new nodes matching nodes of the old graph.
Chris Lattner41c04f72003-02-01 04:52:08 +0000686 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000687
688 // The clone call may invalidate any of the vectors in the data
689 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000690 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000691 ScalarMap = &OldValMap;
692 } else {
693 RetVal = getRetNode();
694 ScalarMap = &getScalarMap();
695 }
696
697 // Merge the return value with the return value of the context...
698 RetVal.mergeWith(CS.getRetVal());
699
700 // Resolve all of the function arguments...
701 Function &F = Graph.getFunction();
702 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000703
Chris Lattner076c1f92002-11-07 06:31:54 +0000704 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
705 // Advance the argument iterator to the first pointer argument...
Chris Lattner5d274582003-02-06 00:15:08 +0000706 while (AI != F.aend() && !isPointerType(AI->getType())) {
Chris Lattner076c1f92002-11-07 06:31:54 +0000707 ++AI;
708#ifndef NDEBUG
709 if (AI == F.aend())
710 std::cerr << "Bad call to Function: " << F.getName() << "\n";
711#endif
Chris Lattner076c1f92002-11-07 06:31:54 +0000712 }
Chris Lattner5d274582003-02-06 00:15:08 +0000713 if (AI == F.aend()) break;
Chris Lattner076c1f92002-11-07 06:31:54 +0000714
715 // Add the link from the argument scalar to the provided value
Chris Lattner72d29a42003-02-11 23:11:51 +0000716 assert(ScalarMap->count(AI) && "Argument not in scalar map?");
Chris Lattner076c1f92002-11-07 06:31:54 +0000717 DSNodeHandle &NH = (*ScalarMap)[AI];
718 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
719 NH.mergeWith(CS.getPtrArg(i));
720 }
721}
722
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000723
Chris Lattner0d9bab82002-07-18 00:12:30 +0000724// markIncompleteNodes - Mark the specified node as having contents that are not
725// known with the current analysis we have performed. Because a node makes all
726// of the nodes it can reach imcomplete if the node itself is incomplete, we
727// must recursively traverse the data structure graph, marking all reachable
728// nodes as incomplete.
729//
730static void markIncompleteNode(DSNode *N) {
731 // Stop recursion if no node, or if node already marked...
732 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
733
734 // Actually mark the node
735 N->NodeType |= DSNode::Incomplete;
736
737 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000738 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
739 if (DSNode *DSN = N->getLink(i).getNode())
740 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000741}
742
Chris Lattnere71ffc22002-11-11 03:36:55 +0000743static void markIncomplete(DSCallSite &Call) {
744 // Then the return value is certainly incomplete!
745 markIncompleteNode(Call.getRetVal().getNode());
746
747 // All objects pointed to by function arguments are incomplete!
748 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
749 markIncompleteNode(Call.getPtrArg(i).getNode());
750}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000751
752// markIncompleteNodes - Traverse the graph, identifying nodes that may be
753// modified by other functions that have not been resolved yet. This marks
754// nodes that are reachable through three sources of "unknownness":
755//
756// Global Variables, Function Calls, and Incoming Arguments
757//
758// For any node that may have unknown components (because something outside the
759// scope of current analysis may have modified it), the 'Incomplete' flag is
760// added to the NodeType.
761//
Chris Lattner394471f2003-01-23 22:05:33 +0000762void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000763 // Mark any incoming arguments as incomplete...
Chris Lattnere77f1452003-02-08 23:08:02 +0000764 if ((Flags & DSGraph::MarkFormalArgs) && Func && Func->getName() != "main")
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000765 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000766 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
767 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000768
769 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000770 if (!shouldPrintAuxCalls())
771 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
772 markIncomplete(FunctionCalls[i]);
773 else
774 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
775 markIncomplete(AuxFunctionCalls[i]);
776
Chris Lattner0d9bab82002-07-18 00:12:30 +0000777
Chris Lattner93d7a212003-02-09 18:41:49 +0000778 // Mark all global nodes as incomplete...
779 if ((Flags & DSGraph::IgnoreGlobals) == 0)
780 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
781 if (Nodes[i]->NodeType & DSNode::GlobalNode)
782 markIncompleteNode(Nodes[i]);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000783}
784
Chris Lattneraa8146f2002-11-10 06:59:55 +0000785static inline void killIfUselessEdge(DSNodeHandle &Edge) {
786 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +0000787 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattneraa8146f2002-11-10 06:59:55 +0000788 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
Chris Lattner18552922002-11-18 21:44:46 +0000789 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000790 Edge.setNode(0); // Kill the edge!
791}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000792
Chris Lattneraa8146f2002-11-10 06:59:55 +0000793static inline bool nodeContainsExternalFunction(const DSNode *N) {
794 const std::vector<GlobalValue*> &Globals = N->getGlobals();
795 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
796 if (Globals[i]->isExternal())
797 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000798 return false;
799}
800
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000801static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000802 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000803 // Remove trivially identical function calls
804 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000805 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
806
807 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +0000808 DSNode *LastCalleeNode = 0;
809 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000810 unsigned NumDuplicateCalls = 0;
811 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000812 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000813 DSCallSite &CS = Calls[i];
814
Chris Lattnere4258442002-11-11 21:35:38 +0000815 // If the Callee is a useless edge, this must be an unreachable call site,
816 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +0000817 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattner923fc052003-02-05 21:59:58 +0000818 CS.getCalleeNode()->NodeType == 0) { // No useful info?
819 std::cerr << "WARNING: Useless call site found??\n";
Chris Lattnere4258442002-11-11 21:35:38 +0000820 CS.swap(Calls.back());
821 Calls.pop_back();
822 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000823 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000824 // If the return value or any arguments point to a void node with no
825 // information at all in it, and the call node is the only node to point
826 // to it, remove the edge to the node (killing the node).
827 //
828 killIfUselessEdge(CS.getRetVal());
829 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
830 killIfUselessEdge(CS.getPtrArg(a));
831
832 // If this call site calls the same function as the last call site, and if
833 // the function pointer contains an external function, this node will
834 // never be resolved. Merge the arguments of the call node because no
835 // information will be lost.
836 //
Chris Lattner923fc052003-02-05 21:59:58 +0000837 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
838 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
Chris Lattnere4258442002-11-11 21:35:38 +0000839 ++NumDuplicateCalls;
840 if (NumDuplicateCalls == 1) {
Chris Lattner923fc052003-02-05 21:59:58 +0000841 if (LastCalleeNode)
842 LastCalleeContainsExternalFunction =
843 nodeContainsExternalFunction(LastCalleeNode);
844 else
845 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +0000846 }
847
848 if (LastCalleeContainsExternalFunction ||
849 // This should be more than enough context sensitivity!
850 // FIXME: Evaluate how many times this is tripped!
851 NumDuplicateCalls > 20) {
852 DSCallSite &OCS = Calls[i-1];
853 OCS.mergeWith(CS);
854
855 // The node will now be eliminated as a duplicate!
856 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
857 CS = OCS;
858 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
859 OCS = CS;
860 }
861 } else {
Chris Lattner923fc052003-02-05 21:59:58 +0000862 if (CS.isDirectCall()) {
863 LastCalleeFunc = CS.getCalleeFunc();
864 LastCalleeNode = 0;
865 } else {
866 LastCalleeNode = CS.getCalleeNode();
867 LastCalleeFunc = 0;
868 }
Chris Lattnere4258442002-11-11 21:35:38 +0000869 NumDuplicateCalls = 0;
870 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000871 }
872 }
873
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000874 Calls.erase(std::unique(Calls.begin(), Calls.end()),
875 Calls.end());
876
Chris Lattner33312f72002-11-08 01:21:07 +0000877 // Track the number of call nodes merged away...
878 NumCallNodesMerged += NumFns-Calls.size();
879
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000880 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000881 std::cerr << "Merged " << (NumFns-Calls.size())
882 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000883}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000884
Chris Lattneraa8146f2002-11-10 06:59:55 +0000885
Chris Lattnere2219762002-07-18 18:22:40 +0000886// removeTriviallyDeadNodes - After the graph has been constructed, this method
887// removes all unreachable nodes that are created because they got merged with
888// other nodes in the graph. These nodes will all be trivially unreachable, so
889// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000890//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000891void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000892 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000893 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
894
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000895 for (unsigned i = 0; i != Nodes.size(); ++i) {
896 DSNode *Node = Nodes[i];
897 if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
Chris Lattner923fc052003-02-05 21:59:58 +0000898 DSNode::DEAD))) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000899 // This is a useless node if it has no mod/ref info (checked above),
900 // outgoing edges (which it cannot, as it is not modified in this
901 // context), and it has no incoming edges. If it is a global node it may
902 // have all of these properties and still have incoming edges, due to the
903 // scalar map, so we check those now.
904 //
Chris Lattner72d29a42003-02-11 23:11:51 +0000905 if (Node->getNumReferrers() == Node->getGlobals().size()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000906 std::vector<GlobalValue*> &Globals = Node->getGlobals();
Chris Lattner72d29a42003-02-11 23:11:51 +0000907
908 // Loop through and make sure all of the globals are referring directly
909 // to the node...
910 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
911 DSNode *N = ScalarMap.find(Globals[j])->second.getNode();
912 assert(N == Node && "ScalarMap doesn't match globals list!");
913 }
914
915 // Make sure numreferrers still agrees, if so, the node is truely dead.
916 if (Node->getNumReferrers() == Globals.size()) {
917 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
918 ScalarMap.erase(Globals[j]);
919
920 Globals.clear();
921 assert(Node->hasNoReferrers() && "Shouldn't have refs now!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000922
Chris Lattner72d29a42003-02-11 23:11:51 +0000923 Node->NodeType = DSNode::DEAD;
924 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000925 }
926 }
927
Chris Lattner2609c072003-02-10 18:18:18 +0000928 if ((Node->NodeType & ~DSNode::DEAD) == 0 && Node->hasNoReferrers()) {
929 // This node is dead!
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000930 delete Node; // Free memory...
Chris Lattnera954b5e2003-02-10 18:47:23 +0000931 Nodes[i--] = Nodes.back();
932 Nodes.pop_back(); // Remove from node list...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000933 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000934 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000935}
936
937
Chris Lattner5c7380e2003-01-29 21:10:20 +0000938/// markReachableNodes - This method recursively traverses the specified
939/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
940/// to the set, which allows it to only traverse visited nodes once.
941///
Chris Lattner41c04f72003-02-01 04:52:08 +0000942void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000943 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +0000944 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner41c04f72003-02-01 04:52:08 +0000945 if (ReachableNodes.count(this)) return; // Already marked reachable
946 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +0000947
Chris Lattner5c7380e2003-01-29 21:10:20 +0000948 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
949 getLink(i).getNode()->markReachableNodes(ReachableNodes);
950}
951
Chris Lattner41c04f72003-02-01 04:52:08 +0000952void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000953 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +0000954 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +0000955
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000956 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
957 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +0000958}
959
Chris Lattnera1220af2003-02-01 06:17:02 +0000960// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
961// looking for a node that is marked alive. If an alive node is found, return
962// true, otherwise return false. If an alive node is reachable, this node is
963// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000964//
Chris Lattnera1220af2003-02-01 06:17:02 +0000965static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
966 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000967 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +0000968 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000969
Chris Lattneraa8146f2002-11-10 06:59:55 +0000970 // If we know that this node is alive, return so!
971 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000972
Chris Lattneraa8146f2002-11-10 06:59:55 +0000973 // Otherwise, we don't think the node is alive yet, check for infinite
974 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +0000975 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +0000976 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000977
Chris Lattner08db7192002-11-06 06:20:27 +0000978 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +0000979 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
980 N->markReachableNodes(Alive);
981 return true;
982 }
983 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000984}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000985
Chris Lattnera1220af2003-02-01 06:17:02 +0000986// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
987// alive nodes.
988//
Chris Lattner41c04f72003-02-01 04:52:08 +0000989static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
990 hash_set<DSNode*> &Visited) {
Chris Lattner923fc052003-02-05 21:59:58 +0000991 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited))
992 return true;
993 if (CS.isIndirectCall() &&
994 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000995 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000996 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
997 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000998 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000999 return false;
1000}
1001
Chris Lattnere2219762002-07-18 18:22:40 +00001002// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1003// subgraphs that are unreachable. This often occurs because the data
1004// structure doesn't "escape" into it's caller, and thus should be eliminated
1005// from the caller's graph entirely. This is only appropriate to use when
1006// inlining graphs.
1007//
Chris Lattner394471f2003-01-23 22:05:33 +00001008void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001009 // Reduce the amount of work we have to do... remove dummy nodes left over by
1010 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001011 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001012
Chris Lattnere2219762002-07-18 18:22:40 +00001013 // FIXME: Merge nontrivially identical call nodes...
1014
1015 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001016 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001017 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001018
Chris Lattneraa8146f2002-11-10 06:59:55 +00001019 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner41c04f72003-02-01 04:52:08 +00001020 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001021 E = ScalarMap.end(); I != E; ++I)
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001022 if (!isa<GlobalValue>(I->first))
Chris Lattner5c7380e2003-01-29 21:10:20 +00001023 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001024 else { // Keep track of global nodes
Chris Lattner394471f2003-01-23 22:05:33 +00001025 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001026 assert(I->second.getNode() && "Null global node?");
1027 }
Chris Lattnere2219762002-07-18 18:22:40 +00001028
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001029 // The return value is alive as well...
Chris Lattner5c7380e2003-01-29 21:10:20 +00001030 RetNode.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001031
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001032 // Mark any nodes reachable by primary calls as alive...
1033 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1034 FunctionCalls[i].markReachableNodes(Alive);
1035
1036 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001037 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001038 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1039 do {
1040 Visited.clear();
1041 // If any global nodes points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001042 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001043 // unreachable globals in the list.
1044 //
1045 Iterate = false;
1046 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1047 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1048 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1049 GlobalNodes.pop_back(); // Erase efficiently
1050 Iterate = true;
1051 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001052
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001053 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1054 if (!AuxFCallsAlive[i] &&
1055 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1056 AuxFunctionCalls[i].markReachableNodes(Alive);
1057 AuxFCallsAlive[i] = true;
1058 Iterate = true;
1059 }
1060 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001061
1062 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001063 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001064 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1065 if (AuxFCallsAlive[i])
1066 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001067 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
Chris Lattnerf52ade92003-02-04 00:03:57 +00001068 assert(GlobalsGraph && "No globals graph available??");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001069 // Move the unreachable call nodes to the globals graph...
1070 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1071 AuxFunctionCalls.begin()+CurIdx,
1072 AuxFunctionCalls.end());
1073 }
1074 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001075 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1076 AuxFunctionCalls.end());
1077
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001078 // At this point, any nodes which are visited, but not alive, are nodes which
1079 // should be moved to the globals graph. Loop over all nodes, eliminating
1080 // completely unreachable nodes, and moving visited nodes to the globals graph
1081 //
Chris Lattner72d29a42003-02-11 23:11:51 +00001082 std::vector<DSNode*> DeadNodes;
1083 DeadNodes.reserve(Nodes.size());
Chris Lattnere2219762002-07-18 18:22:40 +00001084 for (unsigned i = 0; i != Nodes.size(); ++i)
1085 if (!Alive.count(Nodes[i])) {
1086 DSNode *N = Nodes[i];
Chris Lattner72d29a42003-02-11 23:11:51 +00001087 Nodes[i--] = Nodes.back(); // move node to end of vector
1088 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001089 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1090 Visited.count(N)) { // Visited but not alive?
1091 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
Chris Lattner72d29a42003-02-11 23:11:51 +00001092 N->setParentGraph(GlobalsGraph);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001093 } else { // Otherwise, delete the node
1094 assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1095 (Flags & DSGraph::RemoveUnreachableGlobals))
1096 && "Killing a global?");
Chris Lattner72d29a42003-02-11 23:11:51 +00001097 //std::cerr << "[" << i+1 << "/" << DeadNodes.size()
1098 // << "] Node is dead: "; N->dump();
1099 DeadNodes.push_back(N);
1100 N->dropAllReferences();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001101 }
Chris Lattner72d29a42003-02-11 23:11:51 +00001102 } else {
1103 assert(Nodes[i]->getForwardNode() == 0 && "Alive forwarded node?");
Chris Lattnere2219762002-07-18 18:22:40 +00001104 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001105
1106 // Now that the nodes have either been deleted or moved to the globals graph,
1107 // loop over the scalarmap, updating the entries for globals...
1108 //
1109 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1110 // In this array we start the remapping, which can cause merging. Because
1111 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1112 // must always go through the ScalarMap (which contains DSNodeHandles [which
1113 // cannot be invalidated by merging]).
1114 //
1115 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1116 Value *G = GlobalNodes[i].first;
1117 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1118 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1119 assert(I->second.getNode() && "Global not pointing to anything?");
1120 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1121 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1122 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1123 "Global not pointing to anything?");
1124 ScalarMap.erase(I);
1125 }
1126
1127 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1128 // globals graph.
Chris Lattner72d29a42003-02-11 23:11:51 +00001129 if (!GlobalNodes.empty())
1130 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001131 } else {
1132 // If we are in the top-down pass, remove all unreachable globals from the
1133 // ScalarMap...
1134 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1135 ScalarMap.erase(GlobalNodes[i].first);
1136 }
1137
Chris Lattner72d29a42003-02-11 23:11:51 +00001138 // Loop over all of the dead nodes now, deleting them since their referrer
1139 // count is zero.
1140 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
1141 delete DeadNodes[i];
1142
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001143 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001144}
1145
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001146void DSGraph::AssertGraphOK() const {
Chris Lattner72d29a42003-02-11 23:11:51 +00001147 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1148 Nodes[i]->assertOK();
1149 return; // FIXME: remove
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001150 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1151 E = ScalarMap.end(); I != E; ++I) {
1152 assert(I->second.getNode() && "Null node in scalarmap!");
1153 AssertNodeInGraph(I->second.getNode());
1154 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1155 assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1156 "Global points to node, but node isn't global?");
1157 AssertNodeContainsGlobal(I->second.getNode(), GV);
1158 }
1159 }
1160 AssertCallNodesInGraph();
1161 AssertAuxCallNodesInGraph();
1162}