blob: 3e6d424fc09ee9b4caa20c8c99017012263c7472 [file] [log] [blame]
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001//===- Local.cpp - Compute a local data structure graph for a function ----===//
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 Lattnerc68c31b2002-07-10 22:38:08 +00009//
10// Compute the local version of the data structure graph for a function. The
11// external interface to this file is the DSGraph constructor.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner4dabb2c2004-07-07 06:32:21 +000015#include "llvm/Analysis/DataStructure/DataStructure.h"
16#include "llvm/Analysis/DataStructure/DSGraph.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner808a7ae2003-09-20 16:34:13 +000019#include "llvm/Instructions.h"
Chris Lattnera07b72f2004-02-13 16:09:54 +000020#include "llvm/Intrinsics.h"
Chris Lattnerfa3711a2003-11-25 20:19:55 +000021#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000022#include "llvm/Support/InstVisitor.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023#include "llvm/Target/TargetData.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Timer.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000027
28// FIXME: This should eventually be a FunctionPass that is automatically
29// aggregated into a Pass.
30//
31#include "llvm/Module.h"
32
Chris Lattner9a927292003-11-12 23:11:14 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner97f51a32002-07-27 01:12:15 +000035static RegisterAnalysis<LocalDataStructures>
36X("datastructure", "Local Data Structure Analysis");
Chris Lattner97f51a32002-07-27 01:12:15 +000037
Chris Lattnera1907662003-11-13 03:10:49 +000038static cl::opt<bool>
Chris Lattnerf0431b02004-08-02 20:16:21 +000039TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
Chris Lattnera1907662003-11-13 03:10:49 +000040 cl::desc("If this is set, track integers as potential pointers"));
Chris Lattnera1907662003-11-13 03:10:49 +000041
John Criswellfa700522005-12-19 17:38:39 +000042static cl::list<std::string>
43AllocList("alloc-list",
44 cl::value_desc("list"),
45 cl::desc("List of functions that allocate memory from the heap"),
46 cl::CommaSeparated);
47
Chris Lattner9a927292003-11-12 23:11:14 +000048namespace llvm {
Chris Lattnerb1060432002-11-07 05:20:53 +000049namespace DS {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000050 // isPointerType - Return true if this type is big enough to hold a pointer.
51 bool isPointerType(const Type *Ty) {
52 if (isa<PointerType>(Ty))
53 return true;
Chris Lattnera1907662003-11-13 03:10:49 +000054 else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
Chris Lattnerfccd06f2002-10-01 22:33:50 +000055 return Ty->getPrimitiveSize() >= PointerSize;
56 return false;
57 }
Chris Lattner9a927292003-11-12 23:11:14 +000058}}
Chris Lattnerfccd06f2002-10-01 22:33:50 +000059
Brian Gaeked0fde302003-11-11 22:41:34 +000060using namespace DS;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000061
62namespace {
Chris Lattner923fc052003-02-05 21:59:58 +000063 cl::opt<bool>
64 DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
65 cl::desc("Disable direct call optimization in "
66 "DSGraph construction"));
Chris Lattnerca3f7902003-02-08 20:18:39 +000067 cl::opt<bool>
68 DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
69 cl::desc("Disable field sensitivity in DSGraphs"));
Chris Lattner923fc052003-02-05 21:59:58 +000070
Chris Lattnerfccd06f2002-10-01 22:33:50 +000071 //===--------------------------------------------------------------------===//
72 // GraphBuilder Class
73 //===--------------------------------------------------------------------===//
74 //
75 /// This class is the builder class that constructs the local data structure
76 /// graph by performing a single pass over the function in question.
77 ///
Chris Lattnerc68c31b2002-07-10 22:38:08 +000078 class GraphBuilder : InstVisitor<GraphBuilder> {
79 DSGraph &G;
Chris Lattner26c4fc32003-09-20 21:48:16 +000080 DSNodeHandle *RetNode; // Node that gets returned...
Chris Lattner62482e52004-01-28 09:15:42 +000081 DSScalarMap &ScalarMap;
Chris Lattnera9548d92005-01-30 23:51:02 +000082 std::list<DSCallSite> *FunctionCalls;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000083
84 public:
Misha Brukman2b37d7c2005-04-21 21:13:18 +000085 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
Chris Lattnera9548d92005-01-30 23:51:02 +000086 std::list<DSCallSite> &fc)
Chris Lattner26c4fc32003-09-20 21:48:16 +000087 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
88 FunctionCalls(&fc) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000089
90 // Create scalar nodes for all pointer arguments...
Chris Lattnera513fb12005-03-22 02:45:13 +000091 for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end();
92 I != E; ++I)
Chris Lattnerfccd06f2002-10-01 22:33:50 +000093 if (isPointerType(I->getType()))
94 getValueDest(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +000095
Chris Lattner26c4fc32003-09-20 21:48:16 +000096 visit(f); // Single pass over the function
Chris Lattnerc68c31b2002-07-10 22:38:08 +000097 }
98
Chris Lattner26c4fc32003-09-20 21:48:16 +000099 // GraphBuilder ctor for working on the globals graph
100 GraphBuilder(DSGraph &g)
101 : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
102 }
103
104 void mergeInGlobalInitializer(GlobalVariable *GV);
105
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000106 private:
107 // Visitor functions, used to handle each instruction type we encounter...
108 friend class InstVisitor<GraphBuilder>;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000109 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
110 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
111 void handleAlloc(AllocationInst &AI, bool isHeap);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000112
113 void visitPHINode(PHINode &PN);
Chris Lattner6e84bd72005-02-25 01:27:48 +0000114 void visitSelectInst(SelectInst &SI);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000115
Chris Lattner51340062002-11-08 05:00:44 +0000116 void visitGetElementPtrInst(User &GEP);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000117 void visitReturnInst(ReturnInst &RI);
118 void visitLoadInst(LoadInst &LI);
119 void visitStoreInst(StoreInst &SI);
120 void visitCallInst(CallInst &CI);
Chris Lattner808a7ae2003-09-20 16:34:13 +0000121 void visitInvokeInst(InvokeInst &II);
Chris Lattner32672652005-03-05 19:04:31 +0000122 void visitSetCondInst(SetCondInst &SCI);
Vikram S. Advebac06222002-12-06 21:17:10 +0000123 void visitFreeInst(FreeInst &FI);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000124 void visitCastInst(CastInst &CI);
Chris Lattner878e5212003-02-04 00:59:50 +0000125 void visitInstruction(Instruction &I);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000126
Chris Lattner808a7ae2003-09-20 16:34:13 +0000127 void visitCallSite(CallSite CS);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000128 void visitVAArgInst(VAArgInst &I);
Chris Lattner26c4fc32003-09-20 21:48:16 +0000129
130 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000131 private:
132 // Helper functions used to implement the visitation functions...
133
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000134 /// createNode - Create a new DSNode, ensuring that it is properly added to
135 /// the graph.
136 ///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000137 DSNode *createNode(const Type *Ty = 0) {
138 DSNode *N = new DSNode(Ty, &G); // Create the node
Chris Lattnere158b192003-06-16 12:08:18 +0000139 if (DisableFieldSensitivity) {
Chris Lattner2412a052004-05-23 21:14:09 +0000140 // Create node handle referring to the old node so that it is
141 // immediately removed from the graph when the node handle is destroyed.
142 DSNodeHandle OldNNH = N;
Chris Lattnerca3f7902003-02-08 20:18:39 +0000143 N->foldNodeCompletely();
Chris Lattnere158b192003-06-16 12:08:18 +0000144 if (DSNode *FN = N->getForwardNode())
145 N = FN;
146 }
Chris Lattner92673292002-11-02 00:13:20 +0000147 return N;
148 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000149
Chris Lattnerc875f022002-11-03 21:27:48 +0000150 /// setDestTo - Set the ScalarMap entry for the specified value to point to
Chris Lattner92673292002-11-02 00:13:20 +0000151 /// the specified destination. If the Value already points to a node, make
152 /// sure to merge the two destinations together.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000153 ///
Chris Lattner92673292002-11-02 00:13:20 +0000154 void setDestTo(Value &V, const DSNodeHandle &NH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000155
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000156 /// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000157 ///
Chris Lattner92673292002-11-02 00:13:20 +0000158 DSNodeHandle getValueDest(Value &V);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000159
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000160 /// getLink - This method is used to return the specified link in the
161 /// specified node if one exists. If a link does not already exist (it's
Chris Lattner7e51c872002-10-31 06:52:26 +0000162 /// null), then we create a new node, link it, then return it.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000163 ///
Chris Lattner7e51c872002-10-31 06:52:26 +0000164 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000165 };
166}
167
Brian Gaeked0fde302003-11-11 22:41:34 +0000168using namespace DS;
169
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000170//===----------------------------------------------------------------------===//
171// DSGraph constructor - Simply use the GraphBuilder to construct the local
172// graph.
Chris Lattnerf4f62272005-03-19 22:23:45 +0000173DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
174 Function &F, DSGraph *GG)
175 : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
Chris Lattner2a068862002-11-10 06:53:38 +0000176 PrintAuxCalls = false;
Chris Lattner30514192003-07-02 04:37:26 +0000177
178 DEBUG(std::cerr << " [Loc] Calculating graph for: " << F.getName() << "\n");
179
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000180 // Use the graph builder to construct the local version of the graph
Chris Lattner26c4fc32003-09-20 21:48:16 +0000181 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
Chris Lattner4fe34612002-11-18 21:44:19 +0000182#ifndef NDEBUG
183 Timer::addPeakMemoryMeasurement();
184#endif
Chris Lattner1a1a85d2003-02-14 04:55:58 +0000185
Chris Lattnerc420ab62004-02-25 23:31:02 +0000186 // If there are any constant globals referenced in this function, merge their
187 // initializers into the local graph from the globals graph.
188 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
189 ReachabilityCloner RC(*this, *GG, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000190
Chris Lattnerc420ab62004-02-25 23:31:02 +0000191 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
192 I != ScalarMap.global_end(); ++I)
193 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattner76a9eb32004-03-03 23:00:19 +0000194 if (!GV->isExternal() && GV->isConstant())
Chris Lattnerc420ab62004-02-25 23:31:02 +0000195 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
196 }
197
Chris Lattner394471f2003-01-23 22:05:33 +0000198 markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner96517252002-11-09 20:55:24 +0000199
200 // Remove any nodes made dead due to merging...
Chris Lattner394471f2003-01-23 22:05:33 +0000201 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000202}
203
204
205//===----------------------------------------------------------------------===//
206// Helper method implementations...
207//
208
Chris Lattner92673292002-11-02 00:13:20 +0000209/// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000210///
Chris Lattner51340062002-11-08 05:00:44 +0000211DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
212 Value *V = &Val;
Chris Lattner82962de2004-11-03 18:51:26 +0000213 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
Chris Lattner51340062002-11-08 05:00:44 +0000214 return 0; // Null doesn't point to anything, don't add to ScalarMap!
Chris Lattner92673292002-11-02 00:13:20 +0000215
Vikram S. Advebac06222002-12-06 21:17:10 +0000216 DSNodeHandle &NH = ScalarMap[V];
Chris Lattner62c3a952004-10-30 04:22:45 +0000217 if (!NH.isNull())
Vikram S. Advebac06222002-12-06 21:17:10 +0000218 return NH; // Already have a node? Just return it...
219
220 // Otherwise we need to create a new node to point to.
221 // Check first for constant expressions that must be traversed to
222 // extract the actual value.
Reid Spencere8404342004-07-18 00:18:30 +0000223 DSNode* N;
224 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
Chris Lattner48427b52005-03-20 01:18:00 +0000225 // Create a new global node for this global variable.
Reid Spencere8404342004-07-18 00:18:30 +0000226 N = createNode(GV->getType()->getElementType());
227 N->addGlobal(GV);
228 } else if (Constant *C = dyn_cast<Constant>(V)) {
229 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnera513fb12005-03-22 02:45:13 +0000230 if (CE->getOpcode() == Instruction::Cast) {
231 if (isa<PointerType>(CE->getOperand(0)->getType()))
232 NH = getValueDest(*CE->getOperand(0));
233 else
234 NH = createNode()->setUnknownNodeMarker();
235 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner51340062002-11-08 05:00:44 +0000236 visitGetElementPtrInst(*CE);
Chris Lattner62482e52004-01-28 09:15:42 +0000237 DSScalarMap::iterator I = ScalarMap.find(CE);
Chris Lattner2cfbaaf2002-11-09 20:14:03 +0000238 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
Chris Lattner1e56c542003-02-09 23:04:12 +0000239 NH = I->second;
240 } else {
241 // This returns a conservative unknown node for any unhandled ConstExpr
Chris Lattnerbd92b732003-06-19 21:15:11 +0000242 return NH = createNode()->setUnknownNodeMarker();
Chris Lattner51340062002-11-08 05:00:44 +0000243 }
Chris Lattner62c3a952004-10-30 04:22:45 +0000244 if (NH.isNull()) { // (getelementptr null, X) returns null
Chris Lattner1e56c542003-02-09 23:04:12 +0000245 ScalarMap.erase(V);
246 return 0;
247 }
248 return NH;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000249 } else if (isa<UndefValue>(C)) {
250 ScalarMap.erase(V);
251 return 0;
Chris Lattner51340062002-11-08 05:00:44 +0000252 } else {
253 assert(0 && "Unknown constant type!");
254 }
Reid Spencere8404342004-07-18 00:18:30 +0000255 N = createNode(); // just create a shadow node
Chris Lattner92673292002-11-02 00:13:20 +0000256 } else {
257 // Otherwise just create a shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000258 N = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000259 }
260
Chris Lattnerefffdc92004-07-07 06:12:52 +0000261 NH.setTo(N, 0); // Remember that we are pointing to it...
Chris Lattner92673292002-11-02 00:13:20 +0000262 return NH;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000263}
264
Chris Lattner0d9bab82002-07-18 00:12:30 +0000265
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000266/// getLink - This method is used to return the specified link in the
267/// specified node if one exists. If a link does not already exist (it's
268/// null), then we create a new node, link it, then return it. We must
269/// specify the type of the Node field we are accessing so that we know what
270/// type should be linked to if we need to create a new node.
271///
Chris Lattner7e51c872002-10-31 06:52:26 +0000272DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000273 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
Chris Lattner08db7192002-11-06 06:20:27 +0000274 DSNodeHandle &Link = Node.getLink(LinkNo);
Chris Lattner62c3a952004-10-30 04:22:45 +0000275 if (Link.isNull()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000276 // If the link hasn't been created yet, make and return a new shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000277 Link = createNode();
Chris Lattner08db7192002-11-06 06:20:27 +0000278 }
279 return Link;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000280}
281
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000282
Chris Lattnerc875f022002-11-03 21:27:48 +0000283/// setDestTo - Set the ScalarMap entry for the specified value to point to the
Chris Lattner92673292002-11-02 00:13:20 +0000284/// specified destination. If the Value already points to a node, make sure to
285/// merge the two destinations together.
286///
287void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000288 ScalarMap[&V].mergeWith(NH);
Chris Lattner92673292002-11-02 00:13:20 +0000289}
290
291
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000292//===----------------------------------------------------------------------===//
293// Specific instruction type handler implementations...
294//
295
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000296/// Alloca & Malloc instruction implementation - Simply create a new memory
297/// object, pointing the scalar to it.
298///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000299void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
300 DSNode *N = createNode();
301 if (isHeap)
302 N->setHeapNodeMarker();
303 else
304 N->setAllocaNodeMarker();
305 setDestTo(AI, N);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000306}
307
308// PHINode - Make the scalar for the PHI node point to all of the things the
309// incoming values point to... which effectively causes them to be merged.
310//
311void GraphBuilder::visitPHINode(PHINode &PN) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000312 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000313
Chris Lattnerc875f022002-11-03 21:27:48 +0000314 DSNodeHandle &PNDest = ScalarMap[&PN];
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000315 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
Chris Lattner92673292002-11-02 00:13:20 +0000316 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000317}
318
Chris Lattner6e84bd72005-02-25 01:27:48 +0000319void GraphBuilder::visitSelectInst(SelectInst &SI) {
320 if (!isPointerType(SI.getType())) return; // Only pointer Selects
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000321
Chris Lattner6e84bd72005-02-25 01:27:48 +0000322 DSNodeHandle &Dest = ScalarMap[&SI];
323 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
324 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
325}
326
Chris Lattner32672652005-03-05 19:04:31 +0000327void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
328 if (!isPointerType(SCI.getOperand(0)->getType()) ||
329 isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
330 ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
331}
332
333
Chris Lattner51340062002-11-08 05:00:44 +0000334void GraphBuilder::visitGetElementPtrInst(User &GEP) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000335 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
Chris Lattner753b1132005-02-24 19:55:31 +0000336 if (Value.isNull())
337 Value = createNode();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000338
Chris Lattner179bc7d2003-11-14 17:09:46 +0000339 // As a special case, if all of the index operands of GEP are constant zeros,
340 // handle this just like we handle casts (ie, don't do much).
341 bool AllZeros = true;
342 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
343 if (GEP.getOperand(i) !=
344 Constant::getNullValue(GEP.getOperand(i)->getType())) {
345 AllZeros = false;
346 break;
347 }
348
349 // If all of the indices are zero, the result points to the operand without
350 // applying the type.
Chris Lattner0c9707a2005-03-18 23:18:20 +0000351 if (AllZeros || (!Value.isNull() &&
352 Value.getNode()->isNodeCompletelyFolded())) {
Chris Lattner179bc7d2003-11-14 17:09:46 +0000353 setDestTo(GEP, Value);
354 return;
355 }
356
357
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000358 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
359 const Type *CurTy = PTy->getElementType();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000360
Chris Lattner08db7192002-11-06 06:20:27 +0000361 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
362 // If the node had to be folded... exit quickly
Chris Lattner92673292002-11-02 00:13:20 +0000363 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000364 return;
365 }
366
Chris Lattner15869aa2003-11-02 22:27:28 +0000367 const TargetData &TD = Value.getNode()->getTargetData();
368
Chris Lattner08db7192002-11-06 06:20:27 +0000369#if 0
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000370 // Handle the pointer index specially...
371 if (GEP.getNumOperands() > 1 &&
Chris Lattner28977af2004-04-05 01:30:19 +0000372 (!isa<Constant>(GEP.getOperand(1)) ||
373 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000374
375 // If we already know this is an array being accessed, don't do anything...
376 if (!TopTypeRec.isArray) {
377 TopTypeRec.isArray = true;
378
379 // If we are treating some inner field pointer as an array, fold the node
380 // up because we cannot handle it right. This can come because of
381 // something like this: &((&Pt->X)[1]) == &Pt->Y
382 //
383 if (Value.getOffset()) {
384 // Value is now the pointer we want to GEP to be...
385 Value.getNode()->foldNodeCompletely();
Chris Lattner92673292002-11-02 00:13:20 +0000386 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000387 return;
388 } else {
389 // This is a pointer to the first byte of the node. Make sure that we
390 // are pointing to the outter most type in the node.
391 // FIXME: We need to check one more case here...
392 }
393 }
394 }
Chris Lattner08db7192002-11-06 06:20:27 +0000395#endif
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000396
397 // All of these subscripts are indexing INTO the elements we have...
Chris Lattner26c4fc32003-09-20 21:48:16 +0000398 unsigned Offset = 0;
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000399 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
400 I != E; ++I)
401 if (const StructType *STy = dyn_cast<StructType>(*I)) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000402 unsigned FieldNo =
403 (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
404 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
Chris Lattner82e9d722004-03-01 19:02:54 +0000405 } else if (const PointerType *PTy = dyn_cast<PointerType>(*I)) {
406 if (!isa<Constant>(I.getOperand()) ||
407 !cast<Constant>(I.getOperand())->isNullValue())
408 Value.getNode()->setArrayMarker();
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000409 }
410
411
Chris Lattner08db7192002-11-06 06:20:27 +0000412#if 0
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000413 if (const SequentialType *STy = cast<SequentialType>(*I)) {
414 CurTy = STy->getElementType();
Chris Lattnere03f32b2002-10-02 06:24:36 +0000415 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000416 Offset += CS->getValue()*TD.getTypeSize(CurTy);
Chris Lattnere03f32b2002-10-02 06:24:36 +0000417 } else {
418 // Variable index into a node. We must merge all of the elements of the
419 // sequential type here.
420 if (isa<PointerType>(STy))
421 std::cerr << "Pointer indexing not handled yet!\n";
422 else {
423 const ArrayType *ATy = cast<ArrayType>(STy);
424 unsigned ElSize = TD.getTypeSize(CurTy);
425 DSNode *N = Value.getNode();
426 assert(N && "Value must have a node!");
427 unsigned RawOffset = Offset+Value.getOffset();
428
429 // Loop over all of the elements of the array, merging them into the
Misha Brukman2f2d0652003-09-11 18:14:24 +0000430 // zeroth element.
Chris Lattnere03f32b2002-10-02 06:24:36 +0000431 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
432 // Merge all of the byte components of this array element
433 for (unsigned j = 0; j != ElSize; ++j)
434 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
435 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000436 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000437 }
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000438#endif
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000439
440 // Add in the offset calculated...
441 Value.setOffset(Value.getOffset()+Offset);
442
Sumant Kowshik8a3802d2005-12-06 18:04:30 +0000443 // Check the offset
444 DSNode *N = Value.getNode();
445 if (N &&
446 !N->isNodeCompletelyFolded() &&
447 (N->getSize() != 0 || Offset != 0) &&
448 !N->isForwarding()) {
449 if ((Offset >= N->getSize()) || int(Offset) < 0) {
450 // Accessing offsets out of node size range
451 // This is seen in the "magic" struct in named (from bind), where the
452 // fourth field is an array of length 0, presumably used to create struct
453 // instances of different sizes
454
455 // Collapse the node since its size is now variable
456 N->foldNodeCompletely();
457 }
458 }
459
460 // Value is now the pointer we want to GEP to be...
Chris Lattner92673292002-11-02 00:13:20 +0000461 setDestTo(GEP, Value);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000462}
463
464void GraphBuilder::visitLoadInst(LoadInst &LI) {
Chris Lattner92673292002-11-02 00:13:20 +0000465 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
Chris Lattner6e84bd72005-02-25 01:27:48 +0000466 if (Ptr.isNull())
467 Ptr = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000468
469 // Make that the node is read from...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000470 Ptr.getNode()->setReadMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000471
472 // Ensure a typerecord exists...
Chris Lattner088b6392003-03-03 17:13:31 +0000473 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
Chris Lattner92673292002-11-02 00:13:20 +0000474
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000475 if (isPointerType(LI.getType()))
Chris Lattner92673292002-11-02 00:13:20 +0000476 setDestTo(LI, getLink(Ptr));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000477}
478
479void GraphBuilder::visitStoreInst(StoreInst &SI) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000480 const Type *StoredTy = SI.getOperand(0)->getType();
Chris Lattner92673292002-11-02 00:13:20 +0000481 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000482 if (Dest.isNull()) return;
Chris Lattner92673292002-11-02 00:13:20 +0000483
Vikram S. Advebac06222002-12-06 21:17:10 +0000484 // Mark that the node is written to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000485 Dest.getNode()->setModifiedMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000486
Chris Lattner26c4fc32003-09-20 21:48:16 +0000487 // Ensure a type-record exists...
Chris Lattner08db7192002-11-06 06:20:27 +0000488 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000489
490 // Avoid adding edges from null, or processing non-"pointer" stores
Chris Lattner92673292002-11-02 00:13:20 +0000491 if (isPointerType(StoredTy))
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000492 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000493}
494
495void GraphBuilder::visitReturnInst(ReturnInst &RI) {
Chris Lattner92673292002-11-02 00:13:20 +0000496 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
Chris Lattner26c4fc32003-09-20 21:48:16 +0000497 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000498}
499
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000500void GraphBuilder::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +0000501 //FIXME: also updates the argument
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000502 DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
503 if (Ptr.isNull()) return;
504
505 // Make that the node is read from.
506 Ptr.getNode()->setReadMarker();
507
Chris Lattner62c3a952004-10-30 04:22:45 +0000508 // Ensure a type record exists.
509 DSNode *PtrN = Ptr.getNode();
510 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000511
512 if (isPointerType(I.getType()))
513 setDestTo(I, getLink(Ptr));
514}
515
516
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000517void GraphBuilder::visitCallInst(CallInst &CI) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000518 visitCallSite(&CI);
519}
520
521void GraphBuilder::visitInvokeInst(InvokeInst &II) {
522 visitCallSite(&II);
523}
524
525void GraphBuilder::visitCallSite(CallSite CS) {
Chris Lattnercb582402004-02-26 22:07:22 +0000526 Value *Callee = CS.getCalledValue();
Chris Lattnercb582402004-02-26 22:07:22 +0000527
Chris Lattner894263b2003-09-20 16:50:46 +0000528 // Special case handling of certain libc allocation functions here.
Chris Lattnercb582402004-02-26 22:07:22 +0000529 if (Function *F = dyn_cast<Function>(Callee))
Chris Lattner894263b2003-09-20 16:50:46 +0000530 if (F->isExternal())
Chris Lattnera07b72f2004-02-13 16:09:54 +0000531 switch (F->getIntrinsicID()) {
Chris Lattner317201d2004-03-13 00:24:00 +0000532 case Intrinsic::vastart:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000533 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
534 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000535 case Intrinsic::vacopy:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000536 getValueDest(*CS.getInstruction()).
537 mergeWith(getValueDest(**(CS.arg_begin())));
538 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000539 case Intrinsic::vaend:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000540 return; // noop
Chris Lattnera07b72f2004-02-13 16:09:54 +0000541 case Intrinsic::memmove:
542 case Intrinsic::memcpy: {
543 // Merge the first & second arguments, and mark the memory read and
Chris Lattnerfb8c6102003-11-08 21:55:50 +0000544 // modified.
Chris Lattnera07b72f2004-02-13 16:09:54 +0000545 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
Chris Lattner67ce57a2003-11-09 03:32:52 +0000546 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
547 if (DSNode *N = RetNH.getNode())
548 N->setModifiedMarker()->setReadMarker();
549 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000550 }
Chris Lattnereee33b22004-02-16 18:37:40 +0000551 case Intrinsic::memset:
552 // Mark the memory modified.
553 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
554 N->setModifiedMarker();
555 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000556 default:
John Criswellfa700522005-12-19 17:38:39 +0000557 // Determine if the called function is one of the specified heap
558 // allocation functions
559 for (cl::list<std::string>::iterator AllocFunc = AllocList.begin(),
560 LastAllocFunc = AllocList.end();
561 AllocFunc != LastAllocFunc;
562 ++AllocFunc) {
563 if (F->getName() == *(AllocFunc)) {
564 setDestTo(*CS.getInstruction(),
565 createNode()->setHeapNodeMarker()->setModifiedMarker());
566 return;
567 }
568 }
569
Vikram S. Advee4e97ef2004-05-25 08:14:52 +0000570 if (F->getName() == "calloc" || F->getName() == "posix_memalign" ||
571 F->getName() == "memalign" || F->getName() == "valloc") {
Chris Lattnera07b72f2004-02-13 16:09:54 +0000572 setDestTo(*CS.getInstruction(),
573 createNode()->setHeapNodeMarker()->setModifiedMarker());
574 return;
575 } else if (F->getName() == "realloc") {
576 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
Chris Lattner82962de2004-11-03 18:51:26 +0000577 if (CS.arg_begin() != CS.arg_end())
578 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
Chris Lattnera07b72f2004-02-13 16:09:54 +0000579 if (DSNode *N = RetNH.getNode())
580 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
581 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000582 } else if (F->getName() == "memmove") {
583 // Merge the first & second arguments, and mark the memory read and
584 // modified.
585 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
586 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
587 if (DSNode *N = RetNH.getNode())
588 N->setModifiedMarker()->setReadMarker();
589 return;
590
Chris Lattnerd5612092004-02-24 22:02:48 +0000591 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000592 F->getName() == "atol" || F->getName() == "atoll" ||
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000593 F->getName() == "remove" || F->getName() == "unlink" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000594 F->getName() == "rename" || F->getName() == "memcmp" ||
595 F->getName() == "strcmp" || F->getName() == "strncmp" ||
596 F->getName() == "execl" || F->getName() == "execlp" ||
597 F->getName() == "execle" || F->getName() == "execv" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000598 F->getName() == "execvp" || F->getName() == "chmod" ||
599 F->getName() == "puts" || F->getName() == "write" ||
600 F->getName() == "open" || F->getName() == "create" ||
601 F->getName() == "truncate" || F->getName() == "chdir" ||
602 F->getName() == "mkdir" || F->getName() == "rmdir") {
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000603 // These functions read all of their pointer operands.
604 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
605 AI != E; ++AI) {
606 if (isPointerType((*AI)->getType()))
607 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000608 N->setReadMarker();
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000609 }
Chris Lattner304e1432004-02-16 22:57:19 +0000610 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000611 } else if (F->getName() == "read" || F->getName() == "pipe" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000612 F->getName() == "wait" || F->getName() == "time") {
Chris Lattner52fc8d72004-02-25 23:06:40 +0000613 // These functions write all of their pointer operands.
614 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
615 AI != E; ++AI) {
616 if (isPointerType((*AI)->getType()))
617 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000618 N->setModifiedMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000619 }
620 return;
Chris Lattneradc1efe2004-02-25 17:43:20 +0000621 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
622 F->getName() == "lstat") {
623 // These functions read their first operand if its a pointer.
624 CallSite::arg_iterator AI = CS.arg_begin();
625 if (isPointerType((*AI)->getType())) {
626 DSNodeHandle Path = getValueDest(**AI);
627 if (DSNode *N = Path.getNode()) N->setReadMarker();
628 }
Chris Lattner304e1432004-02-16 22:57:19 +0000629
Chris Lattneradc1efe2004-02-25 17:43:20 +0000630 // Then they write into the stat buffer.
631 DSNodeHandle StatBuf = getValueDest(**++AI);
632 if (DSNode *N = StatBuf.getNode()) {
633 N->setModifiedMarker();
634 const Type *StatTy = F->getFunctionType()->getParamType(1);
635 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
636 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
637 }
Chris Lattneradc1efe2004-02-25 17:43:20 +0000638 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000639 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
640 F->getName() == "strtold") {
641 // These functions read the first pointer
642 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
643 Str->setReadMarker();
644 // If the second parameter is passed, it will point to the first
645 // argument node.
646 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
647 if (DSNode *End = EndPtrNH.getNode()) {
648 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
649 EndPtrNH.getOffset(), false);
650 End->setModifiedMarker();
651 DSNodeHandle &Link = getLink(EndPtrNH);
652 Link.mergeWith(getValueDest(**CS.arg_begin()));
653 }
654 }
655
656 return;
Chris Lattner6b586df2004-02-27 20:04:48 +0000657 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
658 F->getName() == "freopen") {
659 // These functions read all of their pointer operands.
660 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
661 AI != E; ++AI)
662 if (isPointerType((*AI)->getType()))
663 if (DSNode *N = getValueDest(**AI).getNode())
664 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000665
Chris Lattner68300db2004-02-13 20:05:32 +0000666 // fopen allocates in an unknown way and writes to the file
667 // descriptor. Also, merge the allocated type into the node.
668 DSNodeHandle Result = getValueDest(*CS.getInstruction());
Chris Lattnerd5612092004-02-24 22:02:48 +0000669 if (DSNode *N = Result.getNode()) {
670 N->setModifiedMarker()->setUnknownNodeMarker();
671 const Type *RetTy = F->getFunctionType()->getReturnType();
672 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
673 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
674 }
Chris Lattner6b586df2004-02-27 20:04:48 +0000675
676 // If this is freopen, merge the file descriptor passed in with the
677 // result.
Chris Lattnerfe781652004-12-08 16:22:26 +0000678 if (F->getName() == "freopen") {
679 // ICC doesn't handle getting the iterator, decrementing and
680 // dereferencing it in one operation without error. Do it in 2 steps
681 CallSite::arg_iterator compit = CS.arg_end();
682 Result.mergeWith(getValueDest(**--compit));
683 }
Chris Lattnerd5612092004-02-24 22:02:48 +0000684 return;
Chris Lattner68300db2004-02-13 20:05:32 +0000685 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
686 // fclose reads and deallocates the memory in an unknown way for the
687 // file descriptor. It merges the FILE type into the descriptor.
688 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattnerd5612092004-02-24 22:02:48 +0000689 if (DSNode *N = H.getNode()) {
690 N->setReadMarker()->setUnknownNodeMarker();
691 const Type *ArgTy = F->getFunctionType()->getParamType(0);
692 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
693 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
694 }
Chris Lattner68300db2004-02-13 20:05:32 +0000695 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000696 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
Chris Lattner304e1432004-02-16 22:57:19 +0000697 (F->getName() == "fflush" || F->getName() == "feof" ||
698 F->getName() == "fileno" || F->getName() == "clearerr" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000699 F->getName() == "rewind" || F->getName() == "ftell" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000700 F->getName() == "ferror" || F->getName() == "fgetc" ||
701 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
Chris Lattner304e1432004-02-16 22:57:19 +0000702 // fflush reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000703 // merges the FILE type into the descriptor.
704 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattnerd5612092004-02-24 22:02:48 +0000705 if (DSNode *N = H.getNode()) {
706 N->setReadMarker()->setModifiedMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000707
Chris Lattnerd5612092004-02-24 22:02:48 +0000708 const Type *ArgTy = F->getFunctionType()->getParamType(0);
709 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
710 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
711 }
712 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000713 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
Chris Lattnerd5612092004-02-24 22:02:48 +0000714 (F->getName() == "fwrite" || F->getName() == "fread")) {
715 // fread writes the first operand, fwrite reads it. They both
716 // read/write the FILE descriptor, and merges the FILE type.
Chris Lattnerfe781652004-12-08 16:22:26 +0000717 CallSite::arg_iterator compit = CS.arg_end();
718 DSNodeHandle H = getValueDest(**--compit);
Chris Lattnerd5612092004-02-24 22:02:48 +0000719 if (DSNode *N = H.getNode()) {
720 N->setReadMarker()->setModifiedMarker();
721 const Type *ArgTy = F->getFunctionType()->getParamType(3);
722 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
723 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
724 }
725
726 H = getValueDest(**CS.arg_begin());
727 if (DSNode *N = H.getNode())
728 if (F->getName() == "fwrite")
729 N->setReadMarker();
730 else
731 N->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000732 return;
733 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
Chris Lattner304e1432004-02-16 22:57:19 +0000734 // fgets reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000735 // merges the FILE type into the descriptor, and writes to the
736 // argument. It returns the argument as well.
737 CallSite::arg_iterator AI = CS.arg_begin();
738 DSNodeHandle H = getValueDest(**AI);
739 if (DSNode *N = H.getNode())
740 N->setModifiedMarker(); // Writes buffer
741 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
742 ++AI; ++AI;
743
744 // Reads and writes file descriptor, merge in FILE type.
Chris Lattneradc1efe2004-02-25 17:43:20 +0000745 H = getValueDest(**AI);
Chris Lattnerd5612092004-02-24 22:02:48 +0000746 if (DSNode *N = H.getNode()) {
Chris Lattner339d8df2004-02-13 21:21:48 +0000747 N->setReadMarker()->setModifiedMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000748 const Type *ArgTy = F->getFunctionType()->getParamType(2);
749 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
750 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
751 }
752 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000753 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
754 F->getName() == "fputs" || F->getName() == "putc" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000755 F->getName() == "ftell" || F->getName() == "rewind" ||
756 F->getName() == "_IO_putc") {
757 // These functions read and write the memory for the file descriptor,
758 // which is passes as the last argument.
Chris Lattnerfe781652004-12-08 16:22:26 +0000759 CallSite::arg_iterator compit = CS.arg_end();
760 DSNodeHandle H = getValueDest(**--compit);
Chris Lattneradc1efe2004-02-25 17:43:20 +0000761 if (DSNode *N = H.getNode()) {
762 N->setReadMarker()->setModifiedMarker();
Chris Lattnerfe781652004-12-08 16:22:26 +0000763 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
764 const Type *ArgTy = *--compit2;
Chris Lattnerd5612092004-02-24 22:02:48 +0000765 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
766 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
767 }
Chris Lattner52fc8d72004-02-25 23:06:40 +0000768
769 // Any pointer arguments are read.
770 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
771 AI != E; ++AI)
772 if (isPointerType((*AI)->getType()))
773 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000774 N->setReadMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000775 return;
776 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
777 F->getName() == "fsetpos") {
778 // These functions read and write the memory for the file descriptor,
779 // and read/write all other arguments.
780 DSNodeHandle H = getValueDest(**CS.arg_begin());
781 if (DSNode *N = H.getNode()) {
Chris Lattnerfe781652004-12-08 16:22:26 +0000782 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
783 const Type *ArgTy = *--compit2;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000784 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
785 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
786 }
787
788 // Any pointer arguments are read.
789 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
790 AI != E; ++AI)
791 if (isPointerType((*AI)->getType()))
792 if (DSNode *N = getValueDest(**AI).getNode())
793 N->setReadMarker()->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000794 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000795 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
796 F->getName() == "sprintf") {
Chris Lattner339d8df2004-02-13 21:21:48 +0000797 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
798
799 if (F->getName() == "fprintf") {
800 // fprintf reads and writes the FILE argument, and applies the type
801 // to it.
802 DSNodeHandle H = getValueDest(**AI);
803 if (DSNode *N = H.getNode()) {
804 N->setModifiedMarker();
805 const Type *ArgTy = (*AI)->getType();
806 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
807 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
808 }
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000809 } else if (F->getName() == "sprintf") {
810 // sprintf writes the first string argument.
811 DSNodeHandle H = getValueDest(**AI++);
812 if (DSNode *N = H.getNode()) {
813 N->setModifiedMarker();
814 const Type *ArgTy = (*AI)->getType();
815 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
816 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
817 }
Chris Lattner339d8df2004-02-13 21:21:48 +0000818 }
819
820 for (; AI != E; ++AI) {
821 // printf reads all pointer arguments.
822 if (isPointerType((*AI)->getType()))
823 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000824 N->setReadMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000825 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000826 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000827 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
828 F->getName() == "vsprintf") {
829 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
830
831 if (F->getName() == "vfprintf") {
832 // ffprintf reads and writes the FILE argument, and applies the type
833 // to it.
834 DSNodeHandle H = getValueDest(**AI);
835 if (DSNode *N = H.getNode()) {
836 N->setModifiedMarker()->setReadMarker();
837 const Type *ArgTy = (*AI)->getType();
838 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
839 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
840 }
841 ++AI;
842 } else if (F->getName() == "vsprintf") {
843 // vsprintf writes the first string argument.
844 DSNodeHandle H = getValueDest(**AI++);
845 if (DSNode *N = H.getNode()) {
846 N->setModifiedMarker();
847 const Type *ArgTy = (*AI)->getType();
848 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
849 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
850 }
851 }
852
853 // Read the format
854 if (AI != E) {
855 if (isPointerType((*AI)->getType()))
856 if (DSNode *N = getValueDest(**AI).getNode())
857 N->setReadMarker();
858 ++AI;
859 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000860
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000861 // Read the valist, and the pointed-to objects.
862 if (AI != E && isPointerType((*AI)->getType())) {
863 const DSNodeHandle &VAList = getValueDest(**AI);
864 if (DSNode *N = VAList.getNode()) {
865 N->setReadMarker();
866 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
867 VAList.getOffset(), false);
868
869 DSNodeHandle &VAListObjs = getLink(VAList);
870 VAListObjs.getNode()->setReadMarker();
871 }
872 }
873
874 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000875 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
876 F->getName() == "sscanf") {
877 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
Chris Lattner339d8df2004-02-13 21:21:48 +0000878
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000879 if (F->getName() == "fscanf") {
880 // fscanf reads and writes the FILE argument, and applies the type
881 // to it.
882 DSNodeHandle H = getValueDest(**AI);
883 if (DSNode *N = H.getNode()) {
884 N->setReadMarker();
885 const Type *ArgTy = (*AI)->getType();
886 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
887 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
888 }
889 } else if (F->getName() == "sscanf") {
890 // sscanf reads the first string argument.
891 DSNodeHandle H = getValueDest(**AI++);
892 if (DSNode *N = H.getNode()) {
893 N->setReadMarker();
894 const Type *ArgTy = (*AI)->getType();
895 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
896 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
897 }
898 }
899
900 for (; AI != E; ++AI) {
901 // scanf writes all pointer arguments.
902 if (isPointerType((*AI)->getType()))
903 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000904 N->setModifiedMarker();
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000905 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000906 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000907 } else if (F->getName() == "strtok") {
908 // strtok reads and writes the first argument, returning it. It reads
909 // its second arg. FIXME: strtok also modifies some hidden static
910 // data. Someday this might matter.
911 CallSite::arg_iterator AI = CS.arg_begin();
912 DSNodeHandle H = getValueDest(**AI++);
913 if (DSNode *N = H.getNode()) {
914 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
915 const Type *ArgTy = F->getFunctionType()->getParamType(0);
916 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
917 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
918 }
919 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
920
921 H = getValueDest(**AI); // Reads delimiter
922 if (DSNode *N = H.getNode()) {
923 N->setReadMarker();
924 const Type *ArgTy = F->getFunctionType()->getParamType(1);
925 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
926 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
927 }
928 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000929 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
930 F->getName() == "strstr") {
931 // These read their arguments, and return the first one
Chris Lattneradc1efe2004-02-25 17:43:20 +0000932 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattner1fe98742004-02-26 03:43:08 +0000933 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
934
935 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
936 AI != E; ++AI)
937 if (isPointerType((*AI)->getType()))
938 if (DSNode *N = getValueDest(**AI).getNode())
939 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000940
Chris Lattneradc1efe2004-02-25 17:43:20 +0000941 if (DSNode *N = H.getNode())
942 N->setReadMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000943 return;
Chris Lattnerbeacefa2004-11-08 21:08:28 +0000944 } else if (F->getName() == "__assert_fail") {
945 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
946 AI != E; ++AI)
947 if (isPointerType((*AI)->getType()))
948 if (DSNode *N = getValueDest(**AI).getNode())
949 N->setReadMarker();
950 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000951 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
952 // This writes its second argument, and forces it to double.
Chris Lattnerfe781652004-12-08 16:22:26 +0000953 CallSite::arg_iterator compit = CS.arg_end();
954 DSNodeHandle H = getValueDest(**--compit);
Chris Lattner52fc8d72004-02-25 23:06:40 +0000955 if (DSNode *N = H.getNode()) {
956 N->setModifiedMarker();
957 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
958 }
959 return;
Chris Lattner339d8df2004-02-13 21:21:48 +0000960 } else {
Chris Lattner304e1432004-02-16 22:57:19 +0000961 // Unknown function, warn if it returns a pointer type or takes a
962 // pointer argument.
963 bool Warn = isPointerType(CS.getInstruction()->getType());
964 if (!Warn)
965 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
966 I != E; ++I)
967 if (isPointerType((*I)->getType())) {
968 Warn = true;
969 break;
970 }
971 if (Warn)
972 std::cerr << "WARNING: Call to unknown external function '"
973 << F->getName() << "' will cause pessimistic results!\n";
Chris Lattnera07b72f2004-02-13 16:09:54 +0000974 }
Chris Lattner894263b2003-09-20 16:50:46 +0000975 }
976
977
Chris Lattnerc314ac42002-07-11 20:32:02 +0000978 // Set up the return value...
Chris Lattner0969c502002-10-21 02:08:03 +0000979 DSNodeHandle RetVal;
Chris Lattner808a7ae2003-09-20 16:34:13 +0000980 Instruction *I = CS.getInstruction();
981 if (isPointerType(I->getType()))
982 RetVal = getValueDest(*I);
Chris Lattnerc314ac42002-07-11 20:32:02 +0000983
Chris Lattnercb582402004-02-26 22:07:22 +0000984 DSNode *CalleeNode = 0;
985 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
986 CalleeNode = getValueDest(*Callee).getNode();
987 if (CalleeNode == 0) {
988 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
Chris Lattnerfbc2d842003-09-24 23:42:58 +0000989 return; // Calling a null pointer?
990 }
991 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000992
Chris Lattner0969c502002-10-21 02:08:03 +0000993 std::vector<DSNodeHandle> Args;
Chris Lattner808a7ae2003-09-20 16:34:13 +0000994 Args.reserve(CS.arg_end()-CS.arg_begin());
Chris Lattner0969c502002-10-21 02:08:03 +0000995
996 // Calculate the arguments vector...
Chris Lattner808a7ae2003-09-20 16:34:13 +0000997 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
998 if (isPointerType((*I)->getType()))
999 Args.push_back(getValueDest(**I));
Chris Lattner0969c502002-10-21 02:08:03 +00001000
1001 // Add a new function call entry...
Chris Lattnercb582402004-02-26 22:07:22 +00001002 if (CalleeNode)
1003 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
Chris Lattner923fc052003-02-05 21:59:58 +00001004 else
Chris Lattnercb582402004-02-26 22:07:22 +00001005 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
Chris Lattner26c4fc32003-09-20 21:48:16 +00001006 Args));
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001007}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001008
Vikram S. Advebac06222002-12-06 21:17:10 +00001009void GraphBuilder::visitFreeInst(FreeInst &FI) {
Vikram S. Advebac06222002-12-06 21:17:10 +00001010 // Mark that the node is written to...
Chris Lattnerd5612092004-02-24 22:02:48 +00001011 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
1012 N->setModifiedMarker()->setHeapNodeMarker();
Vikram S. Advebac06222002-12-06 21:17:10 +00001013}
1014
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001015/// Handle casts...
1016void GraphBuilder::visitCastInst(CastInst &CI) {
Chris Lattner5af344d2002-11-02 00:36:03 +00001017 if (isPointerType(CI.getType()))
1018 if (isPointerType(CI.getOperand(0)->getType())) {
Chris Lattner157b2522004-10-06 19:29:13 +00001019 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
1020 if (Ptr.getNode() == 0) return;
1021
Chris Lattner5af344d2002-11-02 00:36:03 +00001022 // Cast one pointer to the other, just act like a copy instruction
Chris Lattner157b2522004-10-06 19:29:13 +00001023 setDestTo(CI, Ptr);
Chris Lattner5af344d2002-11-02 00:36:03 +00001024 } else {
1025 // Cast something (floating point, small integer) to a pointer. We need
1026 // to track the fact that the node points to SOMETHING, just something we
1027 // don't know about. Make an "Unknown" node.
1028 //
Chris Lattnerbd92b732003-06-19 21:15:11 +00001029 setDestTo(CI, createNode()->setUnknownNodeMarker());
Chris Lattner5af344d2002-11-02 00:36:03 +00001030 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001031}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001032
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001033
Chris Lattner878e5212003-02-04 00:59:50 +00001034// visitInstruction - For all other instruction types, if we have any arguments
1035// that are of pointer type, make them have unknown composition bits, and merge
1036// the nodes together.
1037void GraphBuilder::visitInstruction(Instruction &Inst) {
1038 DSNodeHandle CurNode;
1039 if (isPointerType(Inst.getType()))
1040 CurNode = getValueDest(Inst);
1041 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1042 if (isPointerType((*I)->getType()))
1043 CurNode.mergeWith(getValueDest(**I));
1044
Chris Lattner62c3a952004-10-30 04:22:45 +00001045 if (DSNode *N = CurNode.getNode())
1046 N->setUnknownNodeMarker();
Chris Lattner878e5212003-02-04 00:59:50 +00001047}
1048
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001049
1050
1051//===----------------------------------------------------------------------===//
1052// LocalDataStructures Implementation
1053//===----------------------------------------------------------------------===//
1054
Chris Lattner26c4fc32003-09-20 21:48:16 +00001055// MergeConstantInitIntoNode - Merge the specified constant into the node
1056// pointed to by NH.
1057void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1058 // Ensure a type-record exists...
Chris Lattner62c3a952004-10-30 04:22:45 +00001059 DSNode *NHN = NH.getNode();
1060 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
Chris Lattner26c4fc32003-09-20 21:48:16 +00001061
1062 if (C->getType()->isFirstClassType()) {
1063 if (isPointerType(C->getType()))
1064 // Avoid adding edges from null, or processing non-"pointer" stores
1065 NH.addEdgeTo(getValueDest(*C));
1066 return;
1067 }
Chris Lattner15869aa2003-11-02 22:27:28 +00001068
1069 const TargetData &TD = NH.getNode()->getTargetData();
1070
Chris Lattner26c4fc32003-09-20 21:48:16 +00001071 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1072 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1073 // We don't currently do any indexing for arrays...
1074 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1075 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1076 const StructLayout *SL = TD.getStructLayout(CS->getType());
1077 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattner62c3a952004-10-30 04:22:45 +00001078 DSNode *NHN = NH.getNode();
Chris Lattner507bdf92005-01-12 04:51:37 +00001079 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
Chris Lattner26c4fc32003-09-20 21:48:16 +00001080 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1081 }
Chris Lattner48b2f6b2004-10-26 16:23:03 +00001082 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
Chris Lattner896481e2004-02-15 05:53:42 +00001083 // Noop
Chris Lattner26c4fc32003-09-20 21:48:16 +00001084 } else {
1085 assert(0 && "Unknown constant type!");
1086 }
1087}
1088
1089void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1090 assert(!GV->isExternal() && "Cannot merge in external global!");
1091 // Get a node handle to the global node and merge the initializer into it.
1092 DSNodeHandle NH = getValueDest(*GV);
1093 MergeConstantInitIntoNode(NH, GV->getInitializer());
1094}
1095
1096
Chris Lattner9b426bd2005-03-20 03:32:35 +00001097/// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
1098/// contains multiple globals, DSA will never, ever, be able to tell the globals
1099/// apart. Instead of maintaining this information in all of the graphs
1100/// throughout the entire program, store only a single global (the "leader") in
1101/// the graphs, and build equivalence classes for the rest of the globals.
1102static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1103 DSScalarMap &SM = GG.getScalarMap();
1104 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1105 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1106 I != E; ++I) {
1107 if (I->getGlobalsList().size() <= 1) continue;
1108
1109 // First, build up the equivalence set for this block of globals.
1110 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1111 GlobalValue *First = GVs[0];
1112 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1113 GlobalECs.unionSets(First, GVs[i]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001114
Chris Lattner9b426bd2005-03-20 03:32:35 +00001115 // Next, get the leader element.
1116 assert(First == GlobalECs.getLeaderValue(First) &&
1117 "First did not end up being the leader?");
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001118
Chris Lattner9b426bd2005-03-20 03:32:35 +00001119 // Next, remove all globals from the scalar map that are not the leader.
1120 assert(GVs[0] == First && "First had to be at the front!");
1121 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1122 ECGlobals.insert(GVs[i]);
1123 SM.erase(SM.find(GVs[i]));
1124 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001125
Chris Lattner9b426bd2005-03-20 03:32:35 +00001126 // Finally, change the global node to only contain the leader.
1127 I->clearGlobals();
1128 I->addGlobal(First);
1129 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001130
Chris Lattner9b426bd2005-03-20 03:32:35 +00001131 DEBUG(GG.AssertGraphOK());
1132}
1133
1134/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1135/// really just equivalent to some other globals, remove the globals from the
1136/// specified DSGraph (if present), and merge any nodes with their leader nodes.
1137static void EliminateUsesOfECGlobals(DSGraph &G,
1138 const std::set<GlobalValue*> &ECGlobals) {
1139 DSScalarMap &SM = G.getScalarMap();
1140 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1141
1142 bool MadeChange = false;
1143 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1144 GI != E; ) {
1145 GlobalValue *GV = *GI++;
1146 if (!ECGlobals.count(GV)) continue;
1147
1148 const DSNodeHandle &GVNH = SM[GV];
1149 assert(!GVNH.isNull() && "Global has null NH!?");
1150
1151 // Okay, this global is in some equivalence class. Start by finding the
1152 // leader of the class.
1153 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1154
1155 // If the leader isn't already in the graph, insert it into the node
1156 // corresponding to GV.
1157 if (!SM.global_count(Leader)) {
1158 GVNH.getNode()->addGlobal(Leader);
1159 SM[Leader] = GVNH;
1160 } else {
1161 // Otherwise, the leader is in the graph, make sure the nodes are the
1162 // merged in the specified graph.
1163 const DSNodeHandle &LNH = SM[Leader];
1164 if (LNH.getNode() != GVNH.getNode())
1165 LNH.mergeWith(GVNH);
1166 }
1167
1168 // Next step, remove the global from the DSNode.
1169 GVNH.getNode()->removeGlobal(GV);
1170
1171 // Finally, remove the global from the ScalarMap.
1172 SM.erase(GV);
1173 MadeChange = true;
1174 }
1175
1176 DEBUG(if(MadeChange) G.AssertGraphOK());
1177}
1178
Chris Lattnerb12914b2004-09-20 04:48:05 +00001179bool LocalDataStructures::runOnModule(Module &M) {
Chris Lattner15869aa2003-11-02 22:27:28 +00001180 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattneraa0b4682002-11-09 21:12:07 +00001181
Chris Lattnerf4f62272005-03-19 22:23:45 +00001182 // First step, build the globals graph.
1183 GlobalsGraph = new DSGraph(GlobalECs, TD);
Chris Lattnerc420ab62004-02-25 23:31:02 +00001184 {
1185 GraphBuilder GGB(*GlobalsGraph);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001186
Chris Lattnerf4f62272005-03-19 22:23:45 +00001187 // Add initializers for all of the globals to the globals graph.
1188 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1189 I != E; ++I)
Chris Lattnerc420ab62004-02-25 23:31:02 +00001190 if (!I->isExternal())
1191 GGB.mergeInGlobalInitializer(I);
1192 }
1193
Chris Lattnerf4f62272005-03-19 22:23:45 +00001194 // Next step, iterate through the nodes in the globals graph, unioning
1195 // together the globals into equivalence classes.
Chris Lattner9b426bd2005-03-20 03:32:35 +00001196 std::set<GlobalValue*> ECGlobals;
1197 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1198 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1199 ECGlobals.clear();
Chris Lattnerf4f62272005-03-19 22:23:45 +00001200
Chris Lattneraa0b4682002-11-09 21:12:07 +00001201 // Calculate all of the graphs...
1202 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1203 if (!I->isExternal())
Chris Lattnerf4f62272005-03-19 22:23:45 +00001204 DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1205 GlobalsGraph)));
Chris Lattner26c4fc32003-09-20 21:48:16 +00001206
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001207 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner26c4fc32003-09-20 21:48:16 +00001208 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner9b426bd2005-03-20 03:32:35 +00001209
1210 // Now that we've computed all of the graphs, and merged all of the info into
1211 // the globals graph, see if we have further constrained the globals in the
1212 // program if so, update GlobalECs and remove the extraneous globals from the
1213 // program.
1214 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1215 if (!ECGlobals.empty()) {
1216 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1217 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1218 E = DSInfo.end(); I != E; ++I)
1219 EliminateUsesOfECGlobals(*I->second, ECGlobals);
1220 }
1221
Chris Lattneraa0b4682002-11-09 21:12:07 +00001222 return false;
1223}
1224
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001225// releaseMemory - If the pass pipeline is done with this pass, we can release
1226// our memory... here...
1227//
1228void LocalDataStructures::releaseMemory() {
Chris Lattner81d924d2003-06-30 04:53:27 +00001229 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1230 E = DSInfo.end(); I != E; ++I) {
1231 I->second->getReturnNodes().erase(I->first);
1232 if (I->second->getReturnNodes().empty())
1233 delete I->second;
1234 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001235
1236 // Empty map so next time memory is released, data structures are not
1237 // re-deleted.
1238 DSInfo.clear();
Chris Lattner2e4f9bf2002-11-09 20:01:01 +00001239 delete GlobalsGraph;
1240 GlobalsGraph = 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001241}
Brian Gaeked0fde302003-11-11 22:41:34 +00001242