1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Compute the local version of the data structure graph for a function. The
11 // external interface to this file is the DSGraph constructor.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/DataStructure/DataStructure.h"
16 #include "llvm/Analysis/DataStructure/DSGraph.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Timer.h"
28 // FIXME: This should eventually be a FunctionPass that is automatically
29 // aggregated into a Pass.
31 #include "llvm/Module.h"
35 static RegisterAnalysis<LocalDataStructures>
36 X("datastructure", "Local Data Structure Analysis");
39 TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
40 cl::desc("If this is set, track integers as potential pointers"));
44 // isPointerType - Return true if this type is big enough to hold a pointer.
45 bool isPointerType(const Type *Ty) {
46 if (isa<PointerType>(Ty))
48 else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
49 return Ty->getPrimitiveSize() >= PointerSize;
58 DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
59 cl::desc("Disable direct call optimization in "
60 "DSGraph construction"));
62 DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
63 cl::desc("Disable field sensitivity in DSGraphs"));
65 //===--------------------------------------------------------------------===//
67 //===--------------------------------------------------------------------===//
69 /// This class is the builder class that constructs the local data structure
70 /// graph by performing a single pass over the function in question.
72 class GraphBuilder : InstVisitor<GraphBuilder> {
74 DSNodeHandle *RetNode; // Node that gets returned...
75 DSScalarMap &ScalarMap;
76 std::list<DSCallSite> *FunctionCalls;
79 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
80 std::list<DSCallSite> &fc)
81 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
84 // Create scalar nodes for all pointer arguments...
85 for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end(); I != E; ++I)
86 if (isPointerType(I->getType()))
89 visit(f); // Single pass over the function
92 // GraphBuilder ctor for working on the globals graph
93 GraphBuilder(DSGraph &g)
94 : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
97 void mergeInGlobalInitializer(GlobalVariable *GV);
100 // Visitor functions, used to handle each instruction type we encounter...
101 friend class InstVisitor<GraphBuilder>;
102 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
103 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
104 void handleAlloc(AllocationInst &AI, bool isHeap);
106 void visitPHINode(PHINode &PN);
107 void visitSelectInst(SelectInst &SI);
109 void visitGetElementPtrInst(User &GEP);
110 void visitReturnInst(ReturnInst &RI);
111 void visitLoadInst(LoadInst &LI);
112 void visitStoreInst(StoreInst &SI);
113 void visitCallInst(CallInst &CI);
114 void visitInvokeInst(InvokeInst &II);
115 void visitSetCondInst(SetCondInst &SCI);
116 void visitFreeInst(FreeInst &FI);
117 void visitCastInst(CastInst &CI);
118 void visitInstruction(Instruction &I);
120 void visitCallSite(CallSite CS);
121 void visitVANextInst(VANextInst &I);
122 void visitVAArgInst(VAArgInst &I);
124 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
126 // Helper functions used to implement the visitation functions...
128 /// createNode - Create a new DSNode, ensuring that it is properly added to
131 DSNode *createNode(const Type *Ty = 0) {
132 DSNode *N = new DSNode(Ty, &G); // Create the node
133 if (DisableFieldSensitivity) {
134 // Create node handle referring to the old node so that it is
135 // immediately removed from the graph when the node handle is destroyed.
136 DSNodeHandle OldNNH = N;
137 N->foldNodeCompletely();
138 if (DSNode *FN = N->getForwardNode())
144 /// setDestTo - Set the ScalarMap entry for the specified value to point to
145 /// the specified destination. If the Value already points to a node, make
146 /// sure to merge the two destinations together.
148 void setDestTo(Value &V, const DSNodeHandle &NH);
150 /// getValueDest - Return the DSNode that the actual value points to.
152 DSNodeHandle getValueDest(Value &V);
154 /// getLink - This method is used to return the specified link in the
155 /// specified node if one exists. If a link does not already exist (it's
156 /// null), then we create a new node, link it, then return it.
158 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
164 //===----------------------------------------------------------------------===//
165 // DSGraph constructor - Simply use the GraphBuilder to construct the local
167 DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
168 Function &F, DSGraph *GG)
169 : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
170 PrintAuxCalls = false;
172 DEBUG(std::cerr << " [Loc] Calculating graph for: " << F.getName() << "\n");
174 // Use the graph builder to construct the local version of the graph
175 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
177 Timer::addPeakMemoryMeasurement();
180 // Remove all integral constants from the scalarmap!
181 for (DSScalarMap::iterator I = ScalarMap.begin(); I != ScalarMap.end();)
182 if (isa<ConstantIntegral>(I->first))
183 ScalarMap.erase(I++);
187 // If there are any constant globals referenced in this function, merge their
188 // initializers into the local graph from the globals graph.
189 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
190 ReachabilityCloner RC(*this, *GG, 0);
192 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
193 I != ScalarMap.global_end(); ++I)
194 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
195 if (!GV->isExternal() && GV->isConstant())
196 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
199 markIncompleteNodes(DSGraph::MarkFormalArgs);
201 // Remove any nodes made dead due to merging...
202 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
206 //===----------------------------------------------------------------------===//
207 // Helper method implementations...
210 /// getValueDest - Return the DSNode that the actual value points to.
212 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
214 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
215 return 0; // Null doesn't point to anything, don't add to ScalarMap!
217 DSNodeHandle &NH = ScalarMap[V];
219 return NH; // Already have a node? Just return it...
221 // Otherwise we need to create a new node to point to.
222 // Check first for constant expressions that must be traversed to
223 // extract the actual value.
225 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
226 // Create a new global node for this global variable.
227 N = createNode(GV->getType()->getElementType());
229 } else if (Constant *C = dyn_cast<Constant>(V)) {
230 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
231 if (CE->getOpcode() == Instruction::Cast)
232 NH = getValueDest(*CE->getOperand(0));
233 else if (CE->getOpcode() == Instruction::GetElementPtr) {
234 visitGetElementPtrInst(*CE);
235 DSScalarMap::iterator I = ScalarMap.find(CE);
236 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
239 // This returns a conservative unknown node for any unhandled ConstExpr
240 return NH = createNode()->setUnknownNodeMarker();
242 if (NH.isNull()) { // (getelementptr null, X) returns null
248 } else if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(C)) {
249 // Random constants are unknown mem
250 return NH = createNode()->setUnknownNodeMarker();
251 } else if (isa<UndefValue>(C)) {
255 assert(0 && "Unknown constant type!");
257 N = createNode(); // just create a shadow node
259 // Otherwise just create a shadow node
263 NH.setTo(N, 0); // Remember that we are pointing to it...
268 /// getLink - This method is used to return the specified link in the
269 /// specified node if one exists. If a link does not already exist (it's
270 /// null), then we create a new node, link it, then return it. We must
271 /// specify the type of the Node field we are accessing so that we know what
272 /// type should be linked to if we need to create a new node.
274 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
275 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
276 DSNodeHandle &Link = Node.getLink(LinkNo);
278 // If the link hasn't been created yet, make and return a new shadow node
285 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
286 /// specified destination. If the Value already points to a node, make sure to
287 /// merge the two destinations together.
289 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
290 ScalarMap[&V].mergeWith(NH);
294 //===----------------------------------------------------------------------===//
295 // Specific instruction type handler implementations...
298 /// Alloca & Malloc instruction implementation - Simply create a new memory
299 /// object, pointing the scalar to it.
301 void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
302 DSNode *N = createNode();
304 N->setHeapNodeMarker();
306 N->setAllocaNodeMarker();
310 // PHINode - Make the scalar for the PHI node point to all of the things the
311 // incoming values point to... which effectively causes them to be merged.
313 void GraphBuilder::visitPHINode(PHINode &PN) {
314 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
316 DSNodeHandle &PNDest = ScalarMap[&PN];
317 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
318 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
321 void GraphBuilder::visitSelectInst(SelectInst &SI) {
322 if (!isPointerType(SI.getType())) return; // Only pointer Selects
324 DSNodeHandle &Dest = ScalarMap[&SI];
325 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
326 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
329 void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
330 if (!isPointerType(SCI.getOperand(0)->getType()) ||
331 isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
332 ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
336 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
337 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
339 Value = createNode();
341 // As a special case, if all of the index operands of GEP are constant zeros,
342 // handle this just like we handle casts (ie, don't do much).
343 bool AllZeros = true;
344 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
345 if (GEP.getOperand(i) !=
346 Constant::getNullValue(GEP.getOperand(i)->getType())) {
351 // If all of the indices are zero, the result points to the operand without
352 // applying the type.
353 if (AllZeros || (!Value.isNull() &&
354 Value.getNode()->isNodeCompletelyFolded())) {
355 setDestTo(GEP, Value);
360 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
361 const Type *CurTy = PTy->getElementType();
363 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
364 // If the node had to be folded... exit quickly
365 setDestTo(GEP, Value); // GEP result points to folded node
369 const TargetData &TD = Value.getNode()->getTargetData();
372 // Handle the pointer index specially...
373 if (GEP.getNumOperands() > 1 &&
374 (!isa<Constant>(GEP.getOperand(1)) ||
375 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
377 // If we already know this is an array being accessed, don't do anything...
378 if (!TopTypeRec.isArray) {
379 TopTypeRec.isArray = true;
381 // If we are treating some inner field pointer as an array, fold the node
382 // up because we cannot handle it right. This can come because of
383 // something like this: &((&Pt->X)[1]) == &Pt->Y
385 if (Value.getOffset()) {
386 // Value is now the pointer we want to GEP to be...
387 Value.getNode()->foldNodeCompletely();
388 setDestTo(GEP, Value); // GEP result points to folded node
391 // This is a pointer to the first byte of the node. Make sure that we
392 // are pointing to the outter most type in the node.
393 // FIXME: We need to check one more case here...
399 // All of these subscripts are indexing INTO the elements we have...
401 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
403 if (const StructType *STy = dyn_cast<StructType>(*I)) {
405 (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
406 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
407 } else if (const PointerType *PTy = dyn_cast<PointerType>(*I)) {
408 if (!isa<Constant>(I.getOperand()) ||
409 !cast<Constant>(I.getOperand())->isNullValue())
410 Value.getNode()->setArrayMarker();
415 if (const SequentialType *STy = cast<SequentialType>(*I)) {
416 CurTy = STy->getElementType();
417 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
418 Offset += CS->getValue()*TD.getTypeSize(CurTy);
420 // Variable index into a node. We must merge all of the elements of the
421 // sequential type here.
422 if (isa<PointerType>(STy))
423 std::cerr << "Pointer indexing not handled yet!\n";
425 const ArrayType *ATy = cast<ArrayType>(STy);
426 unsigned ElSize = TD.getTypeSize(CurTy);
427 DSNode *N = Value.getNode();
428 assert(N && "Value must have a node!");
429 unsigned RawOffset = Offset+Value.getOffset();
431 // Loop over all of the elements of the array, merging them into the
433 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
434 // Merge all of the byte components of this array element
435 for (unsigned j = 0; j != ElSize; ++j)
436 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
442 // Add in the offset calculated...
443 Value.setOffset(Value.getOffset()+Offset);
445 // Value is now the pointer we want to GEP to be...
446 setDestTo(GEP, Value);
449 void GraphBuilder::visitLoadInst(LoadInst &LI) {
450 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
454 // Make that the node is read from...
455 Ptr.getNode()->setReadMarker();
457 // Ensure a typerecord exists...
458 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
460 if (isPointerType(LI.getType()))
461 setDestTo(LI, getLink(Ptr));
464 void GraphBuilder::visitStoreInst(StoreInst &SI) {
465 const Type *StoredTy = SI.getOperand(0)->getType();
466 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
467 if (Dest.isNull()) return;
469 // Mark that the node is written to...
470 Dest.getNode()->setModifiedMarker();
472 // Ensure a type-record exists...
473 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
475 // Avoid adding edges from null, or processing non-"pointer" stores
476 if (isPointerType(StoredTy))
477 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
480 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
481 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
482 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
485 void GraphBuilder::visitVANextInst(VANextInst &I) {
486 getValueDest(*I.getOperand(0)).mergeWith(getValueDest(I));
489 void GraphBuilder::visitVAArgInst(VAArgInst &I) {
490 DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
491 if (Ptr.isNull()) return;
493 // Make that the node is read from.
494 Ptr.getNode()->setReadMarker();
496 // Ensure a type record exists.
497 DSNode *PtrN = Ptr.getNode();
498 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
500 if (isPointerType(I.getType()))
501 setDestTo(I, getLink(Ptr));
505 void GraphBuilder::visitCallInst(CallInst &CI) {
509 void GraphBuilder::visitInvokeInst(InvokeInst &II) {
513 void GraphBuilder::visitCallSite(CallSite CS) {
514 Value *Callee = CS.getCalledValue();
516 // Special case handling of certain libc allocation functions here.
517 if (Function *F = dyn_cast<Function>(Callee))
519 switch (F->getIntrinsicID()) {
520 case Intrinsic::vastart:
521 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
523 case Intrinsic::vacopy:
524 getValueDest(*CS.getInstruction()).
525 mergeWith(getValueDest(**(CS.arg_begin())));
527 case Intrinsic::vaend:
529 case Intrinsic::memmove:
530 case Intrinsic::memcpy: {
531 // Merge the first & second arguments, and mark the memory read and
533 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
534 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
535 if (DSNode *N = RetNH.getNode())
536 N->setModifiedMarker()->setReadMarker();
539 case Intrinsic::memset:
540 // Mark the memory modified.
541 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
542 N->setModifiedMarker();
545 if (F->getName() == "calloc" || F->getName() == "posix_memalign" ||
546 F->getName() == "memalign" || F->getName() == "valloc") {
547 setDestTo(*CS.getInstruction(),
548 createNode()->setHeapNodeMarker()->setModifiedMarker());
550 } else if (F->getName() == "realloc") {
551 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
552 if (CS.arg_begin() != CS.arg_end())
553 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
554 if (DSNode *N = RetNH.getNode())
555 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
557 } else if (F->getName() == "memmove") {
558 // Merge the first & second arguments, and mark the memory read and
560 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
561 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
562 if (DSNode *N = RetNH.getNode())
563 N->setModifiedMarker()->setReadMarker();
566 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
567 F->getName() == "atol" || F->getName() == "atoll" ||
568 F->getName() == "remove" || F->getName() == "unlink" ||
569 F->getName() == "rename" || F->getName() == "memcmp" ||
570 F->getName() == "strcmp" || F->getName() == "strncmp" ||
571 F->getName() == "execl" || F->getName() == "execlp" ||
572 F->getName() == "execle" || F->getName() == "execv" ||
573 F->getName() == "execvp" || F->getName() == "chmod" ||
574 F->getName() == "puts" || F->getName() == "write" ||
575 F->getName() == "open" || F->getName() == "create" ||
576 F->getName() == "truncate" || F->getName() == "chdir" ||
577 F->getName() == "mkdir" || F->getName() == "rmdir") {
578 // These functions read all of their pointer operands.
579 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
581 if (isPointerType((*AI)->getType()))
582 if (DSNode *N = getValueDest(**AI).getNode())
586 } else if (F->getName() == "read" || F->getName() == "pipe" ||
587 F->getName() == "wait" || F->getName() == "time") {
588 // These functions write all of their pointer operands.
589 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
591 if (isPointerType((*AI)->getType()))
592 if (DSNode *N = getValueDest(**AI).getNode())
593 N->setModifiedMarker();
596 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
597 F->getName() == "lstat") {
598 // These functions read their first operand if its a pointer.
599 CallSite::arg_iterator AI = CS.arg_begin();
600 if (isPointerType((*AI)->getType())) {
601 DSNodeHandle Path = getValueDest(**AI);
602 if (DSNode *N = Path.getNode()) N->setReadMarker();
605 // Then they write into the stat buffer.
606 DSNodeHandle StatBuf = getValueDest(**++AI);
607 if (DSNode *N = StatBuf.getNode()) {
608 N->setModifiedMarker();
609 const Type *StatTy = F->getFunctionType()->getParamType(1);
610 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
611 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
614 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
615 F->getName() == "strtold") {
616 // These functions read the first pointer
617 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
618 Str->setReadMarker();
619 // If the second parameter is passed, it will point to the first
621 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
622 if (DSNode *End = EndPtrNH.getNode()) {
623 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
624 EndPtrNH.getOffset(), false);
625 End->setModifiedMarker();
626 DSNodeHandle &Link = getLink(EndPtrNH);
627 Link.mergeWith(getValueDest(**CS.arg_begin()));
632 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
633 F->getName() == "freopen") {
634 // These functions read all of their pointer operands.
635 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
637 if (isPointerType((*AI)->getType()))
638 if (DSNode *N = getValueDest(**AI).getNode())
641 // fopen allocates in an unknown way and writes to the file
642 // descriptor. Also, merge the allocated type into the node.
643 DSNodeHandle Result = getValueDest(*CS.getInstruction());
644 if (DSNode *N = Result.getNode()) {
645 N->setModifiedMarker()->setUnknownNodeMarker();
646 const Type *RetTy = F->getFunctionType()->getReturnType();
647 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
648 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
651 // If this is freopen, merge the file descriptor passed in with the
653 if (F->getName() == "freopen") {
654 // ICC doesn't handle getting the iterator, decrementing and
655 // dereferencing it in one operation without error. Do it in 2 steps
656 CallSite::arg_iterator compit = CS.arg_end();
657 Result.mergeWith(getValueDest(**--compit));
660 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
661 // fclose reads and deallocates the memory in an unknown way for the
662 // file descriptor. It merges the FILE type into the descriptor.
663 DSNodeHandle H = getValueDest(**CS.arg_begin());
664 if (DSNode *N = H.getNode()) {
665 N->setReadMarker()->setUnknownNodeMarker();
666 const Type *ArgTy = F->getFunctionType()->getParamType(0);
667 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
668 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
671 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
672 (F->getName() == "fflush" || F->getName() == "feof" ||
673 F->getName() == "fileno" || F->getName() == "clearerr" ||
674 F->getName() == "rewind" || F->getName() == "ftell" ||
675 F->getName() == "ferror" || F->getName() == "fgetc" ||
676 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
677 // fflush reads and writes the memory for the file descriptor. It
678 // merges the FILE type into the descriptor.
679 DSNodeHandle H = getValueDest(**CS.arg_begin());
680 if (DSNode *N = H.getNode()) {
681 N->setReadMarker()->setModifiedMarker();
683 const Type *ArgTy = F->getFunctionType()->getParamType(0);
684 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
685 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
688 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
689 (F->getName() == "fwrite" || F->getName() == "fread")) {
690 // fread writes the first operand, fwrite reads it. They both
691 // read/write the FILE descriptor, and merges the FILE type.
692 CallSite::arg_iterator compit = CS.arg_end();
693 DSNodeHandle H = getValueDest(**--compit);
694 if (DSNode *N = H.getNode()) {
695 N->setReadMarker()->setModifiedMarker();
696 const Type *ArgTy = F->getFunctionType()->getParamType(3);
697 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
698 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
701 H = getValueDest(**CS.arg_begin());
702 if (DSNode *N = H.getNode())
703 if (F->getName() == "fwrite")
706 N->setModifiedMarker();
708 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
709 // fgets reads and writes the memory for the file descriptor. It
710 // merges the FILE type into the descriptor, and writes to the
711 // argument. It returns the argument as well.
712 CallSite::arg_iterator AI = CS.arg_begin();
713 DSNodeHandle H = getValueDest(**AI);
714 if (DSNode *N = H.getNode())
715 N->setModifiedMarker(); // Writes buffer
716 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
719 // Reads and writes file descriptor, merge in FILE type.
720 H = getValueDest(**AI);
721 if (DSNode *N = H.getNode()) {
722 N->setReadMarker()->setModifiedMarker();
723 const Type *ArgTy = F->getFunctionType()->getParamType(2);
724 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
725 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
728 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
729 F->getName() == "fputs" || F->getName() == "putc" ||
730 F->getName() == "ftell" || F->getName() == "rewind" ||
731 F->getName() == "_IO_putc") {
732 // These functions read and write the memory for the file descriptor,
733 // which is passes as the last argument.
734 CallSite::arg_iterator compit = CS.arg_end();
735 DSNodeHandle H = getValueDest(**--compit);
736 if (DSNode *N = H.getNode()) {
737 N->setReadMarker()->setModifiedMarker();
738 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
739 const Type *ArgTy = *--compit2;
740 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
741 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
744 // Any pointer arguments are read.
745 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
747 if (isPointerType((*AI)->getType()))
748 if (DSNode *N = getValueDest(**AI).getNode())
751 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
752 F->getName() == "fsetpos") {
753 // These functions read and write the memory for the file descriptor,
754 // and read/write all other arguments.
755 DSNodeHandle H = getValueDest(**CS.arg_begin());
756 if (DSNode *N = H.getNode()) {
757 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
758 const Type *ArgTy = *--compit2;
759 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
760 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
763 // Any pointer arguments are read.
764 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
766 if (isPointerType((*AI)->getType()))
767 if (DSNode *N = getValueDest(**AI).getNode())
768 N->setReadMarker()->setModifiedMarker();
770 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
771 F->getName() == "sprintf") {
772 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
774 if (F->getName() == "fprintf") {
775 // fprintf reads and writes the FILE argument, and applies the type
777 DSNodeHandle H = getValueDest(**AI);
778 if (DSNode *N = H.getNode()) {
779 N->setModifiedMarker();
780 const Type *ArgTy = (*AI)->getType();
781 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
782 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
784 } else if (F->getName() == "sprintf") {
785 // sprintf writes the first string argument.
786 DSNodeHandle H = getValueDest(**AI++);
787 if (DSNode *N = H.getNode()) {
788 N->setModifiedMarker();
789 const Type *ArgTy = (*AI)->getType();
790 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
791 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
795 for (; AI != E; ++AI) {
796 // printf reads all pointer arguments.
797 if (isPointerType((*AI)->getType()))
798 if (DSNode *N = getValueDest(**AI).getNode())
802 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
803 F->getName() == "vsprintf") {
804 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
806 if (F->getName() == "vfprintf") {
807 // ffprintf reads and writes the FILE argument, and applies the type
809 DSNodeHandle H = getValueDest(**AI);
810 if (DSNode *N = H.getNode()) {
811 N->setModifiedMarker()->setReadMarker();
812 const Type *ArgTy = (*AI)->getType();
813 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
814 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
817 } else if (F->getName() == "vsprintf") {
818 // vsprintf writes the first string argument.
819 DSNodeHandle H = getValueDest(**AI++);
820 if (DSNode *N = H.getNode()) {
821 N->setModifiedMarker();
822 const Type *ArgTy = (*AI)->getType();
823 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
824 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
830 if (isPointerType((*AI)->getType()))
831 if (DSNode *N = getValueDest(**AI).getNode())
836 // Read the valist, and the pointed-to objects.
837 if (AI != E && isPointerType((*AI)->getType())) {
838 const DSNodeHandle &VAList = getValueDest(**AI);
839 if (DSNode *N = VAList.getNode()) {
841 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
842 VAList.getOffset(), false);
844 DSNodeHandle &VAListObjs = getLink(VAList);
845 VAListObjs.getNode()->setReadMarker();
850 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
851 F->getName() == "sscanf") {
852 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
854 if (F->getName() == "fscanf") {
855 // fscanf reads and writes the FILE argument, and applies the type
857 DSNodeHandle H = getValueDest(**AI);
858 if (DSNode *N = H.getNode()) {
860 const Type *ArgTy = (*AI)->getType();
861 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
862 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
864 } else if (F->getName() == "sscanf") {
865 // sscanf reads the first string argument.
866 DSNodeHandle H = getValueDest(**AI++);
867 if (DSNode *N = H.getNode()) {
869 const Type *ArgTy = (*AI)->getType();
870 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
871 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
875 for (; AI != E; ++AI) {
876 // scanf writes all pointer arguments.
877 if (isPointerType((*AI)->getType()))
878 if (DSNode *N = getValueDest(**AI).getNode())
879 N->setModifiedMarker();
882 } else if (F->getName() == "strtok") {
883 // strtok reads and writes the first argument, returning it. It reads
884 // its second arg. FIXME: strtok also modifies some hidden static
885 // data. Someday this might matter.
886 CallSite::arg_iterator AI = CS.arg_begin();
887 DSNodeHandle H = getValueDest(**AI++);
888 if (DSNode *N = H.getNode()) {
889 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
890 const Type *ArgTy = F->getFunctionType()->getParamType(0);
891 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
892 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
894 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
896 H = getValueDest(**AI); // Reads delimiter
897 if (DSNode *N = H.getNode()) {
899 const Type *ArgTy = F->getFunctionType()->getParamType(1);
900 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
901 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
904 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
905 F->getName() == "strstr") {
906 // These read their arguments, and return the first one
907 DSNodeHandle H = getValueDest(**CS.arg_begin());
908 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
910 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
912 if (isPointerType((*AI)->getType()))
913 if (DSNode *N = getValueDest(**AI).getNode())
916 if (DSNode *N = H.getNode())
919 } else if (F->getName() == "__assert_fail") {
920 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
922 if (isPointerType((*AI)->getType()))
923 if (DSNode *N = getValueDest(**AI).getNode())
926 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
927 // This writes its second argument, and forces it to double.
928 CallSite::arg_iterator compit = CS.arg_end();
929 DSNodeHandle H = getValueDest(**--compit);
930 if (DSNode *N = H.getNode()) {
931 N->setModifiedMarker();
932 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
936 // Unknown function, warn if it returns a pointer type or takes a
938 bool Warn = isPointerType(CS.getInstruction()->getType());
940 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
942 if (isPointerType((*I)->getType())) {
947 std::cerr << "WARNING: Call to unknown external function '"
948 << F->getName() << "' will cause pessimistic results!\n";
953 // Set up the return value...
955 Instruction *I = CS.getInstruction();
956 if (isPointerType(I->getType()))
957 RetVal = getValueDest(*I);
959 DSNode *CalleeNode = 0;
960 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
961 CalleeNode = getValueDest(*Callee).getNode();
962 if (CalleeNode == 0) {
963 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
964 return; // Calling a null pointer?
968 std::vector<DSNodeHandle> Args;
969 Args.reserve(CS.arg_end()-CS.arg_begin());
971 // Calculate the arguments vector...
972 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
973 if (isPointerType((*I)->getType()))
974 Args.push_back(getValueDest(**I));
976 // Add a new function call entry...
978 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
980 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
984 void GraphBuilder::visitFreeInst(FreeInst &FI) {
985 // Mark that the node is written to...
986 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
987 N->setModifiedMarker()->setHeapNodeMarker();
991 void GraphBuilder::visitCastInst(CastInst &CI) {
992 if (isPointerType(CI.getType()))
993 if (isPointerType(CI.getOperand(0)->getType())) {
994 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
995 if (Ptr.getNode() == 0) return;
997 // Cast one pointer to the other, just act like a copy instruction
1000 // Cast something (floating point, small integer) to a pointer. We need
1001 // to track the fact that the node points to SOMETHING, just something we
1002 // don't know about. Make an "Unknown" node.
1004 setDestTo(CI, createNode()->setUnknownNodeMarker());
1009 // visitInstruction - For all other instruction types, if we have any arguments
1010 // that are of pointer type, make them have unknown composition bits, and merge
1011 // the nodes together.
1012 void GraphBuilder::visitInstruction(Instruction &Inst) {
1013 DSNodeHandle CurNode;
1014 if (isPointerType(Inst.getType()))
1015 CurNode = getValueDest(Inst);
1016 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1017 if (isPointerType((*I)->getType()))
1018 CurNode.mergeWith(getValueDest(**I));
1020 if (DSNode *N = CurNode.getNode())
1021 N->setUnknownNodeMarker();
1026 //===----------------------------------------------------------------------===//
1027 // LocalDataStructures Implementation
1028 //===----------------------------------------------------------------------===//
1030 // MergeConstantInitIntoNode - Merge the specified constant into the node
1031 // pointed to by NH.
1032 void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1033 // Ensure a type-record exists...
1034 DSNode *NHN = NH.getNode();
1035 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
1037 if (C->getType()->isFirstClassType()) {
1038 if (isPointerType(C->getType()))
1039 // Avoid adding edges from null, or processing non-"pointer" stores
1040 NH.addEdgeTo(getValueDest(*C));
1044 const TargetData &TD = NH.getNode()->getTargetData();
1046 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1047 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1048 // We don't currently do any indexing for arrays...
1049 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1050 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1051 const StructLayout *SL = TD.getStructLayout(CS->getType());
1052 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1053 DSNode *NHN = NH.getNode();
1054 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
1055 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1057 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
1060 assert(0 && "Unknown constant type!");
1064 void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1065 assert(!GV->isExternal() && "Cannot merge in external global!");
1066 // Get a node handle to the global node and merge the initializer into it.
1067 DSNodeHandle NH = getValueDest(*GV);
1068 MergeConstantInitIntoNode(NH, GV->getInitializer());
1072 /// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
1073 /// contains multiple globals, DSA will never, ever, be able to tell the globals
1074 /// apart. Instead of maintaining this information in all of the graphs
1075 /// throughout the entire program, store only a single global (the "leader") in
1076 /// the graphs, and build equivalence classes for the rest of the globals.
1077 static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1078 DSScalarMap &SM = GG.getScalarMap();
1079 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1080 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1082 if (I->getGlobalsList().size() <= 1) continue;
1084 // First, build up the equivalence set for this block of globals.
1085 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1086 GlobalValue *First = GVs[0];
1087 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1088 GlobalECs.unionSets(First, GVs[i]);
1090 // Next, get the leader element.
1091 assert(First == GlobalECs.getLeaderValue(First) &&
1092 "First did not end up being the leader?");
1094 // Next, remove all globals from the scalar map that are not the leader.
1095 assert(GVs[0] == First && "First had to be at the front!");
1096 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1097 ECGlobals.insert(GVs[i]);
1098 SM.erase(SM.find(GVs[i]));
1101 // Finally, change the global node to only contain the leader.
1103 I->addGlobal(First);
1106 DEBUG(GG.AssertGraphOK());
1109 /// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1110 /// really just equivalent to some other globals, remove the globals from the
1111 /// specified DSGraph (if present), and merge any nodes with their leader nodes.
1112 static void EliminateUsesOfECGlobals(DSGraph &G,
1113 const std::set<GlobalValue*> &ECGlobals) {
1114 DSScalarMap &SM = G.getScalarMap();
1115 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1117 bool MadeChange = false;
1118 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1120 GlobalValue *GV = *GI++;
1121 if (!ECGlobals.count(GV)) continue;
1123 const DSNodeHandle &GVNH = SM[GV];
1124 assert(!GVNH.isNull() && "Global has null NH!?");
1126 // Okay, this global is in some equivalence class. Start by finding the
1127 // leader of the class.
1128 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1130 // If the leader isn't already in the graph, insert it into the node
1131 // corresponding to GV.
1132 if (!SM.global_count(Leader)) {
1133 GVNH.getNode()->addGlobal(Leader);
1136 // Otherwise, the leader is in the graph, make sure the nodes are the
1137 // merged in the specified graph.
1138 const DSNodeHandle &LNH = SM[Leader];
1139 if (LNH.getNode() != GVNH.getNode())
1140 LNH.mergeWith(GVNH);
1143 // Next step, remove the global from the DSNode.
1144 GVNH.getNode()->removeGlobal(GV);
1146 // Finally, remove the global from the ScalarMap.
1151 DEBUG(if(MadeChange) G.AssertGraphOK());
1154 bool LocalDataStructures::runOnModule(Module &M) {
1155 const TargetData &TD = getAnalysis<TargetData>();
1157 // First step, build the globals graph.
1158 GlobalsGraph = new DSGraph(GlobalECs, TD);
1160 GraphBuilder GGB(*GlobalsGraph);
1162 // Add initializers for all of the globals to the globals graph.
1163 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1165 if (!I->isExternal())
1166 GGB.mergeInGlobalInitializer(I);
1169 // Next step, iterate through the nodes in the globals graph, unioning
1170 // together the globals into equivalence classes.
1171 std::set<GlobalValue*> ECGlobals;
1172 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1173 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1176 // Calculate all of the graphs...
1177 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1178 if (!I->isExternal())
1179 DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1182 GlobalsGraph->removeTriviallyDeadNodes();
1183 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
1185 // Now that we've computed all of the graphs, and merged all of the info into
1186 // the globals graph, see if we have further constrained the globals in the
1187 // program if so, update GlobalECs and remove the extraneous globals from the
1189 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1190 if (!ECGlobals.empty()) {
1191 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1192 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1193 E = DSInfo.end(); I != E; ++I)
1194 EliminateUsesOfECGlobals(*I->second, ECGlobals);
1200 // releaseMemory - If the pass pipeline is done with this pass, we can release
1201 // our memory... here...
1203 void LocalDataStructures::releaseMemory() {
1204 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1205 E = DSInfo.end(); I != E; ++I) {
1206 I->second->getReturnNodes().erase(I->first);
1207 if (I->second->getReturnNodes().empty())
1211 // Empty map so next time memory is released, data structures are not
1214 delete GlobalsGraph;