blob: 904d8b10b769c53fcbea35d79376de8776d1c99b [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 Lattner0d9bab82002-07-18 00:12:30 +000029#include <algorithm>
Chris Lattner9a927292003-11-12 23:11:14 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattnerb29dd0f2004-12-08 21:03:56 +000032#define COLLAPSE_ARRAYS_AGGRESSIVELY 0
33
Chris Lattner08db7192002-11-06 06:20:27 +000034namespace {
Chris Lattnere92e7642004-02-07 23:58:05 +000035 Statistic<> NumFolds ("dsa", "Number of nodes completely folded");
36 Statistic<> NumCallNodesMerged("dsa", "Number of call nodes merged");
37 Statistic<> NumNodeAllocated ("dsa", "Number of nodes allocated");
38 Statistic<> NumDNE ("dsa", "Number of nodes removed by reachability");
Chris Lattnerc3f5f772004-02-08 01:51:48 +000039 Statistic<> NumTrivialDNE ("dsa", "Number of nodes trivially removed");
40 Statistic<> NumTrivialGlobalDNE("dsa", "Number of globals trivially removed");
Chris Lattner08db7192002-11-06 06:20:27 +000041};
42
Chris Lattner1e9d1472005-03-22 23:54:52 +000043#if 0
Chris Lattner93ddd7e2004-01-22 16:36:28 +000044#define TIME_REGION(VARNAME, DESC) \
45 NamedRegionTimer VARNAME(DESC)
46#else
47#define TIME_REGION(VARNAME, DESC)
48#endif
49
Chris Lattnerb1060432002-11-07 05:20:53 +000050using namespace DS;
Chris Lattnerfccd06f2002-10-01 22:33:50 +000051
Chris Lattner6f967742004-10-30 04:05:01 +000052/// isForwarding - Return true if this NodeHandle is forwarding to another
53/// one.
54bool DSNodeHandle::isForwarding() const {
55 return N && N->isForwarding();
56}
57
Chris Lattner731b2d72003-02-13 19:09:00 +000058DSNode *DSNodeHandle::HandleForwarding() const {
Chris Lattner4ff0b962004-02-08 01:27:18 +000059 assert(N->isForwarding() && "Can only be invoked if forwarding!");
Chris Lattner731b2d72003-02-13 19:09:00 +000060
61 // Handle node forwarding here!
62 DSNode *Next = N->ForwardNH.getNode(); // Cause recursive shrinkage
63 Offset += N->ForwardNH.getOffset();
64
65 if (--N->NumReferrers == 0) {
66 // Removing the last referrer to the node, sever the forwarding link
67 N->stopForwarding();
68 }
69
70 N = Next;
71 N->NumReferrers++;
72 if (N->Size <= Offset) {
73 assert(N->Size <= 1 && "Forwarded to shrunk but not collapsed node?");
74 Offset = 0;
75 }
76 return N;
77}
78
Chris Lattnerbb2a28f2002-03-26 22:39:06 +000079//===----------------------------------------------------------------------===//
Chris Lattner612f0b72005-03-22 00:09:45 +000080// DSScalarMap Implementation
81//===----------------------------------------------------------------------===//
82
83DSNodeHandle &DSScalarMap::AddGlobal(GlobalValue *GV) {
84 assert(ValueMap.count(GV) == 0 && "GV already exists!");
85
86 // If the node doesn't exist, check to see if it's a global that is
87 // equated to another global in the program.
88 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
89 if (ECI != GlobalECs.end()) {
90 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
91 if (Leader != GV) {
92 GV = Leader;
93 iterator I = ValueMap.find(GV);
94 if (I != ValueMap.end())
95 return I->second;
96 }
97 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +000098
Chris Lattner612f0b72005-03-22 00:09:45 +000099 // Okay, this is either not an equivalenced global or it is the leader, it
100 // will be inserted into the scalar map now.
101 GlobalSet.insert(GV);
102
103 return ValueMap.insert(std::make_pair(GV, DSNodeHandle())).first->second;
104}
105
106
107//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000108// DSNode Implementation
109//===----------------------------------------------------------------------===//
Chris Lattnerbb2a28f2002-03-26 22:39:06 +0000110
Chris Lattnerbd92b732003-06-19 21:15:11 +0000111DSNode::DSNode(const Type *T, DSGraph *G)
Chris Lattner70793862003-07-02 23:57:05 +0000112 : NumReferrers(0), Size(0), ParentGraph(G), Ty(Type::VoidTy), NodeType(0) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000113 // Add the type entry if it is specified...
Chris Lattner08db7192002-11-06 06:20:27 +0000114 if (T) mergeTypeInfo(T, 0);
Chris Lattner9857c1a2004-02-08 01:05:37 +0000115 if (G) G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000116 ++NumNodeAllocated;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000117}
118
Chris Lattner0d9bab82002-07-18 00:12:30 +0000119// DSNode copy constructor... do not copy over the referrers list!
Chris Lattner0b144872004-01-27 22:03:40 +0000120DSNode::DSNode(const DSNode &N, DSGraph *G, bool NullLinks)
Chris Lattner70793862003-07-02 23:57:05 +0000121 : NumReferrers(0), Size(N.Size), ParentGraph(G),
Chris Lattneraf2e3e02005-04-12 03:59:27 +0000122 Ty(N.Ty), Globals(N.Globals), NodeType(N.NodeType) {
Chris Lattnerf590ced2004-03-04 17:06:53 +0000123 if (!NullLinks) {
Chris Lattner0b144872004-01-27 22:03:40 +0000124 Links = N.Links;
Chris Lattnerf590ced2004-03-04 17:06:53 +0000125 } else
Chris Lattner0b144872004-01-27 22:03:40 +0000126 Links.resize(N.Links.size()); // Create the appropriate number of null links
Chris Lattnere92e7642004-02-07 23:58:05 +0000127 G->addNode(this);
Chris Lattner0b144872004-01-27 22:03:40 +0000128 ++NumNodeAllocated;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000129}
130
Chris Lattner15869aa2003-11-02 22:27:28 +0000131/// getTargetData - Get the target data object used to construct this node.
132///
133const TargetData &DSNode::getTargetData() const {
134 return ParentGraph->getTargetData();
135}
136
Chris Lattner72d29a42003-02-11 23:11:51 +0000137void DSNode::assertOK() const {
138 assert((Ty != Type::VoidTy ||
139 Ty == Type::VoidTy && (Size == 0 ||
140 (NodeType & DSNode::Array))) &&
141 "Node not OK!");
Chris Lattner85cfe012003-07-03 02:03:53 +0000142
143 assert(ParentGraph && "Node has no parent?");
Chris Lattner62482e52004-01-28 09:15:42 +0000144 const DSScalarMap &SM = ParentGraph->getScalarMap();
Chris Lattner85cfe012003-07-03 02:03:53 +0000145 for (unsigned i = 0, e = Globals.size(); i != e; ++i) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000146 assert(SM.global_count(Globals[i]));
Chris Lattner85cfe012003-07-03 02:03:53 +0000147 assert(SM.find(Globals[i])->second.getNode() == this);
148 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000149}
150
151/// forwardNode - Mark this node as being obsolete, and all references to it
152/// should be forwarded to the specified node and offset.
153///
154void DSNode::forwardNode(DSNode *To, unsigned Offset) {
155 assert(this != To && "Cannot forward a node to itself!");
156 assert(ForwardNH.isNull() && "Already forwarding from this node!");
157 if (To->Size <= 1) Offset = 0;
158 assert((Offset < To->Size || (Offset == To->Size && Offset == 0)) &&
159 "Forwarded offset is wrong!");
Chris Lattnerefffdc92004-07-07 06:12:52 +0000160 ForwardNH.setTo(To, Offset);
Chris Lattner72d29a42003-02-11 23:11:51 +0000161 NodeType = DEAD;
162 Size = 0;
163 Ty = Type::VoidTy;
Chris Lattner4ff0b962004-02-08 01:27:18 +0000164
165 // Remove this node from the parent graph's Nodes list.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000166 ParentGraph->unlinkNode(this);
Chris Lattner4ff0b962004-02-08 01:27:18 +0000167 ParentGraph = 0;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000168}
169
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000170// addGlobal - Add an entry for a global value to the Globals list. This also
171// marks the node with the 'G' flag if it does not already have it.
172//
173void DSNode::addGlobal(GlobalValue *GV) {
Chris Lattnerf4f62272005-03-19 22:23:45 +0000174 // First, check to make sure this is the leader if the global is in an
175 // equivalence class.
176 GV = getParentGraph()->getScalarMap().getLeaderForGlobal(GV);
177
Chris Lattner0d9bab82002-07-18 00:12:30 +0000178 // Keep the list sorted.
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000179 std::vector<GlobalValue*>::iterator I =
Chris Lattner0d9bab82002-07-18 00:12:30 +0000180 std::lower_bound(Globals.begin(), Globals.end(), GV);
181
182 if (I == Globals.end() || *I != GV) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000183 Globals.insert(I, GV);
184 NodeType |= GlobalNode;
185 }
Chris Lattnerf9ae4c52002-07-11 20:32:22 +0000186}
187
Chris Lattner7cdf3212005-03-20 03:29:54 +0000188// removeGlobal - Remove the specified global that is explicitly in the globals
189// list.
190void DSNode::removeGlobal(GlobalValue *GV) {
191 std::vector<GlobalValue*>::iterator I =
192 std::lower_bound(Globals.begin(), Globals.end(), GV);
193 assert(I != Globals.end() && *I == GV && "Global not in node!");
194 Globals.erase(I);
195}
196
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000197/// foldNodeCompletely - If we determine that this node has some funny
198/// behavior happening to it that we cannot represent, we fold it down to a
199/// single, completely pessimistic, node. This node is represented as a
200/// single byte with a single TypeEntry of "void".
201///
202void DSNode::foldNodeCompletely() {
Chris Lattner72d29a42003-02-11 23:11:51 +0000203 if (isNodeCompletelyFolded()) return; // If this node is already folded...
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000204
Chris Lattner08db7192002-11-06 06:20:27 +0000205 ++NumFolds;
206
Chris Lattner0b144872004-01-27 22:03:40 +0000207 // If this node has a size that is <= 1, we don't need to create a forwarding
208 // node.
209 if (getSize() <= 1) {
210 NodeType |= DSNode::Array;
211 Ty = Type::VoidTy;
212 Size = 1;
213 assert(Links.size() <= 1 && "Size is 1, but has more links?");
214 Links.resize(1);
Chris Lattner72d29a42003-02-11 23:11:51 +0000215 } else {
Chris Lattner0b144872004-01-27 22:03:40 +0000216 // Create the node we are going to forward to. This is required because
217 // some referrers may have an offset that is > 0. By forcing them to
218 // forward, the forwarder has the opportunity to correct the offset.
219 DSNode *DestNode = new DSNode(0, ParentGraph);
220 DestNode->NodeType = NodeType|DSNode::Array;
221 DestNode->Ty = Type::VoidTy;
222 DestNode->Size = 1;
223 DestNode->Globals.swap(Globals);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000224
Chris Lattner0b144872004-01-27 22:03:40 +0000225 // Start forwarding to the destination node...
226 forwardNode(DestNode, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000227
Chris Lattner0b144872004-01-27 22:03:40 +0000228 if (!Links.empty()) {
229 DestNode->Links.reserve(1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000230
Chris Lattner0b144872004-01-27 22:03:40 +0000231 DSNodeHandle NH(DestNode);
232 DestNode->Links.push_back(Links[0]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000233
Chris Lattner0b144872004-01-27 22:03:40 +0000234 // If we have links, merge all of our outgoing links together...
235 for (unsigned i = Links.size()-1; i != 0; --i)
236 NH.getNode()->Links[0].mergeWith(Links[i]);
237 Links.clear();
238 } else {
239 DestNode->Links.resize(1);
240 }
Chris Lattner72d29a42003-02-11 23:11:51 +0000241 }
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000242}
Chris Lattner076c1f92002-11-07 06:31:54 +0000243
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000244/// isNodeCompletelyFolded - Return true if this node has been completely
245/// folded down to something that can never be expanded, effectively losing
246/// all of the field sensitivity that may be present in the node.
247///
248bool DSNode::isNodeCompletelyFolded() const {
Chris Lattner18552922002-11-18 21:44:46 +0000249 return getSize() == 1 && Ty == Type::VoidTy && isArray();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000250}
251
Chris Lattner82c6c722005-03-20 02:41:38 +0000252/// addFullGlobalsList - Compute the full set of global values that are
253/// represented by this node. Unlike getGlobalsList(), this requires fair
254/// amount of work to compute, so don't treat this method call as free.
255void DSNode::addFullGlobalsList(std::vector<GlobalValue*> &List) const {
256 if (globals_begin() == globals_end()) return;
257
258 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
259
260 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
261 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
262 if (ECI == EC.end())
263 List.push_back(*I);
264 else
265 List.insert(List.end(), EC.member_begin(ECI), EC.member_end());
266 }
267}
268
269/// addFullFunctionList - Identical to addFullGlobalsList, but only return the
270/// functions in the full list.
271void DSNode::addFullFunctionList(std::vector<Function*> &List) const {
272 if (globals_begin() == globals_end()) return;
273
274 EquivalenceClasses<GlobalValue*> &EC = getParentGraph()->getGlobalECs();
275
276 for (globals_iterator I = globals_begin(), E = globals_end(); I != E; ++I) {
277 EquivalenceClasses<GlobalValue*>::iterator ECI = EC.findValue(*I);
278 if (ECI == EC.end()) {
279 if (Function *F = dyn_cast<Function>(*I))
280 List.push_back(F);
281 } else {
282 for (EquivalenceClasses<GlobalValue*>::member_iterator MI =
283 EC.member_begin(ECI), E = EC.member_end(); MI != E; ++MI)
284 if (Function *F = dyn_cast<Function>(*MI))
285 List.push_back(F);
286 }
287 }
288}
289
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000290namespace {
291 /// TypeElementWalker Class - Used for implementation of physical subtyping...
292 ///
293 class TypeElementWalker {
294 struct StackState {
295 const Type *Ty;
296 unsigned Offset;
297 unsigned Idx;
298 StackState(const Type *T, unsigned Off = 0)
299 : Ty(T), Offset(Off), Idx(0) {}
300 };
301
302 std::vector<StackState> Stack;
Chris Lattner15869aa2003-11-02 22:27:28 +0000303 const TargetData &TD;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000304 public:
Chris Lattner15869aa2003-11-02 22:27:28 +0000305 TypeElementWalker(const Type *T, const TargetData &td) : TD(td) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000306 Stack.push_back(T);
307 StepToLeaf();
308 }
309
310 bool isDone() const { return Stack.empty(); }
311 const Type *getCurrentType() const { return Stack.back().Ty; }
312 unsigned getCurrentOffset() const { return Stack.back().Offset; }
313
314 void StepToNextType() {
315 PopStackAndAdvance();
316 StepToLeaf();
317 }
318
319 private:
320 /// PopStackAndAdvance - Pop the current element off of the stack and
321 /// advance the underlying element to the next contained member.
322 void PopStackAndAdvance() {
323 assert(!Stack.empty() && "Cannot pop an empty stack!");
324 Stack.pop_back();
325 while (!Stack.empty()) {
326 StackState &SS = Stack.back();
327 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
328 ++SS.Idx;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000329 if (SS.Idx != ST->getNumElements()) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000330 const StructLayout *SL = TD.getStructLayout(ST);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000331 SS.Offset +=
Chris Lattner507bdf92005-01-12 04:51:37 +0000332 unsigned(SL->MemberOffsets[SS.Idx]-SL->MemberOffsets[SS.Idx-1]);
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000333 return;
334 }
335 Stack.pop_back(); // At the end of the structure
336 } else {
337 const ArrayType *AT = cast<ArrayType>(SS.Ty);
338 ++SS.Idx;
339 if (SS.Idx != AT->getNumElements()) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000340 SS.Offset += unsigned(TD.getTypeSize(AT->getElementType()));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000341 return;
342 }
343 Stack.pop_back(); // At the end of the array
344 }
345 }
346 }
347
348 /// StepToLeaf - Used by physical subtyping to move to the first leaf node
349 /// on the type stack.
350 void StepToLeaf() {
351 if (Stack.empty()) return;
352 while (!Stack.empty() && !Stack.back().Ty->isFirstClassType()) {
353 StackState &SS = Stack.back();
354 if (const StructType *ST = dyn_cast<StructType>(SS.Ty)) {
Chris Lattnerd21cd802004-02-09 04:37:31 +0000355 if (ST->getNumElements() == 0) {
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000356 assert(SS.Idx == 0);
357 PopStackAndAdvance();
358 } else {
359 // Step into the structure...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000360 assert(SS.Idx < ST->getNumElements());
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000361 const StructLayout *SL = TD.getStructLayout(ST);
Chris Lattnerd21cd802004-02-09 04:37:31 +0000362 Stack.push_back(StackState(ST->getElementType(SS.Idx),
Chris Lattner507bdf92005-01-12 04:51:37 +0000363 SS.Offset+unsigned(SL->MemberOffsets[SS.Idx])));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000364 }
365 } else {
366 const ArrayType *AT = cast<ArrayType>(SS.Ty);
367 if (AT->getNumElements() == 0) {
368 assert(SS.Idx == 0);
369 PopStackAndAdvance();
370 } else {
371 // Step into the array...
372 assert(SS.Idx < AT->getNumElements());
373 Stack.push_back(StackState(AT->getElementType(),
374 SS.Offset+SS.Idx*
Chris Lattner507bdf92005-01-12 04:51:37 +0000375 unsigned(TD.getTypeSize(AT->getElementType()))));
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000376 }
377 }
378 }
379 }
380 };
Brian Gaeked0fde302003-11-11 22:41:34 +0000381} // end anonymous namespace
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000382
383/// ElementTypesAreCompatible - Check to see if the specified types are
384/// "physically" compatible. If so, return true, else return false. We only
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000385/// have to check the fields in T1: T2 may be larger than T1. If AllowLargerT1
386/// is true, then we also allow a larger T1.
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000387///
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000388static bool ElementTypesAreCompatible(const Type *T1, const Type *T2,
Chris Lattner15869aa2003-11-02 22:27:28 +0000389 bool AllowLargerT1, const TargetData &TD){
390 TypeElementWalker T1W(T1, TD), T2W(T2, TD);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000391
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000392 while (!T1W.isDone() && !T2W.isDone()) {
393 if (T1W.getCurrentOffset() != T2W.getCurrentOffset())
394 return false;
395
396 const Type *T1 = T1W.getCurrentType();
397 const Type *T2 = T2W.getCurrentType();
398 if (T1 != T2 && !T1->isLosslesslyConvertibleTo(T2))
399 return false;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000400
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000401 T1W.StepToNextType();
402 T2W.StepToNextType();
403 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000404
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000405 return AllowLargerT1 || T1W.isDone();
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000406}
407
408
Chris Lattner08db7192002-11-06 06:20:27 +0000409/// mergeTypeInfo - This method merges the specified type into the current node
410/// at the specified offset. This may update the current node's type record if
411/// this gives more information to the node, it may do nothing to the node if
412/// this information is already known, or it may merge the node completely (and
413/// return true) if the information is incompatible with what is already known.
Chris Lattner7b7200c2002-10-02 04:57:39 +0000414///
Chris Lattner08db7192002-11-06 06:20:27 +0000415/// This method returns true if the node is completely folded, otherwise false.
416///
Chris Lattner088b6392003-03-03 17:13:31 +0000417bool DSNode::mergeTypeInfo(const Type *NewTy, unsigned Offset,
418 bool FoldIfIncompatible) {
Chris Lattner15869aa2003-11-02 22:27:28 +0000419 const TargetData &TD = getTargetData();
Chris Lattner08db7192002-11-06 06:20:27 +0000420 // Check to make sure the Size member is up-to-date. Size can be one of the
421 // following:
422 // Size = 0, Ty = Void: Nothing is known about this node.
423 // Size = 0, Ty = FnTy: FunctionPtr doesn't have a size, so we use zero
424 // Size = 1, Ty = Void, Array = 1: The node is collapsed
425 // Otherwise, sizeof(Ty) = Size
426 //
Chris Lattner18552922002-11-18 21:44:46 +0000427 assert(((Size == 0 && Ty == Type::VoidTy && !isArray()) ||
428 (Size == 0 && !Ty->isSized() && !isArray()) ||
429 (Size == 1 && Ty == Type::VoidTy && isArray()) ||
430 (Size == 0 && !Ty->isSized() && !isArray()) ||
431 (TD.getTypeSize(Ty) == Size)) &&
Chris Lattner08db7192002-11-06 06:20:27 +0000432 "Size member of DSNode doesn't match the type structure!");
433 assert(NewTy != Type::VoidTy && "Cannot merge void type into DSNode!");
Chris Lattner7b7200c2002-10-02 04:57:39 +0000434
Chris Lattner18552922002-11-18 21:44:46 +0000435 if (Offset == 0 && NewTy == Ty)
Chris Lattner08db7192002-11-06 06:20:27 +0000436 return false; // This should be a common case, handle it efficiently
Chris Lattner7b7200c2002-10-02 04:57:39 +0000437
Chris Lattner08db7192002-11-06 06:20:27 +0000438 // Return true immediately if the node is completely folded.
439 if (isNodeCompletelyFolded()) return true;
440
Chris Lattner23f83dc2002-11-08 22:49:57 +0000441 // If this is an array type, eliminate the outside arrays because they won't
442 // be used anyway. This greatly reduces the size of large static arrays used
443 // as global variables, for example.
444 //
Chris Lattnerd8888932002-11-09 19:25:27 +0000445 bool WillBeArray = false;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000446 while (const ArrayType *AT = dyn_cast<ArrayType>(NewTy)) {
447 // FIXME: we might want to keep small arrays, but must be careful about
448 // things like: [2 x [10000 x int*]]
449 NewTy = AT->getElementType();
Chris Lattnerd8888932002-11-09 19:25:27 +0000450 WillBeArray = true;
Chris Lattner23f83dc2002-11-08 22:49:57 +0000451 }
452
Chris Lattner08db7192002-11-06 06:20:27 +0000453 // Figure out how big the new type we're merging in is...
Chris Lattner507bdf92005-01-12 04:51:37 +0000454 unsigned NewTySize = NewTy->isSized() ? (unsigned)TD.getTypeSize(NewTy) : 0;
Chris Lattner08db7192002-11-06 06:20:27 +0000455
456 // Otherwise check to see if we can fold this type into the current node. If
457 // we can't, we fold the node completely, if we can, we potentially update our
458 // internal state.
459 //
Chris Lattner18552922002-11-18 21:44:46 +0000460 if (Ty == Type::VoidTy) {
Chris Lattner08db7192002-11-06 06:20:27 +0000461 // If this is the first type that this node has seen, just accept it without
462 // question....
Chris Lattnerdbfe36e2003-11-02 21:02:20 +0000463 assert(Offset == 0 && !isArray() &&
464 "Cannot have an offset into a void node!");
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000465
466 // If this node would have to have an unreasonable number of fields, just
467 // collapse it. This can occur for fortran common blocks, which have stupid
468 // things like { [100000000 x double], [1000000 x double] }.
469 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Chris Lattner1e9d1472005-03-22 23:54:52 +0000470 if (NumFields > 256) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000471 foldNodeCompletely();
472 return true;
473 }
474
Chris Lattner18552922002-11-18 21:44:46 +0000475 Ty = NewTy;
476 NodeType &= ~Array;
477 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000478 Size = NewTySize;
479
480 // Calculate the number of outgoing links from this node.
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000481 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000482 return false;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000483 }
Chris Lattner08db7192002-11-06 06:20:27 +0000484
485 // Handle node expansion case here...
486 if (Offset+NewTySize > Size) {
487 // It is illegal to grow this node if we have treated it as an array of
488 // objects...
Chris Lattner18552922002-11-18 21:44:46 +0000489 if (isArray()) {
Chris Lattner088b6392003-03-03 17:13:31 +0000490 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000491 return true;
492 }
493
494 if (Offset) { // We could handle this case, but we don't for now...
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000495 std::cerr << "UNIMP: Trying to merge a growth type into "
496 << "offset != 0: Collapsing!\n";
Chris Lattner088b6392003-03-03 17:13:31 +0000497 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000498 return true;
499 }
500
501 // Okay, the situation is nice and simple, we are trying to merge a type in
502 // at offset 0 that is bigger than our current type. Implement this by
503 // switching to the new type and then merge in the smaller one, which should
504 // hit the other code path here. If the other code path decides it's not
505 // ok, it will collapse the node as appropriate.
506 //
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000507
508 // If this node would have to have an unreasonable number of fields, just
509 // collapse it. This can occur for fortran common blocks, which have stupid
510 // things like { [100000000 x double], [1000000 x double] }.
511 unsigned NumFields = (NewTySize+DS::PointerSize-1) >> DS::PointerShift;
Chris Lattner1e9d1472005-03-22 23:54:52 +0000512 if (NumFields > 256) {
Chris Lattnerec3f5c42005-03-17 05:25:34 +0000513 foldNodeCompletely();
514 return true;
515 }
516
Chris Lattner94f84702005-03-17 19:56:56 +0000517 const Type *OldTy = Ty;
518 Ty = NewTy;
519 NodeType &= ~Array;
520 if (WillBeArray) NodeType |= Array;
Chris Lattner08db7192002-11-06 06:20:27 +0000521 Size = NewTySize;
522
523 // Must grow links to be the appropriate size...
Chris Lattner94f84702005-03-17 19:56:56 +0000524 Links.resize(NumFields);
Chris Lattner08db7192002-11-06 06:20:27 +0000525
526 // Merge in the old type now... which is guaranteed to be smaller than the
527 // "current" type.
528 return mergeTypeInfo(OldTy, 0);
529 }
530
Chris Lattnerf17b39a2002-11-07 04:59:28 +0000531 assert(Offset <= Size &&
Chris Lattner08db7192002-11-06 06:20:27 +0000532 "Cannot merge something into a part of our type that doesn't exist!");
533
Chris Lattner18552922002-11-18 21:44:46 +0000534 // Find the section of Ty that NewTy overlaps with... first we find the
Chris Lattner08db7192002-11-06 06:20:27 +0000535 // type that starts at offset Offset.
536 //
537 unsigned O = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000538 const Type *SubType = Ty;
Chris Lattner08db7192002-11-06 06:20:27 +0000539 while (O < Offset) {
540 assert(Offset-O < TD.getTypeSize(SubType) && "Offset out of range!");
541
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000542 switch (SubType->getTypeID()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000543 case Type::StructTyID: {
544 const StructType *STy = cast<StructType>(SubType);
545 const StructLayout &SL = *TD.getStructLayout(STy);
Chris Lattner2787e032005-03-13 19:05:05 +0000546 unsigned i = SL.getElementContainingOffset(Offset-O);
Chris Lattner08db7192002-11-06 06:20:27 +0000547
548 // The offset we are looking for must be in the i'th element...
Chris Lattnerd21cd802004-02-09 04:37:31 +0000549 SubType = STy->getElementType(i);
Chris Lattner507bdf92005-01-12 04:51:37 +0000550 O += (unsigned)SL.MemberOffsets[i];
Chris Lattner08db7192002-11-06 06:20:27 +0000551 break;
552 }
553 case Type::ArrayTyID: {
554 SubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000555 unsigned ElSize = (unsigned)TD.getTypeSize(SubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000556 unsigned Remainder = (Offset-O) % ElSize;
557 O = Offset-Remainder;
558 break;
559 }
560 default:
Chris Lattner088b6392003-03-03 17:13:31 +0000561 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner0ac7d5c2003-02-03 19:12:15 +0000562 return true;
Chris Lattner08db7192002-11-06 06:20:27 +0000563 }
564 }
565
566 assert(O == Offset && "Could not achieve the correct offset!");
567
568 // If we found our type exactly, early exit
569 if (SubType == NewTy) return false;
570
Misha Brukman96a8bd72004-04-29 04:05:30 +0000571 // Differing function types don't require us to merge. They are not values
572 // anyway.
Chris Lattner0b144872004-01-27 22:03:40 +0000573 if (isa<FunctionType>(SubType) &&
574 isa<FunctionType>(NewTy)) return false;
575
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000576 unsigned SubTypeSize = SubType->isSized() ?
Chris Lattner507bdf92005-01-12 04:51:37 +0000577 (unsigned)TD.getTypeSize(SubType) : 0;
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000578
579 // Ok, we are getting desperate now. Check for physical subtyping, where we
580 // just require each element in the node to be compatible.
Chris Lattner06e24c82003-06-29 22:36:31 +0000581 if (NewTySize <= SubTypeSize && NewTySize && NewTySize < 256 &&
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000582 SubTypeSize && SubTypeSize < 256 &&
Chris Lattner15869aa2003-11-02 22:27:28 +0000583 ElementTypesAreCompatible(NewTy, SubType, !isArray(), TD))
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000584 return false;
585
Chris Lattner08db7192002-11-06 06:20:27 +0000586 // Okay, so we found the leader type at the offset requested. Search the list
587 // of types that starts at this offset. If SubType is currently an array or
588 // structure, the type desired may actually be the first element of the
589 // composite type...
590 //
Chris Lattner18552922002-11-18 21:44:46 +0000591 unsigned PadSize = SubTypeSize; // Size, including pad memory which is ignored
Chris Lattner08db7192002-11-06 06:20:27 +0000592 while (SubType != NewTy) {
593 const Type *NextSubType = 0;
Chris Lattnerbf10f052002-11-09 00:49:05 +0000594 unsigned NextSubTypeSize = 0;
Chris Lattner18552922002-11-18 21:44:46 +0000595 unsigned NextPadSize = 0;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000596 switch (SubType->getTypeID()) {
Chris Lattner18552922002-11-18 21:44:46 +0000597 case Type::StructTyID: {
598 const StructType *STy = cast<StructType>(SubType);
599 const StructLayout &SL = *TD.getStructLayout(STy);
600 if (SL.MemberOffsets.size() > 1)
Chris Lattner507bdf92005-01-12 04:51:37 +0000601 NextPadSize = (unsigned)SL.MemberOffsets[1];
Chris Lattner18552922002-11-18 21:44:46 +0000602 else
603 NextPadSize = SubTypeSize;
Chris Lattnerd21cd802004-02-09 04:37:31 +0000604 NextSubType = STy->getElementType(0);
Chris Lattner507bdf92005-01-12 04:51:37 +0000605 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner08db7192002-11-06 06:20:27 +0000606 break;
Chris Lattner18552922002-11-18 21:44:46 +0000607 }
Chris Lattner08db7192002-11-06 06:20:27 +0000608 case Type::ArrayTyID:
609 NextSubType = cast<ArrayType>(SubType)->getElementType();
Chris Lattner507bdf92005-01-12 04:51:37 +0000610 NextSubTypeSize = (unsigned)TD.getTypeSize(NextSubType);
Chris Lattner18552922002-11-18 21:44:46 +0000611 NextPadSize = NextSubTypeSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000612 break;
613 default: ;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000614 // fall out
Chris Lattner08db7192002-11-06 06:20:27 +0000615 }
616
617 if (NextSubType == 0)
618 break; // In the default case, break out of the loop
619
Chris Lattner18552922002-11-18 21:44:46 +0000620 if (NextPadSize < NewTySize)
Chris Lattner08db7192002-11-06 06:20:27 +0000621 break; // Don't allow shrinking to a smaller type than NewTySize
622 SubType = NextSubType;
623 SubTypeSize = NextSubTypeSize;
Chris Lattner18552922002-11-18 21:44:46 +0000624 PadSize = NextPadSize;
Chris Lattner08db7192002-11-06 06:20:27 +0000625 }
626
627 // If we found the type exactly, return it...
628 if (SubType == NewTy)
629 return false;
630
631 // Check to see if we have a compatible, but different type...
632 if (NewTySize == SubTypeSize) {
Misha Brukmanf117cc92003-05-20 18:45:36 +0000633 // Check to see if this type is obviously convertible... int -> uint f.e.
634 if (NewTy->isLosslesslyConvertibleTo(SubType))
Chris Lattner08db7192002-11-06 06:20:27 +0000635 return false;
636
637 // Check to see if we have a pointer & integer mismatch going on here,
638 // loading a pointer as a long, for example.
639 //
640 if (SubType->isInteger() && isa<PointerType>(NewTy) ||
641 NewTy->isInteger() && isa<PointerType>(SubType))
642 return false;
Chris Lattner18552922002-11-18 21:44:46 +0000643 } else if (NewTySize > SubTypeSize && NewTySize <= PadSize) {
644 // We are accessing the field, plus some structure padding. Ignore the
645 // structure padding.
646 return false;
Chris Lattner08db7192002-11-06 06:20:27 +0000647 }
648
Chris Lattner58f98d02003-07-02 04:38:49 +0000649 Module *M = 0;
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000650 if (getParentGraph()->retnodes_begin() != getParentGraph()->retnodes_end())
651 M = getParentGraph()->retnodes_begin()->first->getParent();
Chris Lattner58f98d02003-07-02 04:38:49 +0000652 DEBUG(std::cerr << "MergeTypeInfo Folding OrigTy: ";
653 WriteTypeSymbolic(std::cerr, Ty, M) << "\n due to:";
654 WriteTypeSymbolic(std::cerr, NewTy, M) << " @ " << Offset << "!\n"
655 << "SubType: ";
656 WriteTypeSymbolic(std::cerr, SubType, M) << "\n\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000657
Chris Lattner088b6392003-03-03 17:13:31 +0000658 if (FoldIfIncompatible) foldNodeCompletely();
Chris Lattner08db7192002-11-06 06:20:27 +0000659 return true;
Chris Lattner7b7200c2002-10-02 04:57:39 +0000660}
661
Chris Lattner08db7192002-11-06 06:20:27 +0000662
663
Misha Brukman96a8bd72004-04-29 04:05:30 +0000664/// addEdgeTo - Add an edge from the current node to the specified node. This
665/// can cause merging of nodes in the graph.
666///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000667void DSNode::addEdgeTo(unsigned Offset, const DSNodeHandle &NH) {
Chris Lattner0b144872004-01-27 22:03:40 +0000668 if (NH.isNull()) return; // Nothing to do
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000669
Chris Lattner08db7192002-11-06 06:20:27 +0000670 DSNodeHandle &ExistingEdge = getLink(Offset);
Chris Lattner0b144872004-01-27 22:03:40 +0000671 if (!ExistingEdge.isNull()) {
Chris Lattner7b7200c2002-10-02 04:57:39 +0000672 // Merge the two nodes...
Chris Lattner08db7192002-11-06 06:20:27 +0000673 ExistingEdge.mergeWith(NH);
Chris Lattner7b7200c2002-10-02 04:57:39 +0000674 } else { // No merging to perform...
675 setLink(Offset, NH); // Just force a link in there...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000676 }
Chris Lattner7b7200c2002-10-02 04:57:39 +0000677}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000678
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000679
Misha Brukman96a8bd72004-04-29 04:05:30 +0000680/// MergeSortedVectors - Efficiently merge a vector into another vector where
681/// duplicates are not allowed and both are sorted. This assumes that 'T's are
682/// efficiently copyable and have sane comparison semantics.
683///
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000684static void MergeSortedVectors(std::vector<GlobalValue*> &Dest,
685 const std::vector<GlobalValue*> &Src) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000686 // By far, the most common cases will be the simple ones. In these cases,
687 // avoid having to allocate a temporary vector...
688 //
689 if (Src.empty()) { // Nothing to merge in...
690 return;
691 } else if (Dest.empty()) { // Just copy the result in...
692 Dest = Src;
693 } else if (Src.size() == 1) { // Insert a single element...
Chris Lattner18552922002-11-18 21:44:46 +0000694 const GlobalValue *V = Src[0];
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000695 std::vector<GlobalValue*>::iterator I =
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000696 std::lower_bound(Dest.begin(), Dest.end(), V);
697 if (I == Dest.end() || *I != Src[0]) // If not already contained...
698 Dest.insert(I, Src[0]);
699 } else if (Dest.size() == 1) {
Chris Lattner18552922002-11-18 21:44:46 +0000700 GlobalValue *Tmp = Dest[0]; // Save value in temporary...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000701 Dest = Src; // Copy over list...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000702 std::vector<GlobalValue*>::iterator I =
Chris Lattner5190ce82002-11-12 07:20:45 +0000703 std::lower_bound(Dest.begin(), Dest.end(), Tmp);
704 if (I == Dest.end() || *I != Tmp) // If not already contained...
705 Dest.insert(I, Tmp);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000706
707 } else {
708 // Make a copy to the side of Dest...
Chris Lattnerb3416bc2003-02-01 04:01:21 +0000709 std::vector<GlobalValue*> Old(Dest);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000710
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000711 // Make space for all of the type entries now...
712 Dest.resize(Dest.size()+Src.size());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000713
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000714 // Merge the two sorted ranges together... into Dest.
715 std::merge(Old.begin(), Old.end(), Src.begin(), Src.end(), Dest.begin());
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000716
717 // Now erase any duplicate entries that may have accumulated into the
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000718 // vectors (because they were in both of the input sets)
719 Dest.erase(std::unique(Dest.begin(), Dest.end()), Dest.end());
720 }
721}
722
Chris Lattner0b144872004-01-27 22:03:40 +0000723void DSNode::mergeGlobals(const std::vector<GlobalValue*> &RHS) {
724 MergeSortedVectors(Globals, RHS);
725}
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000726
Chris Lattner0b144872004-01-27 22:03:40 +0000727// MergeNodes - Helper function for DSNode::mergeWith().
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000728// This function does the hard work of merging two nodes, CurNodeH
729// and NH after filtering out trivial cases and making sure that
730// CurNodeH.offset >= NH.offset.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000731//
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000732// ***WARNING***
733// Since merging may cause either node to go away, we must always
734// use the node-handles to refer to the nodes. These node handles are
735// automatically updated during merging, so will always provide access
736// to the correct node after a merge.
737//
738void DSNode::MergeNodes(DSNodeHandle& CurNodeH, DSNodeHandle& NH) {
739 assert(CurNodeH.getOffset() >= NH.getOffset() &&
740 "This should have been enforced in the caller.");
Chris Lattnerf590ced2004-03-04 17:06:53 +0000741 assert(CurNodeH.getNode()->getParentGraph()==NH.getNode()->getParentGraph() &&
742 "Cannot merge two nodes that are not in the same graph!");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000743
744 // Now we know that Offset >= NH.Offset, so convert it so our "Offset" (with
745 // respect to NH.Offset) is now zero. NOffset is the distance from the base
746 // of our object that N starts from.
747 //
748 unsigned NOffset = CurNodeH.getOffset()-NH.getOffset();
749 unsigned NSize = NH.getNode()->getSize();
750
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000751 // If the two nodes are of different size, and the smaller node has the array
752 // bit set, collapse!
753 if (NSize != CurNodeH.getNode()->getSize()) {
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000754#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000755 if (NSize < CurNodeH.getNode()->getSize()) {
756 if (NH.getNode()->isArray())
757 NH.getNode()->foldNodeCompletely();
758 } else if (CurNodeH.getNode()->isArray()) {
759 NH.getNode()->foldNodeCompletely();
760 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000761#endif
Chris Lattner5c5b10f2003-06-29 20:27:45 +0000762 }
763
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000764 // Merge the type entries of the two nodes together...
Chris Lattner72d29a42003-02-11 23:11:51 +0000765 if (NH.getNode()->Ty != Type::VoidTy)
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000766 CurNodeH.getNode()->mergeTypeInfo(NH.getNode()->Ty, NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000767 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000768
769 // If we are merging a node with a completely folded node, then both nodes are
770 // now completely folded.
771 //
772 if (CurNodeH.getNode()->isNodeCompletelyFolded()) {
773 if (!NH.getNode()->isNodeCompletelyFolded()) {
774 NH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000775 assert(NH.getNode() && NH.getOffset() == 0 &&
776 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000777 NOffset = NH.getOffset();
778 NSize = NH.getNode()->getSize();
779 assert(NOffset == 0 && NSize == 1);
780 }
781 } else if (NH.getNode()->isNodeCompletelyFolded()) {
782 CurNodeH.getNode()->foldNodeCompletely();
Chris Lattner72d29a42003-02-11 23:11:51 +0000783 assert(CurNodeH.getNode() && CurNodeH.getOffset() == 0 &&
784 "folding did not make offset 0?");
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000785 NSize = NH.getNode()->getSize();
Chris Lattner6f967742004-10-30 04:05:01 +0000786 NOffset = NH.getOffset();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000787 assert(NOffset == 0 && NSize == 1);
788 }
789
Chris Lattner72d29a42003-02-11 23:11:51 +0000790 DSNode *N = NH.getNode();
791 if (CurNodeH.getNode() == N || N == 0) return;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000792 assert(!CurNodeH.getNode()->isDeadNode());
793
Chris Lattner0b144872004-01-27 22:03:40 +0000794 // Merge the NodeType information.
Chris Lattnerbd92b732003-06-19 21:15:11 +0000795 CurNodeH.getNode()->NodeType |= N->NodeType;
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000796
Chris Lattner72d29a42003-02-11 23:11:51 +0000797 // Start forwarding to the new node!
Chris Lattner72d29a42003-02-11 23:11:51 +0000798 N->forwardNode(CurNodeH.getNode(), NOffset);
Chris Lattnerbd92b732003-06-19 21:15:11 +0000799 assert(!CurNodeH.getNode()->isDeadNode());
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000800
Chris Lattner72d29a42003-02-11 23:11:51 +0000801 // Make all of the outgoing links of N now be outgoing links of CurNodeH.
802 //
803 for (unsigned i = 0; i < N->getNumLinks(); ++i) {
804 DSNodeHandle &Link = N->getLink(i << DS::PointerShift);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000805 if (Link.getNode()) {
806 // Compute the offset into the current node at which to
807 // merge this link. In the common case, this is a linear
808 // relation to the offset in the original node (with
809 // wrapping), but if the current node gets collapsed due to
810 // recursive merging, we must make sure to merge in all remaining
811 // links at offset zero.
812 unsigned MergeOffset = 0;
Chris Lattner72d29a42003-02-11 23:11:51 +0000813 DSNode *CN = CurNodeH.getNode();
814 if (CN->Size != 1)
815 MergeOffset = ((i << DS::PointerShift)+NOffset) % CN->getSize();
816 CN->addEdgeTo(MergeOffset, Link);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000817 }
818 }
819
820 // Now that there are no outgoing edges, all of the Links are dead.
Chris Lattner72d29a42003-02-11 23:11:51 +0000821 N->Links.clear();
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000822
823 // Merge the globals list...
Chris Lattner72d29a42003-02-11 23:11:51 +0000824 if (!N->Globals.empty()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000825 CurNodeH.getNode()->mergeGlobals(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000826
827 // Delete the globals from the old node...
Chris Lattner72d29a42003-02-11 23:11:51 +0000828 std::vector<GlobalValue*>().swap(N->Globals);
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000829 }
830}
831
832
Misha Brukman96a8bd72004-04-29 04:05:30 +0000833/// mergeWith - Merge this node and the specified node, moving all links to and
834/// from the argument node into the current node, deleting the node argument.
835/// Offset indicates what offset the specified node is to be merged into the
836/// current node.
837///
838/// The specified node may be a null pointer (in which case, we update it to
839/// point to this node).
840///
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000841void DSNode::mergeWith(const DSNodeHandle &NH, unsigned Offset) {
842 DSNode *N = NH.getNode();
Chris Lattner5254a8d2004-01-22 16:31:08 +0000843 if (N == this && NH.getOffset() == Offset)
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000844 return; // Noop
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000845
Chris Lattner5254a8d2004-01-22 16:31:08 +0000846 // If the RHS is a null node, make it point to this node!
847 if (N == 0) {
848 NH.mergeWith(DSNodeHandle(this, Offset));
849 return;
850 }
851
Chris Lattnerbd92b732003-06-19 21:15:11 +0000852 assert(!N->isDeadNode() && !isDeadNode());
Chris Lattner679e8e12002-11-08 21:27:12 +0000853 assert(!hasNoReferrers() && "Should not try to fold a useless node!");
854
Chris Lattner02606632002-11-04 06:48:26 +0000855 if (N == this) {
Chris Lattner08db7192002-11-06 06:20:27 +0000856 // We cannot merge two pieces of the same node together, collapse the node
857 // completely.
Chris Lattner3c87b292002-11-07 01:54:56 +0000858 DEBUG(std::cerr << "Attempting to merge two chunks of"
859 << " the same node together!\n");
Chris Lattner08db7192002-11-06 06:20:27 +0000860 foldNodeCompletely();
Chris Lattner02606632002-11-04 06:48:26 +0000861 return;
862 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000863
Chris Lattner5190ce82002-11-12 07:20:45 +0000864 // If both nodes are not at offset 0, make sure that we are merging the node
865 // at an later offset into the node with the zero offset.
866 //
867 if (Offset < NH.getOffset()) {
868 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
869 return;
870 } else if (Offset == NH.getOffset() && getSize() < N->getSize()) {
871 // If the offsets are the same, merge the smaller node into the bigger node
872 N->mergeWith(DSNodeHandle(this, Offset), NH.getOffset());
873 return;
874 }
875
Vikram S. Adve2b7a92c2002-12-06 21:15:21 +0000876 // Ok, now we can merge the two nodes. Use a static helper that works with
877 // two node handles, since "this" may get merged away at intermediate steps.
878 DSNodeHandle CurNodeH(this, Offset);
879 DSNodeHandle NHCopy(NH);
880 DSNode::MergeNodes(CurNodeH, NHCopy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000881}
882
Chris Lattner0b144872004-01-27 22:03:40 +0000883
884//===----------------------------------------------------------------------===//
885// ReachabilityCloner Implementation
886//===----------------------------------------------------------------------===//
887
888DSNodeHandle ReachabilityCloner::getClonedNH(const DSNodeHandle &SrcNH) {
889 if (SrcNH.isNull()) return DSNodeHandle();
890 const DSNode *SN = SrcNH.getNode();
891
892 DSNodeHandle &NH = NodeMap[SN];
Chris Lattner6f967742004-10-30 04:05:01 +0000893 if (!NH.isNull()) { // Node already mapped?
894 DSNode *NHN = NH.getNode();
895 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
896 }
Chris Lattner0b144872004-01-27 22:03:40 +0000897
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000898 // If SrcNH has globals and the destination graph has one of the same globals,
899 // merge this node with the destination node, which is much more efficient.
Chris Lattner82c6c722005-03-20 02:41:38 +0000900 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000901 DSScalarMap &DestSM = Dest.getScalarMap();
Chris Lattner82c6c722005-03-20 02:41:38 +0000902 for (DSNode::globals_iterator I = SN->globals_begin(),E = SN->globals_end();
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000903 I != E; ++I) {
904 GlobalValue *GV = *I;
905 DSScalarMap::iterator GI = DestSM.find(GV);
906 if (GI != DestSM.end() && !GI->second.isNull()) {
907 // We found one, use merge instead!
908 merge(GI->second, Src.getNodeForValue(GV));
909 assert(!NH.isNull() && "Didn't merge node!");
Chris Lattner6f967742004-10-30 04:05:01 +0000910 DSNode *NHN = NH.getNode();
911 return DSNodeHandle(NHN, NH.getOffset()+SrcNH.getOffset());
Chris Lattnere6e93cc2004-03-04 19:47:04 +0000912 }
913 }
914 }
Chris Lattnerf590ced2004-03-04 17:06:53 +0000915
Chris Lattner0b144872004-01-27 22:03:40 +0000916 DSNode *DN = new DSNode(*SN, &Dest, true /* Null out all links */);
917 DN->maskNodeTypes(BitsToKeep);
Chris Lattner00948c02004-01-28 02:05:05 +0000918 NH = DN;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000919
Chris Lattner0b144872004-01-27 22:03:40 +0000920 // Next, recursively clone all outgoing links as necessary. Note that
921 // adding these links can cause the node to collapse itself at any time, and
922 // the current node may be merged with arbitrary other nodes. For this
923 // reason, we must always go through NH.
924 DN = 0;
925 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
926 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
927 if (!SrcEdge.isNull()) {
928 const DSNodeHandle &DestEdge = getClonedNH(SrcEdge);
929 // Compute the offset into the current node at which to
930 // merge this link. In the common case, this is a linear
931 // relation to the offset in the original node (with
932 // wrapping), but if the current node gets collapsed due to
933 // recursive merging, we must make sure to merge in all remaining
934 // links at offset zero.
935 unsigned MergeOffset = 0;
936 DSNode *CN = NH.getNode();
937 if (CN->getSize() != 1)
Chris Lattner37ec5912004-06-23 06:29:59 +0000938 MergeOffset = ((i << DS::PointerShift)+NH.getOffset()) % CN->getSize();
Chris Lattner0b144872004-01-27 22:03:40 +0000939 CN->addEdgeTo(MergeOffset, DestEdge);
940 }
941 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000942
Chris Lattner0b144872004-01-27 22:03:40 +0000943 // If this node contains any globals, make sure they end up in the scalar
944 // map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +0000945 for (DSNode::globals_iterator I = SN->globals_begin(), E = SN->globals_end();
Chris Lattner0b144872004-01-27 22:03:40 +0000946 I != E; ++I) {
947 GlobalValue *GV = *I;
948 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
949 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
950 assert(DestGNH.getNode() == NH.getNode() &&"Global mapping inconsistent");
951 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattner00948c02004-01-28 02:05:05 +0000952 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000953 }
Chris Lattner82c6c722005-03-20 02:41:38 +0000954 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +0000955
956 return DSNodeHandle(NH.getNode(), NH.getOffset()+SrcNH.getOffset());
957}
958
959void ReachabilityCloner::merge(const DSNodeHandle &NH,
960 const DSNodeHandle &SrcNH) {
961 if (SrcNH.isNull()) return; // Noop
962 if (NH.isNull()) {
963 // If there is no destination node, just clone the source and assign the
964 // destination node to be it.
965 NH.mergeWith(getClonedNH(SrcNH));
966 return;
967 }
968
969 // Okay, at this point, we know that we have both a destination and a source
970 // node that need to be merged. Check to see if the source node has already
971 // been cloned.
972 const DSNode *SN = SrcNH.getNode();
973 DSNodeHandle &SCNH = NodeMap[SN]; // SourceClonedNodeHandle
Chris Lattner0ad91702004-02-22 00:53:54 +0000974 if (!SCNH.isNull()) { // Node already cloned?
Chris Lattner6f967742004-10-30 04:05:01 +0000975 DSNode *SCNHN = SCNH.getNode();
976 NH.mergeWith(DSNodeHandle(SCNHN,
Chris Lattner0b144872004-01-27 22:03:40 +0000977 SCNH.getOffset()+SrcNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +0000978 return; // Nothing to do!
979 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000980
Chris Lattner0b144872004-01-27 22:03:40 +0000981 // Okay, so the source node has not already been cloned. Instead of creating
982 // a new DSNode, only to merge it into the one we already have, try to perform
983 // the merge in-place. The only case we cannot handle here is when the offset
984 // into the existing node is less than the offset into the virtual node we are
985 // merging in. In this case, we have to extend the existing node, which
986 // requires an allocation anyway.
987 DSNode *DN = NH.getNode(); // Make sure the Offset is up-to-date
988 if (NH.getOffset() >= SrcNH.getOffset()) {
Chris Lattner0b144872004-01-27 22:03:40 +0000989 if (!DN->isNodeCompletelyFolded()) {
990 // Make sure the destination node is folded if the source node is folded.
991 if (SN->isNodeCompletelyFolded()) {
992 DN->foldNodeCompletely();
993 DN = NH.getNode();
994 } else if (SN->getSize() != DN->getSize()) {
995 // If the two nodes are of different size, and the smaller node has the
996 // array bit set, collapse!
Chris Lattnerb29dd0f2004-12-08 21:03:56 +0000997#if COLLAPSE_ARRAYS_AGGRESSIVELY
Chris Lattner0b144872004-01-27 22:03:40 +0000998 if (SN->getSize() < DN->getSize()) {
999 if (SN->isArray()) {
1000 DN->foldNodeCompletely();
1001 DN = NH.getNode();
1002 }
1003 } else if (DN->isArray()) {
1004 DN->foldNodeCompletely();
1005 DN = NH.getNode();
1006 }
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00001007#endif
Chris Lattner0b144872004-01-27 22:03:40 +00001008 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001009
1010 // Merge the type entries of the two nodes together...
Chris Lattner0b144872004-01-27 22:03:40 +00001011 if (SN->getType() != Type::VoidTy && !DN->isNodeCompletelyFolded()) {
1012 DN->mergeTypeInfo(SN->getType(), NH.getOffset()-SrcNH.getOffset());
1013 DN = NH.getNode();
1014 }
1015 }
1016
1017 assert(!DN->isDeadNode());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001018
Chris Lattner0b144872004-01-27 22:03:40 +00001019 // Merge the NodeType information.
1020 DN->mergeNodeFlags(SN->getNodeFlags() & BitsToKeep);
1021
1022 // Before we start merging outgoing links and updating the scalar map, make
1023 // sure it is known that this is the representative node for the src node.
1024 SCNH = DSNodeHandle(DN, NH.getOffset()-SrcNH.getOffset());
1025
1026 // If the source node contains any globals, make sure they end up in the
1027 // scalar map with the correct offset.
Chris Lattner82c6c722005-03-20 02:41:38 +00001028 if (SN->globals_begin() != SN->globals_end()) {
Chris Lattner0b144872004-01-27 22:03:40 +00001029 // Update the globals in the destination node itself.
Chris Lattner82c6c722005-03-20 02:41:38 +00001030 DN->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001031
1032 // Update the scalar map for the graph we are merging the source node
1033 // into.
Chris Lattner82c6c722005-03-20 02:41:38 +00001034 for (DSNode::globals_iterator I = SN->globals_begin(),
1035 E = SN->globals_end(); I != E; ++I) {
Chris Lattner0b144872004-01-27 22:03:40 +00001036 GlobalValue *GV = *I;
1037 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1038 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1039 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1040 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
Chris Lattneread9eb72004-01-29 08:36:22 +00001041 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattner0b144872004-01-27 22:03:40 +00001042 }
Chris Lattner82c6c722005-03-20 02:41:38 +00001043 NH.getNode()->mergeGlobals(SN->getGlobalsList());
Chris Lattner0b144872004-01-27 22:03:40 +00001044 }
1045 } else {
1046 // We cannot handle this case without allocating a temporary node. Fall
1047 // back on being simple.
Chris Lattner0b144872004-01-27 22:03:40 +00001048 DSNode *NewDN = new DSNode(*SN, &Dest, true /* Null out all links */);
1049 NewDN->maskNodeTypes(BitsToKeep);
1050
1051 unsigned NHOffset = NH.getOffset();
1052 NH.mergeWith(DSNodeHandle(NewDN, SrcNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001053
Chris Lattner0b144872004-01-27 22:03:40 +00001054 assert(NH.getNode() &&
1055 (NH.getOffset() > NHOffset ||
1056 (NH.getOffset() == 0 && NH.getNode()->isNodeCompletelyFolded())) &&
1057 "Merging did not adjust the offset!");
1058
1059 // Before we start merging outgoing links and updating the scalar map, make
1060 // sure it is known that this is the representative node for the src node.
1061 SCNH = DSNodeHandle(NH.getNode(), NH.getOffset()-SrcNH.getOffset());
Chris Lattneread9eb72004-01-29 08:36:22 +00001062
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001063 // If the source node contained any globals, make sure to create entries
Chris Lattneread9eb72004-01-29 08:36:22 +00001064 // in the scalar map for them!
Chris Lattner82c6c722005-03-20 02:41:38 +00001065 for (DSNode::globals_iterator I = SN->globals_begin(),
1066 E = SN->globals_end(); I != E; ++I) {
Chris Lattneread9eb72004-01-29 08:36:22 +00001067 GlobalValue *GV = *I;
1068 const DSNodeHandle &SrcGNH = Src.getNodeForValue(GV);
1069 DSNodeHandle &DestGNH = NodeMap[SrcGNH.getNode()];
1070 assert(DestGNH.getNode()==NH.getNode() &&"Global mapping inconsistent");
1071 assert(SrcGNH.getNode() == SN && "Global mapping inconsistent");
1072 Dest.getNodeForValue(GV).mergeWith(DSNodeHandle(DestGNH.getNode(),
1073 DestGNH.getOffset()+SrcGNH.getOffset()));
Chris Lattneread9eb72004-01-29 08:36:22 +00001074 }
Chris Lattner0b144872004-01-27 22:03:40 +00001075 }
1076
1077
1078 // Next, recursively merge all outgoing links as necessary. Note that
1079 // adding these links can cause the destination node to collapse itself at
1080 // any time, and the current node may be merged with arbitrary other nodes.
1081 // For this reason, we must always go through NH.
1082 DN = 0;
1083 for (unsigned i = 0, e = SN->getNumLinks(); i != e; ++i) {
1084 const DSNodeHandle &SrcEdge = SN->getLink(i << DS::PointerShift);
1085 if (!SrcEdge.isNull()) {
1086 // Compute the offset into the current node at which to
1087 // merge this link. In the common case, this is a linear
1088 // relation to the offset in the original node (with
1089 // wrapping), but if the current node gets collapsed due to
1090 // recursive merging, we must make sure to merge in all remaining
1091 // links at offset zero.
Chris Lattner0b144872004-01-27 22:03:40 +00001092 DSNode *CN = SCNH.getNode();
Chris Lattnerf590ced2004-03-04 17:06:53 +00001093 unsigned MergeOffset =
1094 ((i << DS::PointerShift)+SCNH.getOffset()) % CN->getSize();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001095
Chris Lattnerf590ced2004-03-04 17:06:53 +00001096 DSNodeHandle Tmp = CN->getLink(MergeOffset);
1097 if (!Tmp.isNull()) {
Chris Lattner0ad91702004-02-22 00:53:54 +00001098 // Perform the recursive merging. Make sure to create a temporary NH,
1099 // because the Link can disappear in the process of recursive merging.
Chris Lattner0ad91702004-02-22 00:53:54 +00001100 merge(Tmp, SrcEdge);
1101 } else {
Chris Lattnerf590ced2004-03-04 17:06:53 +00001102 Tmp.mergeWith(getClonedNH(SrcEdge));
1103 // Merging this could cause all kinds of recursive things to happen,
1104 // culminating in the current node being eliminated. Since this is
1105 // possible, make sure to reaquire the link from 'CN'.
1106
1107 unsigned MergeOffset = 0;
1108 CN = SCNH.getNode();
1109 MergeOffset = ((i << DS::PointerShift)+SCNH.getOffset()) %CN->getSize();
1110 CN->getLink(MergeOffset).mergeWith(Tmp);
Chris Lattner0ad91702004-02-22 00:53:54 +00001111 }
Chris Lattner0b144872004-01-27 22:03:40 +00001112 }
1113 }
1114}
1115
1116/// mergeCallSite - Merge the nodes reachable from the specified src call
1117/// site into the nodes reachable from DestCS.
Chris Lattnerb3439372005-03-21 20:28:50 +00001118void ReachabilityCloner::mergeCallSite(DSCallSite &DestCS,
Chris Lattner0b144872004-01-27 22:03:40 +00001119 const DSCallSite &SrcCS) {
1120 merge(DestCS.getRetVal(), SrcCS.getRetVal());
1121 unsigned MinArgs = DestCS.getNumPtrArgs();
1122 if (SrcCS.getNumPtrArgs() < MinArgs) MinArgs = SrcCS.getNumPtrArgs();
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001123
Chris Lattner0b144872004-01-27 22:03:40 +00001124 for (unsigned a = 0; a != MinArgs; ++a)
1125 merge(DestCS.getPtrArg(a), SrcCS.getPtrArg(a));
Chris Lattner3f90a942005-03-21 09:39:51 +00001126
1127 for (unsigned a = MinArgs, e = SrcCS.getNumPtrArgs(); a != e; ++a)
Chris Lattnerb3439372005-03-21 20:28:50 +00001128 DestCS.addPtrArg(getClonedNH(SrcCS.getPtrArg(a)));
Chris Lattner0b144872004-01-27 22:03:40 +00001129}
1130
1131
Chris Lattner9de906c2002-10-20 22:11:44 +00001132//===----------------------------------------------------------------------===//
1133// DSCallSite Implementation
1134//===----------------------------------------------------------------------===//
1135
Vikram S. Adve26b98262002-10-20 21:41:02 +00001136// Define here to avoid including iOther.h and BasicBlock.h in DSGraph.h
Chris Lattner9de906c2002-10-20 22:11:44 +00001137Function &DSCallSite::getCaller() const {
Chris Lattner808a7ae2003-09-20 16:34:13 +00001138 return *Site.getInstruction()->getParent()->getParent();
Vikram S. Adve26b98262002-10-20 21:41:02 +00001139}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001140
Chris Lattner0b144872004-01-27 22:03:40 +00001141void DSCallSite::InitNH(DSNodeHandle &NH, const DSNodeHandle &Src,
1142 ReachabilityCloner &RC) {
1143 NH = RC.getClonedNH(Src);
1144}
Vikram S. Adve42fd1692002-10-20 18:07:37 +00001145
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001146//===----------------------------------------------------------------------===//
1147// DSGraph Implementation
1148//===----------------------------------------------------------------------===//
1149
Chris Lattnera9d65662003-06-30 05:57:30 +00001150/// getFunctionNames - Return a space separated list of the name of the
1151/// functions in this graph (if any)
1152std::string DSGraph::getFunctionNames() const {
1153 switch (getReturnNodes().size()) {
1154 case 0: return "Globals graph";
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001155 case 1: return retnodes_begin()->first->getName();
Chris Lattnera9d65662003-06-30 05:57:30 +00001156 default:
1157 std::string Return;
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001158 for (DSGraph::retnodes_iterator I = retnodes_begin();
1159 I != retnodes_end(); ++I)
Chris Lattnera9d65662003-06-30 05:57:30 +00001160 Return += I->first->getName() + " ";
1161 Return.erase(Return.end()-1, Return.end()); // Remove last space character
1162 return Return;
1163 }
1164}
1165
1166
Chris Lattnerf09ecff2005-03-21 22:49:53 +00001167DSGraph::DSGraph(const DSGraph &G, EquivalenceClasses<GlobalValue*> &ECs,
1168 unsigned CloneFlags)
Chris Lattnerf4f62272005-03-19 22:23:45 +00001169 : GlobalsGraph(0), ScalarMap(ECs), TD(G.TD) {
Chris Lattneraa8146f2002-11-10 06:59:55 +00001170 PrintAuxCalls = false;
Chris Lattnera2197132005-03-22 00:36:51 +00001171 cloneInto(G, CloneFlags);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001172}
1173
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001174DSGraph::~DSGraph() {
1175 FunctionCalls.clear();
Chris Lattner679e8e12002-11-08 21:27:12 +00001176 AuxFunctionCalls.clear();
Chris Lattnerc875f022002-11-03 21:27:48 +00001177 ScalarMap.clear();
Chris Lattner5a540632003-06-30 03:15:25 +00001178 ReturnNodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001179
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001180 // Drop all intra-node references, so that assertions don't fail...
Chris Lattner28897e12004-02-08 00:53:26 +00001181 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
Chris Lattner84b80a22005-03-16 22:42:19 +00001182 NI->dropAllReferences();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001183
Chris Lattner28897e12004-02-08 00:53:26 +00001184 // Free all of the nodes.
1185 Nodes.clear();
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001186}
1187
Chris Lattner0d9bab82002-07-18 00:12:30 +00001188// dump - Allow inspection of graph in a debugger.
1189void DSGraph::dump() const { print(std::cerr); }
1190
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001191
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001192/// remapLinks - Change all of the Links in the current node according to the
1193/// specified mapping.
Chris Lattner8f0a16e2002-10-31 05:45:02 +00001194///
Chris Lattner8d327672003-06-30 03:36:09 +00001195void DSNode::remapLinks(DSGraph::NodeMapTy &OldNodeMap) {
Chris Lattner2f561382004-01-22 16:56:13 +00001196 for (unsigned i = 0, e = Links.size(); i != e; ++i)
1197 if (DSNode *N = Links[i].getNode()) {
Chris Lattner091f7762004-01-23 01:44:53 +00001198 DSGraph::NodeMapTy::const_iterator ONMI = OldNodeMap.find(N);
Chris Lattner6f967742004-10-30 04:05:01 +00001199 if (ONMI != OldNodeMap.end()) {
1200 DSNode *ONMIN = ONMI->second.getNode();
1201 Links[i].setTo(ONMIN, Links[i].getOffset()+ONMI->second.getOffset());
1202 }
Chris Lattner2f561382004-01-22 16:56:13 +00001203 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001204}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001205
Chris Lattnerd672ab92005-02-15 18:40:55 +00001206/// addObjectToGraph - This method can be used to add global, stack, and heap
1207/// objects to the graph. This can be used when updating DSGraphs due to the
1208/// introduction of new temporary objects. The new object is not pointed to
1209/// and does not point to any other objects in the graph.
1210DSNode *DSGraph::addObjectToGraph(Value *Ptr, bool UseDeclaredType) {
1211 assert(isa<PointerType>(Ptr->getType()) && "Ptr is not a pointer!");
1212 const Type *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1213 DSNode *N = new DSNode(UseDeclaredType ? Ty : 0, this);
Chris Lattner7a0c7752005-02-15 18:48:48 +00001214 assert(ScalarMap[Ptr].isNull() && "Object already in this graph!");
Chris Lattnerd672ab92005-02-15 18:40:55 +00001215 ScalarMap[Ptr] = N;
1216
1217 if (GlobalValue *GV = dyn_cast<GlobalValue>(Ptr)) {
1218 N->addGlobal(GV);
1219 } else if (MallocInst *MI = dyn_cast<MallocInst>(Ptr)) {
1220 N->setHeapNodeMarker();
1221 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
1222 N->setAllocaNodeMarker();
1223 } else {
1224 assert(0 && "Illegal memory object input!");
1225 }
1226 return N;
1227}
1228
1229
Chris Lattner5a540632003-06-30 03:15:25 +00001230/// cloneInto - Clone the specified DSGraph into the current graph. The
Chris Lattner3c920fa2005-03-22 00:21:05 +00001231/// translated ScalarMap for the old function is filled into the ScalarMap
1232/// for the graph, and the translated ReturnNodes map is returned into
1233/// ReturnNodes.
Chris Lattner5a540632003-06-30 03:15:25 +00001234///
1235/// The CloneFlags member controls various aspects of the cloning process.
1236///
Chris Lattnera2197132005-03-22 00:36:51 +00001237void DSGraph::cloneInto(const DSGraph &G, unsigned CloneFlags) {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001238 TIME_REGION(X, "cloneInto");
Chris Lattner33312f72002-11-08 01:21:07 +00001239 assert(&G != this && "Cannot clone graph into itself!");
Chris Lattner0d9bab82002-07-18 00:12:30 +00001240
Chris Lattnera2197132005-03-22 00:36:51 +00001241 NodeMapTy OldNodeMap;
1242
Chris Lattner1e883692003-02-03 20:08:51 +00001243 // Remove alloca or mod/ref bits as specified...
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001244 unsigned BitsToClear = ((CloneFlags & StripAllocaBit)? DSNode::AllocaNode : 0)
1245 | ((CloneFlags & StripModRefBits)? (DSNode::Modified | DSNode::Read) : 0)
1246 | ((CloneFlags & StripIncompleteBit)? DSNode::Incomplete : 0);
Chris Lattnerbd92b732003-06-19 21:15:11 +00001247 BitsToClear |= DSNode::DEAD; // Clear dead flag...
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001248
Chris Lattner84b80a22005-03-16 22:42:19 +00001249 for (node_const_iterator I = G.node_begin(), E = G.node_end(); I != E; ++I) {
1250 assert(!I->isForwarding() &&
Chris Lattnerd85645f2004-02-21 22:28:26 +00001251 "Forward nodes shouldn't be in node list!");
Chris Lattner84b80a22005-03-16 22:42:19 +00001252 DSNode *New = new DSNode(*I, this);
Chris Lattnerd85645f2004-02-21 22:28:26 +00001253 New->maskNodeTypes(~BitsToClear);
Chris Lattner84b80a22005-03-16 22:42:19 +00001254 OldNodeMap[I] = New;
Chris Lattnerd85645f2004-02-21 22:28:26 +00001255 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001256
Chris Lattner18552922002-11-18 21:44:46 +00001257#ifndef NDEBUG
1258 Timer::addPeakMemoryMeasurement();
1259#endif
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001260
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001261 // Rewrite the links in the new nodes to point into the current graph now.
Chris Lattnerd85645f2004-02-21 22:28:26 +00001262 // Note that we don't loop over the node's list to do this. The problem is
1263 // that remaping links can cause recursive merging to happen, which means
1264 // that node_iterator's can get easily invalidated! Because of this, we
1265 // loop over the OldNodeMap, which contains all of the new nodes as the
1266 // .second element of the map elements. Also note that if we remap a node
1267 // more than once, we won't break anything.
1268 for (NodeMapTy::iterator I = OldNodeMap.begin(), E = OldNodeMap.end();
1269 I != E; ++I)
1270 I->second.getNode()->remapLinks(OldNodeMap);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001271
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001272 // Copy the scalar map... merging all of the global nodes...
Chris Lattner62482e52004-01-28 09:15:42 +00001273 for (DSScalarMap::const_iterator I = G.ScalarMap.begin(),
Chris Lattnerc875f022002-11-03 21:27:48 +00001274 E = G.ScalarMap.end(); I != E; ++I) {
Chris Lattnerf8c6aab2002-11-08 05:01:14 +00001275 DSNodeHandle &MappedNode = OldNodeMap[I->second.getNode()];
Chris Lattner3bc703b2005-03-22 01:42:59 +00001276 DSNodeHandle &H = ScalarMap.getRawEntryRef(I->first);
Chris Lattner6f967742004-10-30 04:05:01 +00001277 DSNode *MappedNodeN = MappedNode.getNode();
1278 H.mergeWith(DSNodeHandle(MappedNodeN,
Chris Lattner2cb9acd2003-06-30 05:09:29 +00001279 I->second.getOffset()+MappedNode.getOffset()));
Chris Lattnercf15db32002-10-17 20:09:52 +00001280 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001281
Chris Lattner679e8e12002-11-08 21:27:12 +00001282 if (!(CloneFlags & DontCloneCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001283 // Copy the function calls list.
1284 for (fc_iterator I = G.fc_begin(), E = G.fc_end(); I != E; ++I)
1285 FunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattneracf491f2002-11-08 22:27:09 +00001286 }
Chris Lattner679e8e12002-11-08 21:27:12 +00001287
Chris Lattneracf491f2002-11-08 22:27:09 +00001288 if (!(CloneFlags & DontCloneAuxCallNodes)) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001289 // Copy the auxiliary function calls list.
1290 for (afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
1291 AuxFunctionCalls.push_back(DSCallSite(*I, OldNodeMap));
Chris Lattner679e8e12002-11-08 21:27:12 +00001292 }
Chris Lattnercf15db32002-10-17 20:09:52 +00001293
Chris Lattner5a540632003-06-30 03:15:25 +00001294 // Map the return node pointers over...
Chris Lattnera5f47ea2005-03-15 16:55:04 +00001295 for (retnodes_iterator I = G.retnodes_begin(),
1296 E = G.retnodes_end(); I != E; ++I) {
Chris Lattner5a540632003-06-30 03:15:25 +00001297 const DSNodeHandle &Ret = I->second;
1298 DSNodeHandle &MappedRet = OldNodeMap[Ret.getNode()];
Chris Lattner6f967742004-10-30 04:05:01 +00001299 DSNode *MappedRetN = MappedRet.getNode();
Chris Lattnerd65145b2005-03-22 00:29:44 +00001300 ReturnNodes.insert(std::make_pair(I->first,
1301 DSNodeHandle(MappedRetN,
1302 MappedRet.getOffset()+Ret.getOffset())));
Chris Lattner5a540632003-06-30 03:15:25 +00001303 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001304}
1305
Chris Lattner5734e432005-03-24 23:46:04 +00001306/// spliceFrom - Logically perform the operation of cloning the RHS graph into
1307/// this graph, then clearing the RHS graph. Instead of performing this as
1308/// two seperate operations, do it as a single, much faster, one.
1309///
1310void DSGraph::spliceFrom(DSGraph &RHS) {
1311 // Change all of the nodes in RHS to think we are their parent.
1312 for (NodeListTy::iterator I = RHS.Nodes.begin(), E = RHS.Nodes.end();
1313 I != E; ++I)
1314 I->setParentGraph(this);
1315 // Take all of the nodes.
1316 Nodes.splice(Nodes.end(), RHS.Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001317
Chris Lattner5734e432005-03-24 23:46:04 +00001318 // Take all of the calls.
1319 FunctionCalls.splice(FunctionCalls.end(), RHS.FunctionCalls);
1320 AuxFunctionCalls.splice(AuxFunctionCalls.end(), RHS.AuxFunctionCalls);
1321
1322 // Take all of the return nodes.
Chris Lattnerce7068d2005-03-25 00:02:41 +00001323 if (ReturnNodes.empty()) {
1324 ReturnNodes.swap(RHS.ReturnNodes);
1325 } else {
1326 ReturnNodes.insert(RHS.ReturnNodes.begin(), RHS.ReturnNodes.end());
1327 RHS.ReturnNodes.clear();
1328 }
Chris Lattner5734e432005-03-24 23:46:04 +00001329
1330 // Merge the scalar map in.
1331 ScalarMap.spliceFrom(RHS.ScalarMap);
1332}
1333
1334/// spliceFrom - Copy all entries from RHS, then clear RHS.
1335///
1336void DSScalarMap::spliceFrom(DSScalarMap &RHS) {
1337 // Special case if this is empty.
1338 if (ValueMap.empty()) {
1339 ValueMap.swap(RHS.ValueMap);
1340 GlobalSet.swap(RHS.GlobalSet);
1341 } else {
1342 GlobalSet.insert(RHS.GlobalSet.begin(), RHS.GlobalSet.end());
1343 for (ValueMapTy::iterator I = RHS.ValueMap.begin(), E = RHS.ValueMap.end();
1344 I != E; ++I)
1345 ValueMap[I->first].mergeWith(I->second);
1346 RHS.ValueMap.clear();
1347 }
1348}
1349
1350
Chris Lattnerbb753c42005-02-03 18:40:25 +00001351/// getFunctionArgumentsForCall - Given a function that is currently in this
1352/// graph, return the DSNodeHandles that correspond to the pointer-compatible
1353/// function arguments. The vector is filled in with the return value (or
1354/// null if it is not pointer compatible), followed by all of the
1355/// pointer-compatible arguments.
1356void DSGraph::getFunctionArgumentsForCall(Function *F,
1357 std::vector<DSNodeHandle> &Args) const {
1358 Args.push_back(getReturnNodeFor(*F));
Chris Lattnereb394922005-03-23 16:43:11 +00001359 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1360 AI != E; ++AI)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001361 if (isPointerType(AI->getType())) {
1362 Args.push_back(getNodeForValue(AI));
1363 assert(!Args.back().isNull() && "Pointer argument w/o scalarmap entry!?");
1364 }
1365}
1366
Chris Lattner4da120e2005-03-24 23:06:02 +00001367namespace {
1368 // HackedGraphSCCFinder - This is used to find nodes that have a path from the
1369 // node to a node cloned by the ReachabilityCloner object contained. To be
1370 // extra obnoxious it ignores edges from nodes that are globals, and truncates
1371 // search at RC marked nodes. This is designed as an object so that
1372 // intermediate results can be memoized across invocations of
1373 // PathExistsToClonedNode.
1374 struct HackedGraphSCCFinder {
1375 ReachabilityCloner &RC;
1376 unsigned CurNodeId;
1377 std::vector<const DSNode*> SCCStack;
1378 std::map<const DSNode*, std::pair<unsigned, bool> > NodeInfo;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001379
Chris Lattner4da120e2005-03-24 23:06:02 +00001380 HackedGraphSCCFinder(ReachabilityCloner &rc) : RC(rc), CurNodeId(1) {
1381 // Remove null pointer as a special case.
1382 NodeInfo[0] = std::make_pair(0, false);
Chris Lattnerd8642122005-03-24 21:07:47 +00001383 }
1384
Chris Lattner4da120e2005-03-24 23:06:02 +00001385 std::pair<unsigned, bool> &VisitForSCCs(const DSNode *N);
1386
1387 bool PathExistsToClonedNode(const DSNode *N) {
1388 return VisitForSCCs(N).second;
1389 }
1390
1391 bool PathExistsToClonedNode(const DSCallSite &CS) {
1392 if (PathExistsToClonedNode(CS.getRetVal().getNode()))
1393 return true;
1394 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
1395 if (PathExistsToClonedNode(CS.getPtrArg(i).getNode()))
1396 return true;
1397 return false;
1398 }
1399 };
1400}
1401
1402std::pair<unsigned, bool> &HackedGraphSCCFinder::
1403VisitForSCCs(const DSNode *N) {
1404 std::map<const DSNode*, std::pair<unsigned, bool> >::iterator
1405 NodeInfoIt = NodeInfo.lower_bound(N);
1406 if (NodeInfoIt != NodeInfo.end() && NodeInfoIt->first == N)
1407 return NodeInfoIt->second;
1408
1409 unsigned Min = CurNodeId++;
1410 unsigned MyId = Min;
1411 std::pair<unsigned, bool> &ThisNodeInfo =
1412 NodeInfo.insert(NodeInfoIt,
1413 std::make_pair(N, std::make_pair(MyId, false)))->second;
1414
1415 // Base case: if we find a global, this doesn't reach the cloned graph
1416 // portion.
1417 if (N->isGlobalNode()) {
1418 ThisNodeInfo.second = false;
1419 return ThisNodeInfo;
Chris Lattnerd8642122005-03-24 21:07:47 +00001420 }
1421
Chris Lattner4da120e2005-03-24 23:06:02 +00001422 // Base case: if this does reach the cloned graph portion... it does. :)
1423 if (RC.hasClonedNode(N)) {
1424 ThisNodeInfo.second = true;
1425 return ThisNodeInfo;
1426 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001427
Chris Lattner4da120e2005-03-24 23:06:02 +00001428 SCCStack.push_back(N);
Chris Lattnerd8642122005-03-24 21:07:47 +00001429
Chris Lattner4da120e2005-03-24 23:06:02 +00001430 // Otherwise, check all successors.
1431 bool AnyDirectSuccessorsReachClonedNodes = false;
1432 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
Chris Lattner63320cc2005-04-25 19:16:17 +00001433 EI != EE; ++EI)
1434 if (DSNode *Succ = EI->getNode()) {
1435 std::pair<unsigned, bool> &SuccInfo = VisitForSCCs(Succ);
1436 if (SuccInfo.first < Min) Min = SuccInfo.first;
1437 AnyDirectSuccessorsReachClonedNodes |= SuccInfo.second;
1438 }
Chris Lattner4da120e2005-03-24 23:06:02 +00001439
1440 if (Min != MyId)
1441 return ThisNodeInfo; // Part of a large SCC. Leave self on stack.
1442
1443 if (SCCStack.back() == N) { // Special case single node SCC.
1444 SCCStack.pop_back();
1445 ThisNodeInfo.second = AnyDirectSuccessorsReachClonedNodes;
1446 return ThisNodeInfo;
1447 }
1448
1449 // Find out if any direct successors of any node reach cloned nodes.
1450 if (!AnyDirectSuccessorsReachClonedNodes)
1451 for (unsigned i = SCCStack.size()-1; SCCStack[i] != N; --i)
1452 for (DSNode::const_edge_iterator EI = N->edge_begin(), EE = N->edge_end();
1453 EI != EE; ++EI)
1454 if (DSNode *N = EI->getNode())
1455 if (NodeInfo[N].second) {
1456 AnyDirectSuccessorsReachClonedNodes = true;
1457 goto OutOfLoop;
1458 }
1459OutOfLoop:
1460 // If any successor reaches a cloned node, mark all nodes in this SCC as
1461 // reaching the cloned node.
1462 if (AnyDirectSuccessorsReachClonedNodes)
1463 while (SCCStack.back() != N) {
1464 NodeInfo[SCCStack.back()].second = true;
1465 SCCStack.pop_back();
1466 }
1467 SCCStack.pop_back();
1468 ThisNodeInfo.second = true;
1469 return ThisNodeInfo;
1470}
Chris Lattnerd8642122005-03-24 21:07:47 +00001471
Chris Lattnere8594442005-02-04 19:58:28 +00001472/// mergeInCallFromOtherGraph - This graph merges in the minimal number of
1473/// nodes from G2 into 'this' graph, merging the bindings specified by the
1474/// call site (in this graph) with the bindings specified by the vector in G2.
1475/// The two DSGraphs must be different.
Chris Lattner076c1f92002-11-07 06:31:54 +00001476///
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001477void DSGraph::mergeInGraph(const DSCallSite &CS,
Chris Lattnere8594442005-02-04 19:58:28 +00001478 std::vector<DSNodeHandle> &Args,
Chris Lattner9f930552003-06-30 05:27:18 +00001479 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattner0b144872004-01-27 22:03:40 +00001480 TIME_REGION(X, "mergeInGraph");
1481
Chris Lattnerc14f59c2005-03-23 20:12:08 +00001482 assert((CloneFlags & DontCloneCallNodes) &&
1483 "Doesn't support copying of call nodes!");
1484
Chris Lattner076c1f92002-11-07 06:31:54 +00001485 // If this is not a recursive call, clone the graph into this graph...
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001486 if (&Graph == this) {
Chris Lattnerbb753c42005-02-03 18:40:25 +00001487 // Merge the return value with the return value of the context.
1488 Args[0].mergeWith(CS.getRetVal());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001489
Chris Lattnerbb753c42005-02-03 18:40:25 +00001490 // Resolve all of the function arguments.
1491 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
Chris Lattnere8594442005-02-04 19:58:28 +00001492 if (i == Args.size()-1)
Chris Lattnerbb753c42005-02-03 18:40:25 +00001493 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001494
Chris Lattnerbb753c42005-02-03 18:40:25 +00001495 // Add the link from the argument scalar to the provided value.
1496 Args[i+1].mergeWith(CS.getPtrArg(i));
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001497 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001498 return;
Chris Lattner076c1f92002-11-07 06:31:54 +00001499 }
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001500
1501 // Clone the callee's graph into the current graph, keeping track of where
1502 // scalars in the old graph _used_ to point, and of the new nodes matching
1503 // nodes of the old graph.
1504 ReachabilityCloner RC(*this, Graph, CloneFlags);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001505
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001506 // Map the return node pointer over.
1507 if (!CS.getRetVal().isNull())
1508 RC.merge(CS.getRetVal(), Args[0]);
1509
1510 // Map over all of the arguments.
1511 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i) {
1512 if (i == Args.size()-1)
1513 break;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001514
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001515 // Add the link from the argument scalar to the provided value.
1516 RC.merge(CS.getPtrArg(i), Args[i+1]);
1517 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001518
Chris Lattnerd8642122005-03-24 21:07:47 +00001519 // We generally don't want to copy global nodes or aux calls from the callee
1520 // graph to the caller graph. However, we have to copy them if there is a
1521 // path from the node to a node we have already copied which does not go
1522 // through another global. Compute the set of node that can reach globals and
1523 // aux call nodes to copy over, then do it.
1524 std::vector<const DSCallSite*> AuxCallToCopy;
1525 std::vector<GlobalValue*> GlobalsToCopy;
Chris Lattnere3f1d8a2005-03-23 20:08:59 +00001526
Chris Lattnerd8642122005-03-24 21:07:47 +00001527 // NodesReachCopiedNodes - Memoize results for efficiency. Contains a
1528 // true/false value for every visited node that reaches a copied node without
1529 // going through a global.
Chris Lattner4da120e2005-03-24 23:06:02 +00001530 HackedGraphSCCFinder SCCFinder(RC);
Chris Lattnerd8642122005-03-24 21:07:47 +00001531
1532 if (!(CloneFlags & DontCloneAuxCallNodes))
1533 for (afc_iterator I = Graph.afc_begin(), E = Graph.afc_end(); I!=E; ++I)
Chris Lattner4da120e2005-03-24 23:06:02 +00001534 if (SCCFinder.PathExistsToClonedNode(*I))
Chris Lattnerd8642122005-03-24 21:07:47 +00001535 AuxCallToCopy.push_back(&*I);
1536
Chris Lattner4da120e2005-03-24 23:06:02 +00001537 const DSScalarMap &GSM = Graph.getScalarMap();
Chris Lattnerd8642122005-03-24 21:07:47 +00001538 for (DSScalarMap::global_iterator GI = GSM.global_begin(),
Chris Lattner09adbbc92005-03-24 21:17:27 +00001539 E = GSM.global_end(); GI != E; ++GI) {
1540 DSNode *GlobalNode = Graph.getNodeForValue(*GI).getNode();
1541 for (DSNode::edge_iterator EI = GlobalNode->edge_begin(),
1542 EE = GlobalNode->edge_end(); EI != EE; ++EI)
Chris Lattner4da120e2005-03-24 23:06:02 +00001543 if (SCCFinder.PathExistsToClonedNode(EI->getNode())) {
Chris Lattner09adbbc92005-03-24 21:17:27 +00001544 GlobalsToCopy.push_back(*GI);
1545 break;
1546 }
1547 }
Chris Lattnerd8642122005-03-24 21:07:47 +00001548
1549 // Copy aux calls that are needed.
1550 for (unsigned i = 0, e = AuxCallToCopy.size(); i != e; ++i)
1551 AuxFunctionCalls.push_back(DSCallSite(*AuxCallToCopy[i], RC));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001552
Chris Lattnerd8642122005-03-24 21:07:47 +00001553 // Copy globals that are needed.
1554 for (unsigned i = 0, e = GlobalsToCopy.size(); i != e; ++i)
1555 RC.getClonedNH(Graph.getNodeForValue(GlobalsToCopy[i]));
Chris Lattner076c1f92002-11-07 06:31:54 +00001556}
1557
Chris Lattnere8594442005-02-04 19:58:28 +00001558
1559
1560/// mergeInGraph - The method is used for merging graphs together. If the
1561/// argument graph is not *this, it makes a clone of the specified graph, then
1562/// merges the nodes specified in the call site with the formal arguments in the
1563/// graph.
1564///
1565void DSGraph::mergeInGraph(const DSCallSite &CS, Function &F,
1566 const DSGraph &Graph, unsigned CloneFlags) {
Chris Lattnere8594442005-02-04 19:58:28 +00001567 // Set up argument bindings.
1568 std::vector<DSNodeHandle> Args;
1569 Graph.getFunctionArgumentsForCall(&F, Args);
1570
1571 mergeInGraph(CS, Args, Graph, CloneFlags);
1572}
1573
Chris Lattner58f98d02003-07-02 04:38:49 +00001574/// getCallSiteForArguments - Get the arguments and return value bindings for
1575/// the specified function in the current graph.
1576///
1577DSCallSite DSGraph::getCallSiteForArguments(Function &F) const {
1578 std::vector<DSNodeHandle> Args;
1579
Chris Lattnere4d5c442005-03-15 04:54:21 +00001580 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I)
Chris Lattner58f98d02003-07-02 04:38:49 +00001581 if (isPointerType(I->getType()))
Chris Lattner0b144872004-01-27 22:03:40 +00001582 Args.push_back(getNodeForValue(I));
Chris Lattner58f98d02003-07-02 04:38:49 +00001583
Chris Lattner808a7ae2003-09-20 16:34:13 +00001584 return DSCallSite(CallSite(), getReturnNodeFor(F), &F, Args);
Chris Lattner58f98d02003-07-02 04:38:49 +00001585}
1586
Chris Lattner85fb1be2004-03-09 19:37:06 +00001587/// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
1588/// the context of this graph, return the DSCallSite for it.
1589DSCallSite DSGraph::getDSCallSiteForCallSite(CallSite CS) const {
1590 DSNodeHandle RetVal;
1591 Instruction *I = CS.getInstruction();
1592 if (isPointerType(I->getType()))
1593 RetVal = getNodeForValue(I);
1594
1595 std::vector<DSNodeHandle> Args;
1596 Args.reserve(CS.arg_end()-CS.arg_begin());
1597
1598 // Calculate the arguments vector...
1599 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1600 if (isPointerType((*I)->getType()))
Chris Lattner94f84702005-03-17 19:56:56 +00001601 if (isa<ConstantPointerNull>(*I))
1602 Args.push_back(DSNodeHandle());
1603 else
1604 Args.push_back(getNodeForValue(*I));
Chris Lattner85fb1be2004-03-09 19:37:06 +00001605
1606 // Add a new function call entry...
1607 if (Function *F = CS.getCalledFunction())
1608 return DSCallSite(CS, RetVal, F, Args);
1609 else
1610 return DSCallSite(CS, RetVal,
1611 getNodeForValue(CS.getCalledValue()).getNode(), Args);
1612}
1613
Chris Lattner58f98d02003-07-02 04:38:49 +00001614
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001615
Chris Lattner0d9bab82002-07-18 00:12:30 +00001616// markIncompleteNodes - Mark the specified node as having contents that are not
1617// known with the current analysis we have performed. Because a node makes all
Chris Lattnerbd92b732003-06-19 21:15:11 +00001618// of the nodes it can reach incomplete if the node itself is incomplete, we
Chris Lattner0d9bab82002-07-18 00:12:30 +00001619// must recursively traverse the data structure graph, marking all reachable
1620// nodes as incomplete.
1621//
1622static void markIncompleteNode(DSNode *N) {
1623 // Stop recursion if no node, or if node already marked...
Chris Lattner72d50a02003-06-28 21:58:28 +00001624 if (N == 0 || N->isIncomplete()) return;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001625
1626 // Actually mark the node
Chris Lattnerbd92b732003-06-19 21:15:11 +00001627 N->setIncompleteMarker();
Chris Lattner0d9bab82002-07-18 00:12:30 +00001628
Misha Brukman2f2d0652003-09-11 18:14:24 +00001629 // Recursively process children...
Chris Lattner6be07942005-02-09 03:20:43 +00001630 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1631 if (DSNode *DSN = I->getNode())
Chris Lattner08db7192002-11-06 06:20:27 +00001632 markIncompleteNode(DSN);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001633}
1634
Chris Lattnere71ffc22002-11-11 03:36:55 +00001635static void markIncomplete(DSCallSite &Call) {
1636 // Then the return value is certainly incomplete!
1637 markIncompleteNode(Call.getRetVal().getNode());
1638
1639 // All objects pointed to by function arguments are incomplete!
1640 for (unsigned i = 0, e = Call.getNumPtrArgs(); i != e; ++i)
1641 markIncompleteNode(Call.getPtrArg(i).getNode());
1642}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001643
1644// markIncompleteNodes - Traverse the graph, identifying nodes that may be
1645// modified by other functions that have not been resolved yet. This marks
1646// nodes that are reachable through three sources of "unknownness":
1647//
1648// Global Variables, Function Calls, and Incoming Arguments
1649//
1650// For any node that may have unknown components (because something outside the
1651// scope of current analysis may have modified it), the 'Incomplete' flag is
1652// added to the NodeType.
1653//
Chris Lattner394471f2003-01-23 22:05:33 +00001654void DSGraph::markIncompleteNodes(unsigned Flags) {
Chris Lattnera9548d92005-01-30 23:51:02 +00001655 // Mark any incoming arguments as incomplete.
Chris Lattner5a540632003-06-30 03:15:25 +00001656 if (Flags & DSGraph::MarkFormalArgs)
1657 for (ReturnNodesTy::iterator FI = ReturnNodes.begin(), E =ReturnNodes.end();
1658 FI != E; ++FI) {
1659 Function &F = *FI->first;
Chris Lattner9342a932005-03-29 19:16:59 +00001660 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
1661 I != E; ++I)
Chris Lattnerb5ecd2e2005-03-13 20:22:10 +00001662 if (isPointerType(I->getType()))
1663 markIncompleteNode(getNodeForValue(I).getNode());
Chris Lattnera4319e52005-03-12 14:58:28 +00001664 markIncompleteNode(FI->second.getNode());
Chris Lattner5a540632003-06-30 03:15:25 +00001665 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001666
Chris Lattnera9548d92005-01-30 23:51:02 +00001667 // Mark stuff passed into functions calls as being incomplete.
Chris Lattnere71ffc22002-11-11 03:36:55 +00001668 if (!shouldPrintAuxCalls())
Chris Lattnera9548d92005-01-30 23:51:02 +00001669 for (std::list<DSCallSite>::iterator I = FunctionCalls.begin(),
1670 E = FunctionCalls.end(); I != E; ++I)
1671 markIncomplete(*I);
Chris Lattnere71ffc22002-11-11 03:36:55 +00001672 else
Chris Lattnera9548d92005-01-30 23:51:02 +00001673 for (std::list<DSCallSite>::iterator I = AuxFunctionCalls.begin(),
1674 E = AuxFunctionCalls.end(); I != E; ++I)
1675 markIncomplete(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001676
Chris Lattnere2bc7b22005-03-13 20:36:01 +00001677 // Mark all global nodes as incomplete.
1678 for (DSScalarMap::global_iterator I = ScalarMap.global_begin(),
1679 E = ScalarMap.global_end(); I != E; ++I)
1680 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
1681 if (!GV->hasInitializer() || // Always mark external globals incomp.
1682 (!GV->isConstant() && (Flags & DSGraph::IgnoreGlobals) == 0))
1683 markIncompleteNode(ScalarMap[GV].getNode());
Chris Lattner0d9bab82002-07-18 00:12:30 +00001684}
1685
Chris Lattneraa8146f2002-11-10 06:59:55 +00001686static inline void killIfUselessEdge(DSNodeHandle &Edge) {
1687 if (DSNode *N = Edge.getNode()) // Is there an edge?
Chris Lattner72d29a42003-02-11 23:11:51 +00001688 if (N->getNumReferrers() == 1) // Does it point to a lonely node?
Chris Lattnerbd92b732003-06-19 21:15:11 +00001689 // No interesting info?
1690 if ((N->getNodeFlags() & ~DSNode::Incomplete) == 0 &&
Chris Lattner18552922002-11-18 21:44:46 +00001691 N->getType() == Type::VoidTy && !N->isNodeCompletelyFolded())
Chris Lattnerefffdc92004-07-07 06:12:52 +00001692 Edge.setTo(0, 0); // Kill the edge!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001693}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001694
Chris Lattneraa8146f2002-11-10 06:59:55 +00001695static inline bool nodeContainsExternalFunction(const DSNode *N) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001696 std::vector<Function*> Funcs;
1697 N->addFullFunctionList(Funcs);
1698 for (unsigned i = 0, e = Funcs.size(); i != e; ++i)
1699 if (Funcs[i]->isExternal()) return true;
Chris Lattner0d9bab82002-07-18 00:12:30 +00001700 return false;
1701}
1702
Chris Lattnera9548d92005-01-30 23:51:02 +00001703static void removeIdenticalCalls(std::list<DSCallSite> &Calls) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001704 // Remove trivially identical function calls
Chris Lattnera9548d92005-01-30 23:51:02 +00001705 Calls.sort(); // Sort by callee as primary key!
Chris Lattneraa8146f2002-11-10 06:59:55 +00001706
1707 // Scan the call list cleaning it up as necessary...
Chris Lattner1e9d1472005-03-22 23:54:52 +00001708 DSNodeHandle LastCalleeNode;
Chris Lattner923fc052003-02-05 21:59:58 +00001709 Function *LastCalleeFunc = 0;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001710 unsigned NumDuplicateCalls = 0;
1711 bool LastCalleeContainsExternalFunction = false;
Chris Lattner857eb062004-10-30 05:41:23 +00001712
Chris Lattnera9548d92005-01-30 23:51:02 +00001713 unsigned NumDeleted = 0;
1714 for (std::list<DSCallSite>::iterator I = Calls.begin(), E = Calls.end();
1715 I != E;) {
1716 DSCallSite &CS = *I;
1717 std::list<DSCallSite>::iterator OldIt = I++;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001718
Chris Lattner1e9d1472005-03-22 23:54:52 +00001719 if (!CS.isIndirectCall()) {
1720 LastCalleeNode = 0;
1721 } else {
1722 DSNode *Callee = CS.getCalleeNode();
1723
1724 // If the Callee is a useless edge, this must be an unreachable call site,
1725 // eliminate it.
1726 if (Callee->getNumReferrers() == 1 && Callee->isComplete() &&
1727 Callee->getGlobalsList().empty()) { // No useful info?
Chris Lattner64507e32004-01-28 01:19:52 +00001728#ifndef NDEBUG
Chris Lattner1e9d1472005-03-22 23:54:52 +00001729 std::cerr << "WARNING: Useless call site found.\n";
Chris Lattner64507e32004-01-28 01:19:52 +00001730#endif
Chris Lattner1e9d1472005-03-22 23:54:52 +00001731 Calls.erase(OldIt);
1732 ++NumDeleted;
1733 continue;
1734 }
1735
1736 // If the last call site in the list has the same callee as this one, and
1737 // if the callee contains an external function, it will never be
1738 // resolvable, just merge the call sites.
1739 if (!LastCalleeNode.isNull() && LastCalleeNode.getNode() == Callee) {
1740 LastCalleeContainsExternalFunction =
1741 nodeContainsExternalFunction(Callee);
1742
1743 std::list<DSCallSite>::iterator PrevIt = OldIt;
1744 --PrevIt;
1745 PrevIt->mergeWith(CS);
1746
1747 // No need to keep this call anymore.
1748 Calls.erase(OldIt);
1749 ++NumDeleted;
1750 continue;
1751 } else {
1752 LastCalleeNode = Callee;
1753 }
Chris Lattnera9548d92005-01-30 23:51:02 +00001754 }
1755
1756 // If the return value or any arguments point to a void node with no
1757 // information at all in it, and the call node is the only node to point
1758 // to it, remove the edge to the node (killing the node).
1759 //
1760 killIfUselessEdge(CS.getRetVal());
1761 for (unsigned a = 0, e = CS.getNumPtrArgs(); a != e; ++a)
1762 killIfUselessEdge(CS.getPtrArg(a));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001763
Chris Lattner0b144872004-01-27 22:03:40 +00001764#if 0
Chris Lattnera9548d92005-01-30 23:51:02 +00001765 // If this call site calls the same function as the last call site, and if
1766 // the function pointer contains an external function, this node will
1767 // never be resolved. Merge the arguments of the call node because no
1768 // information will be lost.
1769 //
1770 if ((CS.isDirectCall() && CS.getCalleeFunc() == LastCalleeFunc) ||
1771 (CS.isIndirectCall() && CS.getCalleeNode() == LastCalleeNode)) {
1772 ++NumDuplicateCalls;
1773 if (NumDuplicateCalls == 1) {
1774 if (LastCalleeNode)
1775 LastCalleeContainsExternalFunction =
1776 nodeContainsExternalFunction(LastCalleeNode);
1777 else
1778 LastCalleeContainsExternalFunction = LastCalleeFunc->isExternal();
Chris Lattnere4258442002-11-11 21:35:38 +00001779 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001780
Chris Lattnera9548d92005-01-30 23:51:02 +00001781 // It is not clear why, but enabling this code makes DSA really
1782 // sensitive to node forwarding. Basically, with this enabled, DSA
1783 // performs different number of inlinings based on which nodes are
1784 // forwarding or not. This is clearly a problem, so this code is
1785 // disabled until this can be resolved.
1786#if 1
1787 if (LastCalleeContainsExternalFunction
1788#if 0
1789 ||
1790 // This should be more than enough context sensitivity!
1791 // FIXME: Evaluate how many times this is tripped!
1792 NumDuplicateCalls > 20
1793#endif
1794 ) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001795
Chris Lattnera9548d92005-01-30 23:51:02 +00001796 std::list<DSCallSite>::iterator PrevIt = OldIt;
1797 --PrevIt;
1798 PrevIt->mergeWith(CS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001799
Chris Lattnera9548d92005-01-30 23:51:02 +00001800 // No need to keep this call anymore.
1801 Calls.erase(OldIt);
1802 ++NumDeleted;
1803 continue;
1804 }
1805#endif
1806 } else {
1807 if (CS.isDirectCall()) {
1808 LastCalleeFunc = CS.getCalleeFunc();
1809 LastCalleeNode = 0;
1810 } else {
1811 LastCalleeNode = CS.getCalleeNode();
1812 LastCalleeFunc = 0;
1813 }
1814 NumDuplicateCalls = 0;
1815 }
1816#endif
1817
1818 if (I != Calls.end() && CS == *I) {
Chris Lattner1e9d1472005-03-22 23:54:52 +00001819 LastCalleeNode = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00001820 Calls.erase(OldIt);
1821 ++NumDeleted;
1822 continue;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001823 }
1824 }
Chris Lattner857eb062004-10-30 05:41:23 +00001825
Chris Lattnera9548d92005-01-30 23:51:02 +00001826 // Resort now that we simplified things.
1827 Calls.sort();
Chris Lattner857eb062004-10-30 05:41:23 +00001828
Chris Lattnera9548d92005-01-30 23:51:02 +00001829 // Now that we are in sorted order, eliminate duplicates.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001830 std::list<DSCallSite>::iterator CI = Calls.begin(), CE = Calls.end();
1831 if (CI != CE)
Chris Lattnera9548d92005-01-30 23:51:02 +00001832 while (1) {
Chris Lattnerf9aace22005-01-31 00:10:58 +00001833 std::list<DSCallSite>::iterator OldIt = CI++;
1834 if (CI == CE) break;
Chris Lattnera9548d92005-01-30 23:51:02 +00001835
1836 // If this call site is now the same as the previous one, we can delete it
1837 // as a duplicate.
Chris Lattnerf9aace22005-01-31 00:10:58 +00001838 if (*OldIt == *CI) {
1839 Calls.erase(CI);
1840 CI = OldIt;
Chris Lattnera9548d92005-01-30 23:51:02 +00001841 ++NumDeleted;
1842 }
1843 }
1844
1845 //Calls.erase(std::unique(Calls.begin(), Calls.end()), Calls.end());
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001846
Chris Lattner33312f72002-11-08 01:21:07 +00001847 // Track the number of call nodes merged away...
Chris Lattnera9548d92005-01-30 23:51:02 +00001848 NumCallNodesMerged += NumDeleted;
Chris Lattner33312f72002-11-08 01:21:07 +00001849
Chris Lattnera9548d92005-01-30 23:51:02 +00001850 DEBUG(if (NumDeleted)
1851 std::cerr << "Merged " << NumDeleted << " call nodes.\n";);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001852}
Chris Lattner0d9bab82002-07-18 00:12:30 +00001853
Chris Lattneraa8146f2002-11-10 06:59:55 +00001854
Chris Lattnere2219762002-07-18 18:22:40 +00001855// removeTriviallyDeadNodes - After the graph has been constructed, this method
1856// removes all unreachable nodes that are created because they got merged with
1857// other nodes in the graph. These nodes will all be trivially unreachable, so
1858// we don't have to perform any non-trivial analysis here.
Chris Lattner0d9bab82002-07-18 00:12:30 +00001859//
Chris Lattnerf40f0a32002-11-09 22:07:02 +00001860void DSGraph::removeTriviallyDeadNodes() {
Chris Lattner93ddd7e2004-01-22 16:36:28 +00001861 TIME_REGION(X, "removeTriviallyDeadNodes");
Chris Lattneraa8146f2002-11-10 06:59:55 +00001862
Chris Lattner5ace1e42004-07-08 07:25:51 +00001863#if 0
1864 /// NOTE: This code is disabled. This slows down DSA on 177.mesa
1865 /// substantially!
1866
Chris Lattnerbab8c282003-09-20 21:34:07 +00001867 // Loop over all of the nodes in the graph, calling getNode on each field.
1868 // This will cause all nodes to update their forwarding edges, causing
1869 // forwarded nodes to be delete-able.
Chris Lattner5ace1e42004-07-08 07:25:51 +00001870 { TIME_REGION(X, "removeTriviallyDeadNodes:node_iterate");
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001871 for (node_iterator NI = node_begin(), E = node_end(); NI != E; ++NI) {
Chris Lattner84b80a22005-03-16 22:42:19 +00001872 DSNode &N = *NI;
1873 for (unsigned l = 0, e = N.getNumLinks(); l != e; ++l)
1874 N.getLink(l*N.getPointerSize()).getNode();
Chris Lattnerbab8c282003-09-20 21:34:07 +00001875 }
Chris Lattner5ace1e42004-07-08 07:25:51 +00001876 }
Chris Lattnerbab8c282003-09-20 21:34:07 +00001877
Chris Lattner0b144872004-01-27 22:03:40 +00001878 // NOTE: This code is disabled. Though it should, in theory, allow us to
1879 // remove more nodes down below, the scan of the scalar map is incredibly
1880 // expensive for certain programs (with large SCCs). In the future, if we can
1881 // make the scalar map scan more efficient, then we can reenable this.
Chris Lattner0b144872004-01-27 22:03:40 +00001882 { TIME_REGION(X, "removeTriviallyDeadNodes:scalarmap");
1883
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001884 // Likewise, forward any edges from the scalar nodes. While we are at it,
1885 // clean house a bit.
Chris Lattner62482e52004-01-28 09:15:42 +00001886 for (DSScalarMap::iterator I = ScalarMap.begin(),E = ScalarMap.end();I != E;){
Chris Lattner0b144872004-01-27 22:03:40 +00001887 I->second.getNode();
1888 ++I;
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001889 }
Chris Lattner0b144872004-01-27 22:03:40 +00001890 }
1891#endif
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001892 bool isGlobalsGraph = !GlobalsGraph;
1893
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001894 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E; ) {
Chris Lattner28897e12004-02-08 00:53:26 +00001895 DSNode &Node = *NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001896
1897 // Do not remove *any* global nodes in the globals graph.
1898 // This is a special case because such nodes may not have I, M, R flags set.
Chris Lattner28897e12004-02-08 00:53:26 +00001899 if (Node.isGlobalNode() && isGlobalsGraph) {
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001900 ++NI;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001901 continue;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001902 }
Vikram S. Adve78bbec72003-07-16 21:36:31 +00001903
Chris Lattner28897e12004-02-08 00:53:26 +00001904 if (Node.isComplete() && !Node.isModified() && !Node.isRead()) {
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001905 // This is a useless node if it has no mod/ref info (checked above),
1906 // outgoing edges (which it cannot, as it is not modified in this
1907 // context), and it has no incoming edges. If it is a global node it may
1908 // have all of these properties and still have incoming edges, due to the
1909 // scalar map, so we check those now.
1910 //
Chris Lattner82c6c722005-03-20 02:41:38 +00001911 if (Node.getNumReferrers() == Node.getGlobalsList().size()) {
1912 const std::vector<GlobalValue*> &Globals = Node.getGlobalsList();
Chris Lattner72d29a42003-02-11 23:11:51 +00001913
Chris Lattner17a93e22004-01-29 03:32:15 +00001914 // Loop through and make sure all of the globals are referring directly
1915 // to the node...
1916 for (unsigned j = 0, e = Globals.size(); j != e; ++j) {
1917 DSNode *N = getNodeForValue(Globals[j]).getNode();
Chris Lattner28897e12004-02-08 00:53:26 +00001918 assert(N == &Node && "ScalarMap doesn't match globals list!");
Chris Lattner17a93e22004-01-29 03:32:15 +00001919 }
1920
Chris Lattnerbd92b732003-06-19 21:15:11 +00001921 // Make sure NumReferrers still agrees, if so, the node is truly dead.
Chris Lattner28897e12004-02-08 00:53:26 +00001922 if (Node.getNumReferrers() == Globals.size()) {
Chris Lattner72d29a42003-02-11 23:11:51 +00001923 for (unsigned j = 0, e = Globals.size(); j != e; ++j)
1924 ScalarMap.erase(Globals[j]);
Chris Lattner28897e12004-02-08 00:53:26 +00001925 Node.makeNodeDead();
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001926 ++NumTrivialGlobalDNE;
Chris Lattner72d29a42003-02-11 23:11:51 +00001927 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001928 }
1929 }
1930
Chris Lattner28897e12004-02-08 00:53:26 +00001931 if (Node.getNodeFlags() == 0 && Node.hasNoReferrers()) {
Chris Lattner2609c072003-02-10 18:18:18 +00001932 // This node is dead!
Chris Lattner28897e12004-02-08 00:53:26 +00001933 NI = Nodes.erase(NI); // Erase & remove from node list.
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001934 ++NumTrivialDNE;
Chris Lattner9fd37ba2004-02-08 00:23:16 +00001935 } else {
1936 ++NI;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001937 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001938 }
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001939
1940 removeIdenticalCalls(FunctionCalls);
1941 removeIdenticalCalls(AuxFunctionCalls);
Chris Lattner0d9bab82002-07-18 00:12:30 +00001942}
1943
1944
Chris Lattner5c7380e2003-01-29 21:10:20 +00001945/// markReachableNodes - This method recursively traverses the specified
1946/// DSNodes, marking any nodes which are reachable. All reachable nodes it adds
1947/// to the set, which allows it to only traverse visited nodes once.
1948///
Chris Lattnera9548d92005-01-30 23:51:02 +00001949void DSNode::markReachableNodes(hash_set<const DSNode*> &ReachableNodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001950 if (this == 0) return;
Chris Lattner72d29a42003-02-11 23:11:51 +00001951 assert(getForwardNode() == 0 && "Cannot mark a forwarded node!");
Chris Lattner4c6cb7a2004-01-22 15:30:58 +00001952 if (ReachableNodes.insert(this).second) // Is newly reachable?
Chris Lattner6be07942005-02-09 03:20:43 +00001953 for (DSNode::const_edge_iterator I = edge_begin(), E = edge_end();
1954 I != E; ++I)
1955 I->getNode()->markReachableNodes(ReachableNodes);
Chris Lattner5c7380e2003-01-29 21:10:20 +00001956}
1957
Chris Lattnera9548d92005-01-30 23:51:02 +00001958void DSCallSite::markReachableNodes(hash_set<const DSNode*> &Nodes) const {
Chris Lattner5c7380e2003-01-29 21:10:20 +00001959 getRetVal().getNode()->markReachableNodes(Nodes);
Chris Lattner923fc052003-02-05 21:59:58 +00001960 if (isIndirectCall()) getCalleeNode()->markReachableNodes(Nodes);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001961
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00001962 for (unsigned i = 0, e = getNumPtrArgs(); i != e; ++i)
1963 getPtrArg(i).getNode()->markReachableNodes(Nodes);
Chris Lattnere2219762002-07-18 18:22:40 +00001964}
1965
Chris Lattnera1220af2003-02-01 06:17:02 +00001966// CanReachAliveNodes - Simple graph walker that recursively traverses the graph
1967// looking for a node that is marked alive. If an alive node is found, return
1968// true, otherwise return false. If an alive node is reachable, this node is
1969// marked as alive...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001970//
Chris Lattnera9548d92005-01-30 23:51:02 +00001971static bool CanReachAliveNodes(DSNode *N, hash_set<const DSNode*> &Alive,
1972 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00001973 bool IgnoreGlobals) {
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001974 if (N == 0) return false;
Chris Lattner72d29a42003-02-11 23:11:51 +00001975 assert(N->getForwardNode() == 0 && "Cannot mark a forwarded node!");
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001976
Chris Lattner85cfe012003-07-03 02:03:53 +00001977 // If this is a global node, it will end up in the globals graph anyway, so we
1978 // don't need to worry about it.
1979 if (IgnoreGlobals && N->isGlobalNode()) return false;
1980
Chris Lattneraa8146f2002-11-10 06:59:55 +00001981 // If we know that this node is alive, return so!
1982 if (Alive.count(N)) return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001983
Chris Lattneraa8146f2002-11-10 06:59:55 +00001984 // Otherwise, we don't think the node is alive yet, check for infinite
1985 // recursion.
Chris Lattner41c04f72003-02-01 04:52:08 +00001986 if (Visited.count(N)) return false; // Found a cycle
Chris Lattnera1220af2003-02-01 06:17:02 +00001987 Visited.insert(N); // No recursion, insert into Visited...
Chris Lattneraa8146f2002-11-10 06:59:55 +00001988
Chris Lattner6be07942005-02-09 03:20:43 +00001989 for (DSNode::edge_iterator I = N->edge_begin(),E = N->edge_end(); I != E; ++I)
1990 if (CanReachAliveNodes(I->getNode(), Alive, Visited, IgnoreGlobals)) {
Chris Lattnera1220af2003-02-01 06:17:02 +00001991 N->markReachableNodes(Alive);
1992 return true;
1993 }
1994 return false;
Chris Lattneraa8146f2002-11-10 06:59:55 +00001995}
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00001996
Chris Lattnera1220af2003-02-01 06:17:02 +00001997// CallSiteUsesAliveArgs - Return true if the specified call site can reach any
1998// alive nodes.
1999//
Chris Lattnera9548d92005-01-30 23:51:02 +00002000static bool CallSiteUsesAliveArgs(const DSCallSite &CS,
2001 hash_set<const DSNode*> &Alive,
2002 hash_set<const DSNode*> &Visited,
Chris Lattner85cfe012003-07-03 02:03:53 +00002003 bool IgnoreGlobals) {
2004 if (CanReachAliveNodes(CS.getRetVal().getNode(), Alive, Visited,
2005 IgnoreGlobals))
Chris Lattner923fc052003-02-05 21:59:58 +00002006 return true;
2007 if (CS.isIndirectCall() &&
Chris Lattner85cfe012003-07-03 02:03:53 +00002008 CanReachAliveNodes(CS.getCalleeNode(), Alive, Visited, IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002009 return true;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002010 for (unsigned i = 0, e = CS.getNumPtrArgs(); i != e; ++i)
Chris Lattner85cfe012003-07-03 02:03:53 +00002011 if (CanReachAliveNodes(CS.getPtrArg(i).getNode(), Alive, Visited,
2012 IgnoreGlobals))
Chris Lattneraa8146f2002-11-10 06:59:55 +00002013 return true;
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002014 return false;
2015}
2016
Chris Lattnere2219762002-07-18 18:22:40 +00002017// removeDeadNodes - Use a more powerful reachability analysis to eliminate
2018// subgraphs that are unreachable. This often occurs because the data
2019// structure doesn't "escape" into it's caller, and thus should be eliminated
2020// from the caller's graph entirely. This is only appropriate to use when
2021// inlining graphs.
2022//
Chris Lattner394471f2003-01-23 22:05:33 +00002023void DSGraph::removeDeadNodes(unsigned Flags) {
Chris Lattner9dc41852003-11-12 04:57:58 +00002024 DEBUG(AssertGraphOK(); if (GlobalsGraph) GlobalsGraph->AssertGraphOK());
Chris Lattner85cfe012003-07-03 02:03:53 +00002025
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002026 // Reduce the amount of work we have to do... remove dummy nodes left over by
2027 // merging...
Chris Lattnera3fd88d2004-01-28 03:24:41 +00002028 removeTriviallyDeadNodes();
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002029
Chris Lattner93ddd7e2004-01-22 16:36:28 +00002030 TIME_REGION(X, "removeDeadNodes");
2031
Misha Brukman2f2d0652003-09-11 18:14:24 +00002032 // FIXME: Merge non-trivially identical call nodes...
Chris Lattnere2219762002-07-18 18:22:40 +00002033
2034 // Alive - a set that holds all nodes found to be reachable/alive.
Chris Lattnera9548d92005-01-30 23:51:02 +00002035 hash_set<const DSNode*> Alive;
Chris Lattneraa8146f2002-11-10 06:59:55 +00002036 std::vector<std::pair<Value*, DSNode*> > GlobalNodes;
Chris Lattnere2219762002-07-18 18:22:40 +00002037
Chris Lattner0b144872004-01-27 22:03:40 +00002038 // Copy and merge all information about globals to the GlobalsGraph if this is
2039 // not a final pass (where unreachable globals are removed).
2040 //
2041 // Strip all alloca bits since the current function is only for the BU pass.
2042 // Strip all incomplete bits since they are short-lived properties and they
2043 // will be correctly computed when rematerializing nodes into the functions.
2044 //
2045 ReachabilityCloner GGCloner(*GlobalsGraph, *this, DSGraph::StripAllocaBit |
2046 DSGraph::StripIncompleteBit);
2047
Chris Lattneraa8146f2002-11-10 06:59:55 +00002048 // Mark all nodes reachable by (non-global) scalar nodes as alive...
Chris Lattnerf4f62272005-03-19 22:23:45 +00002049{ TIME_REGION(Y, "removeDeadNodes:scalarscan");
2050 for (DSScalarMap::iterator I = ScalarMap.begin(), E = ScalarMap.end();
2051 I != E; ++I)
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002052 if (isa<GlobalValue>(I->first)) { // Keep track of global nodes
Chris Lattner6f967742004-10-30 04:05:01 +00002053 assert(!I->second.isNull() && "Null global node?");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002054 assert(I->second.getNode()->isGlobalNode() && "Should be a global node!");
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002055 GlobalNodes.push_back(std::make_pair(I->first, I->second.getNode()));
Chris Lattner0b144872004-01-27 22:03:40 +00002056
2057 // Make sure that all globals are cloned over as roots.
Chris Lattner021decc2005-04-02 19:17:18 +00002058 if (!(Flags & DSGraph::RemoveUnreachableGlobals) && GlobalsGraph) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002059 DSGraph::ScalarMapTy::iterator SMI =
Chris Lattner00948c02004-01-28 02:05:05 +00002060 GlobalsGraph->getScalarMap().find(I->first);
2061 if (SMI != GlobalsGraph->getScalarMap().end())
2062 GGCloner.merge(SMI->second, I->second);
2063 else
2064 GGCloner.getClonedNH(I->second);
2065 }
Chris Lattner5f07a8b2003-02-14 06:28:00 +00002066 } else {
Chris Lattnerf4f62272005-03-19 22:23:45 +00002067 I->second.getNode()->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002068 }
Chris Lattnerf4f62272005-03-19 22:23:45 +00002069}
Chris Lattnere2219762002-07-18 18:22:40 +00002070
Chris Lattner0b144872004-01-27 22:03:40 +00002071 // The return values are alive as well.
Chris Lattner5a540632003-06-30 03:15:25 +00002072 for (ReturnNodesTy::iterator I = ReturnNodes.begin(), E = ReturnNodes.end();
2073 I != E; ++I)
2074 I->second.getNode()->markReachableNodes(Alive);
Vikram S. Adve355e2ca2002-07-30 22:05:22 +00002075
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002076 // Mark any nodes reachable by primary calls as alive...
Chris Lattnera9548d92005-01-30 23:51:02 +00002077 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2078 I->markReachableNodes(Alive);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002079
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002080
2081 // Now find globals and aux call nodes that are already live or reach a live
2082 // value (which makes them live in turn), and continue till no more are found.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002083 //
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002084 bool Iterate;
Chris Lattnera9548d92005-01-30 23:51:02 +00002085 hash_set<const DSNode*> Visited;
2086 hash_set<const DSCallSite*> AuxFCallsAlive;
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002087 do {
2088 Visited.clear();
Chris Lattner70793862003-07-02 23:57:05 +00002089 // If any global node points to a non-global that is "alive", the global is
Chris Lattner72d29a42003-02-11 23:11:51 +00002090 // "alive" as well... Remove it from the GlobalNodes list so we only have
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002091 // unreachable globals in the list.
2092 //
2093 Iterate = false;
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002094 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
Chris Lattner0b144872004-01-27 22:03:40 +00002095 for (unsigned i = 0; i != GlobalNodes.size(); ++i)
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002096 if (CanReachAliveNodes(GlobalNodes[i].second, Alive, Visited,
Chris Lattner0b144872004-01-27 22:03:40 +00002097 Flags & DSGraph::RemoveUnreachableGlobals)) {
2098 std::swap(GlobalNodes[i--], GlobalNodes.back()); // Move to end to...
2099 GlobalNodes.pop_back(); // erase efficiently
2100 Iterate = true;
2101 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002102
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002103 // Mark only unresolvable call nodes for moving to the GlobalsGraph since
2104 // call nodes that get resolved will be difficult to remove from that graph.
2105 // The final unresolved call nodes must be handled specially at the end of
2106 // the BU pass (i.e., in main or other roots of the call graph).
Chris Lattnera9548d92005-01-30 23:51:02 +00002107 for (afc_iterator CI = afc_begin(), E = afc_end(); CI != E; ++CI)
Chris Lattnerd7642c42005-02-24 18:48:07 +00002108 if (!AuxFCallsAlive.count(&*CI) &&
Chris Lattnera9548d92005-01-30 23:51:02 +00002109 (CI->isIndirectCall()
2110 || CallSiteUsesAliveArgs(*CI, Alive, Visited,
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002111 Flags & DSGraph::RemoveUnreachableGlobals))) {
Chris Lattnera9548d92005-01-30 23:51:02 +00002112 CI->markReachableNodes(Alive);
Chris Lattnerd7642c42005-02-24 18:48:07 +00002113 AuxFCallsAlive.insert(&*CI);
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002114 Iterate = true;
2115 }
2116 } while (Iterate);
Chris Lattneraa8146f2002-11-10 06:59:55 +00002117
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002118 // Move dead aux function calls to the end of the list
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002119 unsigned CurIdx = 0;
Chris Lattnera9548d92005-01-30 23:51:02 +00002120 for (std::list<DSCallSite>::iterator CI = AuxFunctionCalls.begin(),
2121 E = AuxFunctionCalls.end(); CI != E; )
2122 if (AuxFCallsAlive.count(&*CI))
2123 ++CI;
2124 else {
2125 // Copy and merge global nodes and dead aux call nodes into the
2126 // GlobalsGraph, and all nodes reachable from those nodes. Update their
2127 // target pointers using the GGCloner.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002128 //
Chris Lattnera9548d92005-01-30 23:51:02 +00002129 if (!(Flags & DSGraph::RemoveUnreachableGlobals))
2130 GlobalsGraph->AuxFunctionCalls.push_back(DSCallSite(*CI, GGCloner));
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002131
Chris Lattnera9548d92005-01-30 23:51:02 +00002132 AuxFunctionCalls.erase(CI++);
2133 }
Chris Lattneraa8146f2002-11-10 06:59:55 +00002134
Chris Lattnerc3f5f772004-02-08 01:51:48 +00002135 // We are finally done with the GGCloner so we can destroy it.
2136 GGCloner.destroy();
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002137
Vikram S. Adve40c600e2003-07-22 12:08:58 +00002138 // At this point, any nodes which are visited, but not alive, are nodes
2139 // which can be removed. Loop over all nodes, eliminating completely
2140 // unreachable nodes.
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002141 //
Chris Lattner72d29a42003-02-11 23:11:51 +00002142 std::vector<DSNode*> DeadNodes;
2143 DeadNodes.reserve(Nodes.size());
Chris Lattner51c06ab2004-02-25 23:08:00 +00002144 for (NodeListTy::iterator NI = Nodes.begin(), E = Nodes.end(); NI != E;) {
2145 DSNode *N = NI++;
2146 assert(!N->isForwarding() && "Forwarded node in nodes list?");
2147
2148 if (!Alive.count(N)) {
2149 Nodes.remove(N);
2150 assert(!N->isForwarding() && "Cannot remove a forwarding node!");
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002151 DeadNodes.push_back(N);
2152 N->dropAllReferences();
Chris Lattner51c06ab2004-02-25 23:08:00 +00002153 ++NumDNE;
Chris Lattnere2219762002-07-18 18:22:40 +00002154 }
Chris Lattner51c06ab2004-02-25 23:08:00 +00002155 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002156
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002157 // Remove all unreachable globals from the ScalarMap.
2158 // If flag RemoveUnreachableGlobals is set, GlobalNodes has only dead nodes.
2159 // In either case, the dead nodes will not be in the set Alive.
Chris Lattner0b144872004-01-27 22:03:40 +00002160 for (unsigned i = 0, e = GlobalNodes.size(); i != e; ++i)
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002161 if (!Alive.count(GlobalNodes[i].second))
2162 ScalarMap.erase(GlobalNodes[i].first);
Chris Lattner0b144872004-01-27 22:03:40 +00002163 else
2164 assert((Flags & DSGraph::RemoveUnreachableGlobals) && "non-dead global");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002165
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002166 // Delete all dead nodes now since their referrer counts are zero.
Chris Lattner72d29a42003-02-11 23:11:51 +00002167 for (unsigned i = 0, e = DeadNodes.size(); i != e; ++i)
2168 delete DeadNodes[i];
2169
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002170 DEBUG(AssertGraphOK(); GlobalsGraph->AssertGraphOK());
Chris Lattnere2219762002-07-18 18:22:40 +00002171}
2172
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002173void DSGraph::AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
Chris Lattner82c6c722005-03-20 02:41:38 +00002174 assert(std::find(N->globals_begin(),N->globals_end(), GV) !=
2175 N->globals_end() && "Global value not in node!");
Chris Lattnerb29dd0f2004-12-08 21:03:56 +00002176}
2177
Chris Lattner2c7725a2004-03-03 20:55:27 +00002178void DSGraph::AssertCallSiteInGraph(const DSCallSite &CS) const {
2179 if (CS.isIndirectCall()) {
2180 AssertNodeInGraph(CS.getCalleeNode());
2181#if 0
2182 if (CS.getNumPtrArgs() && CS.getCalleeNode() == CS.getPtrArg(0).getNode() &&
2183 CS.getCalleeNode() && CS.getCalleeNode()->getGlobals().empty())
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002184 std::cerr << "WARNING: WEIRD CALL SITE FOUND!\n";
Chris Lattner2c7725a2004-03-03 20:55:27 +00002185#endif
2186 }
2187 AssertNodeInGraph(CS.getRetVal().getNode());
2188 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
2189 AssertNodeInGraph(CS.getPtrArg(j).getNode());
2190}
2191
2192void DSGraph::AssertCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002193 for (fc_iterator I = fc_begin(), E = fc_end(); I != E; ++I)
2194 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002195}
2196void DSGraph::AssertAuxCallNodesInGraph() const {
Chris Lattnera9548d92005-01-30 23:51:02 +00002197 for (afc_iterator I = afc_begin(), E = afc_end(); I != E; ++I)
2198 AssertCallSiteInGraph(*I);
Chris Lattner2c7725a2004-03-03 20:55:27 +00002199}
2200
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002201void DSGraph::AssertGraphOK() const {
Chris Lattner84b80a22005-03-16 22:42:19 +00002202 for (node_const_iterator NI = node_begin(), E = node_end(); NI != E; ++NI)
2203 NI->assertOK();
Chris Lattner85cfe012003-07-03 02:03:53 +00002204
Chris Lattner8d327672003-06-30 03:36:09 +00002205 for (ScalarMapTy::const_iterator I = ScalarMap.begin(),
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002206 E = ScalarMap.end(); I != E; ++I) {
Chris Lattner6f967742004-10-30 04:05:01 +00002207 assert(!I->second.isNull() && "Null node in scalarmap!");
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002208 AssertNodeInGraph(I->second.getNode());
2209 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first)) {
Chris Lattnerbd92b732003-06-19 21:15:11 +00002210 assert(I->second.getNode()->isGlobalNode() &&
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002211 "Global points to node, but node isn't global?");
2212 AssertNodeContainsGlobal(I->second.getNode(), GV);
2213 }
2214 }
2215 AssertCallNodesInGraph();
2216 AssertAuxCallNodesInGraph();
Chris Lattner7d8d4712004-10-31 17:45:40 +00002217
2218 // Check that all pointer arguments to any functions in this graph have
2219 // destinations.
2220 for (ReturnNodesTy::const_iterator RI = ReturnNodes.begin(),
2221 E = ReturnNodes.end();
2222 RI != E; ++RI) {
2223 Function &F = *RI->first;
Chris Lattnere4d5c442005-03-15 04:54:21 +00002224 for (Function::arg_iterator AI = F.arg_begin(); AI != F.arg_end(); ++AI)
Chris Lattner7d8d4712004-10-31 17:45:40 +00002225 if (isPointerType(AI->getType()))
2226 assert(!getNodeForValue(AI).isNull() &&
2227 "Pointer argument must be in the scalar map!");
2228 }
Chris Lattner0ac7d5c2003-02-03 19:12:15 +00002229}
Vikram S. Adve78bbec72003-07-16 21:36:31 +00002230
Chris Lattner400433d2003-11-11 05:08:59 +00002231/// computeNodeMapping - Given roots in two different DSGraphs, traverse the
Chris Lattnere84c23e2004-10-31 19:57:43 +00002232/// nodes reachable from the two graphs, computing the mapping of nodes from the
2233/// first to the second graph. This mapping may be many-to-one (i.e. the first
2234/// graph may have multiple nodes representing one node in the second graph),
2235/// but it will not work if there is a one-to-many or many-to-many mapping.
Chris Lattner400433d2003-11-11 05:08:59 +00002236///
2237void DSGraph::computeNodeMapping(const DSNodeHandle &NH1,
Chris Lattnerafc1dba2003-11-12 17:58:22 +00002238 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
2239 bool StrictChecking) {
Chris Lattner400433d2003-11-11 05:08:59 +00002240 DSNode *N1 = NH1.getNode(), *N2 = NH2.getNode();
2241 if (N1 == 0 || N2 == 0) return;
2242
2243 DSNodeHandle &Entry = NodeMap[N1];
Chris Lattner6f967742004-10-30 04:05:01 +00002244 if (!Entry.isNull()) {
Chris Lattner400433d2003-11-11 05:08:59 +00002245 // Termination of recursion!
Chris Lattnercc7c4ac2004-03-13 01:14:23 +00002246 if (StrictChecking) {
2247 assert(Entry.getNode() == N2 && "Inconsistent mapping detected!");
2248 assert((Entry.getOffset() == (NH2.getOffset()-NH1.getOffset()) ||
2249 Entry.getNode()->isNodeCompletelyFolded()) &&
2250 "Inconsistent mapping detected!");
2251 }
Chris Lattner400433d2003-11-11 05:08:59 +00002252 return;
2253 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002254
Chris Lattnerefffdc92004-07-07 06:12:52 +00002255 Entry.setTo(N2, NH2.getOffset()-NH1.getOffset());
Chris Lattner400433d2003-11-11 05:08:59 +00002256
2257 // Loop over all of the fields that N1 and N2 have in common, recursively
2258 // mapping the edges together now.
2259 int N2Idx = NH2.getOffset()-NH1.getOffset();
2260 unsigned N2Size = N2->getSize();
Chris Lattner841957e2005-03-15 04:40:24 +00002261 if (N2Size == 0) return; // No edges to map to.
2262
Chris Lattner4d5af8e2005-03-15 21:36:50 +00002263 for (unsigned i = 0, e = N1->getSize(); i < e; i += DS::PointerSize) {
2264 const DSNodeHandle &N1NH = N1->getLink(i);
2265 // Don't call N2->getLink if not needed (avoiding crash if N2Idx is not
2266 // aligned right).
2267 if (!N1NH.isNull()) {
2268 if (unsigned(N2Idx)+i < N2Size)
2269 computeNodeMapping(N1NH, N2->getLink(N2Idx+i), NodeMap);
2270 else
2271 computeNodeMapping(N1NH,
2272 N2->getLink(unsigned(N2Idx+i) % N2Size), NodeMap);
2273 }
2274 }
Chris Lattner400433d2003-11-11 05:08:59 +00002275}
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002276
2277
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002278/// computeGToGGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002279/// nodes in this graph.
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002280void DSGraph::computeGToGGMapping(NodeMapTy &NodeMap) {
Chris Lattnerb2b17bb2005-03-14 19:22:47 +00002281 DSGraph &GG = *getGlobalsGraph();
2282
2283 DSScalarMap &SM = getScalarMap();
2284 for (DSScalarMap::global_iterator I = SM.global_begin(),
2285 E = SM.global_end(); I != E; ++I)
2286 DSGraph::computeNodeMapping(SM[*I], GG.getNodeForValue(*I), NodeMap);
2287}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002288
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002289/// computeGGToGMapping - Compute the mapping of nodes in the global graph to
Chris Lattner36a13cd2005-03-15 17:52:18 +00002290/// nodes in this graph. Note that any uses of this method are probably bugs,
2291/// unless it is known that the globals graph has been merged into this graph!
2292void DSGraph::computeGGToGMapping(InvNodeMapTy &InvNodeMap) {
2293 NodeMapTy NodeMap;
2294 computeGToGGMapping(NodeMap);
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002295
Chris Lattner36a13cd2005-03-15 17:52:18 +00002296 while (!NodeMap.empty()) {
2297 InvNodeMap.insert(std::make_pair(NodeMap.begin()->second,
2298 NodeMap.begin()->first));
2299 NodeMap.erase(NodeMap.begin());
2300 }
Chris Lattnerb0f92e32005-03-15 00:58:16 +00002301}
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002302
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002303
2304/// computeCalleeCallerMapping - Given a call from a function in the current
2305/// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
2306/// mapping of nodes from the callee to nodes in the caller.
2307void DSGraph::computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
2308 DSGraph &CalleeGraph,
2309 NodeMapTy &NodeMap) {
2310
2311 DSCallSite CalleeArgs =
2312 CalleeGraph.getCallSiteForArguments(const_cast<Function&>(Callee));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002313
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002314 computeNodeMapping(CalleeArgs.getRetVal(), CS.getRetVal(), NodeMap);
2315
2316 unsigned NumArgs = CS.getNumPtrArgs();
2317 if (NumArgs > CalleeArgs.getNumPtrArgs())
2318 NumArgs = CalleeArgs.getNumPtrArgs();
2319
2320 for (unsigned i = 0; i != NumArgs; ++i)
2321 computeNodeMapping(CalleeArgs.getPtrArg(i), CS.getPtrArg(i), NodeMap);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002322
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002323 // Map the nodes that are pointed to by globals.
2324 DSScalarMap &CalleeSM = CalleeGraph.getScalarMap();
2325 DSScalarMap &CallerSM = getScalarMap();
2326
2327 if (CalleeSM.global_size() >= CallerSM.global_size()) {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002328 for (DSScalarMap::global_iterator GI = CallerSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002329 E = CallerSM.global_end(); GI != E; ++GI)
2330 if (CalleeSM.global_count(*GI))
2331 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2332 } else {
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002333 for (DSScalarMap::global_iterator GI = CalleeSM.global_begin(),
Chris Lattner4ffe5d82005-03-17 23:45:54 +00002334 E = CalleeSM.global_end(); GI != E; ++GI)
2335 if (CallerSM.global_count(*GI))
2336 computeNodeMapping(CalleeSM[*GI], CallerSM[*GI], NodeMap);
2337 }
2338}