blob: f1b6e420bb9d82ea0e648d35cc2be3f523952d1f [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:
236 assert(0 && "Unknown type!");
237 }
238 }
239
240 assert(O == Offset && "Could not achieve the correct offset!");
241
242 // If we found our type exactly, early exit
243 if (SubType == NewTy) return false;
244
245 // Okay, so we found the leader type at the offset requested. Search the list
246 // of types that starts at this offset. If SubType is currently an array or
247 // structure, the type desired may actually be the first element of the
248 // composite type...
249 //
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000250 unsigned SubTypeSize = SubType->isSized() ? TD.getTypeSize(SubType) : 0;
Chris Lattner18552922002-11-18 21:44:46 +0000251 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000252 while (SubType != NewTy) {
253 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000254 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000255 unsigned NextPadSize = 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000256 switch (SubType->getPrimitiveID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000257 case Type::StructTyID: {
258 const StructType *STy = cast<StructType>(SubType);
259 const StructLayout &SL = *TD.getStructLayout(STy);
260 if (SL.MemberOffsets.size() > 1)
261 NextPadSize = SL.MemberOffsets[1];
262 else
263 NextPadSize = SubTypeSize;
264 NextSubType = STy->getElementTypes()[0];
265 NextSubTypeSize = TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000266 break;
Chris Lattner18552922002-11-18 21:44:46 +0000267 }
Chris Lattner08db7192002-11-06 06:20:27 +0000268 case Type::ArrayTyID:
269 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner18552922002-11-18 21:44:46 +0000270 NextSubTypeSize = TD.getTypeSize(NextSubType);
271 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000272 break;
273 default: ;
274 // fall out
275 }
276
277 if (NextSubType == 0)
278 break; // In the default case, break out of the loop
279
Chris Lattner18552922002-11-18 21:44:46 +0000280 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000281 break; // Don't allow shrinking to a smaller type than NewTySize
282 SubType = NextSubType;
283 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000284 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000285 }
286
287 // If we found the type exactly, return it...
288 if (SubType == NewTy)
289 return false;
290
291 // Check to see if we have a compatible, but different type...
292 if (NewTySize == SubTypeSize) {
293 // Check to see if this type is obviously convertable... int -> uint f.e.
294 if (NewTy->isLosslesslyConvertableTo(SubType))
295 return false;
296
297 // Check to see if we have a pointer & integer mismatch going on here,
298 // loading a pointer as a long, for example.
299 //
300 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
301 NewTy->isInteger() && isa<PointerType>(SubType))
302 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000303 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
304 // We are accessing the field, plus some structure padding. Ignore the
305 // structure padding.
306 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000307 }
308
309
Chris Lattner18552922002-11-18 21:44:46 +0000310 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: " << Ty
Chris Lattner3c87b292002-11-07 01:54:56 +0000311 << "\n due to:" << NewTy << " @ " << Offset << "!\n"
312 << "SubType: " << SubType << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000313
314 foldNodeCompletely();
315 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000316}
317
Chris Lattner08db7192002-11-06 06:20:27 +0000318
319
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000320// addEdgeTo - Add an edge from the current node to the specified node. This
321// can cause merging of nodes in the graph.
322//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000323void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000324 if (NH.getNode() == 0) return; // Nothing to do
325
Chris Lattner08db7192002-11-06 06:20:27 +0000326 DSNodeHandle &ExistingEdge = getLink(Offset);
327 if (ExistingEdge.getNode()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000328 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000329 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000330 } else { // No merging to perform...
331 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000332 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000333}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000334
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000335
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000336// MergeSortedVectors - Efficiently merge a vector into another vector where
337// duplicates are not allowed and both are sorted. This assumes that 'T's are
338// efficiently copyable and have sane comparison semantics.
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000339//
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000340static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
341 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000342 // By far, the most common cases will be the simple ones. In these cases,
343 // avoid having to allocate a temporary vector...
344 //
345 if (Src.empty()) { // Nothing to merge in...
346 return;
347 } else if (Dest.empty()) { // Just copy the result in...
348 Dest = Src;
349 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000350 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000351 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000352 std::lower_bound(Dest.begin(), Dest.end(), V);
353 if (I == Dest.end() || *I != Src[0]) // If not already contained...
354 Dest.insert(I, Src[0]);
355 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000356 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000357 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000358 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000359 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
360 if (I == Dest.end() || *I != Tmp) // If not already contained...
361 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000362
363 } else {
364 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000365 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000366
367 // Make space for all of the type entries now...
368 Dest.resize(Dest.size()+Src.size());
369
370 // Merge the two sorted ranges together... into Dest.
371 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
372
373 // Now erase any duplicate entries that may have accumulated into the
374 // vectors (because they were in both of the input sets)
375 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
376 }
377}
378
379
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000380// MergeNodes() - Helper function for DSNode::mergeWith().
381// This function does the hard work of merging two nodes, CurNodeH
382// and NH after filtering out trivial cases and making sure that
383// CurNodeH.offset >= NH.offset.
384//
385// ***WARNING***
386// Since merging may cause either node to go away, we must always
387// use the node-handles to refer to the nodes. These node handles are
388// automatically updated during merging, so will always provide access
389// to the correct node after a merge.
390//
391void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
392 assert(CurNodeH.getOffset() >= NH.getOffset() &&
393 "This should have been enforced in the caller.");
394
395 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
396 // respect to NH.Offset) is now zero. NOffset is the distance from the base
397 // of our object that N starts from.
398 //
399 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
400 unsigned NSize = NH.getNode()->getSize();
401
402 // Merge the type entries of the two nodes together...
403 if (NH.getNode()->Ty != Type::VoidTy) {
404 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
405 }
406 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
407
408 // If we are merging a node with a completely folded node, then both nodes are
409 // now completely folded.
410 //
411 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
412 if (!NH.getNode()->isNodeCompletelyFolded()) {
413 NH.getNode()->foldNodeCompletely();
414 assert(NH.getOffset()==0 && "folding did not make offset 0?");
415 NOffset = NH.getOffset();
416 NSize = NH.getNode()->getSize();
417 assert(NOffset == 0 && NSize == 1);
418 }
419 } else if (NH.getNode()->isNodeCompletelyFolded()) {
420 CurNodeH.getNode()->foldNodeCompletely();
421 assert(CurNodeH.getOffset()==0 && "folding did not make offset 0?");
422 NOffset = NH.getOffset();
423 NSize = NH.getNode()->getSize();
424 assert(NOffset == 0 && NSize == 1);
425 }
426
427 if (CurNodeH.getNode() == NH.getNode() || NH.getNode() == 0) return;
428 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
429
430 // Remove all edges pointing at N, causing them to point to 'this' instead.
431 // Make sure to adjust their offset, not just the node pointer.
432 // Also, be careful to use the DSNode* rather than NH since NH is one of
433 // the referrers and once NH refers to CurNodeH.getNode() this will
434 // become an infinite loop.
435 DSNode* N = NH.getNode();
436 unsigned OldNHOffset = NH.getOffset();
437 while (!N->Referrers.empty()) {
438 DSNodeHandle &Ref = *N->Referrers.back();
439 Ref = DSNodeHandle(CurNodeH.getNode(), NOffset+Ref.getOffset());
440 }
441 NH = DSNodeHandle(N, OldNHOffset); // reset NH to point back to where it was
442
443 assert((CurNodeH.getNode()->NodeType & DSNode::DEAD) == 0);
444
445 // Make all of the outgoing links of *NH now be outgoing links of
446 // this. This can cause recursive merging!
447 //
Chris Lattner6f6fef82003-01-22 22:00:24 +0000448 for (unsigned i = 0; i < NH.getNode()->getSize(); i += DS::PointerSize) {
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000449 DSNodeHandle &Link = NH.getNode()->getLink(i);
450 if (Link.getNode()) {
451 // Compute the offset into the current node at which to
452 // merge this link. In the common case, this is a linear
453 // relation to the offset in the original node (with
454 // wrapping), but if the current node gets collapsed due to
455 // recursive merging, we must make sure to merge in all remaining
456 // links at offset zero.
457 unsigned MergeOffset = 0;
458 if (CurNodeH.getNode()->Size != 1)
459 MergeOffset = (i+NOffset) % CurNodeH.getNode()->getSize();
460 CurNodeH.getNode()->addEdgeTo(MergeOffset, Link);
461 }
462 }
463
464 // Now that there are no outgoing edges, all of the Links are dead.
465 NH.getNode()->Links.clear();
466 NH.getNode()->Size = 0;
467 NH.getNode()->Ty = Type::VoidTy;
468
469 // Merge the node types
470 CurNodeH.getNode()->NodeType |= NH.getNode()->NodeType;
471 NH.getNode()->NodeType = DEAD; // NH is now a dead node.
472
473 // Merge the globals list...
474 if (!NH.getNode()->Globals.empty()) {
475 MergeSortedVectors(CurNodeH.getNode()->Globals, NH.getNode()->Globals);
476
477 // Delete the globals from the old node...
478 NH.getNode()->Globals.clear();
479 }
480}
481
482
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000483// mergeWith - Merge this node and the specified node, moving all links to and
484// from the argument node into the current node, deleting the node argument.
485// Offset indicates what offset the specified node is to be merged into the
486// current node.
487//
488// The specified node may be a null pointer (in which case, nothing happens).
489//
490void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
491 DSNode *N = NH.getNode();
492 if (N == 0 || (N == this && NH.getOffset() == Offset))
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000493 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000494
Chris Lattner679e8e12002-11-08 21:27:12 +0000495 assert((N->NodeType & DSNode::DEAD) == 0);
496 assert((NodeType & DSNode::DEAD) == 0);
497 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
498
Chris Lattner02606632002-11-04 06:48:26 +0000499 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000500 // We cannot merge two pieces of the same node together, collapse the node
501 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000502 DEBUG(std::cerr << "Attempting to merge two chunks of"
503 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000504 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000505 return;
506 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000507
Chris Lattner5190ce82002-11-12 07:20:45 +0000508 // If both nodes are not at offset 0, make sure that we are merging the node
509 // at an later offset into the node with the zero offset.
510 //
511 if (Offset < NH.getOffset()) {
512 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
513 return;
514 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
515 // If the offsets are the same, merge the smaller node into the bigger node
516 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
517 return;
518 }
519
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000520 // Ok, now we can merge the two nodes. Use a static helper that works with
521 // two node handles, since "this" may get merged away at intermediate steps.
522 DSNodeHandle CurNodeH(this, Offset);
523 DSNodeHandle NHCopy(NH);
524 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000525}
526
Chris Lattner9de906c2002-10-20 22:11:44 +0000527//===----------------------------------------------------------------------===//
528// DSCallSite Implementation
529//===----------------------------------------------------------------------===//
530
Vikram S. Adve26b98262002-10-20 21:41:02 +0000531// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +0000532Function &DSCallSite::getCaller() const {
Chris Lattner0969c502002-10-21 02:08:03 +0000533 return *Inst->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +0000534}
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000535
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000536
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000537//===----------------------------------------------------------------------===//
538// DSGraph Implementation
539//===----------------------------------------------------------------------===//
540
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000541DSGraph::DSGraph(const DSGraph &G) : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000542 PrintAuxCalls = false;
Chris Lattner41c04f72003-02-01 04:52:08 +0000543 hash_map<const DSNode*, DSNodeHandle> NodeMap;
Chris Lattnerc875f022002-11-03 21:27:48 +0000544 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000545}
546
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000547DSGraph::DSGraph(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000548 hash_map<const DSNode*, DSNodeHandle> &NodeMap)
Chris Lattner2e4f9bf2002-11-09 20:01:01 +0000549 : Func(G.Func), GlobalsGraph(0) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000550 PrintAuxCalls = false;
Chris Lattnerc875f022002-11-03 21:27:48 +0000551 RetNode = cloneInto(G, ScalarMap, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +0000552}
553
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000554DSGraph::~DSGraph() {
555 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +0000556 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +0000557 ScalarMap.clear();
Chris Lattner13ec72a2002-10-21 13:31:48 +0000558 RetNode.setNode(0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000559
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000560 // Drop all intra-node references, so that assertions don't fail...
561 std::for_each(Nodes.begin(), Nodes.end(),
562 std::mem_fun(&DSNode::dropAllReferences));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000563
564 // Delete all of the nodes themselves...
565 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
566}
567
Chris Lattner0d9bab82002-07-18 00:12:30 +0000568// dump - Allow inspection of graph in a debugger.
569void DSGraph::dump() const { print(std::cerr); }
570
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000571
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000572/// remapLinks - Change all of the Links in the current node according to the
573/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000574///
Chris Lattner41c04f72003-02-01 04:52:08 +0000575void DSNode::remapLinks(hash_map<const DSNode*, DSNodeHandle> &OldNodeMap) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000576 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
577 DSNodeHandle &H = OldNodeMap[Links[i].getNode()];
578 Links[i].setNode(H.getNode());
579 Links[i].setOffset(Links[i].getOffset()+H.getOffset());
580 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000581}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000582
Vikram S. Adve42fd1692002-10-20 18:07:37 +0000583
Chris Lattner0d9bab82002-07-18 00:12:30 +0000584// cloneInto - Clone the specified DSGraph into the current graph, returning the
Chris Lattnerc875f022002-11-03 21:27:48 +0000585// Return node of the graph. The translated ScalarMap for the old function is
Chris Lattner92673292002-11-02 00:13:20 +0000586// filled into the OldValMap member. If StripAllocas is set to true, Alloca
587// markers are removed from the graph, as the graph is being cloned into a
588// calling function's graph.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000589//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000590DSNodeHandle DSGraph::cloneInto(const DSGraph &G,
Chris Lattner41c04f72003-02-01 04:52:08 +0000591 hash_map<Value*, DSNodeHandle> &OldValMap,
592 hash_map<const DSNode*, DSNodeHandle> &OldNodeMap,
Chris Lattner679e8e12002-11-08 21:27:12 +0000593 unsigned CloneFlags) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000594 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +0000595 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +0000596
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000597 unsigned FN = Nodes.size(); // First new node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000598
599 // Duplicate all of the nodes, populating the node map...
600 Nodes.reserve(FN+G.Nodes.size());
601 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000602 DSNode *Old = G.Nodes[i];
603 DSNode *New = new DSNode(*Old);
Chris Lattner679e8e12002-11-08 21:27:12 +0000604 New->NodeType &= ~DSNode::DEAD; // Clear dead flag...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000605 Nodes.push_back(New);
Vikram S. Adve6aa0d622002-07-18 16:12:08 +0000606 OldNodeMap[Old] = New;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000607 }
608
Chris Lattner18552922002-11-18 21:44:46 +0000609#ifndef NDEBUG
610 Timer::addPeakMemoryMeasurement();
611#endif
612
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000613 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000614 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000615 Nodes[i]->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000616
Chris Lattner460ea292002-11-07 07:06:20 +0000617 // Remove alloca markers as specified
Vikram S. Adve61ff0292002-11-27 17:41:13 +0000618 if (CloneFlags & (StripAllocaBit | StripModRefBits)) {
619 unsigned short clearBits = (CloneFlags & StripAllocaBit
620 ? DSNode::AllocaNode : 0)
621 | (CloneFlags & StripModRefBits
622 ? (DSNode::Modified | DSNode::Read) : 0);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000623 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
Vikram S. Adve61ff0292002-11-27 17:41:13 +0000624 Nodes[i]->NodeType &= ~clearBits;
625 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000626
Chris Lattnercf15db32002-10-17 20:09:52 +0000627 // Copy the value map... and merge all of the global nodes...
Chris Lattner41c04f72003-02-01 04:52:08 +0000628 for (hash_map<Value*, DSNodeHandle>::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +0000629 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnercf15db32002-10-17 20:09:52 +0000630 DSNodeHandle &H = OldValMap[I->first];
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000631 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
632 H.setNode(MappedNode.getNode());
633 H.setOffset(I->second.getOffset()+MappedNode.getOffset());
Chris Lattnercf15db32002-10-17 20:09:52 +0000634
635 if (isa<GlobalValue>(I->first)) { // Is this a global?
Chris Lattner41c04f72003-02-01 04:52:08 +0000636 hash_map<Value*, DSNodeHandle>::iterator GVI = ScalarMap.find(I->first);
Chris Lattnerc875f022002-11-03 21:27:48 +0000637 if (GVI != ScalarMap.end()) { // Is the global value in this fn already?
Chris Lattnercf15db32002-10-17 20:09:52 +0000638 GVI->second.mergeWith(H);
639 } else {
Chris Lattnerc875f022002-11-03 21:27:48 +0000640 ScalarMap[I->first] = H; // Add global pointer to this graph
Chris Lattnercf15db32002-10-17 20:09:52 +0000641 }
642 }
643 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000644
Chris Lattner679e8e12002-11-08 21:27:12 +0000645 if (!(CloneFlags & DontCloneCallNodes)) {
646 // Copy the function calls list...
647 unsigned FC = FunctionCalls.size(); // FirstCall
648 FunctionCalls.reserve(FC+G.FunctionCalls.size());
649 for (unsigned i = 0, ei = G.FunctionCalls.size(); i != ei; ++i)
650 FunctionCalls.push_back(DSCallSite(G.FunctionCalls[i], OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +0000651 }
Chris Lattner679e8e12002-11-08 21:27:12 +0000652
Chris Lattneracf491f2002-11-08 22:27:09 +0000653 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattner679e8e12002-11-08 21:27:12 +0000654 // Copy the auxillary function calls list...
Chris Lattneracf491f2002-11-08 22:27:09 +0000655 unsigned FC = AuxFunctionCalls.size(); // FirstCall
Chris Lattner679e8e12002-11-08 21:27:12 +0000656 AuxFunctionCalls.reserve(FC+G.AuxFunctionCalls.size());
657 for (unsigned i = 0, ei = G.AuxFunctionCalls.size(); i != ei; ++i)
658 AuxFunctionCalls.push_back(DSCallSite(G.AuxFunctionCalls[i], OldNodeMap));
659 }
Chris Lattnercf15db32002-10-17 20:09:52 +0000660
Chris Lattner0d9bab82002-07-18 00:12:30 +0000661 // Return the returned node pointer...
Chris Lattnerf8c6aab2002-11-08 05:01:14 +0000662 DSNodeHandle &MappedRet = OldNodeMap[G.RetNode.getNode()];
663 return DSNodeHandle(MappedRet.getNode(),
664 MappedRet.getOffset()+G.RetNode.getOffset());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000665}
666
Chris Lattner076c1f92002-11-07 06:31:54 +0000667/// mergeInGraph - The method is used for merging graphs together. If the
668/// argument graph is not *this, it makes a clone of the specified graph, then
669/// merges the nodes specified in the call site with the formal arguments in the
670/// graph.
671///
672void DSGraph::mergeInGraph(DSCallSite &CS, const DSGraph &Graph,
Chris Lattner679e8e12002-11-08 21:27:12 +0000673 unsigned CloneFlags) {
Chris Lattner41c04f72003-02-01 04:52:08 +0000674 hash_map<Value*, DSNodeHandle> OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000675 DSNodeHandle RetVal;
Chris Lattner41c04f72003-02-01 04:52:08 +0000676 hash_map<Value*, DSNodeHandle> *ScalarMap = &OldValMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000677
678 // If this is not a recursive call, clone the graph into this graph...
679 if (&Graph != this) {
680 // Clone the callee's graph into the current graph, keeping
681 // track of where scalars in the old graph _used_ to point,
682 // and of the new nodes matching nodes of the old graph.
Chris Lattner41c04f72003-02-01 04:52:08 +0000683 hash_map<const DSNode*, DSNodeHandle> OldNodeMap;
Chris Lattner076c1f92002-11-07 06:31:54 +0000684
685 // The clone call may invalidate any of the vectors in the data
686 // structure graph. Strip locals and don't copy the list of callers
Chris Lattner679e8e12002-11-08 21:27:12 +0000687 RetVal = cloneInto(Graph, OldValMap, OldNodeMap, CloneFlags);
Chris Lattner076c1f92002-11-07 06:31:54 +0000688 ScalarMap = &OldValMap;
689 } else {
690 RetVal = getRetNode();
691 ScalarMap = &getScalarMap();
692 }
693
694 // Merge the return value with the return value of the context...
695 RetVal.mergeWith(CS.getRetVal());
696
697 // Resolve all of the function arguments...
698 Function &F = Graph.getFunction();
699 Function::aiterator AI = F.abegin();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000700
Chris Lattner076c1f92002-11-07 06:31:54 +0000701 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i, ++AI) {
702 // Advance the argument iterator to the first pointer argument...
703 while (!isPointerType(AI->getType())) {
704 ++AI;
705#ifndef NDEBUG
706 if (AI == F.aend())
707 std::cerr << "Bad call to Function: " << F.getName() << "\n";
708#endif
709 assert(AI != F.aend() && "# Args provided is not # Args required!");
710 }
711
712 // Add the link from the argument scalar to the provided value
713 DSNodeHandle &NH = (*ScalarMap)[AI];
714 assert(NH.getNode() && "Pointer argument without scalarmap entry?");
715 NH.mergeWith(CS.getPtrArg(i));
716 }
717}
718
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000719#if 0
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000720// cloneGlobalInto - Clone the given global node and all its target links
721// (and all their llinks, recursively).
722//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000723DSNode *DSGraph::cloneGlobalInto(const DSNode *GNode) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000724 if (GNode == 0 || GNode->getGlobals().size() == 0) return 0;
725
726 // If a clone has already been created for GNode, return it.
Chris Lattnerc875f022002-11-03 21:27:48 +0000727 DSNodeHandle& ValMapEntry = ScalarMap[GNode->getGlobals()[0]];
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000728 if (ValMapEntry != 0)
729 return ValMapEntry;
730
731 // Clone the node and update the ValMap.
732 DSNode* NewNode = new DSNode(*GNode);
733 ValMapEntry = NewNode; // j=0 case of loop below!
734 Nodes.push_back(NewNode);
735 for (unsigned j = 1, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +0000736 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000737
738 // Rewrite the links in the new node to point into the current graph.
739 for (unsigned j = 0, e = GNode->getNumLinks(); j != e; ++j)
740 NewNode->setLink(j, cloneGlobalInto(GNode->getLink(j)));
741
742 return NewNode;
743}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000744#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000745
746
Chris Lattner0d9bab82002-07-18 00:12:30 +0000747// markIncompleteNodes - Mark the specified node as having contents that are not
748// known with the current analysis we have performed. Because a node makes all
749// of the nodes it can reach imcomplete if the node itself is incomplete, we
750// must recursively traverse the data structure graph, marking all reachable
751// nodes as incomplete.
752//
753static void markIncompleteNode(DSNode *N) {
754 // Stop recursion if no node, or if node already marked...
755 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
756
757 // Actually mark the node
758 N->NodeType |= DSNode::Incomplete;
759
760 // Recusively process children...
Chris Lattner08db7192002-11-06 06:20:27 +0000761 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
762 if (DSNode *DSN = N->getLink(i).getNode())
763 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000764}
765
Chris Lattnere71ffc22002-11-11 03:36:55 +0000766static void markIncomplete(DSCallSite &Call) {
767 // Then the return value is certainly incomplete!
768 markIncompleteNode(Call.getRetVal().getNode());
769
770 // All objects pointed to by function arguments are incomplete!
771 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
772 markIncompleteNode(Call.getPtrArg(i).getNode());
773}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000774
775// markIncompleteNodes - Traverse the graph, identifying nodes that may be
776// modified by other functions that have not been resolved yet. This marks
777// nodes that are reachable through three sources of "unknownness":
778//
779// Global Variables, Function Calls, and Incoming Arguments
780//
781// For any node that may have unknown components (because something outside the
782// scope of current analysis may have modified it), the 'Incomplete' flag is
783// added to the NodeType.
784//
Chris Lattner394471f2003-01-23 22:05:33 +0000785void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000786 // Mark any incoming arguments as incomplete...
Chris Lattner394471f2003-01-23 22:05:33 +0000787 if ((Flags & DSGraph::MarkFormalArgs) && Func)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000788 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I != E; ++I)
Chris Lattnerc875f022002-11-03 21:27:48 +0000789 if (isPointerType(I->getType()) && ScalarMap.find(I) != ScalarMap.end())
790 markIncompleteNode(ScalarMap[I].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +0000791
792 // Mark stuff passed into functions calls as being incomplete...
Chris Lattnere71ffc22002-11-11 03:36:55 +0000793 if (!shouldPrintAuxCalls())
794 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
795 markIncomplete(FunctionCalls[i]);
796 else
797 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
798 markIncomplete(AuxFunctionCalls[i]);
799
Chris Lattner0d9bab82002-07-18 00:12:30 +0000800
Chris Lattner92673292002-11-02 00:13:20 +0000801 // Mark all of the nodes pointed to by global nodes as incomplete...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000802 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000803 if (Nodes[i]->NodeType & DSNode::GlobalNode) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000804 DSNode *N = Nodes[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000805 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
806 if (DSNode *DSN = N->getLink(i).getNode())
807 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000808 }
809}
810
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000811// removeRefsToGlobal - Helper function that removes globals from the
Chris Lattnerc875f022002-11-03 21:27:48 +0000812// ScalarMap so that the referrer count will go down to zero.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000813static void removeRefsToGlobal(DSNode* N,
Chris Lattner41c04f72003-02-01 04:52:08 +0000814 hash_map<Value*, DSNodeHandle> &ScalarMap) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000815 while (!N->getGlobals().empty()) {
816 GlobalValue *GV = N->getGlobals().back();
817 N->getGlobals().pop_back();
Chris Lattnerc875f022002-11-03 21:27:48 +0000818 ScalarMap.erase(GV);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000819 }
820}
821
822
Chris Lattner0d9bab82002-07-18 00:12:30 +0000823// isNodeDead - This method checks to see if a node is dead, and if it isn't, it
824// checks to see if there are simple transformations that it can do to make it
825// dead.
826//
827bool DSGraph::isNodeDead(DSNode *N) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000828 // Is it a trivially dead shadow node?
Chris Lattnerd11e9542002-11-10 07:46:08 +0000829 return N->getReferrers().empty() && (N->NodeType & ~DSNode::DEAD) == 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000830}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000831
Chris Lattneraa8146f2002-11-10 06:59:55 +0000832static inline void killIfUselessEdge(DSNodeHandle &Edge) {
833 if (DSNode *N = Edge.getNode()) // Is there an edge?
834 if (N->getReferrers().size() == 1) // Does it point to a lonely node?
835 if ((N->NodeType & ~DSNode::Incomplete) == 0 && // No interesting info?
Chris Lattner18552922002-11-18 21:44:46 +0000836 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattneraa8146f2002-11-10 06:59:55 +0000837 Edge.setNode(0); // Kill the edge!
838}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000839
Chris Lattneraa8146f2002-11-10 06:59:55 +0000840static inline bool nodeContainsExternalFunction(const DSNode *N) {
841 const std::vector<GlobalValue*> &Globals = N->getGlobals();
842 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
843 if (Globals[i]->isExternal())
844 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000845 return false;
846}
847
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000848static void removeIdenticalCalls(std::vector<DSCallSite> &Calls,
Chris Lattner7541b892002-07-31 19:32:12 +0000849 const std::string &where) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000850 // Remove trivially identical function calls
851 unsigned NumFns = Calls.size();
Chris Lattneraa8146f2002-11-10 06:59:55 +0000852 std::sort(Calls.begin(), Calls.end()); // Sort by callee as primary key!
853
854 // Scan the call list cleaning it up as necessary...
855 DSNode *LastCalleeNode = 0;
856 unsigned NumDuplicateCalls = 0;
857 bool LastCalleeContainsExternalFunction = false;
Chris Lattnere4258442002-11-11 21:35:38 +0000858 for (unsigned i = 0; i != Calls.size(); ++i) {
Chris Lattneraa8146f2002-11-10 06:59:55 +0000859 DSCallSite &CS = Calls[i];
860
Chris Lattnere4258442002-11-11 21:35:38 +0000861 // If the Callee is a useless edge, this must be an unreachable call site,
862 // eliminate it.
863 killIfUselessEdge(CS.getCallee());
864 if (CS.getCallee().getNode() == 0) {
865 CS.swap(Calls.back());
866 Calls.pop_back();
867 --i;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000868 } else {
Chris Lattnere4258442002-11-11 21:35:38 +0000869 // If the return value or any arguments point to a void node with no
870 // information at all in it, and the call node is the only node to point
871 // to it, remove the edge to the node (killing the node).
872 //
873 killIfUselessEdge(CS.getRetVal());
874 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
875 killIfUselessEdge(CS.getPtrArg(a));
876
877 // If this call site calls the same function as the last call site, and if
878 // the function pointer contains an external function, this node will
879 // never be resolved. Merge the arguments of the call node because no
880 // information will be lost.
881 //
882 if (CS.getCallee().getNode() == LastCalleeNode) {
883 ++NumDuplicateCalls;
884 if (NumDuplicateCalls == 1) {
885 LastCalleeContainsExternalFunction =
886 nodeContainsExternalFunction(LastCalleeNode);
887 }
888
889 if (LastCalleeContainsExternalFunction ||
890 // This should be more than enough context sensitivity!
891 // FIXME: Evaluate how many times this is tripped!
892 NumDuplicateCalls > 20) {
893 DSCallSite &OCS = Calls[i-1];
894 OCS.mergeWith(CS);
895
896 // The node will now be eliminated as a duplicate!
897 if (CS.getNumPtrArgs() < OCS.getNumPtrArgs())
898 CS = OCS;
899 else if (CS.getNumPtrArgs() > OCS.getNumPtrArgs())
900 OCS = CS;
901 }
902 } else {
903 LastCalleeNode = CS.getCallee().getNode();
904 NumDuplicateCalls = 0;
905 }
Chris Lattneraa8146f2002-11-10 06:59:55 +0000906 }
907 }
908
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000909 Calls.erase(std::unique(Calls.begin(), Calls.end()),
910 Calls.end());
911
Chris Lattner33312f72002-11-08 01:21:07 +0000912 // Track the number of call nodes merged away...
913 NumCallNodesMerged += NumFns-Calls.size();
914
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000915 DEBUG(if (NumFns != Calls.size())
Chris Lattner7541b892002-07-31 19:32:12 +0000916 std::cerr << "Merged " << (NumFns-Calls.size())
917 << " call nodes in " << where << "\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000918}
Chris Lattner0d9bab82002-07-18 00:12:30 +0000919
Chris Lattneraa8146f2002-11-10 06:59:55 +0000920
Chris Lattnere2219762002-07-18 18:22:40 +0000921// removeTriviallyDeadNodes - After the graph has been constructed, this method
922// removes all unreachable nodes that are created because they got merged with
923// other nodes in the graph. These nodes will all be trivially unreachable, so
924// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +0000925//
Chris Lattnerf40f0a32002-11-09 22:07:02 +0000926void DSGraph::removeTriviallyDeadNodes() {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000927 removeIdenticalCalls(FunctionCalls, Func ? Func->getName() : "");
Chris Lattneraa8146f2002-11-10 06:59:55 +0000928 removeIdenticalCalls(AuxFunctionCalls, Func ? Func->getName() : "");
929
930 for (unsigned i = 0; i != Nodes.size(); ++i)
931 if (isNodeDead(Nodes[i])) { // This node is dead!
932 delete Nodes[i]; // Free memory...
933 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
934 }
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 Lattner41c04f72003-02-01 04:52:08 +0000944 if (ReachableNodes.count(this)) return; // Already marked reachable
945 ReachableNodes.insert(this); // Is reachable now
Chris Lattnere2219762002-07-18 18:22:40 +0000946
Chris Lattner5c7380e2003-01-29 21:10:20 +0000947 for (unsigned i = 0, e = getSize(); i < e; i += DS::PointerSize)
948 getLink(i).getNode()->markReachableNodes(ReachableNodes);
949}
950
Chris Lattner41c04f72003-02-01 04:52:08 +0000951void DSCallSite::markReachableNodes(hash_set<DSNode*> &Nodes) {
Chris Lattner5c7380e2003-01-29 21:10:20 +0000952 getRetVal().getNode()->markReachableNodes(Nodes);
953 getCallee().getNode()->markReachableNodes(Nodes);
954
955 for (unsigned j = 0, e = getNumPtrArgs(); j != e; ++j)
956 getPtrArg(j).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +0000957}
958
Chris Lattnera1220af2003-02-01 06:17:02 +0000959// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
960// looking for a node that is marked alive. If an alive node is found, return
961// true, otherwise return false. If an alive node is reachable, this node is
962// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000963//
Chris Lattnera1220af2003-02-01 06:17:02 +0000964static bool CanReachAliveNodes(DSNode *N, hash_set<DSNode*> &Alive,
965 hash_set<DSNode*> &Visited) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000966 if (N == 0) return false;
967
Chris Lattneraa8146f2002-11-10 06:59:55 +0000968 // If we know that this node is alive, return so!
969 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000970
Chris Lattneraa8146f2002-11-10 06:59:55 +0000971 // Otherwise, we don't think the node is alive yet, check for infinite
972 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +0000973 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +0000974 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +0000975
976 if (N->NodeType & DSNode::GlobalNode)
977 return false; // Global nodes will be marked on their own
978
Chris Lattner08db7192002-11-06 06:20:27 +0000979 for (unsigned i = 0, e = N->getSize(); i < e; i += DS::PointerSize)
Chris Lattnera1220af2003-02-01 06:17:02 +0000980 if (CanReachAliveNodes(N->getLink(i).getNode(), Alive, Visited)) {
981 N->markReachableNodes(Alive);
982 return true;
983 }
984 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +0000985}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000986
Chris Lattnera1220af2003-02-01 06:17:02 +0000987// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
988// alive nodes.
989//
Chris Lattner41c04f72003-02-01 04:52:08 +0000990static bool CallSiteUsesAliveArgs(DSCallSite &CS, hash_set<DSNode*> &Alive,
991 hash_set<DSNode*> &Visited) {
Chris Lattnera1220af2003-02-01 06:17:02 +0000992 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited) ||
993 CanReachAliveNodes(CS.getCallee().getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000994 return true;
995 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
Chris Lattnera1220af2003-02-01 06:17:02 +0000996 if (CanReachAliveNodes(CS.getPtrArg(j).getNode(), Alive, Visited))
Chris Lattneraa8146f2002-11-10 06:59:55 +0000997 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +0000998 return false;
999}
1000
Chris Lattner100f8722003-01-31 23:57:36 +00001001// GlobalIsAlivenessRoot - Return true if the specified global node is
1002// intrinsically alive in the context of the current graph (ie, it is a root of
1003// aliveness). For TD graphs, no globals are. For the BU graphs all are unless
1004// they are trivial globals...
1005//
1006static bool GlobalIsAlivenessRoot(DSNode *N, unsigned Flags) {
1007 if (Flags & DSGraph::RemoveUnreachableGlobals)
1008 return false; // If we are to remove all globals, go for it.
1009
1010 // Ok, we are keeping globals... hrm, we can still delete it if it has no
1011 // links, and no mod/ref or other info... If it is not modified, it can't
1012 // have links...
1013 //
1014 if ((N->NodeType & ~(DSNode::Composition | DSNode::Array)) == 0)
1015 return false;
1016 return true;
1017}
1018
Chris Lattnere2219762002-07-18 18:22:40 +00001019// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1020// subgraphs that are unreachable. This often occurs because the data
1021// structure doesn't "escape" into it's caller, and thus should be eliminated
1022// from the caller's graph entirely. This is only appropriate to use when
1023// inlining graphs.
1024//
Chris Lattner394471f2003-01-23 22:05:33 +00001025void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattnere2219762002-07-18 18:22:40 +00001026 // Reduce the amount of work we have to do...
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001027 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001028
Chris Lattnere2219762002-07-18 18:22:40 +00001029 // FIXME: Merge nontrivially identical call nodes...
1030
1031 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattner41c04f72003-02-01 04:52:08 +00001032 hash_set<DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001033 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001034
Chris Lattneraa8146f2002-11-10 06:59:55 +00001035 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattner41c04f72003-02-01 04:52:08 +00001036 for (hash_map<Value*, DSNodeHandle>::iterator I = ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001037 E = ScalarMap.end(); I != E; ++I)
Chris Lattner100f8722003-01-31 23:57:36 +00001038 if (!isa<GlobalValue>(I->first) ||
1039 GlobalIsAlivenessRoot(I->second.getNode(), Flags))
Chris Lattner5c7380e2003-01-29 21:10:20 +00001040 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner394471f2003-01-23 22:05:33 +00001041 else // Keep track of global nodes
1042 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattnere2219762002-07-18 18:22:40 +00001043
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001044 // The return value is alive as well...
Chris Lattner5c7380e2003-01-29 21:10:20 +00001045 RetNode.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001046
Chris Lattneraa8146f2002-11-10 06:59:55 +00001047 // If any global nodes points to a non-global that is "alive", the global is
1048 // "alive" as well...
1049 //
Chris Lattner41c04f72003-02-01 04:52:08 +00001050 hash_set<DSNode*> Visited;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001051 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Chris Lattnera1220af2003-02-01 06:17:02 +00001052 CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001053
1054 std::vector<bool> FCallsAlive(FunctionCalls.size());
1055 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
Chris Lattner100f8722003-01-31 23:57:36 +00001056 if (!(Flags & DSGraph::RemoveUnreachableGlobals) ||
1057 CallSiteUsesAliveArgs(FunctionCalls[i], Alive, Visited)) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001058 FunctionCalls[i].markReachableNodes(Alive);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001059 FCallsAlive[i] = true;
1060 }
1061
1062 std::vector<bool> AuxFCallsAlive(AuxFunctionCalls.size());
1063 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1064 if (CallSiteUsesAliveArgs(AuxFunctionCalls[i], Alive, Visited)) {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001065 AuxFunctionCalls[i].markReachableNodes(Alive);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001066 AuxFCallsAlive[i] = true;
1067 }
1068
1069 // Remove all dead function calls...
1070 unsigned CurIdx = 0;
1071 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
1072 if (FCallsAlive[i])
1073 FunctionCalls[CurIdx++].swap(FunctionCalls[i]);
1074 // Crop all the bad ones out...
1075 FunctionCalls.erase(FunctionCalls.begin()+CurIdx, FunctionCalls.end());
1076
1077 // Remove all dead aux function calls...
1078 CurIdx = 0;
1079 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
1080 if (AuxFCallsAlive[i])
1081 AuxFunctionCalls[CurIdx++].swap(AuxFunctionCalls[i]);
1082 // Crop all the bad ones out...
1083 AuxFunctionCalls.erase(AuxFunctionCalls.begin()+CurIdx,
1084 AuxFunctionCalls.end());
1085
1086
1087 // Remove all unreachable globals from the ScalarMap
1088 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
1089 if (!Alive.count(GlobalNodes[i].second))
1090 ScalarMap.erase(GlobalNodes[i].first);
1091
Chris Lattnere2219762002-07-18 18:22:40 +00001092 // Loop over all unreachable nodes, dropping their references...
Chris Lattnere2219762002-07-18 18:22:40 +00001093 for (unsigned i = 0; i != Nodes.size(); ++i)
1094 if (!Alive.count(Nodes[i])) {
1095 DSNode *N = Nodes[i];
Chris Lattner5e7d0e22003-02-01 06:23:33 +00001096 std::swap(Nodes[i--], Nodes.back()); // move node to end of vector
1097 Nodes.pop_back(); // Erase node from alive list.
Chris Lattnere2219762002-07-18 18:22:40 +00001098 N->dropAllReferences(); // Drop all outgoing edges
Chris Lattnerd4400c82003-02-01 06:41:15 +00001099
1100 while (!N->getReferrers().empty())
1101 N->getReferrers().back()->setNode(0);
1102 delete N;
Chris Lattnere2219762002-07-18 18:22:40 +00001103 }
Chris Lattnere2219762002-07-18 18:22:40 +00001104}
1105
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001106#if 0
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001107//===----------------------------------------------------------------------===//
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001108// GlobalDSGraph Implementation
1109//===----------------------------------------------------------------------===//
1110
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001111#if 0
Chris Lattnerd18f3422002-11-03 21:24:04 +00001112// Bits used in the next function
1113static const char ExternalTypeBits = DSNode::GlobalNode | DSNode::HeapNode;
1114
1115
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001116// GlobalDSGraph::cloneNodeInto - Clone a global node and all its externally
1117// visible target links (and recursively their such links) into this graph.
1118// NodeCache maps the node being cloned to its clone in the Globals graph,
1119// in order to track cycles.
1120// GlobalsAreFinal is a flag that says whether it is safe to assume that
1121// an existing global node is complete. This is important to avoid
1122// reinserting all globals when inserting Calls to functions.
1123// This is a helper function for cloneGlobals and cloneCalls.
1124//
1125DSNode* GlobalDSGraph::cloneNodeInto(DSNode *OldNode,
Chris Lattner41c04f72003-02-01 04:52:08 +00001126 hash_map<const DSNode*, DSNode*> &NodeCache,
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001127 bool GlobalsAreFinal) {
1128 if (OldNode == 0) return 0;
1129
1130 // The caller should check this is an external node. Just more efficient...
1131 assert((OldNode->NodeType & ExternalTypeBits) && "Non-external node");
1132
1133 // If a clone has already been created for OldNode, return it.
1134 DSNode*& CacheEntry = NodeCache[OldNode];
1135 if (CacheEntry != 0)
1136 return CacheEntry;
1137
1138 // The result value...
1139 DSNode* NewNode = 0;
1140
1141 // If nodes already exist for any of the globals of OldNode,
1142 // merge all such nodes together since they are merged in OldNode.
1143 // If ValueCacheIsFinal==true, look for an existing node that has
1144 // an identical list of globals and return it if it exists.
1145 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001146 for (unsigned j = 0, N = OldNode->getGlobals().size(); j != N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001147 if (DSNode *PrevNode = ScalarMap[OldNode->getGlobals()[j]].getNode()) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001148 if (NewNode == 0) {
1149 NewNode = PrevNode; // first existing node found
1150 if (GlobalsAreFinal && j == 0)
1151 if (OldNode->getGlobals() == PrevNode->getGlobals()) {
1152 CacheEntry = NewNode;
1153 return NewNode;
1154 }
1155 }
1156 else if (NewNode != PrevNode) { // found another, different from prev
1157 // update ValMap *before* merging PrevNode into NewNode
1158 for (unsigned k = 0, NK = PrevNode->getGlobals().size(); k < NK; ++k)
Chris Lattnerc875f022002-11-03 21:27:48 +00001159 ScalarMap[PrevNode->getGlobals()[k]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001160 NewNode->mergeWith(PrevNode);
1161 }
1162 } else if (NewNode != 0) {
Chris Lattnerc875f022002-11-03 21:27:48 +00001163 ScalarMap[OldNode->getGlobals()[j]] = NewNode; // add the merged node
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001164 }
1165
1166 // If no existing node was found, clone the node and update the ValMap.
1167 if (NewNode == 0) {
1168 NewNode = new DSNode(*OldNode);
1169 Nodes.push_back(NewNode);
1170 for (unsigned j = 0, e = NewNode->getNumLinks(); j != e; ++j)
1171 NewNode->setLink(j, 0);
1172 for (unsigned j = 0, N = NewNode->getGlobals().size(); j < N; ++j)
Chris Lattnerc875f022002-11-03 21:27:48 +00001173 ScalarMap[NewNode->getGlobals()[j]] = NewNode;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001174 }
1175 else
1176 NewNode->NodeType |= OldNode->NodeType; // Markers may be different!
1177
1178 // Add the entry to NodeCache
1179 CacheEntry = NewNode;
1180
1181 // Rewrite the links in the new node to point into the current graph,
1182 // but only for links to external nodes. Set other links to NULL.
1183 for (unsigned j = 0, e = OldNode->getNumLinks(); j != e; ++j) {
1184 DSNode* OldTarget = OldNode->getLink(j);
1185 if (OldTarget && (OldTarget->NodeType & ExternalTypeBits)) {
1186 DSNode* NewLink = this->cloneNodeInto(OldTarget, NodeCache);
1187 if (NewNode->getLink(j))
1188 NewNode->getLink(j)->mergeWith(NewLink);
1189 else
1190 NewNode->setLink(j, NewLink);
1191 }
1192 }
1193
1194 // Remove all local markers
1195 NewNode->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
1196
1197 return NewNode;
1198}
1199
1200
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001201// GlobalDSGraph::cloneCalls - Clone function calls and their visible target
1202// links (and recursively their such links) into this graph.
1203//
1204void GlobalDSGraph::cloneCalls(DSGraph& Graph) {
Chris Lattner41c04f72003-02-01 04:52:08 +00001205 hash_map<const DSNode*, DSNode*> NodeCache;
Chris Lattnerb3416bc2003-02-01 04:01:21 +00001206 std::vector<DSCallSite >& FromCalls =Graph.FunctionCalls;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001207
1208 FunctionCalls.reserve(FunctionCalls.size() + FromCalls.size());
1209
1210 for (int i = 0, ei = FromCalls.size(); i < ei; ++i) {
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001211 DSCallSite& callCopy = FunctionCalls.back();
1212 callCopy.reserve(FromCalls[i].size());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001213 for (unsigned j = 0, ej = FromCalls[i].size(); j != ej; ++j)
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001214 callCopy.push_back
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001215 ((FromCalls[i][j] && (FromCalls[i][j]->NodeType & ExternalTypeBits))
1216 ? cloneNodeInto(FromCalls[i][j], NodeCache, true)
1217 : 0);
1218 }
1219
1220 // remove trivially identical function calls
Chris Lattner7541b892002-07-31 19:32:12 +00001221 removeIdenticalCalls(FunctionCalls, "Globals Graph");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001222}
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001223#endif
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001224
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001225#endif