1 //===- PointerTracking.cpp - Pointer Bounds Tracking ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements tracking of pointer bounds.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/ConstantFolding.h"
14 #include "llvm/Analysis/Dominators.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/PointerTracking.h"
17 #include "llvm/Analysis/ScalarEvolution.h"
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Module.h"
21 #include "llvm/Value.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/InstIterator.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetData.h"
28 char PointerTracking::ID=0;
29 PointerTracking::PointerTracking() : FunctionPass(&ID) {}
31 bool PointerTracking::runOnFunction(Function &F) {
33 assert(analyzing.empty());
35 TD = getAnalysisIfAvailable<TargetData>();
36 SE = &getAnalysis<ScalarEvolution>();
37 LI = &getAnalysis<LoopInfo>();
38 DT = &getAnalysis<DominatorTree>();
42 void PointerTracking::getAnalysisUsage(AnalysisUsage &AU) const {
43 AU.addRequiredTransitive<DominatorTree>();
44 AU.addRequiredTransitive<LoopInfo>();
45 AU.addRequiredTransitive<ScalarEvolution>();
49 bool PointerTracking::doInitialization(Module &M) {
50 const Type *PTy = PointerType::getUnqual(Type::Int8Ty);
52 // Find calloc(i64, i64) or calloc(i32, i32).
53 callocFunc = M.getFunction("calloc");
55 const FunctionType *Ty = callocFunc->getFunctionType();
57 std::vector<const Type*> args, args2;
58 args.push_back(Type::Int64Ty);
59 args.push_back(Type::Int64Ty);
60 args2.push_back(Type::Int32Ty);
61 args2.push_back(Type::Int32Ty);
62 const FunctionType *Calloc1Type =
63 FunctionType::get(PTy, args, false);
64 const FunctionType *Calloc2Type =
65 FunctionType::get(PTy, args2, false);
66 if (Ty != Calloc1Type && Ty != Calloc2Type)
67 callocFunc = 0; // Give up
70 // Find realloc(i8*, i64) or realloc(i8*, i32).
71 reallocFunc = M.getFunction("realloc");
73 const FunctionType *Ty = reallocFunc->getFunctionType();
74 std::vector<const Type*> args, args2;
76 args.push_back(Type::Int64Ty);
78 args2.push_back(Type::Int32Ty);
80 const FunctionType *Realloc1Type =
81 FunctionType::get(PTy, args, false);
82 const FunctionType *Realloc2Type =
83 FunctionType::get(PTy, args2, false);
84 if (Ty != Realloc1Type && Ty != Realloc2Type)
85 reallocFunc = 0; // Give up
90 // Calculates the number of elements allocated for pointer P,
91 // the type of the element is stored in Ty.
92 const SCEV *PointerTracking::computeAllocationCount(Value *P,
93 const Type *&Ty) const {
94 Value *V = P->stripPointerCasts();
95 if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
96 Value *arraySize = AI->getArraySize();
97 Ty = AI->getAllocatedType();
98 // arraySize elements of type Ty.
99 return SE->getSCEV(arraySize);
102 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
103 if (GV->hasDefinitiveInitializer()) {
104 Constant *C = GV->getInitializer();
105 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
106 Ty = ATy->getElementType();
107 return SE->getConstant(Type::Int32Ty, ATy->getNumElements());
111 return SE->getConstant(Type::Int32Ty, 1);
112 //TODO: implement more tracking for globals
115 if (CallInst *CI = dyn_cast<CallInst>(V)) {
117 Function *F = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
118 const Loop *L = LI->getLoopFor(CI->getParent());
119 if (F == callocFunc) {
121 // calloc allocates arg0*arg1 bytes.
122 return SE->getSCEVAtScope(SE->getMulExpr(SE->getSCEV(CS.getArgument(0)),
123 SE->getSCEV(CS.getArgument(1))),
125 } else if (F == reallocFunc) {
127 // realloc allocates arg1 bytes.
128 return SE->getSCEVAtScope(CS.getArgument(1), L);
132 return SE->getCouldNotCompute();
135 // Calculates the number of elements of type Ty allocated for P.
136 const SCEV *PointerTracking::computeAllocationCountForType(Value *P,
139 const Type *elementTy;
140 const SCEV *Count = computeAllocationCount(P, elementTy);
141 if (isa<SCEVCouldNotCompute>(Count))
146 if (!TD) // need TargetData from this point forward
147 return SE->getCouldNotCompute();
149 uint64_t elementSize = TD->getTypeAllocSize(elementTy);
150 uint64_t wantSize = TD->getTypeAllocSize(Ty);
151 if (elementSize == wantSize)
153 if (elementSize % wantSize) //fractional counts not possible
154 return SE->getCouldNotCompute();
155 return SE->getMulExpr(Count, SE->getConstant(Count->getType(),
156 elementSize/wantSize));
159 const SCEV *PointerTracking::getAllocationElementCount(Value *V) const {
160 // We only deal with pointers.
161 const PointerType *PTy = cast<PointerType>(V->getType());
162 return computeAllocationCountForType(V, PTy->getElementType());
165 const SCEV *PointerTracking::getAllocationSizeInBytes(Value *V) const {
166 return computeAllocationCountForType(V, Type::Int8Ty);
169 // Helper for isLoopGuardedBy that checks the swapped and inverted predicate too
170 enum SolverResult PointerTracking::isLoopGuardedBy(const Loop *L,
173 const SCEV *B) const {
174 if (SE->isLoopGuardedByCond(L, Pred, A, B))
176 Pred = ICmpInst::getSwappedPredicate(Pred);
177 if (SE->isLoopGuardedByCond(L, Pred, B, A))
180 Pred = ICmpInst::getInversePredicate(Pred);
181 if (SE->isLoopGuardedByCond(L, Pred, B, A))
183 Pred = ICmpInst::getSwappedPredicate(Pred);
184 if (SE->isLoopGuardedByCond(L, Pred, A, B))
189 enum SolverResult PointerTracking::checkLimits(const SCEV *Offset,
193 //FIXME: merge implementation
197 void PointerTracking::getPointerOffset(Value *Pointer, Value *&Base,
199 const SCEV *&Offset) const
201 Pointer = Pointer->stripPointerCasts();
202 Base = Pointer->getUnderlyingObject();
203 Limit = getAllocationSizeInBytes(Base);
204 if (isa<SCEVCouldNotCompute>(Limit)) {
210 Offset = SE->getMinusSCEV(SE->getSCEV(Pointer), SE->getSCEV(Base));
211 if (isa<SCEVCouldNotCompute>(Offset)) {
217 void PointerTracking::print(raw_ostream &OS, const Module* M) const {
218 // Calling some PT methods may cause caches to be updated, however
219 // this should be safe for the same reason its safe for SCEV.
220 PointerTracking &PT = *const_cast<PointerTracking*>(this);
221 for (inst_iterator I=inst_begin(*FF), E=inst_end(*FF); I != E; ++I) {
222 if (!isa<PointerType>(I->getType()))
225 const SCEV *Limit, *Offset;
226 getPointerOffset(&*I, Base, Limit, Offset);
231 const SCEV *S = getAllocationElementCount(Base);
232 OS << *Base << " ==> " << *S << " elements, ";
233 OS << *Limit << " bytes allocated\n";
236 OS << &*I << " -- base: " << *Base;
237 OS << " offset: " << *Offset;
239 enum SolverResult res = PT.checkLimits(Offset, Limit, I->getParent());
242 OS << " always safe\n";
245 OS << " always unsafe\n";
248 OS << " <<unknown>>\n";
254 void PointerTracking::print(std::ostream &o, const Module* M) const {
255 raw_os_ostream OS(o);
259 static RegisterPass<PointerTracking> X("pointertracking",
260 "Track pointer bounds", false, true);