1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
3 // Compute the local version of the data structure graph for a function. The
4 // external interface to this file is the DSGraph constructor.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Analysis/DataStructure.h"
9 #include "llvm/Analysis/DSGraph.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iOther.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Function.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Support/InstVisitor.h"
19 #include "llvm/Target/TargetData.h"
20 #include "Support/Statistic.h"
21 #include "Support/Timer.h"
23 // FIXME: This should eventually be a FunctionPass that is automatically
24 // aggregated into a Pass.
26 #include "llvm/Module.h"
31 static RegisterAnalysis<LocalDataStructures>
32 X("datastructure", "Local Data Structure Analysis");
35 // FIXME: Do something smarter with target data!
36 TargetData TD("temp-td");
38 // isPointerType - Return true if this type is big enough to hold a pointer.
39 bool isPointerType(const Type *Ty) {
40 if (isa<PointerType>(Ty))
42 else if (Ty->isPrimitiveType() && Ty->isInteger())
43 return Ty->getPrimitiveSize() >= PointerSize;
51 //===--------------------------------------------------------------------===//
53 //===--------------------------------------------------------------------===//
55 /// This class is the builder class that constructs the local data structure
56 /// graph by performing a single pass over the function in question.
58 class GraphBuilder : InstVisitor<GraphBuilder> {
60 vector<DSNode*> &Nodes;
61 DSNodeHandle &RetNode; // Node that gets returned...
62 map<Value*, DSNodeHandle> &ScalarMap;
63 vector<DSCallSite> &FunctionCalls;
66 GraphBuilder(DSGraph &g, vector<DSNode*> &nodes, DSNodeHandle &retNode,
67 map<Value*, DSNodeHandle> &SM,
68 vector<DSCallSite> &fc)
69 : G(g), Nodes(nodes), RetNode(retNode), ScalarMap(SM), FunctionCalls(fc) {
71 // Create scalar nodes for all pointer arguments...
72 for (Function::aiterator I = G.getFunction().abegin(),
73 E = G.getFunction().aend(); I != E; ++I)
74 if (isPointerType(I->getType()))
77 visit(G.getFunction()); // Single pass over the function
81 // Visitor functions, used to handle each instruction type we encounter...
82 friend class InstVisitor<GraphBuilder>;
83 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, DSNode::HeapNode); }
84 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, DSNode::AllocaNode);}
85 void handleAlloc(AllocationInst &AI, DSNode::NodeTy NT);
87 void visitPHINode(PHINode &PN);
89 void visitGetElementPtrInst(User &GEP);
90 void visitReturnInst(ReturnInst &RI);
91 void visitLoadInst(LoadInst &LI);
92 void visitStoreInst(StoreInst &SI);
93 void visitCallInst(CallInst &CI);
94 void visitSetCondInst(SetCondInst &SCI) {} // SetEQ & friends are ignored
95 void visitFreeInst(FreeInst &FI) {} // Ignore free instructions
96 void visitCastInst(CastInst &CI);
97 void visitInstruction(Instruction &I) {}
100 // Helper functions used to implement the visitation functions...
102 /// createNode - Create a new DSNode, ensuring that it is properly added to
105 DSNode *createNode(DSNode::NodeTy NodeType, const Type *Ty = 0) {
106 DSNode *N = new DSNode(NodeType, Ty); // Create the node
107 Nodes.push_back(N); // Add node to nodes list
111 /// setDestTo - Set the ScalarMap entry for the specified value to point to
112 /// the specified destination. If the Value already points to a node, make
113 /// sure to merge the two destinations together.
115 void setDestTo(Value &V, const DSNodeHandle &NH);
117 /// getValueDest - Return the DSNode that the actual value points to.
119 DSNodeHandle getValueDest(Value &V);
121 /// getLink - This method is used to return the specified link in the
122 /// specified node if one exists. If a link does not already exist (it's
123 /// null), then we create a new node, link it, then return it.
125 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
129 //===----------------------------------------------------------------------===//
130 // DSGraph constructor - Simply use the GraphBuilder to construct the local
132 DSGraph::DSGraph(Function &F, DSGraph *GG) : Func(&F), GlobalsGraph(GG) {
133 PrintAuxCalls = false;
134 // Use the graph builder to construct the local version of the graph
135 GraphBuilder B(*this, Nodes, RetNode, ScalarMap, FunctionCalls);
137 Timer::addPeakMemoryMeasurement();
139 markIncompleteNodes();
141 // Remove any nodes made dead due to merging...
146 //===----------------------------------------------------------------------===//
147 // Helper method implementations...
150 /// getValueDest - Return the DSNode that the actual value points to.
152 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
154 if (V == Constant::getNullValue(V->getType()))
155 return 0; // Null doesn't point to anything, don't add to ScalarMap!
157 if (Constant *C = dyn_cast<Constant>(V))
158 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
159 return getValueDest(*CPR->getValue());
160 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
161 if (CE->getOpcode() == Instruction::Cast)
162 return getValueDest(*CE->getOperand(0));
163 if (CE->getOpcode() == Instruction::GetElementPtr) {
164 visitGetElementPtrInst(*CE);
165 std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(CE);
166 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
167 DSNodeHandle NH = I->second;
168 ScalarMap.erase(I); // Remove constant from scalarmap
172 // This returns a conservative unknown node for any unhandled ConstExpr
173 return createNode(DSNode::UnknownNode);
174 } else if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(C)) {
175 // Random constants are unknown mem
176 return createNode(DSNode::UnknownNode);
178 assert(0 && "Unknown constant type!");
181 DSNodeHandle &NH = ScalarMap[V];
183 return NH; // Already have a node? Just return it...
185 // Otherwise we need to create a new node to point to...
187 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
188 // Create a new global node for this global variable...
189 N = createNode(DSNode::GlobalNode, GV->getType()->getElementType());
192 // Otherwise just create a shadow node
193 N = createNode(DSNode::ShadowNode);
196 NH.setNode(N); // Remember that we are pointing to it...
202 /// getLink - This method is used to return the specified link in the
203 /// specified node if one exists. If a link does not already exist (it's
204 /// null), then we create a new node, link it, then return it. We must
205 /// specify the type of the Node field we are accessing so that we know what
206 /// type should be linked to if we need to create a new node.
208 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
209 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
210 DSNodeHandle &Link = Node.getLink(LinkNo);
211 if (!Link.getNode()) {
212 // If the link hasn't been created yet, make and return a new shadow node
213 Link = createNode(DSNode::ShadowNode);
219 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
220 /// specified destination. If the Value already points to a node, make sure to
221 /// merge the two destinations together.
223 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
224 DSNodeHandle &AINH = ScalarMap[&V];
225 if (AINH.getNode() == 0) // Not pointing to anything yet?
226 AINH = NH; // Just point directly to NH
232 //===----------------------------------------------------------------------===//
233 // Specific instruction type handler implementations...
236 /// Alloca & Malloc instruction implementation - Simply create a new memory
237 /// object, pointing the scalar to it.
239 void GraphBuilder::handleAlloc(AllocationInst &AI, DSNode::NodeTy NodeType) {
240 setDestTo(AI, createNode(NodeType));
243 // PHINode - Make the scalar for the PHI node point to all of the things the
244 // incoming values point to... which effectively causes them to be merged.
246 void GraphBuilder::visitPHINode(PHINode &PN) {
247 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
249 DSNodeHandle &PNDest = ScalarMap[&PN];
250 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
251 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
254 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
255 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
256 if (Value.getNode() == 0) return;
259 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
260 const Type *CurTy = PTy->getElementType();
262 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
263 // If the node had to be folded... exit quickly
264 setDestTo(GEP, Value); // GEP result points to folded node
269 // Handle the pointer index specially...
270 if (GEP.getNumOperands() > 1 &&
271 GEP.getOperand(1) != ConstantSInt::getNullValue(Type::LongTy)) {
273 // If we already know this is an array being accessed, don't do anything...
274 if (!TopTypeRec.isArray) {
275 TopTypeRec.isArray = true;
277 // If we are treating some inner field pointer as an array, fold the node
278 // up because we cannot handle it right. This can come because of
279 // something like this: &((&Pt->X)[1]) == &Pt->Y
281 if (Value.getOffset()) {
282 // Value is now the pointer we want to GEP to be...
283 Value.getNode()->foldNodeCompletely();
284 setDestTo(GEP, Value); // GEP result points to folded node
287 // This is a pointer to the first byte of the node. Make sure that we
288 // are pointing to the outter most type in the node.
289 // FIXME: We need to check one more case here...
295 // All of these subscripts are indexing INTO the elements we have...
296 for (unsigned i = 2, e = GEP.getNumOperands(); i < e; ++i)
297 if (GEP.getOperand(i)->getType() == Type::LongTy) {
298 // Get the type indexing into...
299 const SequentialType *STy = cast<SequentialType>(CurTy);
300 CurTy = STy->getElementType();
302 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
303 Offset += CS->getValue()*TD.getTypeSize(CurTy);
305 // Variable index into a node. We must merge all of the elements of the
306 // sequential type here.
307 if (isa<PointerType>(STy))
308 std::cerr << "Pointer indexing not handled yet!\n";
310 const ArrayType *ATy = cast<ArrayType>(STy);
311 unsigned ElSize = TD.getTypeSize(CurTy);
312 DSNode *N = Value.getNode();
313 assert(N && "Value must have a node!");
314 unsigned RawOffset = Offset+Value.getOffset();
316 // Loop over all of the elements of the array, merging them into the
318 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
319 // Merge all of the byte components of this array element
320 for (unsigned j = 0; j != ElSize; ++j)
321 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
325 } else if (GEP.getOperand(i)->getType() == Type::UByteTy) {
326 unsigned FieldNo = cast<ConstantUInt>(GEP.getOperand(i))->getValue();
327 const StructType *STy = cast<StructType>(CurTy);
328 Offset += TD.getStructLayout(STy)->MemberOffsets[FieldNo];
329 CurTy = STy->getContainedType(FieldNo);
332 // Add in the offset calculated...
333 Value.setOffset(Value.getOffset()+Offset);
335 // Value is now the pointer we want to GEP to be...
336 setDestTo(GEP, Value);
339 void GraphBuilder::visitLoadInst(LoadInst &LI) {
340 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
341 if (Ptr.getNode() == 0) return;
343 // Make that the node is read from...
344 Ptr.getNode()->NodeType |= DSNode::Read;
346 // Ensure a typerecord exists...
347 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset());
349 if (isPointerType(LI.getType()))
350 setDestTo(LI, getLink(Ptr));
353 void GraphBuilder::visitStoreInst(StoreInst &SI) {
354 const Type *StoredTy = SI.getOperand(0)->getType();
355 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
356 if (Dest.getNode() == 0) return;
358 // Make that the node is written to...
359 Dest.getNode()->NodeType |= DSNode::Modified;
361 // Ensure a typerecord exists...
362 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
364 // Avoid adding edges from null, or processing non-"pointer" stores
365 if (isPointerType(StoredTy))
366 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
369 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
370 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
371 RetNode.mergeWith(getValueDest(*RI.getOperand(0)));
374 void GraphBuilder::visitCallInst(CallInst &CI) {
375 // Set up the return value...
377 if (isPointerType(CI.getType()))
378 RetVal = getValueDest(CI);
380 DSNodeHandle Callee = getValueDest(*CI.getOperand(0));
382 std::vector<DSNodeHandle> Args;
383 Args.reserve(CI.getNumOperands()-1);
385 // Calculate the arguments vector...
386 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
387 if (isPointerType(CI.getOperand(i)->getType()))
388 Args.push_back(getValueDest(*CI.getOperand(i)));
390 // Add a new function call entry...
391 FunctionCalls.push_back(DSCallSite(CI, RetVal, Callee, Args));
395 void GraphBuilder::visitCastInst(CastInst &CI) {
396 if (isPointerType(CI.getType()))
397 if (isPointerType(CI.getOperand(0)->getType())) {
398 // Cast one pointer to the other, just act like a copy instruction
399 setDestTo(CI, getValueDest(*CI.getOperand(0)));
401 // Cast something (floating point, small integer) to a pointer. We need
402 // to track the fact that the node points to SOMETHING, just something we
403 // don't know about. Make an "Unknown" node.
405 setDestTo(CI, createNode(DSNode::UnknownNode));
412 //===----------------------------------------------------------------------===//
413 // LocalDataStructures Implementation
414 //===----------------------------------------------------------------------===//
416 bool LocalDataStructures::run(Module &M) {
417 GlobalsGraph = new DSGraph();
419 // Calculate all of the graphs...
420 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
421 if (!I->isExternal())
422 DSInfo.insert(std::make_pair(I, new DSGraph(*I, GlobalsGraph)));
426 // releaseMemory - If the pass pipeline is done with this pass, we can release
427 // our memory... here...
429 void LocalDataStructures::releaseMemory() {
430 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
431 E = DSInfo.end(); I != E; ++I)
434 // Empty map so next time memory is released, data structures are not