blob: 25aadbafc2b88e8fdaf4c1845fd2c59fa13b66e4 [file] [log] [blame]
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001//===- DataStructure.cpp - Implement the core data structure analysis -----===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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"
Chris Lattnerd8642122005-03-24 21:07:47 +000026#include "llvm/ADT/SCCIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/Statistic.h"
28#include "llvm/Support/Timer.h"
Chris Lattner72382102006-01-22 23:19:18 +000029#include <iostream>
Chris Lattner0d9bab82002-07-18 00:12:30 +000030#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000033#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
34
Chris Lattner08db7192002-11-06 06:20:27 +000035namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000036 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
37 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
38 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
39 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000040 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
41 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000042};
43
Chris Lattner1e9d1472005-03-22 23:54:52 +000044#if 0
Chris Lattner93ddd7e2004-01-22 16:36:28 +000045#define TIME_REGION(VARNAME, DESC) \
46 NamedRegionTimer VARNAME(DESC)
47#else
48#define TIME_REGION(VARNAME, DESC)
49#endif
50
Chris Lattnerb1060432002-11-07 05:20:53 +000051using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000052
Chris Lattner6f967742004-10-30 04:05:01 +000053/// isForwarding - Return true if this NodeHandle is forwarding to another
54/// one.
55bool DSNodeHandle::isForwarding() const {
56 return N && N->isForwarding();
57}
58
Chris Lattner731b2d72003-02-13 19:09:00 +000059DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000060 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000061
62 // Handle node forwarding here!
63 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
64 Offset += N->ForwardNH.getOffset();
65
66 if (--N->NumReferrers == 0) {
67 // Removing the last referrer to the node, sever the forwarding link
68 N->stopForwarding();
69 }
70
71 N = Next;
72 N->NumReferrers++;
73 if (N->Size <= Offset) {
74 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
75 Offset = 0;
76 }
77 return N;
78}
79
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000080//===----------------------------------------------------------------------===//
Chris Lattner612f0b72005-03-22 00:09:45 +000081// DSScalarMap Implementation
82//===----------------------------------------------------------------------===//
83
84DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
85 assert(ValueMap.count(GV) == 0 && "GV already exists!");
86
87 // If the node doesn't exist, check to see if it's a global that is
88 // equated to another global in the program.
89 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
90 if (ECI != GlobalECs.end()) {
91 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
92 if (Leader != GV) {
93 GV = Leader;
94 iterator I = ValueMap.find(GV);
95 if (I != ValueMap.end())
96 return I->second;
97 }
98 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +000099
Chris Lattner612f0b72005-03-22 00:09:45 +0000100 // Okay, this is either not an equivalenced global or it is the leader, it
101 // will be inserted into the scalar map now.
102 GlobalSet.insert(GV);
103
104 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
105}
106
107
108//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000109// DSNode Implementation
110//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000111
Chris Lattnerbd92b732003-06-19 21:15:11 +0000112DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +0000113 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000114 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +0000115 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +0000116 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000117 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000118}
119
Chris Lattner0d9bab82002-07-18 00:12:30 +0000120// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +0000121DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +0000122 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattneraf2e3e02005-04-12 03:59:27 +0000123 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattnerf590ced2004-03-04 17:06:53 +0000124 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +0000125 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +0000126 } else
Chris Lattner0b144872004-01-27 22:03:40 +0000127 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +0000128 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000129 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000130}
131
Chris Lattner15869aa2003-11-02 22:27:28 +0000132/// getTargetData - Get the target data object used to construct this node.
133///
134const TargetData &DSNode::getTargetData() const {
135 return ParentGraph->getTargetData();
136}
137
Chris Lattner72d29a42003-02-11 23:11:51 +0000138void DSNode::assertOK() const {
139 assert((Ty != Type::VoidTy ||
140 Ty == Type::VoidTy && (Size == 0 ||
141 (NodeType & DSNode::Array))) &&
142 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000143
144 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000145 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000146 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000147 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000148 assert(SM.find(Globals[i])->second.getNode() == this);
149 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000150}
151
152/// forwardNode - Mark this node as being obsolete, and all references to it
153/// should be forwarded to the specified node and offset.
154///
155void DSNode::forwardNode(DSNode *To, unsigned Offset) {
156 assert(this != To && "Cannot forward a node to itself!");
157 assert(ForwardNH.isNull() && "Already forwarding from this node!");
158 if (To->Size <= 1) Offset = 0;
159 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
160 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000161 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000162 NodeType = DEAD;
163 Size = 0;
164 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000165
166 // Remove this node from the parent graph's Nodes list.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000167 ParentGraph->unlinkNode(this);
Chris Lattner4ff0b962004-02-08 01:27:18 +0000168 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000169}
170
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000171// addGlobal - Add an entry for a global value to the Globals list. This also
172// marks the node with the 'G' flag if it does not already have it.
173//
174void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000175 // First, check to make sure this is the leader if the global is in an
176 // equivalence class.
177 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
178
Chris Lattner0d9bab82002-07-18 00:12:30 +0000179 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000180 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000181 std::lower_bound(Globals.begin(), Globals.end(), GV);
182
183 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000184 Globals.insert(I, GV);
185 NodeType |= GlobalNode;
186 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000187}
188
Chris Lattner7cdf3212005-03-20 03:29:54 +0000189// removeGlobal - Remove the specified global that is explicitly in the globals
190// list.
191void DSNode::removeGlobal(GlobalValue *GV) {
192 std::vector<GlobalValue*>::iterator I =
193 std::lower_bound(Globals.begin(), Globals.end(), GV);
194 assert(I != Globals.end() && *I == GV && "Global not in node!");
195 Globals.erase(I);
196}
197
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000198/// foldNodeCompletely - If we determine that this node has some funny
199/// behavior happening to it that we cannot represent, we fold it down to a
200/// single, completely pessimistic, node. This node is represented as a
201/// single byte with a single TypeEntry of "void".
202///
203void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000204 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000205
Chris Lattner08db7192002-11-06 06:20:27 +0000206 ++NumFolds;
207
Chris Lattner0b144872004-01-27 22:03:40 +0000208 // If this node has a size that is <= 1, we don't need to create a forwarding
209 // node.
210 if (getSize() <= 1) {
211 NodeType |= DSNode::Array;
212 Ty = Type::VoidTy;
213 Size = 1;
214 assert(Links.size() <= 1 && "Size is 1, but has more links?");
215 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000216 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000217 // Create the node we are going to forward to. This is required because
218 // some referrers may have an offset that is > 0. By forcing them to
219 // forward, the forwarder has the opportunity to correct the offset.
220 DSNode *DestNode = new DSNode(0, ParentGraph);
221 DestNode->NodeType = NodeType|DSNode::Array;
222 DestNode->Ty = Type::VoidTy;
223 DestNode->Size = 1;
224 DestNode->Globals.swap(Globals);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000225
Chris Lattner0b144872004-01-27 22:03:40 +0000226 // Start forwarding to the destination node...
227 forwardNode(DestNode, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000228
Chris Lattner0b144872004-01-27 22:03:40 +0000229 if (!Links.empty()) {
230 DestNode->Links.reserve(1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000231
Chris Lattner0b144872004-01-27 22:03:40 +0000232 DSNodeHandle NH(DestNode);
233 DestNode->Links.push_back(Links[0]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000234
Chris Lattner0b144872004-01-27 22:03:40 +0000235 // If we have links, merge all of our outgoing links together...
236 for (unsigned i = Links.size()-1; i != 0; --i)
237 NH.getNode()->Links[0].mergeWith(Links[i]);
238 Links.clear();
239 } else {
240 DestNode->Links.resize(1);
241 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000242 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000243}
Chris Lattner076c1f92002-11-07 06:31:54 +0000244
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000245/// isNodeCompletelyFolded - Return true if this node has been completely
246/// folded down to something that can never be expanded, effectively losing
247/// all of the field sensitivity that may be present in the node.
248///
249bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000250 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000251}
252
Chris Lattner82c6c722005-03-20 02:41:38 +0000253/// addFullGlobalsList - Compute the full set of global values that are
254/// represented by this node. Unlike getGlobalsList(), this requires fair
255/// amount of work to compute, so don't treat this method call as free.
256void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
257 if (globals_begin() == globals_end()) return;
258
259 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
260
261 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
262 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
263 if (ECI == EC.end())
264 List.push_back(*I);
265 else
266 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
267 }
268}
269
270/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
271/// functions in the full list.
272void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
273 if (globals_begin() == globals_end()) return;
274
275 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
276
277 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
278 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
279 if (ECI == EC.end()) {
280 if (Function *F = dyn_cast<Function>(*I))
281 List.push_back(F);
282 } else {
283 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
284 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
285 if (Function *F = dyn_cast<Function>(*MI))
286 List.push_back(F);
287 }
288 }
289}
290
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000291namespace {
292 /// TypeElementWalker Class - Used for implementation of physical subtyping...
293 ///
294 class TypeElementWalker {
295 struct StackState {
296 const Type *Ty;
297 unsigned Offset;
298 unsigned Idx;
299 StackState(const Type *T, unsigned Off = 0)
300 : Ty(T), Offset(Off), Idx(0) {}
301 };
302
303 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000304 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000305 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000306 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000307 Stack.push_back(T);
308 StepToLeaf();
309 }
310
311 bool isDone() const { return Stack.empty(); }
312 const Type *getCurrentType() const { return Stack.back().Ty; }
313 unsigned getCurrentOffset() const { return Stack.back().Offset; }
314
315 void StepToNextType() {
316 PopStackAndAdvance();
317 StepToLeaf();
318 }
319
320 private:
321 /// PopStackAndAdvance - Pop the current element off of the stack and
322 /// advance the underlying element to the next contained member.
323 void PopStackAndAdvance() {
324 assert(!Stack.empty() && "Cannot pop an empty stack!");
325 Stack.pop_back();
326 while (!Stack.empty()) {
327 StackState &SS = Stack.back();
328 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
329 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000330 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000331 const StructLayout *SL = TD.getStructLayout(ST);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000332 SS.Offset +=
Chris Lattner507bdf92005-01-12 04:51:37 +0000333 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000334 return;
335 }
336 Stack.pop_back(); // At the end of the structure
337 } else {
338 const ArrayType *AT = cast<ArrayType>(SS.Ty);
339 ++SS.Idx;
340 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000341 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000342 return;
343 }
344 Stack.pop_back(); // At the end of the array
345 }
346 }
347 }
348
349 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
350 /// on the type stack.
351 void StepToLeaf() {
352 if (Stack.empty()) return;
353 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
354 StackState &SS = Stack.back();
355 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000356 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000357 assert(SS.Idx == 0);
358 PopStackAndAdvance();
359 } else {
360 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000361 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000362 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000363 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000364 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000365 }
366 } else {
367 const ArrayType *AT = cast<ArrayType>(SS.Ty);
368 if (AT->getNumElements() == 0) {
369 assert(SS.Idx == 0);
370 PopStackAndAdvance();
371 } else {
372 // Step into the array...
373 assert(SS.Idx < AT->getNumElements());
374 Stack.push_back(StackState(AT->getElementType(),
375 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000376 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000377 }
378 }
379 }
380 }
381 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000382} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000383
384/// ElementTypesAreCompatible - Check to see if the specified types are
385/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000386/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
387/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000388///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000389static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000390 bool AllowLargerT1, const TargetData &TD){
391 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000392
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000393 while (!T1W.isDone() && !T2W.isDone()) {
394 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
395 return false;
396
397 const Type *T1 = T1W.getCurrentType();
398 const Type *T2 = T2W.getCurrentType();
399 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
400 return false;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000401
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000402 T1W.StepToNextType();
403 T2W.StepToNextType();
404 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000405
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000406 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000407}
408
409
Chris Lattner08db7192002-11-06 06:20:27 +0000410/// mergeTypeInfo - This method merges the specified type into the current node
411/// at the specified offset. This may update the current node's type record if
412/// this gives more information to the node, it may do nothing to the node if
413/// this information is already known, or it may merge the node completely (and
414/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000415///
Chris Lattner08db7192002-11-06 06:20:27 +0000416/// This method returns true if the node is completely folded, otherwise false.
417///
Chris Lattner088b6392003-03-03 17:13:31 +0000418bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
419 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000420 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000421 // Check to make sure the Size member is up-to-date. Size can be one of the
422 // following:
423 // Size = 0, Ty = Void: Nothing is known about this node.
424 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
425 // Size = 1, Ty = Void, Array = 1: The node is collapsed
426 // Otherwise, sizeof(Ty) = Size
427 //
Chris Lattner18552922002-11-18 21:44:46 +0000428 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
429 (Size == 0 && !Ty->isSized() && !isArray()) ||
430 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
431 (Size == 0 && !Ty->isSized() && !isArray()) ||
432 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000433 "Size member of DSNode doesn't match the type structure!");
434 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000435
Chris Lattner18552922002-11-18 21:44:46 +0000436 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000437 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000438
Chris Lattner08db7192002-11-06 06:20:27 +0000439 // Return true immediately if the node is completely folded.
440 if (isNodeCompletelyFolded()) return true;
441
Chris Lattner23f83dc2002-11-08 22:49:57 +0000442 // If this is an array type, eliminate the outside arrays because they won't
443 // be used anyway. This greatly reduces the size of large static arrays used
444 // as global variables, for example.
445 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000446 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000447 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
448 // FIXME: we might want to keep small arrays, but must be careful about
449 // things like: [2 x [10000 x int*]]
450 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000451 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000452 }
453
Chris Lattner08db7192002-11-06 06:20:27 +0000454 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000455 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000456
457 // Otherwise check to see if we can fold this type into the current node. If
458 // we can't, we fold the node completely, if we can, we potentially update our
459 // internal state.
460 //
Chris Lattner18552922002-11-18 21:44:46 +0000461 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000462 // If this is the first type that this node has seen, just accept it without
463 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000464 assert(Offset == 0 && !isArray() &&
465 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000466
467 // If this node would have to have an unreasonable number of fields, just
468 // collapse it. This can occur for fortran common blocks, which have stupid
469 // things like { [100000000 x double], [1000000 x double] }.
470 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Chris Lattner1e9d1472005-03-22 23:54:52 +0000471 if (NumFields > 256) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000472 foldNodeCompletely();
473 return true;
474 }
475
Chris Lattner18552922002-11-18 21:44:46 +0000476 Ty = NewTy;
477 NodeType &= ~Array;
478 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000479 Size = NewTySize;
480
481 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000482 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000483 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000484 }
Chris Lattner08db7192002-11-06 06:20:27 +0000485
486 // Handle node expansion case here...
487 if (Offset+NewTySize > Size) {
488 // It is illegal to grow this node if we have treated it as an array of
489 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000490 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000491 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000492 return true;
493 }
494
495 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000496 std::cerr << "UNIMP: Trying to merge a growth type into "
497 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000498 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000499 return true;
500 }
501
502 // Okay, the situation is nice and simple, we are trying to merge a type in
503 // at offset 0 that is bigger than our current type. Implement this by
504 // switching to the new type and then merge in the smaller one, which should
505 // hit the other code path here. If the other code path decides it's not
506 // ok, it will collapse the node as appropriate.
507 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000508
509 // If this node would have to have an unreasonable number of fields, just
510 // collapse it. This can occur for fortran common blocks, which have stupid
511 // things like { [100000000 x double], [1000000 x double] }.
512 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Chris Lattner1e9d1472005-03-22 23:54:52 +0000513 if (NumFields > 256) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000514 foldNodeCompletely();
515 return true;
516 }
517
Chris Lattner94f84702005-03-17 19:56:56 +0000518 const Type *OldTy = Ty;
519 Ty = NewTy;
520 NodeType &= ~Array;
521 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000522 Size = NewTySize;
523
524 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000525 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000526
527 // Merge in the old type now... which is guaranteed to be smaller than the
528 // "current" type.
529 return mergeTypeInfo(OldTy, 0);
530 }
531
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000532 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000533 "Cannot merge something into a part of our type that doesn't exist!");
534
Chris Lattner18552922002-11-18 21:44:46 +0000535 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000536 // type that starts at offset Offset.
537 //
538 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000539 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000540 while (O < Offset) {
541 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
542
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000543 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000544 case Type::StructTyID: {
545 const StructType *STy = cast<StructType>(SubType);
546 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000547 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000548
549 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000550 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000551 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000552 break;
553 }
554 case Type::ArrayTyID: {
555 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000556 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000557 unsigned Remainder = (Offset-O) % ElSize;
558 O = Offset-Remainder;
559 break;
560 }
561 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000562 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000563 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000564 }
565 }
566
567 assert(O == Offset && "Could not achieve the correct offset!");
568
569 // If we found our type exactly, early exit
570 if (SubType == NewTy) return false;
571
Misha Brukman96a8bd72004-04-29 04:05:30 +0000572 // Differing function types don't require us to merge. They are not values
573 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000574 if (isa<FunctionType>(SubType) &&
575 isa<FunctionType>(NewTy)) return false;
576
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000577 unsigned SubTypeSize = SubType->isSized() ?
Chris Lattner507bdf92005-01-12 04:51:37 +0000578 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000579
580 // Ok, we are getting desperate now. Check for physical subtyping, where we
581 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000582 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000583 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000584 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000585 return false;
586
Chris Lattner08db7192002-11-06 06:20:27 +0000587 // Okay, so we found the leader type at the offset requested. Search the list
588 // of types that starts at this offset. If SubType is currently an array or
589 // structure, the type desired may actually be the first element of the
590 // composite type...
591 //
Chris Lattner18552922002-11-18 21:44:46 +0000592 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000593 while (SubType != NewTy) {
594 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000595 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000596 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000597 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000598 case Type::StructTyID: {
599 const StructType *STy = cast<StructType>(SubType);
600 const StructLayout &SL = *TD.getStructLayout(STy);
601 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000602 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000603 else
604 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000605 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000606 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000607 break;
Chris Lattner18552922002-11-18 21:44:46 +0000608 }
Chris Lattner08db7192002-11-06 06:20:27 +0000609 case Type::ArrayTyID:
610 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000611 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000612 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000613 break;
614 default: ;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000615 // fall out
Chris Lattner08db7192002-11-06 06:20:27 +0000616 }
617
618 if (NextSubType == 0)
619 break; // In the default case, break out of the loop
620
Chris Lattner18552922002-11-18 21:44:46 +0000621 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000622 break; // Don't allow shrinking to a smaller type than NewTySize
623 SubType = NextSubType;
624 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000625 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000626 }
627
628 // If we found the type exactly, return it...
629 if (SubType == NewTy)
630 return false;
631
632 // Check to see if we have a compatible, but different type...
633 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000634 // Check to see if this type is obviously convertible... int -> uint f.e.
635 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000636 return false;
637
638 // Check to see if we have a pointer & integer mismatch going on here,
639 // loading a pointer as a long, for example.
640 //
641 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
642 NewTy->isInteger() && isa<PointerType>(SubType))
643 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000644 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
645 // We are accessing the field, plus some structure padding. Ignore the
646 // structure padding.
647 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000648 }
649
Chris Lattner58f98d02003-07-02 04:38:49 +0000650 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000651 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
652 M = getParentGraph()->retnodes_begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000653 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
654 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
655 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
656 << "SubType: ";
657 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000658
Chris Lattner088b6392003-03-03 17:13:31 +0000659 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000660 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000661}
662
Chris Lattner08db7192002-11-06 06:20:27 +0000663
664
Misha Brukman96a8bd72004-04-29 04:05:30 +0000665/// addEdgeTo - Add an edge from the current node to the specified node. This
666/// can cause merging of nodes in the graph.
667///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000668void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000669 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000670
Chris Lattner08db7192002-11-06 06:20:27 +0000671 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000672 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000673 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000674 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000675 } else { // No merging to perform...
676 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000677 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000678}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000679
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000680
Misha Brukman96a8bd72004-04-29 04:05:30 +0000681/// MergeSortedVectors - Efficiently merge a vector into another vector where
682/// duplicates are not allowed and both are sorted. This assumes that 'T's are
683/// efficiently copyable and have sane comparison semantics.
684///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000685static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
686 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000687 // By far, the most common cases will be the simple ones. In these cases,
688 // avoid having to allocate a temporary vector...
689 //
690 if (Src.empty()) { // Nothing to merge in...
691 return;
692 } else if (Dest.empty()) { // Just copy the result in...
693 Dest = Src;
694 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000695 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000696 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000697 std::lower_bound(Dest.begin(), Dest.end(), V);
698 if (I == Dest.end() || *I != Src[0]) // If not already contained...
699 Dest.insert(I, Src[0]);
700 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000701 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000702 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000703 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000704 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
705 if (I == Dest.end() || *I != Tmp) // If not already contained...
706 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000707
708 } else {
709 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000710 std::vector<GlobalValue*> Old(Dest);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000711
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000712 // Make space for all of the type entries now...
713 Dest.resize(Dest.size()+Src.size());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000714
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000715 // Merge the two sorted ranges together... into Dest.
716 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000717
718 // Now erase any duplicate entries that may have accumulated into the
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000719 // vectors (because they were in both of the input sets)
720 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
721 }
722}
723
Chris Lattner0b144872004-01-27 22:03:40 +0000724void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
725 MergeSortedVectors(Globals, RHS);
726}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000727
Chris Lattner0b144872004-01-27 22:03:40 +0000728// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000729// This function does the hard work of merging two nodes, CurNodeH
730// and NH after filtering out trivial cases and making sure that
731// CurNodeH.offset >= NH.offset.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000732//
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000733// ***WARNING***
734// Since merging may cause either node to go away, we must always
735// use the node-handles to refer to the nodes. These node handles are
736// automatically updated during merging, so will always provide access
737// to the correct node after a merge.
738//
739void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
740 assert(CurNodeH.getOffset() >= NH.getOffset() &&
741 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000742 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
743 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000744
745 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
746 // respect to NH.Offset) is now zero. NOffset is the distance from the base
747 // of our object that N starts from.
748 //
749 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
750 unsigned NSize = NH.getNode()->getSize();
751
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000752 // If the two nodes are of different size, and the smaller node has the array
753 // bit set, collapse!
754 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000755#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000756 if (NSize < CurNodeH.getNode()->getSize()) {
757 if (NH.getNode()->isArray())
758 NH.getNode()->foldNodeCompletely();
759 } else if (CurNodeH.getNode()->isArray()) {
760 NH.getNode()->foldNodeCompletely();
761 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000762#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000763 }
764
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000765 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000766 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000767 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000768 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000769
770 // If we are merging a node with a completely folded node, then both nodes are
771 // now completely folded.
772 //
773 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
774 if (!NH.getNode()->isNodeCompletelyFolded()) {
775 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000776 assert(NH.getNode() && NH.getOffset() == 0 &&
777 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000778 NOffset = NH.getOffset();
779 NSize = NH.getNode()->getSize();
780 assert(NOffset == 0 && NSize == 1);
781 }
782 } else if (NH.getNode()->isNodeCompletelyFolded()) {
783 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000784 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
785 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000786 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000787 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000788 assert(NOffset == 0 && NSize == 1);
789 }
790
Chris Lattner72d29a42003-02-11 23:11:51 +0000791 DSNode *N = NH.getNode();
792 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000793 assert(!CurNodeH.getNode()->isDeadNode());
794
Chris Lattner0b144872004-01-27 22:03:40 +0000795 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000796 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000797
Chris Lattner72d29a42003-02-11 23:11:51 +0000798 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000799 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000800 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000801
Chris Lattner72d29a42003-02-11 23:11:51 +0000802 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
803 //
804 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
805 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000806 if (Link.getNode()) {
807 // Compute the offset into the current node at which to
808 // merge this link. In the common case, this is a linear
809 // relation to the offset in the original node (with
810 // wrapping), but if the current node gets collapsed due to
811 // recursive merging, we must make sure to merge in all remaining
812 // links at offset zero.
813 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000814 DSNode *CN = CurNodeH.getNode();
815 if (CN->Size != 1)
816 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
817 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000818 }
819 }
820
821 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000822 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000823
824 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000825 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000826 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000827
828 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000829 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000830 }
831}
832
833
Misha Brukman96a8bd72004-04-29 04:05:30 +0000834/// mergeWith - Merge this node and the specified node, moving all links to and
835/// from the argument node into the current node, deleting the node argument.
836/// Offset indicates what offset the specified node is to be merged into the
837/// current node.
838///
839/// The specified node may be a null pointer (in which case, we update it to
840/// point to this node).
841///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000842void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
843 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000844 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000845 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000846
Chris Lattner5254a8d2004-01-22 16:31:08 +0000847 // If the RHS is a null node, make it point to this node!
848 if (N == 0) {
849 NH.mergeWith(DSNodeHandle(this, Offset));
850 return;
851 }
852
Chris Lattnerbd92b732003-06-19 21:15:11 +0000853 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000854 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
855
Chris Lattner02606632002-11-04 06:48:26 +0000856 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000857 // We cannot merge two pieces of the same node together, collapse the node
858 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000859 DEBUG(std::cerr << "Attempting to merge two chunks of"
860 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000861 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000862 return;
863 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000864
Chris Lattner5190ce82002-11-12 07:20:45 +0000865 // If both nodes are not at offset 0, make sure that we are merging the node
866 // at an later offset into the node with the zero offset.
867 //
868 if (Offset < NH.getOffset()) {
869 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
870 return;
871 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
872 // If the offsets are the same, merge the smaller node into the bigger node
873 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
874 return;
875 }
876
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000877 // Ok, now we can merge the two nodes. Use a static helper that works with
878 // two node handles, since "this" may get merged away at intermediate steps.
879 DSNodeHandle CurNodeH(this, Offset);
880 DSNodeHandle NHCopy(NH);
881 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000882}
883
Chris Lattner0b144872004-01-27 22:03:40 +0000884
885//===----------------------------------------------------------------------===//
886// ReachabilityCloner Implementation
887//===----------------------------------------------------------------------===//
888
889DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
890 if (SrcNH.isNull()) return DSNodeHandle();
891 const DSNode *SN = SrcNH.getNode();
892
893 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000894 if (!NH.isNull()) { // Node already mapped?
895 DSNode *NHN = NH.getNode();
896 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
897 }
Chris Lattner0b144872004-01-27 22:03:40 +0000898
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000899 // If SrcNH has globals and the destination graph has one of the same globals,
900 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000901 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000902 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000903 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000904 I != E; ++I) {
905 GlobalValue *GV = *I;
906 DSScalarMap::iterator GI = DestSM.find(GV);
907 if (GI != DestSM.end() && !GI->second.isNull()) {
908 // We found one, use merge instead!
909 merge(GI->second, Src.getNodeForValue(GV));
910 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000911 DSNode *NHN = NH.getNode();
912 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000913 }
914 }
915 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000916
Chris Lattner0b144872004-01-27 22:03:40 +0000917 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
918 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000919 NH = DN;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000920
Chris Lattner0b144872004-01-27 22:03:40 +0000921 // Next, recursively clone all outgoing links as necessary. Note that
922 // adding these links can cause the node to collapse itself at any time, and
923 // the current node may be merged with arbitrary other nodes. For this
924 // reason, we must always go through NH.
925 DN = 0;
926 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
927 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
928 if (!SrcEdge.isNull()) {
929 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
930 // Compute the offset into the current node at which to
931 // merge this link. In the common case, this is a linear
932 // relation to the offset in the original node (with
933 // wrapping), but if the current node gets collapsed due to
934 // recursive merging, we must make sure to merge in all remaining
935 // links at offset zero.
936 unsigned MergeOffset = 0;
937 DSNode *CN = NH.getNode();
938 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000939 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000940 CN->addEdgeTo(MergeOffset, DestEdge);
941 }
942 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000943
Chris Lattner0b144872004-01-27 22:03:40 +0000944 // If this node contains any globals, make sure they end up in the scalar
945 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +0000946 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +0000947 I != E; ++I) {
948 GlobalValue *GV = *I;
949 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
950 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
951 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
952 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000953 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000954 }
Chris Lattner82c6c722005-03-20 02:41:38 +0000955 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +0000956
957 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
958}
959
960void ReachabilityCloner::merge(const DSNodeHandle &NH,
961 const DSNodeHandle &SrcNH) {
962 if (SrcNH.isNull()) return; // Noop
963 if (NH.isNull()) {
964 // If there is no destination node, just clone the source and assign the
965 // destination node to be it.
966 NH.mergeWith(getClonedNH(SrcNH));
967 return;
968 }
969
970 // Okay, at this point, we know that we have both a destination and a source
971 // node that need to be merged. Check to see if the source node has already
972 // been cloned.
973 const DSNode *SN = SrcNH.getNode();
974 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000975 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000976 DSNode *SCNHN = SCNH.getNode();
977 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000978 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000979 return; // Nothing to do!
980 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000981
Chris Lattner0b144872004-01-27 22:03:40 +0000982 // Okay, so the source node has not already been cloned. Instead of creating
983 // a new DSNode, only to merge it into the one we already have, try to perform
984 // the merge in-place. The only case we cannot handle here is when the offset
985 // into the existing node is less than the offset into the virtual node we are
986 // merging in. In this case, we have to extend the existing node, which
987 // requires an allocation anyway.
988 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
989 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000990 if (!DN->isNodeCompletelyFolded()) {
991 // Make sure the destination node is folded if the source node is folded.
992 if (SN->isNodeCompletelyFolded()) {
993 DN->foldNodeCompletely();
994 DN = NH.getNode();
995 } else if (SN->getSize() != DN->getSize()) {
996 // If the two nodes are of different size, and the smaller node has the
997 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000998#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000999 if (SN->getSize() < DN->getSize()) {
1000 if (SN->isArray()) {
1001 DN->foldNodeCompletely();
1002 DN = NH.getNode();
1003 }
1004 } else if (DN->isArray()) {
1005 DN->foldNodeCompletely();
1006 DN = NH.getNode();
1007 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001008#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001009 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001010
1011 // Merge the type entries of the two nodes together...
Chris Lattner0b144872004-01-27 22:03:40 +00001012 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1013 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1014 DN = NH.getNode();
1015 }
1016 }
1017
1018 assert(!DN->isDeadNode());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001019
Chris Lattner0b144872004-01-27 22:03:40 +00001020 // Merge the NodeType information.
1021 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1022
1023 // Before we start merging outgoing links and updating the scalar map, make
1024 // sure it is known that this is the representative node for the src node.
1025 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1026
1027 // If the source node contains any globals, make sure they end up in the
1028 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001029 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001030 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001031 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001032
1033 // Update the scalar map for the graph we are merging the source node
1034 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001035 for (DSNode::globals_iterator I = SN->globals_begin(),
1036 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001037 GlobalValue *GV = *I;
1038 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1039 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1040 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1041 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001042 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001043 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001044 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001045 }
1046 } else {
1047 // We cannot handle this case without allocating a temporary node. Fall
1048 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001049 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1050 NewDN->maskNodeTypes(BitsToKeep);
1051
1052 unsigned NHOffset = NH.getOffset();
1053 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001054
Chris Lattner0b144872004-01-27 22:03:40 +00001055 assert(NH.getNode() &&
1056 (NH.getOffset() > NHOffset ||
1057 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1058 "Merging did not adjust the offset!");
1059
1060 // Before we start merging outgoing links and updating the scalar map, make
1061 // sure it is known that this is the representative node for the src node.
1062 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001063
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001064 // If the source node contained any globals, make sure to create entries
Chris Lattneread9eb72004-01-29 08:36:22 +00001065 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001066 for (DSNode::globals_iterator I = SN->globals_begin(),
1067 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001068 GlobalValue *GV = *I;
1069 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1070 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1071 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1072 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1073 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1074 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001075 }
Chris Lattner0b144872004-01-27 22:03:40 +00001076 }
1077
1078
1079 // Next, recursively merge all outgoing links as necessary. Note that
1080 // adding these links can cause the destination node to collapse itself at
1081 // any time, and the current node may be merged with arbitrary other nodes.
1082 // For this reason, we must always go through NH.
1083 DN = 0;
1084 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1085 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1086 if (!SrcEdge.isNull()) {
1087 // Compute the offset into the current node at which to
1088 // merge this link. In the common case, this is a linear
1089 // relation to the offset in the original node (with
1090 // wrapping), but if the current node gets collapsed due to
1091 // recursive merging, we must make sure to merge in all remaining
1092 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001093 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001094 unsigned MergeOffset =
1095 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001096
Chris Lattnerf590ced2004-03-04 17:06:53 +00001097 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1098 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001099 // Perform the recursive merging. Make sure to create a temporary NH,
1100 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001101 merge(Tmp, SrcEdge);
1102 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001103 Tmp.mergeWith(getClonedNH(SrcEdge));
1104 // Merging this could cause all kinds of recursive things to happen,
1105 // culminating in the current node being eliminated. Since this is
1106 // possible, make sure to reaquire the link from 'CN'.
1107
1108 unsigned MergeOffset = 0;
1109 CN = SCNH.getNode();
1110 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1111 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001112 }
Chris Lattner0b144872004-01-27 22:03:40 +00001113 }
1114 }
1115}
1116
1117/// mergeCallSite - Merge the nodes reachable from the specified src call
1118/// site into the nodes reachable from DestCS.
Chris Lattnerb3439372005-03-21 20:28:50 +00001119void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
Chris Lattner0b144872004-01-27 22:03:40 +00001120 const DSCallSite &SrcCS) {
1121 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1122 unsigned MinArgs = DestCS.getNumPtrArgs();
1123 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001124
Chris Lattner0b144872004-01-27 22:03:40 +00001125 for (unsigned a = 0; a != MinArgs; ++a)
1126 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
Chris Lattner3f90a942005-03-21 09:39:51 +00001127
1128 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
Chris Lattnerb3439372005-03-21 20:28:50 +00001129 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
Chris Lattner0b144872004-01-27 22:03:40 +00001130}
1131
1132
Chris Lattner9de906c2002-10-20 22:11:44 +00001133//===----------------------------------------------------------------------===//
1134// DSCallSite Implementation
1135//===----------------------------------------------------------------------===//
1136
Vikram S. Adve26b98262002-10-20 21:41:02 +00001137// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001138Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001139 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001140}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001141
Chris Lattner0b144872004-01-27 22:03:40 +00001142void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1143 ReachabilityCloner &RC) {
1144 NH = RC.getClonedNH(Src);
1145}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001146
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001147//===----------------------------------------------------------------------===//
1148// DSGraph Implementation
1149//===----------------------------------------------------------------------===//
1150
Chris Lattnera9d65662003-06-30 05:57:30 +00001151/// getFunctionNames - Return a space separated list of the name of the
1152/// functions in this graph (if any)
1153std::string DSGraph::getFunctionNames() const {
1154 switch (getReturnNodes().size()) {
1155 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001156 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001157 default:
1158 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001159 for (DSGraph::retnodes_iterator I = retnodes_begin();
1160 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001161 Return += I->first->getName() + " ";
1162 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1163 return Return;
1164 }
1165}
1166
1167
Chris Lattnerf09ecff2005-03-21 22:49:53 +00001168DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1169 unsigned CloneFlags)
Chris Lattnerf4f62272005-03-19 22:23:45 +00001170 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001171 PrintAuxCalls = false;
Chris Lattnera2197132005-03-22 00:36:51 +00001172 cloneInto(G, CloneFlags);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001173}
1174
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001175DSGraph::~DSGraph() {
1176 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001177 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001178 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001179 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001180
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001181 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001182 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001183 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001184
Chris Lattner28897e12004-02-08 00:53:26 +00001185 // Free all of the nodes.
1186 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001187}
1188
Chris Lattner0d9bab82002-07-18 00:12:30 +00001189// dump - Allow inspection of graph in a debugger.
1190void DSGraph::dump() const { print(std::cerr); }
1191
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001192
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001193/// remapLinks - Change all of the Links in the current node according to the
1194/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001195///
Chris Lattner8d327672003-06-30 03:36:09 +00001196void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001197 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1198 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001199 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001200 if (ONMI != OldNodeMap.end()) {
1201 DSNode *ONMIN = ONMI->second.getNode();
1202 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1203 }
Chris Lattner2f561382004-01-22 16:56:13 +00001204 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001205}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001206
Chris Lattnerd672ab92005-02-15 18:40:55 +00001207/// addObjectToGraph - This method can be used to add global, stack, and heap
1208/// objects to the graph. This can be used when updating DSGraphs due to the
1209/// introduction of new temporary objects. The new object is not pointed to
1210/// and does not point to any other objects in the graph.
1211DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1212 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1213 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1214 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001215 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001216 ScalarMap[Ptr] = N;
1217
1218 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1219 N->addGlobal(GV);
1220 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1221 N->setHeapNodeMarker();
1222 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1223 N->setAllocaNodeMarker();
1224 } else {
1225 assert(0 && "Illegal memory object input!");
1226 }
1227 return N;
1228}
1229
1230
Chris Lattner5a540632003-06-30 03:15:25 +00001231/// cloneInto - Clone the specified DSGraph into the current graph. The
Chris Lattner3c920fa2005-03-22 00:21:05 +00001232/// translated ScalarMap for the old function is filled into the ScalarMap
1233/// for the graph, and the translated ReturnNodes map is returned into
1234/// ReturnNodes.
Chris Lattner5a540632003-06-30 03:15:25 +00001235///
1236/// The CloneFlags member controls various aspects of the cloning process.
1237///
Chris Lattnera2197132005-03-22 00:36:51 +00001238void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001239 TIME_REGION(X, "cloneInto");
Chris Lattner33312f72002-11-08 01:21:07 +00001240 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001241
Chris Lattnera2197132005-03-22 00:36:51 +00001242 NodeMapTy OldNodeMap;
1243
Chris Lattner1e883692003-02-03 20:08:51 +00001244 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001245 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1246 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1247 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001248 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001249
Chris Lattner84b80a22005-03-16 22:42:19 +00001250 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1251 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001252 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001253 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001254 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001255 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001256 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001257
Chris Lattner18552922002-11-18 21:44:46 +00001258#ifndef NDEBUG
1259 Timer::addPeakMemoryMeasurement();
1260#endif
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001261
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001262 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001263 // Note that we don't loop over the node's list to do this. The problem is
1264 // that remaping links can cause recursive merging to happen, which means
1265 // that node_iterator's can get easily invalidated! Because of this, we
1266 // loop over the OldNodeMap, which contains all of the new nodes as the
1267 // .second element of the map elements. Also note that if we remap a node
1268 // more than once, we won't break anything.
1269 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1270 I != E; ++I)
1271 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001272
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001273 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001274 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001275 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001276 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner3bc703b2005-03-22 01:42:59 +00001277 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
Chris Lattner6f967742004-10-30 04:05:01 +00001278 DSNode *MappedNodeN = MappedNode.getNode();
1279 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001280 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001281 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001282
Chris Lattner679e8e12002-11-08 21:27:12 +00001283 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001284 // Copy the function calls list.
1285 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1286 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001287 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001288
Chris Lattneracf491f2002-11-08 22:27:09 +00001289 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001290 // Copy the auxiliary function calls list.
1291 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1292 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001293 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001294
Chris Lattner5a540632003-06-30 03:15:25 +00001295 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001296 for (retnodes_iterator I = G.retnodes_begin(),
1297 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001298 const DSNodeHandle &Ret = I->second;
1299 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001300 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattnerd65145b2005-03-22 00:29:44 +00001301 ReturnNodes.insert(std::make_pair(I->first,
1302 DSNodeHandle(MappedRetN,
1303 MappedRet.getOffset()+Ret.getOffset())));
Chris Lattner5a540632003-06-30 03:15:25 +00001304 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001305}
1306
Chris Lattner5734e432005-03-24 23:46:04 +00001307/// spliceFrom - Logically perform the operation of cloning the RHS graph into
1308/// this graph, then clearing the RHS graph. Instead of performing this as
1309/// two seperate operations, do it as a single, much faster, one.
1310///
1311void DSGraph::spliceFrom(DSGraph &RHS) {
1312 // Change all of the nodes in RHS to think we are their parent.
1313 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1314 I != E; ++I)
1315 I->setParentGraph(this);
1316 // Take all of the nodes.
1317 Nodes.splice(Nodes.end(), RHS.Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001318
Chris Lattner5734e432005-03-24 23:46:04 +00001319 // Take all of the calls.
1320 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1321 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1322
1323 // Take all of the return nodes.
Chris Lattnerce7068d2005-03-25 00:02:41 +00001324 if (ReturnNodes.empty()) {
1325 ReturnNodes.swap(RHS.ReturnNodes);
1326 } else {
1327 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1328 RHS.ReturnNodes.clear();
1329 }
Chris Lattner5734e432005-03-24 23:46:04 +00001330
1331 // Merge the scalar map in.
1332 ScalarMap.spliceFrom(RHS.ScalarMap);
1333}
1334
1335/// spliceFrom - Copy all entries from RHS, then clear RHS.
1336///
1337void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1338 // Special case if this is empty.
1339 if (ValueMap.empty()) {
1340 ValueMap.swap(RHS.ValueMap);
1341 GlobalSet.swap(RHS.GlobalSet);
1342 } else {
1343 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1344 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1345 I != E; ++I)
1346 ValueMap[I->first].mergeWith(I->second);
1347 RHS.ValueMap.clear();
1348 }
1349}
1350
1351
Chris Lattnerbb753c42005-02-03 18:40:25 +00001352/// getFunctionArgumentsForCall - Given a function that is currently in this
1353/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1354/// function arguments. The vector is filled in with the return value (or
1355/// null if it is not pointer compatible), followed by all of the
1356/// pointer-compatible arguments.
1357void DSGraph::getFunctionArgumentsForCall(Function *F,
1358 std::vector<DSNodeHandle> &Args) const {
1359 Args.push_back(getReturnNodeFor(*F));
Chris Lattnereb394922005-03-23 16:43:11 +00001360 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1361 AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001362 if (isPointerType(AI->getType())) {
1363 Args.push_back(getNodeForValue(AI));
1364 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1365 }
1366}
1367
Chris Lattner4da120e2005-03-24 23:06:02 +00001368namespace {
1369 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1370 // node to a node cloned by the ReachabilityCloner object contained. To be
1371 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1372 // search at RC marked nodes. This is designed as an object so that
1373 // intermediate results can be memoized across invocations of
1374 // PathExistsToClonedNode.
1375 struct HackedGraphSCCFinder {
1376 ReachabilityCloner &RC;
1377 unsigned CurNodeId;
1378 std::vector<const DSNode*> SCCStack;
1379 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001380
Chris Lattner4da120e2005-03-24 23:06:02 +00001381 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1382 // Remove null pointer as a special case.
1383 NodeInfo[0] = std::make_pair(0, false);
Chris Lattnerd8642122005-03-24 21:07:47 +00001384 }
1385
Chris Lattner4da120e2005-03-24 23:06:02 +00001386 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1387
1388 bool PathExistsToClonedNode(const DSNode *N) {
1389 return VisitForSCCs(N).second;
1390 }
1391
1392 bool PathExistsToClonedNode(const DSCallSite &CS) {
1393 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1394 return true;
1395 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1396 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1397 return true;
1398 return false;
1399 }
1400 };
1401}
1402
1403std::pair<unsigned, bool> &HackedGraphSCCFinder::
1404VisitForSCCs(const DSNode *N) {
1405 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1406 NodeInfoIt = NodeInfo.lower_bound(N);
1407 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1408 return NodeInfoIt->second;
1409
1410 unsigned Min = CurNodeId++;
1411 unsigned MyId = Min;
1412 std::pair<unsigned, bool> &ThisNodeInfo =
1413 NodeInfo.insert(NodeInfoIt,
1414 std::make_pair(N, std::make_pair(MyId, false)))->second;
1415
1416 // Base case: if we find a global, this doesn't reach the cloned graph
1417 // portion.
1418 if (N->isGlobalNode()) {
1419 ThisNodeInfo.second = false;
1420 return ThisNodeInfo;
Chris Lattnerd8642122005-03-24 21:07:47 +00001421 }
1422
Chris Lattner4da120e2005-03-24 23:06:02 +00001423 // Base case: if this does reach the cloned graph portion... it does. :)
1424 if (RC.hasClonedNode(N)) {
1425 ThisNodeInfo.second = true;
1426 return ThisNodeInfo;
1427 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001428
Chris Lattner4da120e2005-03-24 23:06:02 +00001429 SCCStack.push_back(N);
Chris Lattnerd8642122005-03-24 21:07:47 +00001430
Chris Lattner4da120e2005-03-24 23:06:02 +00001431 // Otherwise, check all successors.
1432 bool AnyDirectSuccessorsReachClonedNodes = false;
1433 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
Chris Lattner63320cc2005-04-25 19:16:17 +00001434 EI != EE; ++EI)
1435 if (DSNode *Succ = EI->getNode()) {
1436 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1437 if (SuccInfo.first < Min) Min = SuccInfo.first;
1438 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1439 }
Chris Lattner4da120e2005-03-24 23:06:02 +00001440
1441 if (Min != MyId)
1442 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1443
1444 if (SCCStack.back() == N) { // Special case single node SCC.
1445 SCCStack.pop_back();
1446 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1447 return ThisNodeInfo;
1448 }
1449
1450 // Find out if any direct successors of any node reach cloned nodes.
1451 if (!AnyDirectSuccessorsReachClonedNodes)
1452 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1453 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1454 EI != EE; ++EI)
1455 if (DSNode *N = EI->getNode())
1456 if (NodeInfo[N].second) {
1457 AnyDirectSuccessorsReachClonedNodes = true;
1458 goto OutOfLoop;
1459 }
1460OutOfLoop:
1461 // If any successor reaches a cloned node, mark all nodes in this SCC as
1462 // reaching the cloned node.
1463 if (AnyDirectSuccessorsReachClonedNodes)
1464 while (SCCStack.back() != N) {
1465 NodeInfo[SCCStack.back()].second = true;
1466 SCCStack.pop_back();
1467 }
1468 SCCStack.pop_back();
1469 ThisNodeInfo.second = true;
1470 return ThisNodeInfo;
1471}
Chris Lattnerd8642122005-03-24 21:07:47 +00001472
Chris Lattnere8594442005-02-04 19:58:28 +00001473/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1474/// nodes from G2 into 'this' graph, merging the bindings specified by the
1475/// call site (in this graph) with the bindings specified by the vector in G2.
1476/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001477///
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001478void DSGraph::mergeInGraph(const DSCallSite &CS,
Chris Lattnere8594442005-02-04 19:58:28 +00001479 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001480 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001481 TIME_REGION(X, "mergeInGraph");
1482
Chris Lattnerc14f59c2005-03-23 20:12:08 +00001483 assert((CloneFlags & DontCloneCallNodes) &&
1484 "Doesn't support copying of call nodes!");
1485
Chris Lattner076c1f92002-11-07 06:31:54 +00001486 // If this is not a recursive call, clone the graph into this graph...
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001487 if (&Graph == this) {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001488 // Merge the return value with the return value of the context.
1489 Args[0].mergeWith(CS.getRetVal());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001490
Chris Lattnerbb753c42005-02-03 18:40:25 +00001491 // Resolve all of the function arguments.
1492 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001493 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001494 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001495
Chris Lattnerbb753c42005-02-03 18:40:25 +00001496 // Add the link from the argument scalar to the provided value.
1497 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001498 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001499 return;
Chris Lattner076c1f92002-11-07 06:31:54 +00001500 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001501
1502 // Clone the callee's graph into the current graph, keeping track of where
1503 // scalars in the old graph _used_ to point, and of the new nodes matching
1504 // nodes of the old graph.
1505 ReachabilityCloner RC(*this, Graph, CloneFlags);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001506
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001507 // Map the return node pointer over.
1508 if (!CS.getRetVal().isNull())
1509 RC.merge(CS.getRetVal(), Args[0]);
1510
1511 // Map over all of the arguments.
1512 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1513 if (i == Args.size()-1)
1514 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001515
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001516 // Add the link from the argument scalar to the provided value.
1517 RC.merge(CS.getPtrArg(i), Args[i+1]);
1518 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001519
Chris Lattnerd8642122005-03-24 21:07:47 +00001520 // We generally don't want to copy global nodes or aux calls from the callee
1521 // graph to the caller graph. However, we have to copy them if there is a
1522 // path from the node to a node we have already copied which does not go
1523 // through another global. Compute the set of node that can reach globals and
1524 // aux call nodes to copy over, then do it.
1525 std::vector<const DSCallSite*> AuxCallToCopy;
1526 std::vector<GlobalValue*> GlobalsToCopy;
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001527
Chris Lattnerd8642122005-03-24 21:07:47 +00001528 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1529 // true/false value for every visited node that reaches a copied node without
1530 // going through a global.
Chris Lattner4da120e2005-03-24 23:06:02 +00001531 HackedGraphSCCFinder SCCFinder(RC);
Chris Lattnerd8642122005-03-24 21:07:47 +00001532
1533 if (!(CloneFlags & DontCloneAuxCallNodes))
1534 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
Chris Lattner4da120e2005-03-24 23:06:02 +00001535 if (SCCFinder.PathExistsToClonedNode(*I))
Chris Lattnerd8642122005-03-24 21:07:47 +00001536 AuxCallToCopy.push_back(&*I);
1537
Chris Lattner4da120e2005-03-24 23:06:02 +00001538 const DSScalarMap &GSM = Graph.getScalarMap();
Chris Lattnerd8642122005-03-24 21:07:47 +00001539 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
Chris Lattner09adbbc92005-03-24 21:17:27 +00001540 E = GSM.global_end(); GI != E; ++GI) {
1541 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1542 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1543 EE = GlobalNode->edge_end(); EI != EE; ++EI)
Chris Lattner4da120e2005-03-24 23:06:02 +00001544 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
Chris Lattner09adbbc92005-03-24 21:17:27 +00001545 GlobalsToCopy.push_back(*GI);
1546 break;
1547 }
1548 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001549
1550 // Copy aux calls that are needed.
1551 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1552 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001553
Chris Lattnerd8642122005-03-24 21:07:47 +00001554 // Copy globals that are needed.
1555 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1556 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
Chris Lattner076c1f92002-11-07 06:31:54 +00001557}
1558
Chris Lattnere8594442005-02-04 19:58:28 +00001559
1560
1561/// mergeInGraph - The method is used for merging graphs together. If the
1562/// argument graph is not *this, it makes a clone of the specified graph, then
1563/// merges the nodes specified in the call site with the formal arguments in the
1564/// graph.
1565///
1566void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1567 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001568 // Set up argument bindings.
1569 std::vector<DSNodeHandle> Args;
1570 Graph.getFunctionArgumentsForCall(&F, Args);
1571
1572 mergeInGraph(CS, Args, Graph, CloneFlags);
1573}
1574
Chris Lattner58f98d02003-07-02 04:38:49 +00001575/// getCallSiteForArguments - Get the arguments and return value bindings for
1576/// the specified function in the current graph.
1577///
1578DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1579 std::vector<DSNodeHandle> Args;
1580
Chris Lattnere4d5c442005-03-15 04:54:21 +00001581 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001582 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001583 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001584
Chris Lattner808a7ae2003-09-20 16:34:13 +00001585 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001586}
1587
Chris Lattner85fb1be2004-03-09 19:37:06 +00001588/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1589/// the context of this graph, return the DSCallSite for it.
1590DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1591 DSNodeHandle RetVal;
1592 Instruction *I = CS.getInstruction();
1593 if (isPointerType(I->getType()))
1594 RetVal = getNodeForValue(I);
1595
1596 std::vector<DSNodeHandle> Args;
1597 Args.reserve(CS.arg_end()-CS.arg_begin());
1598
1599 // Calculate the arguments vector...
1600 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1601 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001602 if (isa<ConstantPointerNull>(*I))
1603 Args.push_back(DSNodeHandle());
1604 else
1605 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001606
1607 // Add a new function call entry...
1608 if (Function *F = CS.getCalledFunction())
1609 return DSCallSite(CS, RetVal, F, Args);
1610 else
1611 return DSCallSite(CS, RetVal,
1612 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1613}
1614
Chris Lattner58f98d02003-07-02 04:38:49 +00001615
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001616
Chris Lattner0d9bab82002-07-18 00:12:30 +00001617// markIncompleteNodes - Mark the specified node as having contents that are not
1618// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001619// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001620// must recursively traverse the data structure graph, marking all reachable
1621// nodes as incomplete.
1622//
1623static void markIncompleteNode(DSNode *N) {
1624 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001625 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001626
1627 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001628 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001629
Misha Brukman2f2d0652003-09-11 18:14:24 +00001630 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001631 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1632 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001633 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001634}
1635
Chris Lattnere71ffc22002-11-11 03:36:55 +00001636static void markIncomplete(DSCallSite &Call) {
1637 // Then the return value is certainly incomplete!
1638 markIncompleteNode(Call.getRetVal().getNode());
1639
1640 // All objects pointed to by function arguments are incomplete!
1641 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1642 markIncompleteNode(Call.getPtrArg(i).getNode());
1643}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001644
1645// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1646// modified by other functions that have not been resolved yet. This marks
1647// nodes that are reachable through three sources of "unknownness":
1648//
1649// Global Variables, Function Calls, and Incoming Arguments
1650//
1651// For any node that may have unknown components (because something outside the
1652// scope of current analysis may have modified it), the 'Incomplete' flag is
1653// added to the NodeType.
1654//
Chris Lattner394471f2003-01-23 22:05:33 +00001655void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001656 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001657 if (Flags & DSGraph::MarkFormalArgs)
1658 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1659 FI != E; ++FI) {
1660 Function &F = *FI->first;
Chris Lattner9342a932005-03-29 19:16:59 +00001661 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1662 I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001663 if (isPointerType(I->getType()))
1664 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001665 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001666 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001667
Chris Lattnera9548d92005-01-30 23:51:02 +00001668 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001669 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001670 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1671 E = FunctionCalls.end(); I != E; ++I)
1672 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001673 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001674 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1675 E = AuxFunctionCalls.end(); I != E; ++I)
1676 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001677
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001678 // Mark all global nodes as incomplete.
1679 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1680 E = ScalarMap.global_end(); I != E; ++I)
1681 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1682 if (!GV->hasInitializer() || // Always mark external globals incomp.
1683 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1684 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001685}
1686
Chris Lattneraa8146f2002-11-10 06:59:55 +00001687static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1688 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001689 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001690 // No interesting info?
1691 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001692 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001693 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001694}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001695
Chris Lattneraa8146f2002-11-10 06:59:55 +00001696static inline bool nodeContainsExternalFunction(const DSNode *N) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001697 std::vector<Function*> Funcs;
1698 N->addFullFunctionList(Funcs);
1699 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1700 if (Funcs[i]->isExternal()) return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001701 return false;
1702}
1703
Chris Lattnera9548d92005-01-30 23:51:02 +00001704static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001705 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001706 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001707
1708 // Scan the call list cleaning it up as necessary...
Chris Lattner1e9d1472005-03-22 23:54:52 +00001709 DSNodeHandle LastCalleeNode;
Chris Lattner923fc052003-02-05 21:59:58 +00001710 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001711 unsigned NumDuplicateCalls = 0;
1712 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001713
Chris Lattnera9548d92005-01-30 23:51:02 +00001714 unsigned NumDeleted = 0;
1715 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1716 I != E;) {
1717 DSCallSite &CS = *I;
1718 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001719
Chris Lattner1e9d1472005-03-22 23:54:52 +00001720 if (!CS.isIndirectCall()) {
1721 LastCalleeNode = 0;
1722 } else {
1723 DSNode *Callee = CS.getCalleeNode();
1724
1725 // If the Callee is a useless edge, this must be an unreachable call site,
1726 // eliminate it.
1727 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1728 Callee->getGlobalsList().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001729#ifndef NDEBUG
Chris Lattner1e9d1472005-03-22 23:54:52 +00001730 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001731#endif
Chris Lattner1e9d1472005-03-22 23:54:52 +00001732 Calls.erase(OldIt);
1733 ++NumDeleted;
1734 continue;
1735 }
1736
1737 // If the last call site in the list has the same callee as this one, and
1738 // if the callee contains an external function, it will never be
1739 // resolvable, just merge the call sites.
1740 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1741 LastCalleeContainsExternalFunction =
1742 nodeContainsExternalFunction(Callee);
1743
1744 std::list<DSCallSite>::iterator PrevIt = OldIt;
1745 --PrevIt;
1746 PrevIt->mergeWith(CS);
1747
1748 // No need to keep this call anymore.
1749 Calls.erase(OldIt);
1750 ++NumDeleted;
1751 continue;
1752 } else {
1753 LastCalleeNode = Callee;
1754 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001755 }
1756
1757 // If the return value or any arguments point to a void node with no
1758 // information at all in it, and the call node is the only node to point
1759 // to it, remove the edge to the node (killing the node).
1760 //
1761 killIfUselessEdge(CS.getRetVal());
1762 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1763 killIfUselessEdge(CS.getPtrArg(a));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001764
Chris Lattner0b144872004-01-27 22:03:40 +00001765#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001766 // If this call site calls the same function as the last call site, and if
1767 // the function pointer contains an external function, this node will
1768 // never be resolved. Merge the arguments of the call node because no
1769 // information will be lost.
1770 //
1771 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1772 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1773 ++NumDuplicateCalls;
1774 if (NumDuplicateCalls == 1) {
1775 if (LastCalleeNode)
1776 LastCalleeContainsExternalFunction =
1777 nodeContainsExternalFunction(LastCalleeNode);
1778 else
1779 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001780 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001781
Chris Lattnera9548d92005-01-30 23:51:02 +00001782 // It is not clear why, but enabling this code makes DSA really
1783 // sensitive to node forwarding. Basically, with this enabled, DSA
1784 // performs different number of inlinings based on which nodes are
1785 // forwarding or not. This is clearly a problem, so this code is
1786 // disabled until this can be resolved.
1787#if 1
1788 if (LastCalleeContainsExternalFunction
1789#if 0
1790 ||
1791 // This should be more than enough context sensitivity!
1792 // FIXME: Evaluate how many times this is tripped!
1793 NumDuplicateCalls > 20
1794#endif
1795 ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001796
Chris Lattnera9548d92005-01-30 23:51:02 +00001797 std::list<DSCallSite>::iterator PrevIt = OldIt;
1798 --PrevIt;
1799 PrevIt->mergeWith(CS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001800
Chris Lattnera9548d92005-01-30 23:51:02 +00001801 // No need to keep this call anymore.
1802 Calls.erase(OldIt);
1803 ++NumDeleted;
1804 continue;
1805 }
1806#endif
1807 } else {
1808 if (CS.isDirectCall()) {
1809 LastCalleeFunc = CS.getCalleeFunc();
1810 LastCalleeNode = 0;
1811 } else {
1812 LastCalleeNode = CS.getCalleeNode();
1813 LastCalleeFunc = 0;
1814 }
1815 NumDuplicateCalls = 0;
1816 }
1817#endif
1818
1819 if (I != Calls.end() && CS == *I) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001820 LastCalleeNode = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001821 Calls.erase(OldIt);
1822 ++NumDeleted;
1823 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001824 }
1825 }
Chris Lattner857eb062004-10-30 05:41:23 +00001826
Chris Lattnera9548d92005-01-30 23:51:02 +00001827 // Resort now that we simplified things.
1828 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001829
Chris Lattnera9548d92005-01-30 23:51:02 +00001830 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001831 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1832 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001833 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001834 std::list<DSCallSite>::iterator OldIt = CI++;
1835 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001836
1837 // If this call site is now the same as the previous one, we can delete it
1838 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001839 if (*OldIt == *CI) {
1840 Calls.erase(CI);
1841 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001842 ++NumDeleted;
1843 }
1844 }
1845
1846 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001847
Chris Lattner33312f72002-11-08 01:21:07 +00001848 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001849 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001850
Chris Lattnera9548d92005-01-30 23:51:02 +00001851 DEBUG(if (NumDeleted)
1852 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001853}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001854
Chris Lattneraa8146f2002-11-10 06:59:55 +00001855
Chris Lattnere2219762002-07-18 18:22:40 +00001856// removeTriviallyDeadNodes - After the graph has been constructed, this method
1857// removes all unreachable nodes that are created because they got merged with
1858// other nodes in the graph. These nodes will all be trivially unreachable, so
1859// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001860//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001861void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001862 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001863
Chris Lattner5ace1e42004-07-08 07:25:51 +00001864#if 0
1865 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1866 /// substantially!
1867
Chris Lattnerbab8c282003-09-20 21:34:07 +00001868 // Loop over all of the nodes in the graph, calling getNode on each field.
1869 // This will cause all nodes to update their forwarding edges, causing
1870 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001871 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001872 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001873 DSNode &N = *NI;
1874 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1875 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001876 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001877 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001878
Chris Lattner0b144872004-01-27 22:03:40 +00001879 // NOTE: This code is disabled. Though it should, in theory, allow us to
1880 // remove more nodes down below, the scan of the scalar map is incredibly
1881 // expensive for certain programs (with large SCCs). In the future, if we can
1882 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001883 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1884
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001885 // Likewise, forward any edges from the scalar nodes. While we are at it,
1886 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001887 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001888 I->second.getNode();
1889 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001890 }
Chris Lattner0b144872004-01-27 22:03:40 +00001891 }
1892#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001893 bool isGlobalsGraph = !GlobalsGraph;
1894
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001895 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001896 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001897
1898 // Do not remove *any* global nodes in the globals graph.
1899 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001900 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001901 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001902 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001903 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001904
Chris Lattner28897e12004-02-08 00:53:26 +00001905 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001906 // This is a useless node if it has no mod/ref info (checked above),
1907 // outgoing edges (which it cannot, as it is not modified in this
1908 // context), and it has no incoming edges. If it is a global node it may
1909 // have all of these properties and still have incoming edges, due to the
1910 // scalar map, so we check those now.
1911 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001912 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1913 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001914
Chris Lattner17a93e22004-01-29 03:32:15 +00001915 // Loop through and make sure all of the globals are referring directly
1916 // to the node...
1917 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1918 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001919 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001920 }
1921
Chris Lattnerbd92b732003-06-19 21:15:11 +00001922 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001923 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001924 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1925 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001926 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001927 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001928 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001929 }
1930 }
1931
Chris Lattner28897e12004-02-08 00:53:26 +00001932 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001933 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001934 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001935 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001936 } else {
1937 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001938 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001939 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001940
1941 removeIdenticalCalls(FunctionCalls);
1942 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001943}
1944
1945
Chris Lattner5c7380e2003-01-29 21:10:20 +00001946/// markReachableNodes - This method recursively traverses the specified
1947/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1948/// to the set, which allows it to only traverse visited nodes once.
1949///
Chris Lattnera9548d92005-01-30 23:51:02 +00001950void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001951 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001952 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001953 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001954 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1955 I != E; ++I)
1956 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001957}
1958
Chris Lattnera9548d92005-01-30 23:51:02 +00001959void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001960 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001961 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001962
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001963 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1964 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001965}
1966
Chris Lattnera1220af2003-02-01 06:17:02 +00001967// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1968// looking for a node that is marked alive. If an alive node is found, return
1969// true, otherwise return false. If an alive node is reachable, this node is
1970// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001971//
Chris Lattnera9548d92005-01-30 23:51:02 +00001972static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1973 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001974 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001975 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001976 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001977
Chris Lattner85cfe012003-07-03 02:03:53 +00001978 // If this is a global node, it will end up in the globals graph anyway, so we
1979 // don't need to worry about it.
1980 if (IgnoreGlobals && N->isGlobalNode()) return false;
1981
Chris Lattneraa8146f2002-11-10 06:59:55 +00001982 // If we know that this node is alive, return so!
1983 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001984
Chris Lattneraa8146f2002-11-10 06:59:55 +00001985 // Otherwise, we don't think the node is alive yet, check for infinite
1986 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001987 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001988 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001989
Chris Lattner6be07942005-02-09 03:20:43 +00001990 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1991 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001992 N->markReachableNodes(Alive);
1993 return true;
1994 }
1995 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001996}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001997
Chris Lattnera1220af2003-02-01 06:17:02 +00001998// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1999// alive nodes.
2000//
Chris Lattnera9548d92005-01-30 23:51:02 +00002001static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2002 hash_set<const DSNode*> &Alive,
2003 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002004 bool IgnoreGlobals) {
2005 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2006 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00002007 return true;
2008 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00002009 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002010 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002011 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00002012 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2013 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002014 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002015 return false;
2016}
2017
Chris Lattnere2219762002-07-18 18:22:40 +00002018// removeDeadNodes - Use a more powerful reachability analysis to eliminate
2019// subgraphs that are unreachable. This often occurs because the data
2020// structure doesn't "escape" into it's caller, and thus should be eliminated
2021// from the caller's graph entirely. This is only appropriate to use when
2022// inlining graphs.
2023//
Chris Lattner394471f2003-01-23 22:05:33 +00002024void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00002025 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00002026
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002027 // Reduce the amount of work we have to do... remove dummy nodes left over by
2028 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00002029 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002030
Chris Lattner93ddd7e2004-01-22 16:36:28 +00002031 TIME_REGION(X, "removeDeadNodes");
2032
Misha Brukman2f2d0652003-09-11 18:14:24 +00002033 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00002034
2035 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00002036 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002037 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00002038
Chris Lattner0b144872004-01-27 22:03:40 +00002039 // Copy and merge all information about globals to the GlobalsGraph if this is
2040 // not a final pass (where unreachable globals are removed).
2041 //
2042 // Strip all alloca bits since the current function is only for the BU pass.
2043 // Strip all incomplete bits since they are short-lived properties and they
2044 // will be correctly computed when rematerializing nodes into the functions.
2045 //
2046 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2047 DSGraph::StripIncompleteBit);
2048
Chris Lattneraa8146f2002-11-10 06:59:55 +00002049 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00002050{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
2051 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2052 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002053 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00002054 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002055 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002056 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00002057
2058 // Make sure that all globals are cloned over as roots.
Chris Lattner021decc2005-04-02 19:17:18 +00002059 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002060 DSGraph::ScalarMapTy::iterator SMI =
Chris Lattner00948c02004-01-28 02:05:05 +00002061 GlobalsGraph->getScalarMap().find(I->first);
2062 if (SMI != GlobalsGraph->getScalarMap().end())
2063 GGCloner.merge(SMI->second, I->second);
2064 else
2065 GGCloner.getClonedNH(I->second);
2066 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002067 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00002068 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002069 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00002070}
Chris Lattnere2219762002-07-18 18:22:40 +00002071
Chris Lattner0b144872004-01-27 22:03:40 +00002072 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00002073 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2074 I != E; ++I)
2075 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002076
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002077 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00002078 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2079 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002080
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002081
2082 // Now find globals and aux call nodes that are already live or reach a live
2083 // value (which makes them live in turn), and continue till no more are found.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002084 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002085 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00002086 hash_set<const DSNode*> Visited;
2087 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002088 do {
2089 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00002090 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00002091 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002092 // unreachable globals in the list.
2093 //
2094 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002095 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00002096 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002097 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
Chris Lattner0b144872004-01-27 22:03:40 +00002098 Flags & DSGraph::RemoveUnreachableGlobals)) {
2099 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2100 GlobalNodes.pop_back(); // erase efficiently
2101 Iterate = true;
2102 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002103
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002104 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2105 // call nodes that get resolved will be difficult to remove from that graph.
2106 // The final unresolved call nodes must be handled specially at the end of
2107 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00002108 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00002109 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00002110 (CI->isIndirectCall()
2111 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002112 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00002113 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00002114 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002115 Iterate = true;
2116 }
2117 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00002118
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002119 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002120 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00002121 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2122 E = AuxFunctionCalls.end(); CI != E; )
2123 if (AuxFCallsAlive.count(&*CI))
2124 ++CI;
2125 else {
2126 // Copy and merge global nodes and dead aux call nodes into the
2127 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2128 // target pointers using the GGCloner.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002129 //
Chris Lattnera9548d92005-01-30 23:51:02 +00002130 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2131 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002132
Chris Lattnera9548d92005-01-30 23:51:02 +00002133 AuxFunctionCalls.erase(CI++);
2134 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002135
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002136 // We are finally done with the GGCloner so we can destroy it.
2137 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002138
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002139 // At this point, any nodes which are visited, but not alive, are nodes
2140 // which can be removed. Loop over all nodes, eliminating completely
2141 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002142 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002143 std::vector<DSNode*> DeadNodes;
2144 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002145 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2146 DSNode *N = NI++;
2147 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2148
2149 if (!Alive.count(N)) {
2150 Nodes.remove(N);
2151 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002152 DeadNodes.push_back(N);
2153 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002154 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002155 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002156 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002157
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002158 // Remove all unreachable globals from the ScalarMap.
2159 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2160 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002161 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002162 if (!Alive.count(GlobalNodes[i].second))
2163 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002164 else
2165 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002166
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002167 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002168 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2169 delete DeadNodes[i];
2170
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002171 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002172}
2173
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002174void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002175 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2176 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002177}
2178
Chris Lattner2c7725a2004-03-03 20:55:27 +00002179void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2180 if (CS.isIndirectCall()) {
2181 AssertNodeInGraph(CS.getCalleeNode());
2182#if 0
2183 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2184 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002185 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002186#endif
2187 }
2188 AssertNodeInGraph(CS.getRetVal().getNode());
2189 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2190 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2191}
2192
2193void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002194 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2195 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002196}
2197void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002198 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2199 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002200}
2201
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002202void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002203 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2204 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002205
Chris Lattner8d327672003-06-30 03:36:09 +00002206 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002207 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002208 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002209 AssertNodeInGraph(I->second.getNode());
2210 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002211 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002212 "Global points to node, but node isn't global?");
2213 AssertNodeContainsGlobal(I->second.getNode(), GV);
2214 }
2215 }
2216 AssertCallNodesInGraph();
2217 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002218
2219 // Check that all pointer arguments to any functions in this graph have
2220 // destinations.
2221 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2222 E = ReturnNodes.end();
2223 RI != E; ++RI) {
2224 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002225 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002226 if (isPointerType(AI->getType()))
2227 assert(!getNodeForValue(AI).isNull() &&
2228 "Pointer argument must be in the scalar map!");
2229 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002230}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002231
Chris Lattner400433d2003-11-11 05:08:59 +00002232/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002233/// nodes reachable from the two graphs, computing the mapping of nodes from the
2234/// first to the second graph. This mapping may be many-to-one (i.e. the first
2235/// graph may have multiple nodes representing one node in the second graph),
2236/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002237///
2238void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002239 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2240 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002241 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2242 if (N1 == 0 || N2 == 0) return;
2243
2244 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002245 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002246 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002247 if (StrictChecking) {
2248 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2249 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2250 Entry.getNode()->isNodeCompletelyFolded()) &&
2251 "Inconsistent mapping detected!");
2252 }
Chris Lattner400433d2003-11-11 05:08:59 +00002253 return;
2254 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002255
Chris Lattnerefffdc92004-07-07 06:12:52 +00002256 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002257
2258 // Loop over all of the fields that N1 and N2 have in common, recursively
2259 // mapping the edges together now.
2260 int N2Idx = NH2.getOffset()-NH1.getOffset();
2261 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002262 if (N2Size == 0) return; // No edges to map to.
2263
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002264 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2265 const DSNodeHandle &N1NH = N1->getLink(i);
2266 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2267 // aligned right).
2268 if (!N1NH.isNull()) {
2269 if (unsigned(N2Idx)+i < N2Size)
2270 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2271 else
2272 computeNodeMapping(N1NH,
2273 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2274 }
2275 }
Chris Lattner400433d2003-11-11 05:08:59 +00002276}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002277
2278
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002279/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002280/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002281void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002282 DSGraph &GG = *getGlobalsGraph();
2283
2284 DSScalarMap &SM = getScalarMap();
2285 for (DSScalarMap::global_iterator I = SM.global_begin(),
2286 E = SM.global_end(); I != E; ++I)
2287 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2288}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002289
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002290/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002291/// nodes in this graph. Note that any uses of this method are probably bugs,
2292/// unless it is known that the globals graph has been merged into this graph!
2293void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2294 NodeMapTy NodeMap;
2295 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002296
Chris Lattner36a13cd2005-03-15 17:52:18 +00002297 while (!NodeMap.empty()) {
2298 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2299 NodeMap.begin()->first));
2300 NodeMap.erase(NodeMap.begin());
2301 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002302}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002303
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002304
2305/// computeCalleeCallerMapping - Given a call from a function in the current
2306/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2307/// mapping of nodes from the callee to nodes in the caller.
2308void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2309 DSGraph &CalleeGraph,
2310 NodeMapTy &NodeMap) {
2311
2312 DSCallSite CalleeArgs =
2313 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002314
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002315 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2316
2317 unsigned NumArgs = CS.getNumPtrArgs();
2318 if (NumArgs > CalleeArgs.getNumPtrArgs())
2319 NumArgs = CalleeArgs.getNumPtrArgs();
2320
2321 for (unsigned i = 0; i != NumArgs; ++i)
2322 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002323
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002324 // Map the nodes that are pointed to by globals.
2325 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2326 DSScalarMap &CallerSM = getScalarMap();
2327
2328 if (CalleeSM.global_size() >= CallerSM.global_size()) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002329 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002330 E = CallerSM.global_end(); GI != E; ++GI)
2331 if (CalleeSM.global_count(*GI))
2332 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2333 } else {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002334 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002335 E = CalleeSM.global_end(); GI != E; ++GI)
2336 if (CallerSM.global_count(*GI))
2337 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2338 }
2339}