blob: 818ca3781fc2f1ba7f64dd302883c1d5064a8527 [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 Lattner08db7192002-11-06 06:20:27 +000031DSNode::DSNode(enum NodeTy NT, const Type *T)
32 : Ty(Type::VoidTy), Size(0), 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 Lattnerc68c31b2002-07-10 22:38:08 +000035}
36
Chris Lattner0d9bab82002-07-18 00:12:30 +000037// DSNode copy constructor... do not copy over the referrers list!
38DSNode::DSNode(const DSNode &N)
Chris Lattner08db7192002-11-06 06:20:27 +000039 : Links(N.Links), Globals(N.Globals), Ty(N.Ty), Size(N.Size),
40 NodeType(N.NodeType) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000041}
42
Chris Lattnerc68c31b2002-07-10 22:38:08 +000043void DSNode::removeReferrer(DSNodeHandle *H) {
44 // Search backwards, because we depopulate the list from the back for
45 // efficiency (because it's a vector).
Chris Lattnerb3416bc2003-02-01 04:01:21 +000046 std::vector<DSNodeHandle*>::reverse_iterator I =
Chris Lattnerc68c31b2002-07-10 22:38:08 +000047 std::find(Referrers.rbegin(), Referrers.rend(), H);
48 assert(I != Referrers.rend() && "Referrer not pointing to node!");
49 Referrers.erase(I.base()-1);
50}
51
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000052// addGlobal - Add an entry for a global value to the Globals list. This also
53// marks the node with the 'G' flag if it does not already have it.
54//
55void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000056 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000057 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +000058 std::lower_bound(Globals.begin(), Globals.end(), GV);
59
60 if (I == Globals.end() || *I != GV) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000061 //assert(GV->getType()->getElementType() == Ty);
Chris Lattner0d9bab82002-07-18 00:12:30 +000062 Globals.insert(I, GV);
63 NodeType |= GlobalNode;
64 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +000065}
66
Chris Lattner8f0a16e2002-10-31 05:45:02 +000067/// foldNodeCompletely - If we determine that this node has some funny
68/// behavior happening to it that we cannot represent, we fold it down to a
69/// single, completely pessimistic, node. This node is represented as a
70/// single byte with a single TypeEntry of "void".
71///
72void DSNode::foldNodeCompletely() {
Chris Lattner08db7192002-11-06 06:20:27 +000073 if (isNodeCompletelyFolded()) return;
Chris Lattner8f0a16e2002-10-31 05:45:02 +000074
Chris Lattner08db7192002-11-06 06:20:27 +000075 ++NumFolds;
76
77 // We are no longer typed at all...
Chris Lattner18552922002-11-18 21:44:46 +000078 Ty = Type::VoidTy;
79 NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +000080 Size = 1;
81
82 // Loop over all of our referrers, making them point to our zero bytes of
83 // space.
Chris Lattnerb3416bc2003-02-01 04:01:21 +000084 for (std::vector<DSNodeHandle*>::iterator I = Referrers.begin(),
85 E = Referrers.end(); I != E; ++I)
Chris Lattner8f0a16e2002-10-31 05:45:02 +000086 (*I)->setOffset(0);
87
Chris Lattner8f0a16e2002-10-31 05:45:02 +000088 // If we have links, merge all of our outgoing links together...
Chris Lattner08db7192002-11-06 06:20:27 +000089 for (unsigned i = 1, e = Links.size(); i < e; ++i)
90 Links[0].mergeWith(Links[i]);
91 Links.resize(1);
Chris Lattner8f0a16e2002-10-31 05:45:02 +000092}
Chris Lattner076c1f92002-11-07 06:31:54 +000093
Chris Lattner8f0a16e2002-10-31 05:45:02 +000094/// isNodeCompletelyFolded - Return true if this node has been completely
95/// folded down to something that can never be expanded, effectively losing
96/// all of the field sensitivity that may be present in the node.
97///
98bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +000099 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000100}
101
102
Chris Lattner08db7192002-11-06 06:20:27 +0000103/// mergeTypeInfo - This method merges the specified type into the current node
104/// at the specified offset. This may update the current node's type record if
105/// this gives more information to the node, it may do nothing to the node if
106/// this information is already known, or it may merge the node completely (and
107/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000108///
Chris Lattner08db7192002-11-06 06:20:27 +0000109/// This method returns true if the node is completely folded, otherwise false.
110///
111bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset) {
112 // Check to make sure the Size member is up-to-date. Size can be one of the
113 // following:
114 // Size = 0, Ty = Void: Nothing is known about this node.
115 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
116 // Size = 1, Ty = Void, Array = 1: The node is collapsed
117 // Otherwise, sizeof(Ty) = Size
118 //
Chris Lattner18552922002-11-18 21:44:46 +0000119 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
120 (Size == 0 && !Ty->isSized() && !isArray()) ||
121 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
122 (Size == 0 && !Ty->isSized() && !isArray()) ||
123 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000124 "Size member of DSNode doesn't match the type structure!");
125 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000126
Chris Lattner18552922002-11-18 21:44:46 +0000127 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000128 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000129
Chris Lattner08db7192002-11-06 06:20:27 +0000130 // Return true immediately if the node is completely folded.
131 if (isNodeCompletelyFolded()) return true;
132
Chris Lattner23f83dc2002-11-08 22:49:57 +0000133 // If this is an array type, eliminate the outside arrays because they won't
134 // be used anyway. This greatly reduces the size of large static arrays used
135 // as global variables, for example.
136 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000137 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000138 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
139 // FIXME: we might want to keep small arrays, but must be careful about
140 // things like: [2 x [10000 x int*]]
141 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000142 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000143 }
144
Chris Lattner08db7192002-11-06 06:20:27 +0000145 // Figure out how big the new type we're merging in is...
146 unsigned NewTySize = NewTy->isSized() ? TD.getTypeSize(NewTy) : 0;
147
148 // Otherwise check to see if we can fold this type into the current node. If
149 // we can't, we fold the node completely, if we can, we potentially update our
150 // internal state.
151 //
Chris Lattner18552922002-11-18 21:44:46 +0000152 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000153 // If this is the first type that this node has seen, just accept it without
154 // question....
155 assert(Offset == 0 && "Cannot have an offset into a void node!");
Chris Lattner18552922002-11-18 21:44:46 +0000156 assert(!isArray() && "This shouldn't happen!");
157 Ty = NewTy;
158 NodeType &= ~Array;
159 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000160 Size = NewTySize;
161
162 // Calculate the number of outgoing links from this node.
163 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
164 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000165 }
Chris Lattner08db7192002-11-06 06:20:27 +0000166
167 // Handle node expansion case here...
168 if (Offset+NewTySize > Size) {
169 // It is illegal to grow this node if we have treated it as an array of
170 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000171 if (isArray()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000172 foldNodeCompletely();
173 return true;
174 }
175
176 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner3c87b292002-11-07 01:54:56 +0000177 DEBUG(std::cerr << "UNIMP: Trying to merge a growth type into "
178 << "offset != 0: Collapsing!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000179 foldNodeCompletely();
180 return true;
181 }
182
183 // Okay, the situation is nice and simple, we are trying to merge a type in
184 // at offset 0 that is bigger than our current type. Implement this by
185 // switching to the new type and then merge in the smaller one, which should
186 // hit the other code path here. If the other code path decides it's not
187 // ok, it will collapse the node as appropriate.
188 //
Chris Lattner18552922002-11-18 21:44:46 +0000189 const Type *OldTy = Ty;
190 Ty = NewTy;
191 NodeType &= ~Array;
192 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000193 Size = NewTySize;
194
195 // Must grow links to be the appropriate size...
196 Links.resize((Size+DS::PointerSize-1) >> DS::PointerShift);
197
198 // Merge in the old type now... which is guaranteed to be smaller than the
199 // "current" type.
200 return mergeTypeInfo(OldTy, 0);
201 }
202
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000203 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000204 "Cannot merge something into a part of our type that doesn't exist!");
205
Chris Lattner18552922002-11-18 21:44:46 +0000206 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000207 // type that starts at offset Offset.
208 //
209 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000210 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000211 while (O < Offset) {
212 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
213
214 switch (SubType->getPrimitiveID()) {
215 case Type::StructTyID: {
216 const StructType *STy = cast<StructType>(SubType);
217 const StructLayout &SL = *TD.getStructLayout(STy);
218
219 unsigned i = 0, e = SL.MemberOffsets.size();
220 for (; i+1 < e && SL.MemberOffsets[i+1] <= Offset-O; ++i)
221 /* empty */;
222
223 // The offset we are looking for must be in the i'th element...
224 SubType = STy->getElementTypes()[i];
225 O += SL.MemberOffsets[i];
226 break;
227 }
228 case Type::ArrayTyID: {
229 SubType = cast<ArrayType>(SubType)->getElementType();
230 unsigned ElSize = TD.getTypeSize(SubType);
231 unsigned Remainder = (Offset-O) % ElSize;
232 O = Offset-Remainder;
233 break;
234 }
235 default:
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000236 foldNodeCompletely();
237 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000238 }
239 }
240
241 assert(O == Offset && "Could not achieve the correct offset!");
242
243 // If we found our type exactly, early exit
244 if (SubType == NewTy) return false;
245
246 // Okay, so we found the leader type at the offset requested. Search the list
247 // of types that starts at this offset. If SubType is currently an array or
248 // structure, the type desired may actually be the first element of the
249 // composite type...
250 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000251 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner18552922002-11-18 21:44:46 +0000252 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000253 while (SubType != NewTy) {
254 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000255 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000256 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000257 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000258 case Type::StructTyID: {
259 const StructType *STy = cast<StructType>(SubType);
260 const StructLayout &SL = *TD.getStructLayout(STy);
261 if (SL.MemberOffsets.size() > 1)
262 NextPadSize = SL.MemberOffsets[1];
263 else
264 NextPadSize = SubTypeSize;
265 NextSubType = STy->getElementTypes()[0];
266 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000267 break;
Chris Lattner18552922002-11-18 21:44:46 +0000268 }
Chris Lattner08db7192002-11-06 06:20:27 +0000269 case Type::ArrayTyID:
270 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000271 NextSubTypeSize = TD.getTypeSize(NextSubType);
272 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000273 break;
274 default: ;
275 // fall out
276 }
277
278 if (NextSubType == 0)
279 break; // In the default case, break out of the loop
280
Chris Lattner18552922002-11-18 21:44:46 +0000281 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000282 break; // Don't allow shrinking to a smaller type than NewTySize
283 SubType = NextSubType;
284 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000285 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000286 }
287
288 // If we found the type exactly, return it...
289 if (SubType == NewTy)
290 return false;
291
292 // Check to see if we have a compatible, but different type...
293 if (NewTySize == SubTypeSize) {
294 // Check to see if this type is obviously convertable... int -> uint f.e.
295 if (NewTy->isLosslesslyConvertableTo(SubType))
296 return false;
297
298 // Check to see if we have a pointer & integer mismatch going on here,
299 // loading a pointer as a long, for example.
300 //
301 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
302 NewTy->isInteger() && isa<PointerType>(SubType))
303 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000304 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
305 // We are accessing the field, plus some structure padding. Ignore the
306 // structure padding.
307 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000308 }
309
310
Chris Lattner18552922002-11-18 21:44:46 +0000311 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000312 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
313 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000314
315 foldNodeCompletely();
316 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000317}
318
Chris Lattner08db7192002-11-06 06:20:27 +0000319
320
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000321// addEdgeTo - Add an edge from the current node to the specified node. This
322// can cause merging of nodes in the graph.
323//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000324void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000325 if (NH.getNode() == 0) return; // Nothing to do
326
Chris Lattner08db7192002-11-06 06:20:27 +0000327 DSNodeHandle &ExistingEdge = getLink(Offset);
328 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000329 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000330 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000331 } else { // No merging to perform...
332 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000333 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000334}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000335
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000336
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000337// MergeSortedVectors - Efficiently merge a vector into another vector where
338// duplicates are not allowed and both are sorted. This assumes that 'T's are
339// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000340//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000341static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
342 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000343 // By far, the most common cases will be the simple ones. In these cases,
344 // avoid having to allocate a temporary vector...
345 //
346 if (Src.empty()) { // Nothing to merge in...
347 return;
348 } else if (Dest.empty()) { // Just copy the result in...
349 Dest = Src;
350 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000351 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000352 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000353 std::lower_bound(Dest.begin(), Dest.end(), V);
354 if (I == Dest.end() || *I != Src[0]) // If not already contained...
355 Dest.insert(I, Src[0]);
356 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000357 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000358 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000359 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000360 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
361 if (I == Dest.end() || *I != Tmp) // If not already contained...
362 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000363
364 } else {
365 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000366 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000367
368 // Make space for all of the type entries now...
369 Dest.resize(Dest.size()+Src.size());
370
371 // Merge the two sorted ranges together... into Dest.
372 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
373
374 // Now erase any duplicate entries that may have accumulated into the
375 // vectors (because they were in both of the input sets)
376 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
377 }
378}
379
380
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000381// MergeNodes() - Helper function for DSNode::mergeWith().
382// This function does the hard work of merging two nodes, CurNodeH
383// and NH after filtering out trivial cases and making sure that
384// CurNodeH.offset >= NH.offset.
385//
386// ***WARNING***
387// Since merging may cause either node to go away, we must always
388// use the node-handles to refer to the nodes. These node handles are
389// automatically updated during merging, so will always provide access
390// to the correct node after a merge.
391//
392void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
393 assert(CurNodeH.getOffset() >= NH.getOffset() &&
394 "This should have been enforced in the caller.");
395
396 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
397 // respect to NH.Offset) is now zero. NOffset is the distance from the base
398 // of our object that N starts from.
399 //
400 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
401 unsigned NSize = NH.getNode()->getSize();
402
403 // Merge the type entries of the two nodes together...
404 if (NH.getNode()->Ty != Type::VoidTy) {
405 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
406 }
407 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
408
409 // If we are merging a node with a completely folded node, then both nodes are
410 // now completely folded.
411 //
412 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
413 if (!NH.getNode()->isNodeCompletelyFolded()) {
414 NH.getNode()->foldNodeCompletely();
415 assert(NH.getOffset()==0 && "folding did not make offset 0?");
416 NOffset = NH.getOffset();
417 NSize = NH.getNode()->getSize();
418 assert(NOffset == 0 && NSize == 1);
419 }
420 } else if (NH.getNode()->isNodeCompletelyFolded()) {
421 CurNodeH.getNode()->foldNodeCompletely();
422 assert(CurNodeH.getOffset()==0 && "folding did not make offset 0?");
423 NOffset = NH.getOffset();
424 NSize = NH.getNode()->getSize();
425 assert(NOffset == 0 && NSize == 1);
426 }
427
428 if (CurNodeH.getNode() == NH.getNode() || NH.getNode() == 0) return;
429 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
430
431 // Remove all edges pointing at N, causing them to point to 'this' instead.
432 // Make sure to adjust their offset, not just the node pointer.
433 // Also, be careful to use the DSNode* rather than NH since NH is one of
434 // the referrers and once NH refers to CurNodeH.getNode() this will
435 // become an infinite loop.
436 DSNode* N = NH.getNode();
437 unsigned OldNHOffset = NH.getOffset();
438 while (!N->Referrers.empty()) {
439 DSNodeHandle &Ref = *N->Referrers.back();
440 Ref = DSNodeHandle(CurNodeH.getNode(), NOffset+Ref.getOffset());
441 }
442 NH = DSNodeHandle(N, OldNHOffset); // reset NH to point back to where it was
443
444 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
445
446 // Make all of the outgoing links of *NH now be outgoing links of
447 // this. This can cause recursive merging!
448 //
Chris Lattner6f6fef82003-01-22 22:00:24 +0000449 for (unsigned i = 0; i < NH.getNode()->getSize(); i += DS::PointerSize) {
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000450 DSNodeHandle &Link = NH.getNode()->getLink(i);
451 if (Link.getNode()) {
452 // Compute the offset into the current node at which to
453 // merge this link. In the common case, this is a linear
454 // relation to the offset in the original node (with
455 // wrapping), but if the current node gets collapsed due to
456 // recursive merging, we must make sure to merge in all remaining
457 // links at offset zero.
458 unsigned MergeOffset = 0;
459 if (CurNodeH.getNode()->Size != 1)
460 MergeOffset = (i+NOffset) % CurNodeH.getNode()->getSize();
461 CurNodeH.getNode()->addEdgeTo(MergeOffset, Link);
462 }
463 }
464
465 // Now that there are no outgoing edges, all of the Links are dead.
466 NH.getNode()->Links.clear();
467 NH.getNode()->Size = 0;
468 NH.getNode()->Ty = Type::VoidTy;
469
470 // Merge the node types
471 CurNodeH.getNode()->NodeType |= NH.getNode()->NodeType;
472 NH.getNode()->NodeType = DEAD; // NH is now a dead node.
473
474 // Merge the globals list...
475 if (!NH.getNode()->Globals.empty()) {
476 MergeSortedVectors(CurNodeH.getNode()->Globals, NH.getNode()->Globals);
477
478 // Delete the globals from the old node...
479 NH.getNode()->Globals.clear();
480 }
481}
482
483
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000484// mergeWith - Merge this node and the specified node, moving all links to and
485// from the argument node into the current node, deleting the node argument.
486// Offset indicates what offset the specified node is to be merged into the
487// current node.
488//
489// The specified node may be a null pointer (in which case, nothing happens).
490//
491void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
492 DSNode *N = NH.getNode();
493 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000494 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000495
Chris Lattner679e8e12002-11-08 21:27:12 +0000496 assert((N->NodeType & DSNode::DEAD) == 0);
497 assert((NodeType & DSNode::DEAD) == 0);
498 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
499
Chris Lattner02606632002-11-04 06:48:26 +0000500 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000501 // We cannot merge two pieces of the same node together, collapse the node
502 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000503 DEBUG(std::cerr << "Attempting to merge two chunks of"
504 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000505 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000506 return;
507 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000508
Chris Lattner5190ce82002-11-12 07:20:45 +0000509 // If both nodes are not at offset 0, make sure that we are merging the node
510 // at an later offset into the node with the zero offset.
511 //
512 if (Offset < NH.getOffset()) {
513 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
514 return;
515 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
516 // If the offsets are the same, merge the smaller node into the bigger node
517 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
518 return;
519 }
520
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000521 // Ok, now we can merge the two nodes. Use a static helper that works with
522 // two node handles, since "this" may get merged away at intermediate steps.
523 DSNodeHandle CurNodeH(this, Offset);
524 DSNodeHandle NHCopy(NH);
525 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000526}
527
Chris Lattner9de906c2002-10-20 22:11:44 +0000528//===----------------------------------------------------------------------===//
529// DSCallSite Implementation
530//===----------------------------------------------------------------------===//
531
Vikram S. Adve26b98262002-10-20 21:41:02 +0000532// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000533Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000534 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000535}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000536
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000537
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000538//===----------------------------------------------------------------------===//
539// DSGraph Implementation
540//===----------------------------------------------------------------------===//
541
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000542DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000543 PrintAuxCalls = false;
Chris Lattner41c04f72003-02-01 04:52:08 +0000544 hash_map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000545 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000546}
547
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000548DSGraph::DSGraph(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000549 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000550 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000551 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000552 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000553}
554
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000555DSGraph::~DSGraph() {
556 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000557 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000558 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000559 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000560
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000561 // Drop all intra-node references, so that assertions don't fail...
562 std::for_each(Nodes.begin(), Nodes.end(),
563 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000564
565 // Delete all of the nodes themselves...
566 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
567}
568
Chris Lattner0d9bab82002-07-18 00:12:30 +0000569// dump - Allow inspection of graph in a debugger.
570void DSGraph::dump() const { print(std::cerr); }
571
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000572
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000573/// remapLinks - Change all of the Links in the current node according to the
574/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000575///
Chris Lattner41c04f72003-02-01 04:52:08 +0000576void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000577 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
578 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
579 Links[i].setNode(H.getNode());
580 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
581 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000582}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000583
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000584
Chris Lattner0d9bab82002-07-18 00:12:30 +0000585// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000586// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000587// filled into the OldValMap member. If StripAllocas is set to true, Alloca
588// markers are removed from the graph, as the graph is being cloned into a
589// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000590//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000591DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000592 hash_map<Value*, DSNodeHandle> &OldValMap,
593 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000594 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000595 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000596 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000597
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000598 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000599
600 // Duplicate all of the nodes, populating the node map...
601 Nodes.reserve(FN+G.Nodes.size());
602 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000603 DSNode *Old = G.Nodes[i];
604 DSNode *New = new DSNode(*Old);
Chris Lattner679e8e12002-11-08 21:27:12 +0000605 New->NodeType &= ~DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000606 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000607 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000608 }
609
Chris Lattner18552922002-11-18 21:44:46 +0000610#ifndef NDEBUG
611 Timer::addPeakMemoryMeasurement();
612#endif
613
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000614 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000615 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000616 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000617
Chris Lattner460ea292002-11-07 07:06:20 +0000618 // Remove alloca markers as specified
Vikram S. Adve61ff0292002-11-27 17:41:13 +0000619 if (CloneFlags & (StripAllocaBit | StripModRefBits)) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000620 unsigned clearBits = (CloneFlags & StripAllocaBit ? DSNode::AllocaNode : 0)
621 | (CloneFlags & StripModRefBits ? (DSNode::Modified | DSNode::Read) : 0);
622 maskNodeTypes(~clearBits);
Vikram S. Adve61ff0292002-11-27 17:41:13 +0000623 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000624
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000625 // Copy the scalar map... merging all of the global nodes...
Chris Lattner41c04f72003-02-01 04:52:08 +0000626 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000627 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000628 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000629 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
630 H.setNode(MappedNode.getNode());
631 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000632
633 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattner41c04f72003-02-01 04:52:08 +0000634 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000635 if (GVI != ScalarMap.end()) // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000636 GVI->second.mergeWith(H);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000637 else
Chris Lattnerc875f022002-11-03 21:27:48 +0000638 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000639 }
640 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000641
Chris Lattner679e8e12002-11-08 21:27:12 +0000642 if (!(CloneFlags & DontCloneCallNodes)) {
643 // Copy the function calls list...
644 unsigned FC = FunctionCalls.size(); // FirstCall
645 FunctionCalls.reserve(FC+G.FunctionCalls.size());
646 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
647 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000648 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000649
Chris Lattneracf491f2002-11-08 22:27:09 +0000650 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000651 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000652 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000653 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
654 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
655 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
656 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000657
Chris Lattner0d9bab82002-07-18 00:12:30 +0000658 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000659 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
660 return DSNodeHandle(MappedRet.getNode(),
661 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000662}
663
Chris Lattner076c1f92002-11-07 06:31:54 +0000664/// mergeInGraph - The method is used for merging graphs together. If the
665/// argument graph is not *this, it makes a clone of the specified graph, then
666/// merges the nodes specified in the call site with the formal arguments in the
667/// graph.
668///
669void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000670 unsigned CloneFlags) {
Chris Lattner41c04f72003-02-01 04:52:08 +0000671 hash_map<Value*, DSNodeHandle> OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000672 DSNodeHandle RetVal;
Chris Lattner41c04f72003-02-01 04:52:08 +0000673 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000674
675 // If this is not a recursive call, clone the graph into this graph...
676 if (&Graph != this) {
677 // Clone the callee's graph into the current graph, keeping
678 // track of where scalars in the old graph _used_ to point,
679 // and of the new nodes matching nodes of the old graph.
Chris Lattner41c04f72003-02-01 04:52:08 +0000680 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000681
682 // The clone call may invalidate any of the vectors in the data
683 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000684 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000685 ScalarMap = &OldValMap;
686 } else {
687 RetVal = getRetNode();
688 ScalarMap = &getScalarMap();
689 }
690
691 // Merge the return value with the return value of the context...
692 RetVal.mergeWith(CS.getRetVal());
693
694 // Resolve all of the function arguments...
695 Function &F = Graph.getFunction();
696 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000697
Chris Lattner076c1f92002-11-07 06:31:54 +0000698 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
699 // Advance the argument iterator to the first pointer argument...
700 while (!isPointerType(AI->getType())) {
701 ++AI;
702#ifndef NDEBUG
703 if (AI == F.aend())
704 std::cerr << "Bad call to Function: " << F.getName() << "\n";
705#endif
706 assert(AI != F.aend() && "# Args provided is not # Args required!");
707 }
708
709 // Add the link from the argument scalar to the provided value
710 DSNodeHandle &NH = (*ScalarMap)[AI];
711 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
712 NH.mergeWith(CS.getPtrArg(i));
713 }
714}
715
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000716
Chris Lattner0d9bab82002-07-18 00:12:30 +0000717// markIncompleteNodes - Mark the specified node as having contents that are not
718// known with the current analysis we have performed. Because a node makes all
719// of the nodes it can reach imcomplete if the node itself is incomplete, we
720// must recursively traverse the data structure graph, marking all reachable
721// nodes as incomplete.
722//
723static void markIncompleteNode(DSNode *N) {
724 // Stop recursion if no node, or if node already marked...
725 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
726
727 // Actually mark the node
728 N->NodeType |= DSNode::Incomplete;
729
730 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000731 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
732 if (DSNode *DSN = N->getLink(i).getNode())
733 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000734}
735
Chris Lattnere71ffc22002-11-11 03:36:55 +0000736static void markIncomplete(DSCallSite &Call) {
737 // Then the return value is certainly incomplete!
738 markIncompleteNode(Call.getRetVal().getNode());
739
740 // All objects pointed to by function arguments are incomplete!
741 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
742 markIncompleteNode(Call.getPtrArg(i).getNode());
743}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000744
745// markIncompleteNodes - Traverse the graph, identifying nodes that may be
746// modified by other functions that have not been resolved yet. This marks
747// nodes that are reachable through three sources of "unknownness":
748//
749// Global Variables, Function Calls, and Incoming Arguments
750//
751// For any node that may have unknown components (because something outside the
752// scope of current analysis may have modified it), the 'Incomplete' flag is
753// added to the NodeType.
754//
Chris Lattner394471f2003-01-23 22:05:33 +0000755void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000756 // Mark any incoming arguments as incomplete...
Chris Lattner394471f2003-01-23 22:05:33 +0000757 if ((Flags & DSGraph::MarkFormalArgs) && Func)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000758 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000759 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
760 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000761
762 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000763 if (!shouldPrintAuxCalls())
764 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
765 markIncomplete(FunctionCalls[i]);
766 else
767 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
768 markIncomplete(AuxFunctionCalls[i]);
769
Chris Lattner0d9bab82002-07-18 00:12:30 +0000770
Chris Lattner92673292002-11-02 00:13:20 +0000771 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000772 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000773 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000774 DSNode *N = Nodes[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000775 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
776 if (DSNode *DSN = N->getLink(i).getNode())
777 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000778 }
779}
780
Chris Lattneraa8146f2002-11-10 06:59:55 +0000781static inline void killIfUselessEdge(DSNodeHandle &Edge) {
782 if (DSNode *N = Edge.getNode()) // Is there an edge?
783 if (N->getReferrers().size() == 1) // Does it point to a lonely node?
784 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
Chris Lattner18552922002-11-18 21:44:46 +0000785 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000786 Edge.setNode(0); // Kill the edge!
787}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000788
Chris Lattneraa8146f2002-11-10 06:59:55 +0000789static inline bool nodeContainsExternalFunction(const DSNode *N) {
790 const std::vector<GlobalValue*> &Globals = N->getGlobals();
791 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
792 if (Globals[i]->isExternal())
793 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000794 return false;
795}
796
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000797static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000798 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000799 // Remove trivially identical function calls
800 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000801 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
802
803 // Scan the call list cleaning it up as necessary...
804 DSNode *LastCalleeNode = 0;
805 unsigned NumDuplicateCalls = 0;
806 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000807 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000808 DSCallSite &CS = Calls[i];
809
Chris Lattnere4258442002-11-11 21:35:38 +0000810 // If the Callee is a useless edge, this must be an unreachable call site,
811 // eliminate it.
812 killIfUselessEdge(CS.getCallee());
813 if (CS.getCallee().getNode() == 0) {
814 CS.swap(Calls.back());
815 Calls.pop_back();
816 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000817 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000818 // If the return value or any arguments point to a void node with no
819 // information at all in it, and the call node is the only node to point
820 // to it, remove the edge to the node (killing the node).
821 //
822 killIfUselessEdge(CS.getRetVal());
823 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
824 killIfUselessEdge(CS.getPtrArg(a));
825
826 // If this call site calls the same function as the last call site, and if
827 // the function pointer contains an external function, this node will
828 // never be resolved. Merge the arguments of the call node because no
829 // information will be lost.
830 //
831 if (CS.getCallee().getNode() == LastCalleeNode) {
832 ++NumDuplicateCalls;
833 if (NumDuplicateCalls == 1) {
834 LastCalleeContainsExternalFunction =
835 nodeContainsExternalFunction(LastCalleeNode);
836 }
837
838 if (LastCalleeContainsExternalFunction ||
839 // This should be more than enough context sensitivity!
840 // FIXME: Evaluate how many times this is tripped!
841 NumDuplicateCalls > 20) {
842 DSCallSite &OCS = Calls[i-1];
843 OCS.mergeWith(CS);
844
845 // The node will now be eliminated as a duplicate!
846 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
847 CS = OCS;
848 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
849 OCS = CS;
850 }
851 } else {
852 LastCalleeNode = CS.getCallee().getNode();
853 NumDuplicateCalls = 0;
854 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000855 }
856 }
857
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000858 Calls.erase(std::unique(Calls.begin(), Calls.end()),
859 Calls.end());
860
Chris Lattner33312f72002-11-08 01:21:07 +0000861 // Track the number of call nodes merged away...
862 NumCallNodesMerged += NumFns-Calls.size();
863
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000864 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000865 std::cerr << "Merged " << (NumFns-Calls.size())
866 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000867}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000868
Chris Lattneraa8146f2002-11-10 06:59:55 +0000869
Chris Lattnere2219762002-07-18 18:22:40 +0000870// removeTriviallyDeadNodes - After the graph has been constructed, this method
871// removes all unreachable nodes that are created because they got merged with
872// other nodes in the graph. These nodes will all be trivially unreachable, so
873// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000874//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000875void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000876 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000877 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
878
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000879 for (unsigned i = 0; i != Nodes.size(); ++i) {
880 DSNode *Node = Nodes[i];
881 if (!(Node->NodeType & ~(DSNode::Composition | DSNode::Array |
882 DSNode::DEAD))) {
883 // This is a useless node if it has no mod/ref info (checked above),
884 // outgoing edges (which it cannot, as it is not modified in this
885 // context), and it has no incoming edges. If it is a global node it may
886 // have all of these properties and still have incoming edges, due to the
887 // scalar map, so we check those now.
888 //
889 if (Node->getReferrers().size() == Node->getGlobals().size()) {
890 std::vector<GlobalValue*> &Globals = Node->getGlobals();
891 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
892 ScalarMap.erase(Globals[j]);
893 Globals.clear();
894
895 Node->NodeType = DSNode::DEAD;
896 }
897 }
898
899 if ((Node->NodeType & ~DSNode::DEAD) == 0 &&
900 Node->getReferrers().empty()) { // This node is dead!
901 delete Node; // Free memory...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000902 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
903 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000904 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000905}
906
907
Chris Lattner5c7380e2003-01-29 21:10:20 +0000908/// markReachableNodes - This method recursively traverses the specified
909/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
910/// to the set, which allows it to only traverse visited nodes once.
911///
Chris Lattner41c04f72003-02-01 04:52:08 +0000912void DSNode::markReachableNodes(hash_set<DSNode*> &ReachableNodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000913 if (this == 0) return;
Chris Lattner41c04f72003-02-01 04:52:08 +0000914 if (ReachableNodes.count(this)) return; // Already marked reachable
915 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +0000916
Chris Lattner5c7380e2003-01-29 21:10:20 +0000917 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
918 getLink(i).getNode()->markReachableNodes(ReachableNodes);
919}
920
Chris Lattner41c04f72003-02-01 04:52:08 +0000921void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000922 getRetVal().getNode()->markReachableNodes(Nodes);
923 getCallee().getNode()->markReachableNodes(Nodes);
924
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000925 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
926 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +0000927}
928
Chris Lattnera1220af2003-02-01 06:17:02 +0000929// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
930// looking for a node that is marked alive. If an alive node is found, return
931// true, otherwise return false. If an alive node is reachable, this node is
932// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000933//
Chris Lattnera1220af2003-02-01 06:17:02 +0000934static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
935 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000936 if (N == 0) return false;
937
Chris Lattneraa8146f2002-11-10 06:59:55 +0000938 // If we know that this node is alive, return so!
939 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000940
Chris Lattneraa8146f2002-11-10 06:59:55 +0000941 // Otherwise, we don't think the node is alive yet, check for infinite
942 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +0000943 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +0000944 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000945
Chris Lattner08db7192002-11-06 06:20:27 +0000946 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +0000947 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
948 N->markReachableNodes(Alive);
949 return true;
950 }
951 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000952}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000953
Chris Lattnera1220af2003-02-01 06:17:02 +0000954// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
955// alive nodes.
956//
Chris Lattner41c04f72003-02-01 04:52:08 +0000957static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
958 hash_set<DSNode*> &Visited) {
Chris Lattnera1220af2003-02-01 06:17:02 +0000959 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited) ||
960 CanReachAliveNodes(CS.getCallee().getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000961 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000962 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
963 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000964 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000965 return false;
966}
967
Chris Lattnere2219762002-07-18 18:22:40 +0000968// removeDeadNodes - Use a more powerful reachability analysis to eliminate
969// subgraphs that are unreachable. This often occurs because the data
970// structure doesn't "escape" into it's caller, and thus should be eliminated
971// from the caller's graph entirely. This is only appropriate to use when
972// inlining graphs.
973//
Chris Lattner394471f2003-01-23 22:05:33 +0000974void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000975 // Reduce the amount of work we have to do... remove dummy nodes left over by
976 // merging...
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000977 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000978
Chris Lattnere2219762002-07-18 18:22:40 +0000979 // FIXME: Merge nontrivially identical call nodes...
980
981 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +0000982 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000983 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +0000984
Chris Lattneraa8146f2002-11-10 06:59:55 +0000985 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner41c04f72003-02-01 04:52:08 +0000986 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000987 E = ScalarMap.end(); I != E; ++I)
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000988 if (!isa<GlobalValue>(I->first))
Chris Lattner5c7380e2003-01-29 21:10:20 +0000989 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000990 else { // Keep track of global nodes
Chris Lattner394471f2003-01-23 22:05:33 +0000991 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000992 assert(I->second.getNode() && "Null global node?");
993 }
Chris Lattnere2219762002-07-18 18:22:40 +0000994
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000995 // The return value is alive as well...
Chris Lattner5c7380e2003-01-29 21:10:20 +0000996 RetNode.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000997
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000998 // Mark any nodes reachable by primary calls as alive...
999 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1000 FunctionCalls[i].markReachableNodes(Alive);
1001
1002 bool Iterate;
Chris Lattner41c04f72003-02-01 04:52:08 +00001003 hash_set<DSNode*> Visited;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001004 std::vector<unsigned char> AuxFCallsAlive(AuxFunctionCalls.size());
1005 do {
1006 Visited.clear();
1007 // If any global nodes points to a non-global that is "alive", the global is
1008 // "alive" as well... Remov it from the GlobalNodes list so we only have
1009 // unreachable globals in the list.
1010 //
1011 Iterate = false;
1012 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1013 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited)) {
1014 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to erase
1015 GlobalNodes.pop_back(); // Erase efficiently
1016 Iterate = true;
1017 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001018
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001019 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1020 if (!AuxFCallsAlive[i] &&
1021 CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
1022 AuxFunctionCalls[i].markReachableNodes(Alive);
1023 AuxFCallsAlive[i] = true;
1024 Iterate = true;
1025 }
1026 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001027
1028 // Remove all dead aux function calls...
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001029 unsigned CurIdx = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001030 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1031 if (AuxFCallsAlive[i])
1032 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001033 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1034 // Move the unreachable call nodes to the globals graph...
1035 GlobalsGraph->AuxFunctionCalls.insert(GlobalsGraph->AuxFunctionCalls.end(),
1036 AuxFunctionCalls.begin()+CurIdx,
1037 AuxFunctionCalls.end());
1038 }
1039 // Crop all the useless ones out...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001040 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1041 AuxFunctionCalls.end());
1042
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001043 // At this point, any nodes which are visited, but not alive, are nodes which
1044 // should be moved to the globals graph. Loop over all nodes, eliminating
1045 // completely unreachable nodes, and moving visited nodes to the globals graph
1046 //
Chris Lattnere2219762002-07-18 18:22:40 +00001047 for (unsigned i = 0; i != Nodes.size(); ++i)
1048 if (!Alive.count(Nodes[i])) {
1049 DSNode *N = Nodes[i];
Chris Lattner5e7d0e22003-02-01 06:23:33 +00001050 std::swap(Nodes[i--], Nodes.back()); // move node to end of vector
1051 Nodes.pop_back(); // Erase node from alive list.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001052 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && // Not in TD pass
1053 Visited.count(N)) { // Visited but not alive?
1054 GlobalsGraph->Nodes.push_back(N); // Move node to globals graph
1055 } else { // Otherwise, delete the node
1056 assert(((N->NodeType & DSNode::GlobalNode) == 0 ||
1057 (Flags & DSGraph::RemoveUnreachableGlobals))
1058 && "Killing a global?");
1059 while (!N->getReferrers().empty()) // Rewrite referrers
1060 N->getReferrers().back()->setNode(0);
1061 delete N; // Usecount is zero
1062 }
Chris Lattnere2219762002-07-18 18:22:40 +00001063 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001064
1065 // Now that the nodes have either been deleted or moved to the globals graph,
1066 // loop over the scalarmap, updating the entries for globals...
1067 //
1068 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) { // Not in the TD pass?
1069 // In this array we start the remapping, which can cause merging. Because
1070 // of this, the DSNode pointers in GlobalNodes may be invalidated, so we
1071 // must always go through the ScalarMap (which contains DSNodeHandles [which
1072 // cannot be invalidated by merging]).
1073 //
1074 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i) {
1075 Value *G = GlobalNodes[i].first;
1076 hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(G);
1077 assert(I != ScalarMap.end() && "Global not in scalar map anymore?");
1078 assert(I->second.getNode() && "Global not pointing to anything?");
1079 assert(!Alive.count(I->second.getNode()) && "Node is alive??");
1080 GlobalsGraph->ScalarMap[G].mergeWith(I->second);
1081 assert(GlobalsGraph->ScalarMap[G].getNode() &&
1082 "Global not pointing to anything?");
1083 ScalarMap.erase(I);
1084 }
1085
1086 // Merging leaves behind silly nodes, we remove them to avoid polluting the
1087 // globals graph.
1088 GlobalsGraph->removeTriviallyDeadNodes();
1089 } else {
1090 // If we are in the top-down pass, remove all unreachable globals from the
1091 // ScalarMap...
1092 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1093 ScalarMap.erase(GlobalNodes[i].first);
1094 }
1095
1096 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00001097}
1098
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001099void DSGraph::AssertGraphOK() const {
1100 for (hash_map<Value*, DSNodeHandle>::const_iterator I = ScalarMap.begin(),
1101 E = ScalarMap.end(); I != E; ++I) {
1102 assert(I->second.getNode() && "Null node in scalarmap!");
1103 AssertNodeInGraph(I->second.getNode());
1104 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
1105 assert((I->second.getNode()->NodeType & DSNode::GlobalNode) &&
1106 "Global points to node, but node isn't global?");
1107 AssertNodeContainsGlobal(I->second.getNode(), GV);
1108 }
1109 }
1110 AssertCallNodesInGraph();
1111 AssertAuxCallNodesInGraph();
1112}
1113
1114
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001115#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001116//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001117// GlobalDSGraph Implementation
1118//===----------------------------------------------------------------------===//
1119
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001120#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001121// Bits used in the next function
1122static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1123
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001124// cloneGlobalInto - Clone the given global node and all its target links
1125// (and all their llinks, recursively).
1126//
1127DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
1128 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
1129
1130 // If a clone has already been created for GNode, return it.
1131 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
1132 if (ValMapEntry != 0)
1133 return ValMapEntry;
1134
1135 // Clone the node and update the ValMap.
1136 DSNode* NewNode = new DSNode(*GNode);
1137 ValMapEntry = NewNode; // j=0 case of loop below!
1138 Nodes.push_back(NewNode);
1139 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
1140 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
1141
1142 // Rewrite the links in the new node to point into the current graph.
1143 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
1144 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
1145
1146 return NewNode;
1147}
Chris Lattnerd18f3422002-11-03 21:24:04 +00001148
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001149// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1150// visible target links (and recursively their such links) into this graph.
1151// NodeCache maps the node being cloned to its clone in the Globals graph,
1152// in order to track cycles.
1153// GlobalsAreFinal is a flag that says whether it is safe to assume that
1154// an existing global node is complete. This is important to avoid
1155// reinserting all globals when inserting Calls to functions.
1156// This is a helper function for cloneGlobals and cloneCalls.
1157//
1158DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
Chris Lattner41c04f72003-02-01 04:52:08 +00001159 hash_map<const DSNode*, DSNode*> &NodeCache,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001160 bool GlobalsAreFinal) {
1161 if (OldNode == 0) return 0;
1162
1163 // The caller should check this is an external node. Just more efficient...
1164 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1165
1166 // If a clone has already been created for OldNode, return it.
1167 DSNode*& CacheEntry = NodeCache[OldNode];
1168 if (CacheEntry != 0)
1169 return CacheEntry;
1170
1171 // The result value...
1172 DSNode* NewNode = 0;
1173
1174 // If nodes already exist for any of the globals of OldNode,
1175 // merge all such nodes together since they are merged in OldNode.
1176 // If ValueCacheIsFinal==true, look for an existing node that has
1177 // an identical list of globals and return it if it exists.
1178 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001179 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001180 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001181 if (NewNode == 0) {
1182 NewNode = PrevNode; // first existing node found
1183 if (GlobalsAreFinal && j == 0)
1184 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1185 CacheEntry = NewNode;
1186 return NewNode;
1187 }
1188 }
1189 else if (NewNode != PrevNode) { // found another, different from prev
1190 // update ValMap *before* merging PrevNode into NewNode
1191 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001192 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001193 NewNode->mergeWith(PrevNode);
1194 }
1195 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001196 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001197 }
1198
1199 // If no existing node was found, clone the node and update the ValMap.
1200 if (NewNode == 0) {
1201 NewNode = new DSNode(*OldNode);
1202 Nodes.push_back(NewNode);
1203 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1204 NewNode->setLink(j, 0);
1205 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001206 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001207 }
1208 else
1209 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1210
1211 // Add the entry to NodeCache
1212 CacheEntry = NewNode;
1213
1214 // Rewrite the links in the new node to point into the current graph,
1215 // but only for links to external nodes. Set other links to NULL.
1216 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1217 DSNode* OldTarget = OldNode->getLink(j);
1218 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1219 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1220 if (NewNode->getLink(j))
1221 NewNode->getLink(j)->mergeWith(NewLink);
1222 else
1223 NewNode->setLink(j, NewLink);
1224 }
1225 }
1226
1227 // Remove all local markers
1228 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1229
1230 return NewNode;
1231}
1232
1233
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001234// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1235// links (and recursively their such links) into this graph.
1236//
1237void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
Chris Lattner41c04f72003-02-01 04:52:08 +00001238 hash_map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerb3416bc2003-02-01 04:01:21 +00001239 std::vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001240
1241 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1242
1243 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001244 DSCallSite& callCopy = FunctionCalls.back();
1245 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001246 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001247 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001248 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1249 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1250 : 0);
1251 }
1252
1253 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001254 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001255}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001256#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001257
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001258#endif