blob: 416766b166cb19493293b9f3ab60b82976815cc4 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +00009//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000010// This file implements the core data structure functionality.
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner4dabb2c2004-07-07 06:32:21 +000014#include "llvm/Analysis/DataStructure/DSGraphTraits.h"
Chris Lattner94f84702005-03-17 19:56:56 +000015#include "llvm/Constants.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000016#include "llvm/Function.h"
Chris Lattnercf14e712004-02-25 23:36:08 +000017#include "llvm/GlobalVariable.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000018#include "llvm/Instructions.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000019#include "llvm/DerivedTypes.h"
Chris Lattner7b7200c2002-10-02 04:57:39 +000020#include "llvm/Target/TargetData.h"
Chris Lattner58f98d02003-07-02 04:38:49 +000021#include "llvm/Assembly/Writer.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Timer.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000028#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000031#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
32
Chris Lattner08db7192002-11-06 06:20:27 +000033namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000034 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
35 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
36 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
37 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000038 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
39 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000040};
41
Chris Lattnera88a55c2004-01-28 02:41:32 +000042#if 1
Chris Lattner93ddd7e2004-01-22 16:36:28 +000043#define TIME_REGION(VARNAME, DESC) \
44 NamedRegionTimer VARNAME(DESC)
45#else
46#define TIME_REGION(VARNAME, DESC)
47#endif
48
Chris Lattnerb1060432002-11-07 05:20:53 +000049using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000050
Chris Lattner6f967742004-10-30 04:05:01 +000051/// isForwarding - Return true if this NodeHandle is forwarding to another
52/// one.
53bool DSNodeHandle::isForwarding() const {
54 return N && N->isForwarding();
55}
56
Chris Lattner731b2d72003-02-13 19:09:00 +000057DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000058 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000059
60 // Handle node forwarding here!
61 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
62 Offset += N->ForwardNH.getOffset();
63
64 if (--N->NumReferrers == 0) {
65 // Removing the last referrer to the node, sever the forwarding link
66 N->stopForwarding();
67 }
68
69 N = Next;
70 N->NumReferrers++;
71 if (N->Size <= Offset) {
72 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
73 Offset = 0;
74 }
75 return N;
76}
77
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000078//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +000079// DSNode Implementation
80//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000081
Chris Lattnerbd92b732003-06-19 21:15:11 +000082DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +000083 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +000084 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +000085 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +000086 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +000087 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000088}
89
Chris Lattner0d9bab82002-07-18 00:12:30 +000090// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +000091DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +000092 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattnerf590ced2004-03-04 17:06:53 +000093 Ty(N.Ty), NodeType(N.NodeType) {
94 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +000095 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +000096 Globals = N.Globals;
97 } else
Chris Lattner0b144872004-01-27 22:03:40 +000098 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +000099 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000100 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000101}
102
Chris Lattner15869aa2003-11-02 22:27:28 +0000103/// getTargetData - Get the target data object used to construct this node.
104///
105const TargetData &DSNode::getTargetData() const {
106 return ParentGraph->getTargetData();
107}
108
Chris Lattner72d29a42003-02-11 23:11:51 +0000109void DSNode::assertOK() const {
110 assert((Ty != Type::VoidTy ||
111 Ty == Type::VoidTy && (Size == 0 ||
112 (NodeType & DSNode::Array))) &&
113 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000114
115 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000116 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000117 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000118 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000119 assert(SM.find(Globals[i])->second.getNode() == this);
120 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000121}
122
123/// forwardNode - Mark this node as being obsolete, and all references to it
124/// should be forwarded to the specified node and offset.
125///
126void DSNode::forwardNode(DSNode *To, unsigned Offset) {
127 assert(this != To && "Cannot forward a node to itself!");
128 assert(ForwardNH.isNull() && "Already forwarding from this node!");
129 if (To->Size <= 1) Offset = 0;
130 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
131 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000132 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000133 NodeType = DEAD;
134 Size = 0;
135 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000136
137 // Remove this node from the parent graph's Nodes list.
138 ParentGraph->unlinkNode(this);
139 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000140}
141
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000142// addGlobal - Add an entry for a global value to the Globals list. This also
143// marks the node with the 'G' flag if it does not already have it.
144//
145void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000146 // First, check to make sure this is the leader if the global is in an
147 // equivalence class.
148 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
149
Chris Lattner0d9bab82002-07-18 00:12:30 +0000150 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000151 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000152 std::lower_bound(Globals.begin(), Globals.end(), GV);
153
154 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000155 Globals.insert(I, GV);
156 NodeType |= GlobalNode;
157 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000158}
159
Chris Lattner7cdf3212005-03-20 03:29:54 +0000160// removeGlobal - Remove the specified global that is explicitly in the globals
161// list.
162void DSNode::removeGlobal(GlobalValue *GV) {
163 std::vector<GlobalValue*>::iterator I =
164 std::lower_bound(Globals.begin(), Globals.end(), GV);
165 assert(I != Globals.end() && *I == GV && "Global not in node!");
166 Globals.erase(I);
167}
168
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000169/// foldNodeCompletely - If we determine that this node has some funny
170/// behavior happening to it that we cannot represent, we fold it down to a
171/// single, completely pessimistic, node. This node is represented as a
172/// single byte with a single TypeEntry of "void".
173///
174void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000175 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000176
Chris Lattner08db7192002-11-06 06:20:27 +0000177 ++NumFolds;
178
Chris Lattner0b144872004-01-27 22:03:40 +0000179 // If this node has a size that is <= 1, we don't need to create a forwarding
180 // node.
181 if (getSize() <= 1) {
182 NodeType |= DSNode::Array;
183 Ty = Type::VoidTy;
184 Size = 1;
185 assert(Links.size() <= 1 && "Size is 1, but has more links?");
186 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000187 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000188 // Create the node we are going to forward to. This is required because
189 // some referrers may have an offset that is > 0. By forcing them to
190 // forward, the forwarder has the opportunity to correct the offset.
191 DSNode *DestNode = new DSNode(0, ParentGraph);
192 DestNode->NodeType = NodeType|DSNode::Array;
193 DestNode->Ty = Type::VoidTy;
194 DestNode->Size = 1;
195 DestNode->Globals.swap(Globals);
196
197 // Start forwarding to the destination node...
198 forwardNode(DestNode, 0);
199
200 if (!Links.empty()) {
201 DestNode->Links.reserve(1);
202
203 DSNodeHandle NH(DestNode);
204 DestNode->Links.push_back(Links[0]);
205
206 // If we have links, merge all of our outgoing links together...
207 for (unsigned i = Links.size()-1; i != 0; --i)
208 NH.getNode()->Links[0].mergeWith(Links[i]);
209 Links.clear();
210 } else {
211 DestNode->Links.resize(1);
212 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000213 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000214}
Chris Lattner076c1f92002-11-07 06:31:54 +0000215
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000216/// isNodeCompletelyFolded - Return true if this node has been completely
217/// folded down to something that can never be expanded, effectively losing
218/// all of the field sensitivity that may be present in the node.
219///
220bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000221 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000222}
223
Chris Lattner82c6c722005-03-20 02:41:38 +0000224/// addFullGlobalsList - Compute the full set of global values that are
225/// represented by this node. Unlike getGlobalsList(), this requires fair
226/// amount of work to compute, so don't treat this method call as free.
227void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
228 if (globals_begin() == globals_end()) return;
229
230 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
231
232 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
233 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
234 if (ECI == EC.end())
235 List.push_back(*I);
236 else
237 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
238 }
239}
240
241/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
242/// functions in the full list.
243void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
244 if (globals_begin() == globals_end()) return;
245
246 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
247
248 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
249 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
250 if (ECI == EC.end()) {
251 if (Function *F = dyn_cast<Function>(*I))
252 List.push_back(F);
253 } else {
254 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
255 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
256 if (Function *F = dyn_cast<Function>(*MI))
257 List.push_back(F);
258 }
259 }
260}
261
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000262namespace {
263 /// TypeElementWalker Class - Used for implementation of physical subtyping...
264 ///
265 class TypeElementWalker {
266 struct StackState {
267 const Type *Ty;
268 unsigned Offset;
269 unsigned Idx;
270 StackState(const Type *T, unsigned Off = 0)
271 : Ty(T), Offset(Off), Idx(0) {}
272 };
273
274 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000275 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000276 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000277 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000278 Stack.push_back(T);
279 StepToLeaf();
280 }
281
282 bool isDone() const { return Stack.empty(); }
283 const Type *getCurrentType() const { return Stack.back().Ty; }
284 unsigned getCurrentOffset() const { return Stack.back().Offset; }
285
286 void StepToNextType() {
287 PopStackAndAdvance();
288 StepToLeaf();
289 }
290
291 private:
292 /// PopStackAndAdvance - Pop the current element off of the stack and
293 /// advance the underlying element to the next contained member.
294 void PopStackAndAdvance() {
295 assert(!Stack.empty() && "Cannot pop an empty stack!");
296 Stack.pop_back();
297 while (!Stack.empty()) {
298 StackState &SS = Stack.back();
299 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
300 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000301 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000302 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattner507bdf92005-01-12 04:51:37 +0000303 SS.Offset +=
304 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000305 return;
306 }
307 Stack.pop_back(); // At the end of the structure
308 } else {
309 const ArrayType *AT = cast<ArrayType>(SS.Ty);
310 ++SS.Idx;
311 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000312 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000313 return;
314 }
315 Stack.pop_back(); // At the end of the array
316 }
317 }
318 }
319
320 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
321 /// on the type stack.
322 void StepToLeaf() {
323 if (Stack.empty()) return;
324 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
325 StackState &SS = Stack.back();
326 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000327 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000328 assert(SS.Idx == 0);
329 PopStackAndAdvance();
330 } else {
331 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000332 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000333 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000334 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000335 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000336 }
337 } else {
338 const ArrayType *AT = cast<ArrayType>(SS.Ty);
339 if (AT->getNumElements() == 0) {
340 assert(SS.Idx == 0);
341 PopStackAndAdvance();
342 } else {
343 // Step into the array...
344 assert(SS.Idx < AT->getNumElements());
345 Stack.push_back(StackState(AT->getElementType(),
346 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000347 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000348 }
349 }
350 }
351 }
352 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000353} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000354
355/// ElementTypesAreCompatible - Check to see if the specified types are
356/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000357/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
358/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000359///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000360static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000361 bool AllowLargerT1, const TargetData &TD){
362 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000363
364 while (!T1W.isDone() && !T2W.isDone()) {
365 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
366 return false;
367
368 const Type *T1 = T1W.getCurrentType();
369 const Type *T2 = T2W.getCurrentType();
370 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
371 return false;
372
373 T1W.StepToNextType();
374 T2W.StepToNextType();
375 }
376
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000377 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000378}
379
380
Chris Lattner08db7192002-11-06 06:20:27 +0000381/// mergeTypeInfo - This method merges the specified type into the current node
382/// at the specified offset. This may update the current node's type record if
383/// this gives more information to the node, it may do nothing to the node if
384/// this information is already known, or it may merge the node completely (and
385/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000386///
Chris Lattner08db7192002-11-06 06:20:27 +0000387/// This method returns true if the node is completely folded, otherwise false.
388///
Chris Lattner088b6392003-03-03 17:13:31 +0000389bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
390 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000391 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000392 // Check to make sure the Size member is up-to-date. Size can be one of the
393 // following:
394 // Size = 0, Ty = Void: Nothing is known about this node.
395 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
396 // Size = 1, Ty = Void, Array = 1: The node is collapsed
397 // Otherwise, sizeof(Ty) = Size
398 //
Chris Lattner18552922002-11-18 21:44:46 +0000399 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
400 (Size == 0 && !Ty->isSized() && !isArray()) ||
401 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
402 (Size == 0 && !Ty->isSized() && !isArray()) ||
403 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000404 "Size member of DSNode doesn't match the type structure!");
405 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000406
Chris Lattner18552922002-11-18 21:44:46 +0000407 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000408 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000409
Chris Lattner08db7192002-11-06 06:20:27 +0000410 // Return true immediately if the node is completely folded.
411 if (isNodeCompletelyFolded()) return true;
412
Chris Lattner23f83dc2002-11-08 22:49:57 +0000413 // If this is an array type, eliminate the outside arrays because they won't
414 // be used anyway. This greatly reduces the size of large static arrays used
415 // as global variables, for example.
416 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000417 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000418 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
419 // FIXME: we might want to keep small arrays, but must be careful about
420 // things like: [2 x [10000 x int*]]
421 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000422 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000423 }
424
Chris Lattner08db7192002-11-06 06:20:27 +0000425 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000426 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000427
428 // Otherwise check to see if we can fold this type into the current node. If
429 // we can't, we fold the node completely, if we can, we potentially update our
430 // internal state.
431 //
Chris Lattner18552922002-11-18 21:44:46 +0000432 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000433 // If this is the first type that this node has seen, just accept it without
434 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000435 assert(Offset == 0 && !isArray() &&
436 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000437
438 // If this node would have to have an unreasonable number of fields, just
439 // collapse it. This can occur for fortran common blocks, which have stupid
440 // things like { [100000000 x double], [1000000 x double] }.
441 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
442 if (NumFields > 64) {
443 foldNodeCompletely();
444 return true;
445 }
446
Chris Lattner18552922002-11-18 21:44:46 +0000447 Ty = NewTy;
448 NodeType &= ~Array;
449 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000450 Size = NewTySize;
451
452 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000453 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000454 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000455 }
Chris Lattner08db7192002-11-06 06:20:27 +0000456
457 // Handle node expansion case here...
458 if (Offset+NewTySize > Size) {
459 // It is illegal to grow this node if we have treated it as an array of
460 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000461 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000462 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000463 return true;
464 }
465
466 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000467 std::cerr << "UNIMP: Trying to merge a growth type into "
468 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000469 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000470 return true;
471 }
472
473 // Okay, the situation is nice and simple, we are trying to merge a type in
474 // at offset 0 that is bigger than our current type. Implement this by
475 // switching to the new type and then merge in the smaller one, which should
476 // hit the other code path here. If the other code path decides it's not
477 // ok, it will collapse the node as appropriate.
478 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000479
480 // If this node would have to have an unreasonable number of fields, just
481 // collapse it. This can occur for fortran common blocks, which have stupid
482 // things like { [100000000 x double], [1000000 x double] }.
483 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
484 if (NumFields > 64) {
485 foldNodeCompletely();
486 return true;
487 }
488
Chris Lattner94f84702005-03-17 19:56:56 +0000489 const Type *OldTy = Ty;
490 Ty = NewTy;
491 NodeType &= ~Array;
492 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000493 Size = NewTySize;
494
495 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000496 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000497
498 // Merge in the old type now... which is guaranteed to be smaller than the
499 // "current" type.
500 return mergeTypeInfo(OldTy, 0);
501 }
502
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000503 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000504 "Cannot merge something into a part of our type that doesn't exist!");
505
Chris Lattner18552922002-11-18 21:44:46 +0000506 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000507 // type that starts at offset Offset.
508 //
509 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000510 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000511 while (O < Offset) {
512 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
513
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000514 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000515 case Type::StructTyID: {
516 const StructType *STy = cast<StructType>(SubType);
517 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000518 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000519
520 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000521 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000522 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000523 break;
524 }
525 case Type::ArrayTyID: {
526 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000527 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000528 unsigned Remainder = (Offset-O) % ElSize;
529 O = Offset-Remainder;
530 break;
531 }
532 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000533 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000534 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000535 }
536 }
537
538 assert(O == Offset && "Could not achieve the correct offset!");
539
540 // If we found our type exactly, early exit
541 if (SubType == NewTy) return false;
542
Misha Brukman96a8bd72004-04-29 04:05:30 +0000543 // Differing function types don't require us to merge. They are not values
544 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000545 if (isa<FunctionType>(SubType) &&
546 isa<FunctionType>(NewTy)) return false;
547
Chris Lattner507bdf92005-01-12 04:51:37 +0000548 unsigned SubTypeSize = SubType->isSized() ?
549 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000550
551 // Ok, we are getting desperate now. Check for physical subtyping, where we
552 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000553 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000554 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000555 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000556 return false;
557
Chris Lattner08db7192002-11-06 06:20:27 +0000558 // Okay, so we found the leader type at the offset requested. Search the list
559 // of types that starts at this offset. If SubType is currently an array or
560 // structure, the type desired may actually be the first element of the
561 // composite type...
562 //
Chris Lattner18552922002-11-18 21:44:46 +0000563 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000564 while (SubType != NewTy) {
565 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000566 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000567 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000568 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000569 case Type::StructTyID: {
570 const StructType *STy = cast<StructType>(SubType);
571 const StructLayout &SL = *TD.getStructLayout(STy);
572 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000573 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000574 else
575 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000576 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000577 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000578 break;
Chris Lattner18552922002-11-18 21:44:46 +0000579 }
Chris Lattner08db7192002-11-06 06:20:27 +0000580 case Type::ArrayTyID:
581 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000582 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000583 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000584 break;
585 default: ;
586 // fall out
587 }
588
589 if (NextSubType == 0)
590 break; // In the default case, break out of the loop
591
Chris Lattner18552922002-11-18 21:44:46 +0000592 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000593 break; // Don't allow shrinking to a smaller type than NewTySize
594 SubType = NextSubType;
595 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000596 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000597 }
598
599 // If we found the type exactly, return it...
600 if (SubType == NewTy)
601 return false;
602
603 // Check to see if we have a compatible, but different type...
604 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000605 // Check to see if this type is obviously convertible... int -> uint f.e.
606 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000607 return false;
608
609 // Check to see if we have a pointer & integer mismatch going on here,
610 // loading a pointer as a long, for example.
611 //
612 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
613 NewTy->isInteger() && isa<PointerType>(SubType))
614 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000615 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
616 // We are accessing the field, plus some structure padding. Ignore the
617 // structure padding.
618 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000619 }
620
Chris Lattner58f98d02003-07-02 04:38:49 +0000621 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000622 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
623 M = getParentGraph()->retnodes_begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000624 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
625 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
626 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
627 << "SubType: ";
628 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000629
Chris Lattner088b6392003-03-03 17:13:31 +0000630 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000631 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000632}
633
Chris Lattner08db7192002-11-06 06:20:27 +0000634
635
Misha Brukman96a8bd72004-04-29 04:05:30 +0000636/// addEdgeTo - Add an edge from the current node to the specified node. This
637/// can cause merging of nodes in the graph.
638///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000639void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000640 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000641
Chris Lattner08db7192002-11-06 06:20:27 +0000642 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000643 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000644 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000645 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000646 } else { // No merging to perform...
647 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000648 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000649}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000650
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000651
Misha Brukman96a8bd72004-04-29 04:05:30 +0000652/// MergeSortedVectors - Efficiently merge a vector into another vector where
653/// duplicates are not allowed and both are sorted. This assumes that 'T's are
654/// efficiently copyable and have sane comparison semantics.
655///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000656static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
657 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000658 // By far, the most common cases will be the simple ones. In these cases,
659 // avoid having to allocate a temporary vector...
660 //
661 if (Src.empty()) { // Nothing to merge in...
662 return;
663 } else if (Dest.empty()) { // Just copy the result in...
664 Dest = Src;
665 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000666 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000667 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000668 std::lower_bound(Dest.begin(), Dest.end(), V);
669 if (I == Dest.end() || *I != Src[0]) // If not already contained...
670 Dest.insert(I, Src[0]);
671 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000672 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000673 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000674 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000675 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
676 if (I == Dest.end() || *I != Tmp) // If not already contained...
677 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000678
679 } else {
680 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000681 std::vector<GlobalValue*> Old(Dest);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000682
683 // Make space for all of the type entries now...
684 Dest.resize(Dest.size()+Src.size());
685
686 // Merge the two sorted ranges together... into Dest.
687 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
688
689 // Now erase any duplicate entries that may have accumulated into the
690 // vectors (because they were in both of the input sets)
691 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
692 }
693}
694
Chris Lattner0b144872004-01-27 22:03:40 +0000695void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
696 MergeSortedVectors(Globals, RHS);
697}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000698
Chris Lattner0b144872004-01-27 22:03:40 +0000699// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000700// This function does the hard work of merging two nodes, CurNodeH
701// and NH after filtering out trivial cases and making sure that
702// CurNodeH.offset >= NH.offset.
703//
704// ***WARNING***
705// Since merging may cause either node to go away, we must always
706// use the node-handles to refer to the nodes. These node handles are
707// automatically updated during merging, so will always provide access
708// to the correct node after a merge.
709//
710void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
711 assert(CurNodeH.getOffset() >= NH.getOffset() &&
712 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000713 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
714 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000715
716 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
717 // respect to NH.Offset) is now zero. NOffset is the distance from the base
718 // of our object that N starts from.
719 //
720 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
721 unsigned NSize = NH.getNode()->getSize();
722
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000723 // If the two nodes are of different size, and the smaller node has the array
724 // bit set, collapse!
725 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000726#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000727 if (NSize < CurNodeH.getNode()->getSize()) {
728 if (NH.getNode()->isArray())
729 NH.getNode()->foldNodeCompletely();
730 } else if (CurNodeH.getNode()->isArray()) {
731 NH.getNode()->foldNodeCompletely();
732 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000733#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000734 }
735
736 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000737 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000738 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000739 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000740
741 // If we are merging a node with a completely folded node, then both nodes are
742 // now completely folded.
743 //
744 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
745 if (!NH.getNode()->isNodeCompletelyFolded()) {
746 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000747 assert(NH.getNode() && NH.getOffset() == 0 &&
748 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000749 NOffset = NH.getOffset();
750 NSize = NH.getNode()->getSize();
751 assert(NOffset == 0 && NSize == 1);
752 }
753 } else if (NH.getNode()->isNodeCompletelyFolded()) {
754 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000755 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
756 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000757 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000758 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000759 assert(NOffset == 0 && NSize == 1);
760 }
761
Chris Lattner72d29a42003-02-11 23:11:51 +0000762 DSNode *N = NH.getNode();
763 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000764 assert(!CurNodeH.getNode()->isDeadNode());
765
Chris Lattner0b144872004-01-27 22:03:40 +0000766 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000767 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000768
Chris Lattner72d29a42003-02-11 23:11:51 +0000769 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000770 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000771 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000772
Chris Lattner72d29a42003-02-11 23:11:51 +0000773 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
774 //
775 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
776 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000777 if (Link.getNode()) {
778 // Compute the offset into the current node at which to
779 // merge this link. In the common case, this is a linear
780 // relation to the offset in the original node (with
781 // wrapping), but if the current node gets collapsed due to
782 // recursive merging, we must make sure to merge in all remaining
783 // links at offset zero.
784 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000785 DSNode *CN = CurNodeH.getNode();
786 if (CN->Size != 1)
787 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
788 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000789 }
790 }
791
792 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000793 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000794
795 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000796 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000797 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000798
799 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000800 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000801 }
802}
803
804
Misha Brukman96a8bd72004-04-29 04:05:30 +0000805/// mergeWith - Merge this node and the specified node, moving all links to and
806/// from the argument node into the current node, deleting the node argument.
807/// Offset indicates what offset the specified node is to be merged into the
808/// current node.
809///
810/// The specified node may be a null pointer (in which case, we update it to
811/// point to this node).
812///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000813void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
814 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000815 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000816 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000817
Chris Lattner5254a8d2004-01-22 16:31:08 +0000818 // If the RHS is a null node, make it point to this node!
819 if (N == 0) {
820 NH.mergeWith(DSNodeHandle(this, Offset));
821 return;
822 }
823
Chris Lattnerbd92b732003-06-19 21:15:11 +0000824 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000825 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
826
Chris Lattner02606632002-11-04 06:48:26 +0000827 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000828 // We cannot merge two pieces of the same node together, collapse the node
829 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000830 DEBUG(std::cerr << "Attempting to merge two chunks of"
831 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000832 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000833 return;
834 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000835
Chris Lattner5190ce82002-11-12 07:20:45 +0000836 // If both nodes are not at offset 0, make sure that we are merging the node
837 // at an later offset into the node with the zero offset.
838 //
839 if (Offset < NH.getOffset()) {
840 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
841 return;
842 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
843 // If the offsets are the same, merge the smaller node into the bigger node
844 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
845 return;
846 }
847
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000848 // Ok, now we can merge the two nodes. Use a static helper that works with
849 // two node handles, since "this" may get merged away at intermediate steps.
850 DSNodeHandle CurNodeH(this, Offset);
851 DSNodeHandle NHCopy(NH);
852 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000853}
854
Chris Lattner0b144872004-01-27 22:03:40 +0000855
856//===----------------------------------------------------------------------===//
857// ReachabilityCloner Implementation
858//===----------------------------------------------------------------------===//
859
860DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
861 if (SrcNH.isNull()) return DSNodeHandle();
862 const DSNode *SN = SrcNH.getNode();
863
864 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000865 if (!NH.isNull()) { // Node already mapped?
866 DSNode *NHN = NH.getNode();
867 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
868 }
Chris Lattner0b144872004-01-27 22:03:40 +0000869
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000870 // If SrcNH has globals and the destination graph has one of the same globals,
871 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000872 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000873 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000874 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000875 I != E; ++I) {
876 GlobalValue *GV = *I;
877 DSScalarMap::iterator GI = DestSM.find(GV);
878 if (GI != DestSM.end() && !GI->second.isNull()) {
879 // We found one, use merge instead!
880 merge(GI->second, Src.getNodeForValue(GV));
881 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000882 DSNode *NHN = NH.getNode();
883 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000884 }
885 }
886 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000887
Chris Lattner0b144872004-01-27 22:03:40 +0000888 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
889 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000890 NH = DN;
Chris Lattner0b144872004-01-27 22:03:40 +0000891
892 // Next, recursively clone all outgoing links as necessary. Note that
893 // adding these links can cause the node to collapse itself at any time, and
894 // the current node may be merged with arbitrary other nodes. For this
895 // reason, we must always go through NH.
896 DN = 0;
897 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
898 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
899 if (!SrcEdge.isNull()) {
900 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
901 // Compute the offset into the current node at which to
902 // merge this link. In the common case, this is a linear
903 // relation to the offset in the original node (with
904 // wrapping), but if the current node gets collapsed due to
905 // recursive merging, we must make sure to merge in all remaining
906 // links at offset zero.
907 unsigned MergeOffset = 0;
908 DSNode *CN = NH.getNode();
909 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000910 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000911 CN->addEdgeTo(MergeOffset, DestEdge);
912 }
913 }
914
915 // If this node contains any globals, make sure they end up in the scalar
916 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +0000917 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +0000918 I != E; ++I) {
919 GlobalValue *GV = *I;
920 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
921 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
922 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
923 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000924 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000925
926 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
927 Dest.getInlinedGlobals().insert(GV);
928 }
Chris Lattner82c6c722005-03-20 02:41:38 +0000929 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +0000930
931 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
932}
933
934void ReachabilityCloner::merge(const DSNodeHandle &NH,
935 const DSNodeHandle &SrcNH) {
936 if (SrcNH.isNull()) return; // Noop
937 if (NH.isNull()) {
938 // If there is no destination node, just clone the source and assign the
939 // destination node to be it.
940 NH.mergeWith(getClonedNH(SrcNH));
941 return;
942 }
943
944 // Okay, at this point, we know that we have both a destination and a source
945 // node that need to be merged. Check to see if the source node has already
946 // been cloned.
947 const DSNode *SN = SrcNH.getNode();
948 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000949 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000950 DSNode *SCNHN = SCNH.getNode();
951 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000952 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000953 return; // Nothing to do!
954 }
Chris Lattner6f967742004-10-30 04:05:01 +0000955
Chris Lattner0b144872004-01-27 22:03:40 +0000956 // Okay, so the source node has not already been cloned. Instead of creating
957 // a new DSNode, only to merge it into the one we already have, try to perform
958 // the merge in-place. The only case we cannot handle here is when the offset
959 // into the existing node is less than the offset into the virtual node we are
960 // merging in. In this case, we have to extend the existing node, which
961 // requires an allocation anyway.
962 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
963 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000964 if (!DN->isNodeCompletelyFolded()) {
965 // Make sure the destination node is folded if the source node is folded.
966 if (SN->isNodeCompletelyFolded()) {
967 DN->foldNodeCompletely();
968 DN = NH.getNode();
969 } else if (SN->getSize() != DN->getSize()) {
970 // If the two nodes are of different size, and the smaller node has the
971 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000972#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000973 if (SN->getSize() < DN->getSize()) {
974 if (SN->isArray()) {
975 DN->foldNodeCompletely();
976 DN = NH.getNode();
977 }
978 } else if (DN->isArray()) {
979 DN->foldNodeCompletely();
980 DN = NH.getNode();
981 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000982#endif
Chris Lattner0b144872004-01-27 22:03:40 +0000983 }
984
985 // Merge the type entries of the two nodes together...
986 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
987 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
988 DN = NH.getNode();
989 }
990 }
991
992 assert(!DN->isDeadNode());
993
994 // Merge the NodeType information.
995 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
996
997 // Before we start merging outgoing links and updating the scalar map, make
998 // sure it is known that this is the representative node for the src node.
999 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1000
1001 // If the source node contains any globals, make sure they end up in the
1002 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001003 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001004 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001005 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001006
1007 // Update the scalar map for the graph we are merging the source node
1008 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001009 for (DSNode::globals_iterator I = SN->globals_begin(),
1010 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001011 GlobalValue *GV = *I;
1012 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1013 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1014 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1015 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001016 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001017
1018 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1019 Dest.getInlinedGlobals().insert(GV);
1020 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001021 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001022 }
1023 } else {
1024 // We cannot handle this case without allocating a temporary node. Fall
1025 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001026 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1027 NewDN->maskNodeTypes(BitsToKeep);
1028
1029 unsigned NHOffset = NH.getOffset();
1030 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001031
Chris Lattner0b144872004-01-27 22:03:40 +00001032 assert(NH.getNode() &&
1033 (NH.getOffset() > NHOffset ||
1034 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1035 "Merging did not adjust the offset!");
1036
1037 // Before we start merging outgoing links and updating the scalar map, make
1038 // sure it is known that this is the representative node for the src node.
1039 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001040
1041 // If the source node contained any globals, make sure to create entries
1042 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001043 for (DSNode::globals_iterator I = SN->globals_begin(),
1044 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001045 GlobalValue *GV = *I;
1046 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1047 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1048 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1049 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1050 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1051 DestGNH.getOffset()+SrcGNH.getOffset()));
1052
1053 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1054 Dest.getInlinedGlobals().insert(GV);
1055 }
Chris Lattner0b144872004-01-27 22:03:40 +00001056 }
1057
1058
1059 // Next, recursively merge all outgoing links as necessary. Note that
1060 // adding these links can cause the destination node to collapse itself at
1061 // any time, and the current node may be merged with arbitrary other nodes.
1062 // For this reason, we must always go through NH.
1063 DN = 0;
1064 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1065 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1066 if (!SrcEdge.isNull()) {
1067 // Compute the offset into the current node at which to
1068 // merge this link. In the common case, this is a linear
1069 // relation to the offset in the original node (with
1070 // wrapping), but if the current node gets collapsed due to
1071 // recursive merging, we must make sure to merge in all remaining
1072 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001073 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001074 unsigned MergeOffset =
1075 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +00001076
Chris Lattnerf590ced2004-03-04 17:06:53 +00001077 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1078 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001079 // Perform the recursive merging. Make sure to create a temporary NH,
1080 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001081 merge(Tmp, SrcEdge);
1082 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001083 Tmp.mergeWith(getClonedNH(SrcEdge));
1084 // Merging this could cause all kinds of recursive things to happen,
1085 // culminating in the current node being eliminated. Since this is
1086 // possible, make sure to reaquire the link from 'CN'.
1087
1088 unsigned MergeOffset = 0;
1089 CN = SCNH.getNode();
1090 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1091 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001092 }
Chris Lattner0b144872004-01-27 22:03:40 +00001093 }
1094 }
1095}
1096
1097/// mergeCallSite - Merge the nodes reachable from the specified src call
1098/// site into the nodes reachable from DestCS.
1099void ReachabilityCloner::mergeCallSite(const DSCallSite &DestCS,
1100 const DSCallSite &SrcCS) {
1101 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1102 unsigned MinArgs = DestCS.getNumPtrArgs();
1103 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
1104
1105 for (unsigned a = 0; a != MinArgs; ++a)
1106 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
1107}
1108
1109
Chris Lattner9de906c2002-10-20 22:11:44 +00001110//===----------------------------------------------------------------------===//
1111// DSCallSite Implementation
1112//===----------------------------------------------------------------------===//
1113
Vikram S. Adve26b98262002-10-20 21:41:02 +00001114// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001115Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001116 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001117}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001118
Chris Lattner0b144872004-01-27 22:03:40 +00001119void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1120 ReachabilityCloner &RC) {
1121 NH = RC.getClonedNH(Src);
1122}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001123
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001124//===----------------------------------------------------------------------===//
1125// DSGraph Implementation
1126//===----------------------------------------------------------------------===//
1127
Chris Lattnera9d65662003-06-30 05:57:30 +00001128/// getFunctionNames - Return a space separated list of the name of the
1129/// functions in this graph (if any)
1130std::string DSGraph::getFunctionNames() const {
1131 switch (getReturnNodes().size()) {
1132 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001133 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001134 default:
1135 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001136 for (DSGraph::retnodes_iterator I = retnodes_begin();
1137 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001138 Return += I->first->getName() + " ";
1139 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1140 return Return;
1141 }
1142}
1143
1144
Chris Lattnerf4f62272005-03-19 22:23:45 +00001145DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs)
1146 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001147 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001148 NodeMapTy NodeMap;
1149 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001150}
1151
Chris Lattnerf4f62272005-03-19 22:23:45 +00001152DSGraph::DSGraph(const DSGraph &G, NodeMapTy &NodeMap,
1153 EquivalenceClasses<GlobalValue*> &ECs)
1154 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001155 PrintAuxCalls = false;
Chris Lattner5a540632003-06-30 03:15:25 +00001156 cloneInto(G, ScalarMap, ReturnNodes, NodeMap);
Chris Lattnereff0da92002-10-21 15:32:34 +00001157}
1158
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001159DSGraph::~DSGraph() {
1160 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001161 AuxFunctionCalls.clear();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001162 InlinedGlobals.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001163 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001164 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001165
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001166 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001167 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001168 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001169
Chris Lattner28897e12004-02-08 00:53:26 +00001170 // Free all of the nodes.
1171 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001172}
1173
Chris Lattner0d9bab82002-07-18 00:12:30 +00001174// dump - Allow inspection of graph in a debugger.
1175void DSGraph::dump() const { print(std::cerr); }
1176
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001177
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001178/// remapLinks - Change all of the Links in the current node according to the
1179/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001180///
Chris Lattner8d327672003-06-30 03:36:09 +00001181void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001182 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1183 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001184 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001185 if (ONMI != OldNodeMap.end()) {
1186 DSNode *ONMIN = ONMI->second.getNode();
1187 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1188 }
Chris Lattner2f561382004-01-22 16:56:13 +00001189 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001190}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001191
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001192/// updateFromGlobalGraph - This function rematerializes global nodes and
1193/// nodes reachable from them from the globals graph into the current graph.
Chris Lattner0b144872004-01-27 22:03:40 +00001194/// It uses the vector InlinedGlobals to avoid cloning and merging globals that
1195/// are already up-to-date in the current graph. In practice, in the TD pass,
1196/// this is likely to be a large fraction of the live global nodes in each
1197/// function (since most live nodes are likely to have been brought up-to-date
1198/// in at _some_ caller or callee).
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001199///
1200void DSGraph::updateFromGlobalGraph() {
Chris Lattner0b144872004-01-27 22:03:40 +00001201 TIME_REGION(X, "updateFromGlobalGraph");
Chris Lattner0b144872004-01-27 22:03:40 +00001202 ReachabilityCloner RC(*this, *GlobalsGraph, 0);
1203
1204 // Clone the non-up-to-date global nodes into this graph.
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001205 for (DSScalarMap::global_iterator I = getScalarMap().global_begin(),
1206 E = getScalarMap().global_end(); I != E; ++I)
1207 if (InlinedGlobals.count(*I) == 0) { // GNode is not up-to-date
Chris Lattner62482e52004-01-28 09:15:42 +00001208 DSScalarMap::iterator It = GlobalsGraph->ScalarMap.find(*I);
Chris Lattnerbdce7b72004-01-28 03:03:06 +00001209 if (It != GlobalsGraph->ScalarMap.end())
1210 RC.merge(getNodeForValue(*I), It->second);
1211 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001212}
1213
Chris Lattnerd672ab92005-02-15 18:40:55 +00001214/// addObjectToGraph - This method can be used to add global, stack, and heap
1215/// objects to the graph. This can be used when updating DSGraphs due to the
1216/// introduction of new temporary objects. The new object is not pointed to
1217/// and does not point to any other objects in the graph.
1218DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1219 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1220 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1221 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001222 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001223 ScalarMap[Ptr] = N;
1224
1225 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1226 N->addGlobal(GV);
1227 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1228 N->setHeapNodeMarker();
1229 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1230 N->setAllocaNodeMarker();
1231 } else {
1232 assert(0 && "Illegal memory object input!");
1233 }
1234 return N;
1235}
1236
1237
Chris Lattner5a540632003-06-30 03:15:25 +00001238/// cloneInto - Clone the specified DSGraph into the current graph. The
1239/// translated ScalarMap for the old function is filled into the OldValMap
1240/// member, and the translated ReturnNodes map is returned into ReturnNodes.
1241///
1242/// The CloneFlags member controls various aspects of the cloning process.
1243///
Chris Lattner62482e52004-01-28 09:15:42 +00001244void DSGraph::cloneInto(const DSGraph &G, DSScalarMap &OldValMap,
Chris Lattner5a540632003-06-30 03:15:25 +00001245 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
1246 unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001247 TIME_REGION(X, "cloneInto");
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001248 assert(OldNodeMap.empty() && "Returned OldNodeMap should be empty!");
Chris Lattner33312f72002-11-08 01:21:07 +00001249 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001250
Chris Lattner1e883692003-02-03 20:08:51 +00001251 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001252 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1253 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1254 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001255 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001256
Chris Lattner84b80a22005-03-16 22:42:19 +00001257 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1258 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001259 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001260 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001261 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001262 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001263 }
1264
Chris Lattner18552922002-11-18 21:44:46 +00001265#ifndef NDEBUG
1266 Timer::addPeakMemoryMeasurement();
1267#endif
Chris Lattnerd85645f2004-02-21 22:28:26 +00001268
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001269 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001270 // Note that we don't loop over the node's list to do this. The problem is
1271 // that remaping links can cause recursive merging to happen, which means
1272 // that node_iterator's can get easily invalidated! Because of this, we
1273 // loop over the OldNodeMap, which contains all of the new nodes as the
1274 // .second element of the map elements. Also note that if we remap a node
1275 // more than once, we won't break anything.
1276 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1277 I != E; ++I)
1278 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001279
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001280 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001281 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001282 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001283 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001284 DSNodeHandle &H = OldValMap[I->first];
Chris Lattner6f967742004-10-30 04:05:01 +00001285 DSNode *MappedNodeN = MappedNode.getNode();
1286 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001287 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001288
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001289 // If this is a global, add the global to this fn or merge if already exists
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001290 if (GlobalValue* GV = dyn_cast<GlobalValue>(I->first)) {
1291 ScalarMap[GV].mergeWith(H);
Chris Lattner091f7762004-01-23 01:44:53 +00001292 if (CloneFlags & DSGraph::UpdateInlinedGlobals)
1293 InlinedGlobals.insert(GV);
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001294 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001295 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001296
Chris Lattner679e8e12002-11-08 21:27:12 +00001297 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001298 // Copy the function calls list.
1299 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1300 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001301 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001302
Chris Lattneracf491f2002-11-08 22:27:09 +00001303 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001304 // Copy the auxiliary function calls list.
1305 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1306 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001307 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001308
Chris Lattner5a540632003-06-30 03:15:25 +00001309 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001310 for (retnodes_iterator I = G.retnodes_begin(),
1311 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001312 const DSNodeHandle &Ret = I->second;
1313 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001314 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattner5a540632003-06-30 03:15:25 +00001315 OldReturnNodes.insert(std::make_pair(I->first,
Chris Lattner6f967742004-10-30 04:05:01 +00001316 DSNodeHandle(MappedRetN,
Chris Lattner5a540632003-06-30 03:15:25 +00001317 MappedRet.getOffset()+Ret.getOffset())));
1318 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001319}
1320
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001321static bool PathExistsToClonedNode(const DSNode *N, ReachabilityCloner &RC) {
Chris Lattner2f346902004-03-04 03:57:53 +00001322 if (N)
1323 for (df_iterator<const DSNode*> I = df_begin(N), E = df_end(N); I != E; ++I)
1324 if (RC.hasClonedNode(*I))
1325 return true;
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001326 return false;
1327}
1328
Chris Lattner2f346902004-03-04 03:57:53 +00001329static bool PathExistsToClonedNode(const DSCallSite &CS,
1330 ReachabilityCloner &RC) {
1331 if (PathExistsToClonedNode(CS.getRetVal().getNode(), RC))
1332 return true;
1333 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1334 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode(), RC))
1335 return true;
1336 return false;
1337}
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001338
Chris Lattnerbb753c42005-02-03 18:40:25 +00001339/// getFunctionArgumentsForCall - Given a function that is currently in this
1340/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1341/// function arguments. The vector is filled in with the return value (or
1342/// null if it is not pointer compatible), followed by all of the
1343/// pointer-compatible arguments.
1344void DSGraph::getFunctionArgumentsForCall(Function *F,
1345 std::vector<DSNodeHandle> &Args) const {
1346 Args.push_back(getReturnNodeFor(*F));
Chris Lattnere4d5c442005-03-15 04:54:21 +00001347 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001348 if (isPointerType(AI->getType())) {
1349 Args.push_back(getNodeForValue(AI));
1350 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1351 }
1352}
1353
Chris Lattnere8594442005-02-04 19:58:28 +00001354/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1355/// nodes from G2 into 'this' graph, merging the bindings specified by the
1356/// call site (in this graph) with the bindings specified by the vector in G2.
1357/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001358///
Chris Lattnere8594442005-02-04 19:58:28 +00001359void DSGraph::mergeInGraph(const DSCallSite &CS,
1360 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001361 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001362 TIME_REGION(X, "mergeInGraph");
1363
Chris Lattner076c1f92002-11-07 06:31:54 +00001364 // If this is not a recursive call, clone the graph into this graph...
1365 if (&Graph != this) {
Chris Lattner0b144872004-01-27 22:03:40 +00001366 // Clone the callee's graph into the current graph, keeping track of where
1367 // scalars in the old graph _used_ to point, and of the new nodes matching
1368 // nodes of the old graph.
1369 ReachabilityCloner RC(*this, Graph, CloneFlags);
1370
Chris Lattner0b144872004-01-27 22:03:40 +00001371 // Map the return node pointer over.
Chris Lattner0ad91702004-02-22 00:53:54 +00001372 if (!CS.getRetVal().isNull())
Chris Lattnerbb753c42005-02-03 18:40:25 +00001373 RC.merge(CS.getRetVal(), Args[0]);
Chris Lattnerf590ced2004-03-04 17:06:53 +00001374
Chris Lattnerbb753c42005-02-03 18:40:25 +00001375 // Map over all of the arguments.
1376 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001377 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001378 break;
Chris Lattnerbb753c42005-02-03 18:40:25 +00001379
1380 // Add the link from the argument scalar to the provided value.
1381 RC.merge(CS.getPtrArg(i), Args[i+1]);
1382 }
1383
Chris Lattner2f346902004-03-04 03:57:53 +00001384 // If requested, copy all of the calls.
Chris Lattner0b144872004-01-27 22:03:40 +00001385 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001386 // Copy the function calls list.
1387 for (fc_iterator I = Graph.fc_begin(), E = Graph.fc_end(); I != E; ++I)
1388 FunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner0b144872004-01-27 22:03:40 +00001389 }
Chris Lattner2f346902004-03-04 03:57:53 +00001390
1391 // If the user has us copying aux calls (the normal case), set up a data
1392 // structure to keep track of which ones we've copied over.
Chris Lattnera9548d92005-01-30 23:51:02 +00001393 std::set<const DSCallSite*> CopiedAuxCall;
Chris Lattner0b144872004-01-27 22:03:40 +00001394
Chris Lattner0321b682004-02-27 20:05:15 +00001395 // Clone over all globals that appear in the caller and callee graphs.
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001396 hash_set<GlobalVariable*> NonCopiedGlobals;
Chris Lattner0321b682004-02-27 20:05:15 +00001397 for (DSScalarMap::global_iterator GI = Graph.getScalarMap().global_begin(),
1398 E = Graph.getScalarMap().global_end(); GI != E; ++GI)
1399 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*GI))
1400 if (ScalarMap.count(GV))
1401 RC.merge(ScalarMap[GV], Graph.getNodeForValue(GV));
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001402 else
1403 NonCopiedGlobals.insert(GV);
1404
1405 // If the global does not appear in the callers graph we generally don't
1406 // want to copy the node. However, if there is a path from the node global
1407 // node to a node that we did copy in the graph, we *must* copy it to
1408 // maintain the connection information. Every time we decide to include a
1409 // new global, this might make other globals live, so we must iterate
1410 // unfortunately.
Chris Lattner2f346902004-03-04 03:57:53 +00001411 bool MadeChange = true;
1412 while (MadeChange) {
1413 MadeChange = false;
1414 for (hash_set<GlobalVariable*>::iterator I = NonCopiedGlobals.begin();
1415 I != NonCopiedGlobals.end();) {
1416 DSNode *GlobalNode = Graph.getNodeForValue(*I).getNode();
1417 if (RC.hasClonedNode(GlobalNode)) {
1418 // Already cloned it, remove from set.
1419 NonCopiedGlobals.erase(I++);
1420 MadeChange = true;
1421 } else if (PathExistsToClonedNode(GlobalNode, RC)) {
1422 RC.getClonedNH(Graph.getNodeForValue(*I));
1423 NonCopiedGlobals.erase(I++);
1424 MadeChange = true;
1425 } else {
1426 ++I;
1427 }
1428 }
1429
1430 // If requested, copy any aux calls that can reach copied nodes.
1431 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001432 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
1433 if (CopiedAuxCall.insert(&*I).second &&
1434 PathExistsToClonedNode(*I, RC)) {
1435 AuxFunctionCalls.push_back(DSCallSite(*I, RC));
Chris Lattner2f346902004-03-04 03:57:53 +00001436 MadeChange = true;
1437 }
Chris Lattnerc4ebdce2004-03-03 22:01:09 +00001438 }
1439 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001440
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001441 } else {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001442 // Merge the return value with the return value of the context.
1443 Args[0].mergeWith(CS.getRetVal());
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001444
Chris Lattnerbb753c42005-02-03 18:40:25 +00001445 // Resolve all of the function arguments.
1446 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001447 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001448 break;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001449
Chris Lattnerbb753c42005-02-03 18:40:25 +00001450 // Add the link from the argument scalar to the provided value.
1451 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001452 }
Chris Lattner076c1f92002-11-07 06:31:54 +00001453 }
1454}
1455
Chris Lattnere8594442005-02-04 19:58:28 +00001456
1457
1458/// mergeInGraph - The method is used for merging graphs together. If the
1459/// argument graph is not *this, it makes a clone of the specified graph, then
1460/// merges the nodes specified in the call site with the formal arguments in the
1461/// graph.
1462///
1463void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1464 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001465 // Set up argument bindings.
1466 std::vector<DSNodeHandle> Args;
1467 Graph.getFunctionArgumentsForCall(&F, Args);
1468
1469 mergeInGraph(CS, Args, Graph, CloneFlags);
1470}
1471
Chris Lattner58f98d02003-07-02 04:38:49 +00001472/// getCallSiteForArguments - Get the arguments and return value bindings for
1473/// the specified function in the current graph.
1474///
1475DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1476 std::vector<DSNodeHandle> Args;
1477
Chris Lattnere4d5c442005-03-15 04:54:21 +00001478 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001479 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001480 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001481
Chris Lattner808a7ae2003-09-20 16:34:13 +00001482 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001483}
1484
Chris Lattner85fb1be2004-03-09 19:37:06 +00001485/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1486/// the context of this graph, return the DSCallSite for it.
1487DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1488 DSNodeHandle RetVal;
1489 Instruction *I = CS.getInstruction();
1490 if (isPointerType(I->getType()))
1491 RetVal = getNodeForValue(I);
1492
1493 std::vector<DSNodeHandle> Args;
1494 Args.reserve(CS.arg_end()-CS.arg_begin());
1495
1496 // Calculate the arguments vector...
1497 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1498 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001499 if (isa<ConstantPointerNull>(*I))
1500 Args.push_back(DSNodeHandle());
1501 else
1502 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001503
1504 // Add a new function call entry...
1505 if (Function *F = CS.getCalledFunction())
1506 return DSCallSite(CS, RetVal, F, Args);
1507 else
1508 return DSCallSite(CS, RetVal,
1509 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1510}
1511
Chris Lattner58f98d02003-07-02 04:38:49 +00001512
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001513
Chris Lattner0d9bab82002-07-18 00:12:30 +00001514// markIncompleteNodes - Mark the specified node as having contents that are not
1515// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001516// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001517// must recursively traverse the data structure graph, marking all reachable
1518// nodes as incomplete.
1519//
1520static void markIncompleteNode(DSNode *N) {
1521 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001522 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001523
1524 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001525 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001526
Misha Brukman2f2d0652003-09-11 18:14:24 +00001527 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001528 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1529 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001530 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001531}
1532
Chris Lattnere71ffc22002-11-11 03:36:55 +00001533static void markIncomplete(DSCallSite &Call) {
1534 // Then the return value is certainly incomplete!
1535 markIncompleteNode(Call.getRetVal().getNode());
1536
1537 // All objects pointed to by function arguments are incomplete!
1538 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1539 markIncompleteNode(Call.getPtrArg(i).getNode());
1540}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001541
1542// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1543// modified by other functions that have not been resolved yet. This marks
1544// nodes that are reachable through three sources of "unknownness":
1545//
1546// Global Variables, Function Calls, and Incoming Arguments
1547//
1548// For any node that may have unknown components (because something outside the
1549// scope of current analysis may have modified it), the 'Incomplete' flag is
1550// added to the NodeType.
1551//
Chris Lattner394471f2003-01-23 22:05:33 +00001552void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001553 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001554 if (Flags & DSGraph::MarkFormalArgs)
1555 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1556 FI != E; ++FI) {
1557 Function &F = *FI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00001558 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001559 if (isPointerType(I->getType()))
1560 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001561 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001562 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001563
Chris Lattnera9548d92005-01-30 23:51:02 +00001564 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001565 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001566 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1567 E = FunctionCalls.end(); I != E; ++I)
1568 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001569 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001570 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1571 E = AuxFunctionCalls.end(); I != E; ++I)
1572 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001573
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001574 // Mark all global nodes as incomplete.
1575 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1576 E = ScalarMap.global_end(); I != E; ++I)
1577 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1578 if (!GV->hasInitializer() || // Always mark external globals incomp.
1579 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1580 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001581}
1582
Chris Lattneraa8146f2002-11-10 06:59:55 +00001583static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1584 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001585 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001586 // No interesting info?
1587 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001588 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001589 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001590}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001591
Chris Lattner82c6c722005-03-20 02:41:38 +00001592#if 0
Chris Lattneraa8146f2002-11-10 06:59:55 +00001593static inline bool nodeContainsExternalFunction(const DSNode *N) {
1594 const std::vector<GlobalValue*> &Globals = N->getGlobals();
1595 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
Chris Lattner857eb062004-10-30 05:41:23 +00001596 if (Globals[i]->isExternal() && isa<Function>(Globals[i]))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001597 return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001598 return false;
1599}
Chris Lattner82c6c722005-03-20 02:41:38 +00001600#endif
Chris Lattner0d9bab82002-07-18 00:12:30 +00001601
Chris Lattnera9548d92005-01-30 23:51:02 +00001602static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001603 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001604 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001605
1606 // Scan the call list cleaning it up as necessary...
Chris Lattner923fc052003-02-05 21:59:58 +00001607 DSNode *LastCalleeNode = 0;
1608 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001609 unsigned NumDuplicateCalls = 0;
1610 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001611
Chris Lattnera9548d92005-01-30 23:51:02 +00001612 unsigned NumDeleted = 0;
1613 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1614 I != E;) {
1615 DSCallSite &CS = *I;
1616 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001617
Chris Lattnere4258442002-11-11 21:35:38 +00001618 // If the Callee is a useless edge, this must be an unreachable call site,
1619 // eliminate it.
Chris Lattner72d29a42003-02-11 23:11:51 +00001620 if (CS.isIndirectCall() && CS.getCalleeNode()->getNumReferrers() == 1 &&
Chris Lattnerabcdf802004-02-26 03:43:43 +00001621 CS.getCalleeNode()->isComplete() &&
Chris Lattner82c6c722005-03-20 02:41:38 +00001622 CS.getCalleeNode()->getGlobalsList().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001623#ifndef NDEBUG
Chris Lattnerabcdf802004-02-26 03:43:43 +00001624 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001625#endif
Chris Lattnera9548d92005-01-30 23:51:02 +00001626 Calls.erase(OldIt);
1627 ++NumDeleted;
1628 continue;
1629 }
1630
1631 // If the return value or any arguments point to a void node with no
1632 // information at all in it, and the call node is the only node to point
1633 // to it, remove the edge to the node (killing the node).
1634 //
1635 killIfUselessEdge(CS.getRetVal());
1636 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1637 killIfUselessEdge(CS.getPtrArg(a));
1638
Chris Lattner0b144872004-01-27 22:03:40 +00001639#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001640 // If this call site calls the same function as the last call site, and if
1641 // the function pointer contains an external function, this node will
1642 // never be resolved. Merge the arguments of the call node because no
1643 // information will be lost.
1644 //
1645 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1646 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1647 ++NumDuplicateCalls;
1648 if (NumDuplicateCalls == 1) {
1649 if (LastCalleeNode)
1650 LastCalleeContainsExternalFunction =
1651 nodeContainsExternalFunction(LastCalleeNode);
1652 else
1653 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001654 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001655
1656 // It is not clear why, but enabling this code makes DSA really
1657 // sensitive to node forwarding. Basically, with this enabled, DSA
1658 // performs different number of inlinings based on which nodes are
1659 // forwarding or not. This is clearly a problem, so this code is
1660 // disabled until this can be resolved.
1661#if 1
1662 if (LastCalleeContainsExternalFunction
1663#if 0
1664 ||
1665 // This should be more than enough context sensitivity!
1666 // FIXME: Evaluate how many times this is tripped!
1667 NumDuplicateCalls > 20
1668#endif
1669 ) {
1670
1671 std::list<DSCallSite>::iterator PrevIt = OldIt;
1672 --PrevIt;
1673 PrevIt->mergeWith(CS);
1674
1675 // No need to keep this call anymore.
1676 Calls.erase(OldIt);
1677 ++NumDeleted;
1678 continue;
1679 }
1680#endif
1681 } else {
1682 if (CS.isDirectCall()) {
1683 LastCalleeFunc = CS.getCalleeFunc();
1684 LastCalleeNode = 0;
1685 } else {
1686 LastCalleeNode = CS.getCalleeNode();
1687 LastCalleeFunc = 0;
1688 }
1689 NumDuplicateCalls = 0;
1690 }
1691#endif
1692
1693 if (I != Calls.end() && CS == *I) {
1694 Calls.erase(OldIt);
1695 ++NumDeleted;
1696 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001697 }
1698 }
Chris Lattner857eb062004-10-30 05:41:23 +00001699
Chris Lattnera9548d92005-01-30 23:51:02 +00001700 // Resort now that we simplified things.
1701 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001702
Chris Lattnera9548d92005-01-30 23:51:02 +00001703 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001704 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1705 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001706 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001707 std::list<DSCallSite>::iterator OldIt = CI++;
1708 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001709
1710 // If this call site is now the same as the previous one, we can delete it
1711 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001712 if (*OldIt == *CI) {
1713 Calls.erase(CI);
1714 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001715 ++NumDeleted;
1716 }
1717 }
1718
1719 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001720
Chris Lattner33312f72002-11-08 01:21:07 +00001721 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001722 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001723
Chris Lattnera9548d92005-01-30 23:51:02 +00001724 DEBUG(if (NumDeleted)
1725 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001726}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001727
Chris Lattneraa8146f2002-11-10 06:59:55 +00001728
Chris Lattnere2219762002-07-18 18:22:40 +00001729// removeTriviallyDeadNodes - After the graph has been constructed, this method
1730// removes all unreachable nodes that are created because they got merged with
1731// other nodes in the graph. These nodes will all be trivially unreachable, so
1732// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001733//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001734void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001735 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001736
Chris Lattner5ace1e42004-07-08 07:25:51 +00001737#if 0
1738 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1739 /// substantially!
1740
Chris Lattnerbab8c282003-09-20 21:34:07 +00001741 // Loop over all of the nodes in the graph, calling getNode on each field.
1742 // This will cause all nodes to update their forwarding edges, causing
1743 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001744 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001745 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001746 DSNode &N = *NI;
1747 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1748 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001749 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001750 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001751
Chris Lattner0b144872004-01-27 22:03:40 +00001752 // NOTE: This code is disabled. Though it should, in theory, allow us to
1753 // remove more nodes down below, the scan of the scalar map is incredibly
1754 // expensive for certain programs (with large SCCs). In the future, if we can
1755 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001756 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1757
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001758 // Likewise, forward any edges from the scalar nodes. While we are at it,
1759 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001760 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001761 I->second.getNode();
1762 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001763 }
Chris Lattner0b144872004-01-27 22:03:40 +00001764 }
1765#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001766 bool isGlobalsGraph = !GlobalsGraph;
1767
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001768 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001769 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001770
1771 // Do not remove *any* global nodes in the globals graph.
1772 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001773 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001774 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001775 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001776 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001777
Chris Lattner28897e12004-02-08 00:53:26 +00001778 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001779 // This is a useless node if it has no mod/ref info (checked above),
1780 // outgoing edges (which it cannot, as it is not modified in this
1781 // context), and it has no incoming edges. If it is a global node it may
1782 // have all of these properties and still have incoming edges, due to the
1783 // scalar map, so we check those now.
1784 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001785 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1786 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001787
Chris Lattner17a93e22004-01-29 03:32:15 +00001788 // Loop through and make sure all of the globals are referring directly
1789 // to the node...
1790 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1791 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001792 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001793 }
1794
Chris Lattnerbd92b732003-06-19 21:15:11 +00001795 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001796 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001797 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1798 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001799 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001800 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001801 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001802 }
1803 }
1804
Chris Lattner28897e12004-02-08 00:53:26 +00001805 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001806 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001807 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001808 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001809 } else {
1810 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001811 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001812 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001813
1814 removeIdenticalCalls(FunctionCalls);
1815 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001816}
1817
1818
Chris Lattner5c7380e2003-01-29 21:10:20 +00001819/// markReachableNodes - This method recursively traverses the specified
1820/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1821/// to the set, which allows it to only traverse visited nodes once.
1822///
Chris Lattnera9548d92005-01-30 23:51:02 +00001823void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001824 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001825 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001826 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001827 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1828 I != E; ++I)
1829 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001830}
1831
Chris Lattnera9548d92005-01-30 23:51:02 +00001832void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001833 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001834 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001835
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001836 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1837 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001838}
1839
Chris Lattnera1220af2003-02-01 06:17:02 +00001840// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1841// looking for a node that is marked alive. If an alive node is found, return
1842// true, otherwise return false. If an alive node is reachable, this node is
1843// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001844//
Chris Lattnera9548d92005-01-30 23:51:02 +00001845static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1846 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001847 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001848 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001849 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001850
Chris Lattner85cfe012003-07-03 02:03:53 +00001851 // If this is a global node, it will end up in the globals graph anyway, so we
1852 // don't need to worry about it.
1853 if (IgnoreGlobals && N->isGlobalNode()) return false;
1854
Chris Lattneraa8146f2002-11-10 06:59:55 +00001855 // If we know that this node is alive, return so!
1856 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001857
Chris Lattneraa8146f2002-11-10 06:59:55 +00001858 // Otherwise, we don't think the node is alive yet, check for infinite
1859 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001860 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001861 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001862
Chris Lattner6be07942005-02-09 03:20:43 +00001863 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1864 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001865 N->markReachableNodes(Alive);
1866 return true;
1867 }
1868 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001869}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001870
Chris Lattnera1220af2003-02-01 06:17:02 +00001871// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1872// alive nodes.
1873//
Chris Lattnera9548d92005-01-30 23:51:02 +00001874static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
1875 hash_set<const DSNode*> &Alive,
1876 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001877 bool IgnoreGlobals) {
1878 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
1879 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00001880 return true;
1881 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00001882 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001883 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001884 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00001885 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
1886 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00001887 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001888 return false;
1889}
1890
Chris Lattnere2219762002-07-18 18:22:40 +00001891// removeDeadNodes - Use a more powerful reachability analysis to eliminate
1892// subgraphs that are unreachable. This often occurs because the data
1893// structure doesn't "escape" into it's caller, and thus should be eliminated
1894// from the caller's graph entirely. This is only appropriate to use when
1895// inlining graphs.
1896//
Chris Lattner394471f2003-01-23 22:05:33 +00001897void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00001898 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00001899
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001900 // Reduce the amount of work we have to do... remove dummy nodes left over by
1901 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00001902 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001903
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001904 TIME_REGION(X, "removeDeadNodes");
1905
Misha Brukman2f2d0652003-09-11 18:14:24 +00001906 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00001907
1908 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00001909 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001910 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00001911
Chris Lattner0b144872004-01-27 22:03:40 +00001912 // Copy and merge all information about globals to the GlobalsGraph if this is
1913 // not a final pass (where unreachable globals are removed).
1914 //
1915 // Strip all alloca bits since the current function is only for the BU pass.
1916 // Strip all incomplete bits since they are short-lived properties and they
1917 // will be correctly computed when rematerializing nodes into the functions.
1918 //
1919 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
1920 DSGraph::StripIncompleteBit);
1921
Chris Lattneraa8146f2002-11-10 06:59:55 +00001922 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00001923{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
1924 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
1925 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001926 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00001927 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001928 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001929 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00001930
1931 // Make sure that all globals are cloned over as roots.
Chris Lattner00948c02004-01-28 02:05:05 +00001932 if (!(Flags & DSGraph::RemoveUnreachableGlobals)) {
1933 DSGraph::ScalarMapTy::iterator SMI =
1934 GlobalsGraph->getScalarMap().find(I->first);
1935 if (SMI != GlobalsGraph->getScalarMap().end())
1936 GGCloner.merge(SMI->second, I->second);
1937 else
1938 GGCloner.getClonedNH(I->second);
1939 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00001940 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00001941 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001942 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00001943}
Chris Lattnere2219762002-07-18 18:22:40 +00001944
Chris Lattner0b144872004-01-27 22:03:40 +00001945 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00001946 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
1947 I != E; ++I)
1948 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001949
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001950 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00001951 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
1952 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001953
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001954
1955 // Now find globals and aux call nodes that are already live or reach a live
1956 // value (which makes them live in turn), and continue till no more are found.
1957 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001958 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00001959 hash_set<const DSNode*> Visited;
1960 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001961 do {
1962 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00001963 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00001964 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001965 // unreachable globals in the list.
1966 //
1967 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001968 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00001969 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
1970 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
1971 Flags & DSGraph::RemoveUnreachableGlobals)) {
1972 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
1973 GlobalNodes.pop_back(); // erase efficiently
1974 Iterate = true;
1975 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00001976
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001977 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
1978 // call nodes that get resolved will be difficult to remove from that graph.
1979 // The final unresolved call nodes must be handled specially at the end of
1980 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00001981 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00001982 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00001983 (CI->isIndirectCall()
1984 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001985 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001986 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00001987 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001988 Iterate = true;
1989 }
1990 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00001991
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001992 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001993 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001994 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
1995 E = AuxFunctionCalls.end(); CI != E; )
1996 if (AuxFCallsAlive.count(&*CI))
1997 ++CI;
1998 else {
1999 // Copy and merge global nodes and dead aux call nodes into the
2000 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2001 // target pointers using the GGCloner.
2002 //
2003 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2004 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002005
Chris Lattnera9548d92005-01-30 23:51:02 +00002006 AuxFunctionCalls.erase(CI++);
2007 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002008
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002009 // We are finally done with the GGCloner so we can destroy it.
2010 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002011
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002012 // At this point, any nodes which are visited, but not alive, are nodes
2013 // which can be removed. Loop over all nodes, eliminating completely
2014 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002015 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002016 std::vector<DSNode*> DeadNodes;
2017 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002018 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2019 DSNode *N = NI++;
2020 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2021
2022 if (!Alive.count(N)) {
2023 Nodes.remove(N);
2024 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002025 DeadNodes.push_back(N);
2026 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002027 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002028 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002029 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002030
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002031 // Remove all unreachable globals from the ScalarMap.
2032 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2033 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002034 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002035 if (!Alive.count(GlobalNodes[i].second))
2036 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002037 else
2038 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002039
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002040 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002041 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2042 delete DeadNodes[i];
2043
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002044 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002045}
2046
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002047void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002048 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2049 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002050}
2051
Chris Lattner2c7725a2004-03-03 20:55:27 +00002052void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2053 if (CS.isIndirectCall()) {
2054 AssertNodeInGraph(CS.getCalleeNode());
2055#if 0
2056 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2057 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Chris Lattnerf8db8a02005-02-27 06:15:51 +00002058 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002059#endif
2060 }
2061 AssertNodeInGraph(CS.getRetVal().getNode());
2062 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2063 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2064}
2065
2066void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002067 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2068 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002069}
2070void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002071 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2072 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002073}
2074
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002075void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002076 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2077 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002078
Chris Lattner8d327672003-06-30 03:36:09 +00002079 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002080 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002081 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002082 AssertNodeInGraph(I->second.getNode());
2083 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002084 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002085 "Global points to node, but node isn't global?");
2086 AssertNodeContainsGlobal(I->second.getNode(), GV);
2087 }
2088 }
2089 AssertCallNodesInGraph();
2090 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002091
2092 // Check that all pointer arguments to any functions in this graph have
2093 // destinations.
2094 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2095 E = ReturnNodes.end();
2096 RI != E; ++RI) {
2097 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002098 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002099 if (isPointerType(AI->getType()))
2100 assert(!getNodeForValue(AI).isNull() &&
2101 "Pointer argument must be in the scalar map!");
2102 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002103}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002104
Chris Lattner400433d2003-11-11 05:08:59 +00002105/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002106/// nodes reachable from the two graphs, computing the mapping of nodes from the
2107/// first to the second graph. This mapping may be many-to-one (i.e. the first
2108/// graph may have multiple nodes representing one node in the second graph),
2109/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002110///
2111void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002112 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2113 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002114 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2115 if (N1 == 0 || N2 == 0) return;
2116
2117 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002118 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002119 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002120 if (StrictChecking) {
2121 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2122 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2123 Entry.getNode()->isNodeCompletelyFolded()) &&
2124 "Inconsistent mapping detected!");
2125 }
Chris Lattner400433d2003-11-11 05:08:59 +00002126 return;
2127 }
2128
Chris Lattnerefffdc92004-07-07 06:12:52 +00002129 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002130
2131 // Loop over all of the fields that N1 and N2 have in common, recursively
2132 // mapping the edges together now.
2133 int N2Idx = NH2.getOffset()-NH1.getOffset();
2134 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002135 if (N2Size == 0) return; // No edges to map to.
2136
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002137 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2138 const DSNodeHandle &N1NH = N1->getLink(i);
2139 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2140 // aligned right).
2141 if (!N1NH.isNull()) {
2142 if (unsigned(N2Idx)+i < N2Size)
2143 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2144 else
2145 computeNodeMapping(N1NH,
2146 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2147 }
2148 }
Chris Lattner400433d2003-11-11 05:08:59 +00002149}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002150
2151
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002152/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002153/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002154void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002155 DSGraph &GG = *getGlobalsGraph();
2156
2157 DSScalarMap &SM = getScalarMap();
2158 for (DSScalarMap::global_iterator I = SM.global_begin(),
2159 E = SM.global_end(); I != E; ++I)
2160 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2161}
2162
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002163/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002164/// nodes in this graph. Note that any uses of this method are probably bugs,
2165/// unless it is known that the globals graph has been merged into this graph!
2166void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2167 NodeMapTy NodeMap;
2168 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002169
Chris Lattner36a13cd2005-03-15 17:52:18 +00002170 while (!NodeMap.empty()) {
2171 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2172 NodeMap.begin()->first));
2173 NodeMap.erase(NodeMap.begin());
2174 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002175}
2176
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002177
2178/// computeCalleeCallerMapping - Given a call from a function in the current
2179/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2180/// mapping of nodes from the callee to nodes in the caller.
2181void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2182 DSGraph &CalleeGraph,
2183 NodeMapTy &NodeMap) {
2184
2185 DSCallSite CalleeArgs =
2186 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
2187
2188 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2189
2190 unsigned NumArgs = CS.getNumPtrArgs();
2191 if (NumArgs > CalleeArgs.getNumPtrArgs())
2192 NumArgs = CalleeArgs.getNumPtrArgs();
2193
2194 for (unsigned i = 0; i != NumArgs; ++i)
2195 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
2196
2197 // Map the nodes that are pointed to by globals.
2198 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2199 DSScalarMap &CallerSM = getScalarMap();
2200
2201 if (CalleeSM.global_size() >= CallerSM.global_size()) {
2202 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
2203 E = CallerSM.global_end(); GI != E; ++GI)
2204 if (CalleeSM.global_count(*GI))
2205 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2206 } else {
2207 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
2208 E = CalleeSM.global_end(); GI != E; ++GI)
2209 if (CallerSM.global_count(*GI))
2210 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2211 }
2212}