Add special case handling for calloc and realloc
[oota-llvm.git] / lib / Analysis / DataStructure / Local.cpp
1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
2 //
3 // Compute the local version of the data structure graph for a function.  The
4 // external interface to this file is the DSGraph constructor.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Analysis/DataStructure.h"
9 #include "llvm/Analysis/DSGraph.h"
10 #include "llvm/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Function.h"
13 #include "llvm/GlobalVariable.h"
14 #include "llvm/Instructions.h"
15 #include "llvm/Support/InstVisitor.h"
16 #include "llvm/Target/TargetData.h"
17 #include "Support/CommandLine.h"
18 #include "Support/Debug.h"
19 #include "Support/Timer.h"
20
21 // FIXME: This should eventually be a FunctionPass that is automatically
22 // aggregated into a Pass.
23 //
24 #include "llvm/Module.h"
25
26 static RegisterAnalysis<LocalDataStructures>
27 X("datastructure", "Local Data Structure Analysis");
28
29 namespace DS {
30   // FIXME: Do something smarter with target data!
31   TargetData TD("temp-td");
32
33   // isPointerType - Return true if this type is big enough to hold a pointer.
34   bool isPointerType(const Type *Ty) {
35     if (isa<PointerType>(Ty))
36       return true;
37     else if (Ty->isPrimitiveType() && Ty->isInteger())
38       return Ty->getPrimitiveSize() >= PointerSize;
39     return false;
40   }
41 }
42 using namespace DS;
43
44
45 namespace {
46   cl::opt<bool>
47   DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
48                        cl::desc("Disable direct call optimization in "
49                                 "DSGraph construction"));
50   cl::opt<bool>
51   DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
52                           cl::desc("Disable field sensitivity in DSGraphs"));
53
54   //===--------------------------------------------------------------------===//
55   //  GraphBuilder Class
56   //===--------------------------------------------------------------------===//
57   //
58   /// This class is the builder class that constructs the local data structure
59   /// graph by performing a single pass over the function in question.
60   ///
61   class GraphBuilder : InstVisitor<GraphBuilder> {
62     Function &F;
63     DSGraph &G;
64     DSNodeHandle &RetNode;               // Node that gets returned...
65     DSGraph::ScalarMapTy &ScalarMap;
66     std::vector<DSCallSite> &FunctionCalls;
67
68   public:
69     GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode, 
70                  DSGraph::ScalarMapTy &SM, std::vector<DSCallSite> &fc)
71       : F(f), G(g), RetNode(retNode), ScalarMap(SM),
72         FunctionCalls(fc) {
73
74       // Create scalar nodes for all pointer arguments...
75       for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I)
76         if (isPointerType(I->getType()))
77           getValueDest(*I);
78
79       visit(F);  // Single pass over the function
80     }
81
82   private:
83     // Visitor functions, used to handle each instruction type we encounter...
84     friend class InstVisitor<GraphBuilder>;
85     void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
86     void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
87     void handleAlloc(AllocationInst &AI, bool isHeap);
88
89     void visitPHINode(PHINode &PN);
90
91     void visitGetElementPtrInst(User &GEP);
92     void visitReturnInst(ReturnInst &RI);
93     void visitLoadInst(LoadInst &LI);
94     void visitStoreInst(StoreInst &SI);
95     void visitCallInst(CallInst &CI);
96     void visitInvokeInst(InvokeInst &II);
97     void visitSetCondInst(SetCondInst &SCI) {}  // SetEQ & friends are ignored
98     void visitFreeInst(FreeInst &FI);
99     void visitCastInst(CastInst &CI);
100     void visitInstruction(Instruction &I);
101
102     void visitCallSite(CallSite CS);
103   private:
104     // Helper functions used to implement the visitation functions...
105
106     /// createNode - Create a new DSNode, ensuring that it is properly added to
107     /// the graph.
108     ///
109     DSNode *createNode(const Type *Ty = 0) {
110       DSNode *N = new DSNode(Ty, &G);   // Create the node
111       if (DisableFieldSensitivity) {
112         N->foldNodeCompletely();
113         if (DSNode *FN = N->getForwardNode())
114           N = FN;
115       }
116       return N;
117     }
118
119     /// setDestTo - Set the ScalarMap entry for the specified value to point to
120     /// the specified destination.  If the Value already points to a node, make
121     /// sure to merge the two destinations together.
122     ///
123     void setDestTo(Value &V, const DSNodeHandle &NH);
124
125     /// getValueDest - Return the DSNode that the actual value points to. 
126     ///
127     DSNodeHandle getValueDest(Value &V);
128
129     /// getLink - This method is used to return the specified link in the
130     /// specified node if one exists.  If a link does not already exist (it's
131     /// null), then we create a new node, link it, then return it.
132     ///
133     DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
134   };
135 }
136
137 //===----------------------------------------------------------------------===//
138 // DSGraph constructor - Simply use the GraphBuilder to construct the local
139 // graph.
140 DSGraph::DSGraph(Function &F, DSGraph *GG) : GlobalsGraph(GG) {
141   PrintAuxCalls = false;
142
143   DEBUG(std::cerr << "  [Loc] Calculating graph for: " << F.getName() << "\n");
144
145   // Use the graph builder to construct the local version of the graph
146   GraphBuilder B(F, *this, ReturnNodes[&F], ScalarMap, FunctionCalls);
147 #ifndef NDEBUG
148   Timer::addPeakMemoryMeasurement();
149 #endif
150
151   // Remove all integral constants from the scalarmap!
152   for (ScalarMapTy::iterator I = ScalarMap.begin(); I != ScalarMap.end();)
153     if (isa<ConstantIntegral>(I->first)) {
154       ScalarMapTy::iterator J = I++;
155       ScalarMap.erase(J);
156     } else
157       ++I;
158
159   markIncompleteNodes(DSGraph::MarkFormalArgs);
160
161   // Remove any nodes made dead due to merging...
162   removeDeadNodes(DSGraph::KeepUnreachableGlobals);
163 }
164
165
166 //===----------------------------------------------------------------------===//
167 // Helper method implementations...
168 //
169
170 /// getValueDest - Return the DSNode that the actual value points to.
171 ///
172 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
173   Value *V = &Val;
174   if (V == Constant::getNullValue(V->getType()))
175     return 0;  // Null doesn't point to anything, don't add to ScalarMap!
176
177   DSNodeHandle &NH = ScalarMap[V];
178   if (NH.getNode())
179     return NH;     // Already have a node?  Just return it...
180
181   // Otherwise we need to create a new node to point to.
182   // Check first for constant expressions that must be traversed to
183   // extract the actual value.
184   if (Constant *C = dyn_cast<Constant>(V))
185     if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
186       return NH = getValueDest(*CPR->getValue());
187     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
188       if (CE->getOpcode() == Instruction::Cast)
189         NH = getValueDest(*CE->getOperand(0));
190       else if (CE->getOpcode() == Instruction::GetElementPtr) {
191         visitGetElementPtrInst(*CE);
192         DSGraph::ScalarMapTy::iterator I = ScalarMap.find(CE);
193         assert(I != ScalarMap.end() && "GEP didn't get processed right?");
194         NH = I->second;
195       } else {
196         // This returns a conservative unknown node for any unhandled ConstExpr
197         return NH = createNode()->setUnknownNodeMarker();
198       }
199       if (NH.getNode() == 0) {  // (getelementptr null, X) returns null
200         ScalarMap.erase(V);
201         return 0;
202       }
203       return NH;
204
205     } else if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(C)) {
206       // Random constants are unknown mem
207       return NH = createNode()->setUnknownNodeMarker();
208     } else {
209       assert(0 && "Unknown constant type!");
210     }
211
212   // Otherwise we need to create a new node to point to...
213   DSNode *N;
214   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
215     // Create a new global node for this global variable...
216     N = createNode(GV->getType()->getElementType());
217     N->addGlobal(GV);
218   } else {
219     // Otherwise just create a shadow node
220     N = createNode();
221   }
222
223   NH.setNode(N);      // Remember that we are pointing to it...
224   NH.setOffset(0);
225   return NH;
226 }
227
228
229 /// getLink - This method is used to return the specified link in the
230 /// specified node if one exists.  If a link does not already exist (it's
231 /// null), then we create a new node, link it, then return it.  We must
232 /// specify the type of the Node field we are accessing so that we know what
233 /// type should be linked to if we need to create a new node.
234 ///
235 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
236   DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
237   DSNodeHandle &Link = Node.getLink(LinkNo);
238   if (!Link.getNode()) {
239     // If the link hasn't been created yet, make and return a new shadow node
240     Link = createNode();
241   }
242   return Link;
243 }
244
245
246 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
247 /// specified destination.  If the Value already points to a node, make sure to
248 /// merge the two destinations together.
249 ///
250 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
251   DSNodeHandle &AINH = ScalarMap[&V];
252   if (AINH.getNode() == 0)   // Not pointing to anything yet?
253     AINH = NH;               // Just point directly to NH
254   else
255     AINH.mergeWith(NH);
256 }
257
258
259 //===----------------------------------------------------------------------===//
260 // Specific instruction type handler implementations...
261 //
262
263 /// Alloca & Malloc instruction implementation - Simply create a new memory
264 /// object, pointing the scalar to it.
265 ///
266 void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
267   DSNode *N = createNode();
268   if (isHeap)
269     N->setHeapNodeMarker();
270   else
271     N->setAllocaNodeMarker();
272   setDestTo(AI, N);
273 }
274
275 // PHINode - Make the scalar for the PHI node point to all of the things the
276 // incoming values point to... which effectively causes them to be merged.
277 //
278 void GraphBuilder::visitPHINode(PHINode &PN) {
279   if (!isPointerType(PN.getType())) return; // Only pointer PHIs
280
281   DSNodeHandle &PNDest = ScalarMap[&PN];
282   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
283     PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
284 }
285
286 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
287   DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
288   if (Value.getNode() == 0) return;
289
290   unsigned Offset = 0;
291   const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
292   const Type *CurTy = PTy->getElementType();
293
294   if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
295     // If the node had to be folded... exit quickly
296     setDestTo(GEP, Value);  // GEP result points to folded node
297     return;
298   }
299
300 #if 0
301   // Handle the pointer index specially...
302   if (GEP.getNumOperands() > 1 &&
303       GEP.getOperand(1) != ConstantSInt::getNullValue(Type::LongTy)) {
304
305     // If we already know this is an array being accessed, don't do anything...
306     if (!TopTypeRec.isArray) {
307       TopTypeRec.isArray = true;
308
309       // If we are treating some inner field pointer as an array, fold the node
310       // up because we cannot handle it right.  This can come because of
311       // something like this:  &((&Pt->X)[1]) == &Pt->Y
312       //
313       if (Value.getOffset()) {
314         // Value is now the pointer we want to GEP to be...
315         Value.getNode()->foldNodeCompletely();
316         setDestTo(GEP, Value);  // GEP result points to folded node
317         return;
318       } else {
319         // This is a pointer to the first byte of the node.  Make sure that we
320         // are pointing to the outter most type in the node.
321         // FIXME: We need to check one more case here...
322       }
323     }
324   }
325 #endif
326
327   // All of these subscripts are indexing INTO the elements we have...
328   for (unsigned i = 2, e = GEP.getNumOperands(); i < e; ++i)
329     if (GEP.getOperand(i)->getType() == Type::LongTy) {
330       // Get the type indexing into...
331       const SequentialType *STy = cast<SequentialType>(CurTy);
332       CurTy = STy->getElementType();
333 #if 0
334       if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
335         Offset += CS->getValue()*TD.getTypeSize(CurTy);
336       } else {
337         // Variable index into a node.  We must merge all of the elements of the
338         // sequential type here.
339         if (isa<PointerType>(STy))
340           std::cerr << "Pointer indexing not handled yet!\n";
341         else {
342           const ArrayType *ATy = cast<ArrayType>(STy);
343           unsigned ElSize = TD.getTypeSize(CurTy);
344           DSNode *N = Value.getNode();
345           assert(N && "Value must have a node!");
346           unsigned RawOffset = Offset+Value.getOffset();
347
348           // Loop over all of the elements of the array, merging them into the
349           // zeroth element.
350           for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
351             // Merge all of the byte components of this array element
352             for (unsigned j = 0; j != ElSize; ++j)
353               N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
354         }
355       }
356 #endif
357     } else if (GEP.getOperand(i)->getType() == Type::UByteTy) {
358       unsigned FieldNo = cast<ConstantUInt>(GEP.getOperand(i))->getValue();
359       const StructType *STy = cast<StructType>(CurTy);
360       Offset += TD.getStructLayout(STy)->MemberOffsets[FieldNo];
361       CurTy = STy->getContainedType(FieldNo);
362     }
363
364   // Add in the offset calculated...
365   Value.setOffset(Value.getOffset()+Offset);
366
367   // Value is now the pointer we want to GEP to be...
368   setDestTo(GEP, Value);
369 }
370
371 void GraphBuilder::visitLoadInst(LoadInst &LI) {
372   DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
373   if (Ptr.getNode() == 0) return;
374
375   // Make that the node is read from...
376   Ptr.getNode()->setReadMarker();
377
378   // Ensure a typerecord exists...
379   Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
380
381   if (isPointerType(LI.getType()))
382     setDestTo(LI, getLink(Ptr));
383 }
384
385 void GraphBuilder::visitStoreInst(StoreInst &SI) {
386   const Type *StoredTy = SI.getOperand(0)->getType();
387   DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
388   if (Dest.getNode() == 0) return;
389
390   // Mark that the node is written to...
391   Dest.getNode()->setModifiedMarker();
392
393   // Ensure a typerecord exists...
394   Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
395
396   // Avoid adding edges from null, or processing non-"pointer" stores
397   if (isPointerType(StoredTy))
398     Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
399 }
400
401 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
402   if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
403     RetNode.mergeWith(getValueDest(*RI.getOperand(0)));
404 }
405
406 void GraphBuilder::visitCallInst(CallInst &CI) {
407   visitCallSite(&CI);
408 }
409
410 void GraphBuilder::visitInvokeInst(InvokeInst &II) {
411   visitCallSite(&II);
412 }
413
414 void GraphBuilder::visitCallSite(CallSite CS) {
415   // Special case handling of certain libc allocation functions here.
416   if (Function *F = CS.getCalledFunction())
417     if (F->isExternal())
418       if (F->getName() == "calloc") {
419         setDestTo(*CS.getInstruction(),
420                   createNode()->setHeapNodeMarker()->setModifiedMarker());
421         return;
422       } else if (F->getName() == "realloc") {
423         DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
424         RetNH.mergeWith(getValueDest(**CS.arg_begin()));
425         DSNode *N = RetNH.getNode();
426         if (N) N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
427         return;
428       }
429
430
431   // Set up the return value...
432   DSNodeHandle RetVal;
433   Instruction *I = CS.getInstruction();
434   if (isPointerType(I->getType()))
435     RetVal = getValueDest(*I);
436
437   DSNode *Callee = 0;
438   if (DisableDirectCallOpt || !isa<Function>(CS.getCalledValue()))
439     Callee = getValueDest(*CS.getCalledValue()).getNode();
440
441   std::vector<DSNodeHandle> Args;
442   Args.reserve(CS.arg_end()-CS.arg_begin());
443
444   // Calculate the arguments vector...
445   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
446     if (isPointerType((*I)->getType()))
447       Args.push_back(getValueDest(**I));
448
449   // Add a new function call entry...
450   if (Callee)
451     FunctionCalls.push_back(DSCallSite(CS, RetVal, Callee, Args));
452   else
453     FunctionCalls.push_back(DSCallSite(CS, RetVal, CS.getCalledFunction(),
454                                        Args));
455 }
456
457 void GraphBuilder::visitFreeInst(FreeInst &FI) {
458   // Mark that the node is written to...
459   DSNode *N = getValueDest(*FI.getOperand(0)).getNode();
460   N->setModifiedMarker();
461   N->setHeapNodeMarker();
462 }
463
464 /// Handle casts...
465 void GraphBuilder::visitCastInst(CastInst &CI) {
466   if (isPointerType(CI.getType()))
467     if (isPointerType(CI.getOperand(0)->getType())) {
468       // Cast one pointer to the other, just act like a copy instruction
469       setDestTo(CI, getValueDest(*CI.getOperand(0)));
470     } else {
471       // Cast something (floating point, small integer) to a pointer.  We need
472       // to track the fact that the node points to SOMETHING, just something we
473       // don't know about.  Make an "Unknown" node.
474       //
475       setDestTo(CI, createNode()->setUnknownNodeMarker());
476     }
477 }
478
479
480 // visitInstruction - For all other instruction types, if we have any arguments
481 // that are of pointer type, make them have unknown composition bits, and merge
482 // the nodes together.
483 void GraphBuilder::visitInstruction(Instruction &Inst) {
484   DSNodeHandle CurNode;
485   if (isPointerType(Inst.getType()))
486     CurNode = getValueDest(Inst);
487   for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
488     if (isPointerType((*I)->getType()))
489       CurNode.mergeWith(getValueDest(**I));
490
491   if (CurNode.getNode())
492     CurNode.getNode()->setUnknownNodeMarker();
493 }
494
495
496
497 //===----------------------------------------------------------------------===//
498 // LocalDataStructures Implementation
499 //===----------------------------------------------------------------------===//
500
501 bool LocalDataStructures::run(Module &M) {
502   GlobalsGraph = new DSGraph();
503
504   // Calculate all of the graphs...
505   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
506     if (!I->isExternal())
507       DSInfo.insert(std::make_pair(I, new DSGraph(*I, GlobalsGraph)));
508   return false;
509 }
510
511 // releaseMemory - If the pass pipeline is done with this pass, we can release
512 // our memory... here...
513 //
514 void LocalDataStructures::releaseMemory() {
515   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
516          E = DSInfo.end(); I != E; ++I) {
517     I->second->getReturnNodes().erase(I->first);
518     if (I->second->getReturnNodes().empty())
519       delete I->second;
520   }
521
522   // Empty map so next time memory is released, data structures are not
523   // re-deleted.
524   DSInfo.clear();
525   delete GlobalsGraph;
526   GlobalsGraph = 0;
527 }