blob: 22818369b8bf7e1eeb572c2ca10f7101b2ec3005 [file] [log] [blame]
Torok Edwin969f28d2009-07-14 18:44:28 +00001//===- PointerTracking.cpp - Pointer Bounds Tracking ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements tracking of pointer bounds.
11//
12//===----------------------------------------------------------------------===//
13#include "llvm/Analysis/ConstantFolding.h"
14#include "llvm/Analysis/Dominators.h"
15#include "llvm/Analysis/LoopInfo.h"
Victor Hernandez46e83122009-09-18 21:34:51 +000016#include "llvm/Analysis/MallocHelper.h"
Torok Edwin969f28d2009-07-14 18:44:28 +000017#include "llvm/Analysis/PointerTracking.h"
18#include "llvm/Analysis/ScalarEvolution.h"
19#include "llvm/Analysis/ScalarEvolutionExpressions.h"
20#include "llvm/Constants.h"
21#include "llvm/Module.h"
22#include "llvm/Value.h"
23#include "llvm/Support/CallSite.h"
24#include "llvm/Support/InstIterator.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/Target/TargetData.h"
Chris Lattner9661c132009-08-24 02:39:26 +000027using namespace llvm;
Torok Edwin969f28d2009-07-14 18:44:28 +000028
Chris Lattner9661c132009-08-24 02:39:26 +000029char PointerTracking::ID = 0;
Torok Edwin969f28d2009-07-14 18:44:28 +000030PointerTracking::PointerTracking() : FunctionPass(&ID) {}
31
32bool PointerTracking::runOnFunction(Function &F) {
33 predCache.clear();
34 assert(analyzing.empty());
35 FF = &F;
36 TD = getAnalysisIfAvailable<TargetData>();
37 SE = &getAnalysis<ScalarEvolution>();
38 LI = &getAnalysis<LoopInfo>();
39 DT = &getAnalysis<DominatorTree>();
40 return false;
41}
42
43void PointerTracking::getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addRequiredTransitive<DominatorTree>();
45 AU.addRequiredTransitive<LoopInfo>();
46 AU.addRequiredTransitive<ScalarEvolution>();
47 AU.setPreservesAll();
48}
49
50bool PointerTracking::doInitialization(Module &M) {
Owen Anderson1d0be152009-08-13 21:58:54 +000051 const Type *PTy = PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
Torok Edwin969f28d2009-07-14 18:44:28 +000052
53 // Find calloc(i64, i64) or calloc(i32, i32).
54 callocFunc = M.getFunction("calloc");
55 if (callocFunc) {
56 const FunctionType *Ty = callocFunc->getFunctionType();
57
58 std::vector<const Type*> args, args2;
Owen Anderson1d0be152009-08-13 21:58:54 +000059 args.push_back(Type::getInt64Ty(M.getContext()));
60 args.push_back(Type::getInt64Ty(M.getContext()));
61 args2.push_back(Type::getInt32Ty(M.getContext()));
62 args2.push_back(Type::getInt32Ty(M.getContext()));
Torok Edwin969f28d2009-07-14 18:44:28 +000063 const FunctionType *Calloc1Type =
64 FunctionType::get(PTy, args, false);
65 const FunctionType *Calloc2Type =
66 FunctionType::get(PTy, args2, false);
67 if (Ty != Calloc1Type && Ty != Calloc2Type)
68 callocFunc = 0; // Give up
69 }
70
71 // Find realloc(i8*, i64) or realloc(i8*, i32).
72 reallocFunc = M.getFunction("realloc");
73 if (reallocFunc) {
74 const FunctionType *Ty = reallocFunc->getFunctionType();
75 std::vector<const Type*> args, args2;
76 args.push_back(PTy);
Owen Anderson1d0be152009-08-13 21:58:54 +000077 args.push_back(Type::getInt64Ty(M.getContext()));
Torok Edwin969f28d2009-07-14 18:44:28 +000078 args2.push_back(PTy);
Owen Anderson1d0be152009-08-13 21:58:54 +000079 args2.push_back(Type::getInt32Ty(M.getContext()));
Torok Edwin969f28d2009-07-14 18:44:28 +000080
81 const FunctionType *Realloc1Type =
82 FunctionType::get(PTy, args, false);
83 const FunctionType *Realloc2Type =
84 FunctionType::get(PTy, args2, false);
85 if (Ty != Realloc1Type && Ty != Realloc2Type)
86 reallocFunc = 0; // Give up
87 }
88 return false;
89}
90
91// Calculates the number of elements allocated for pointer P,
92// the type of the element is stored in Ty.
93const SCEV *PointerTracking::computeAllocationCount(Value *P,
94 const Type *&Ty) const {
95 Value *V = P->stripPointerCasts();
96 if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
97 Value *arraySize = AI->getArraySize();
98 Ty = AI->getAllocatedType();
99 // arraySize elements of type Ty.
100 return SE->getSCEV(arraySize);
101 }
102
Victor Hernandez46e83122009-09-18 21:34:51 +0000103 if (CallInst *CI = extractMallocCall(V)) {
104 Value *arraySize = getMallocArraySize(CI, P->getContext(), TD);
105 Ty = getMallocAllocatedType(CI);
106 if (!Ty || !arraySize) return SE->getCouldNotCompute();
107 // arraySize elements of type Ty.
108 return SE->getSCEV(arraySize);
109 }
110
Torok Edwin969f28d2009-07-14 18:44:28 +0000111 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
112 if (GV->hasDefinitiveInitializer()) {
113 Constant *C = GV->getInitializer();
114 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
115 Ty = ATy->getElementType();
Owen Anderson0e275dc2009-08-13 23:27:32 +0000116 return SE->getConstant(Type::getInt32Ty(P->getContext()),
Owen Anderson1d0be152009-08-13 21:58:54 +0000117 ATy->getNumElements());
Torok Edwin969f28d2009-07-14 18:44:28 +0000118 }
119 }
120 Ty = GV->getType();
Owen Anderson0e275dc2009-08-13 23:27:32 +0000121 return SE->getConstant(Type::getInt32Ty(P->getContext()), 1);
Torok Edwin969f28d2009-07-14 18:44:28 +0000122 //TODO: implement more tracking for globals
123 }
124
125 if (CallInst *CI = dyn_cast<CallInst>(V)) {
126 CallSite CS(CI);
127 Function *F = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
128 const Loop *L = LI->getLoopFor(CI->getParent());
129 if (F == callocFunc) {
Owen Anderson0e275dc2009-08-13 23:27:32 +0000130 Ty = Type::getInt8Ty(P->getContext());
Torok Edwin969f28d2009-07-14 18:44:28 +0000131 // calloc allocates arg0*arg1 bytes.
132 return SE->getSCEVAtScope(SE->getMulExpr(SE->getSCEV(CS.getArgument(0)),
133 SE->getSCEV(CS.getArgument(1))),
134 L);
135 } else if (F == reallocFunc) {
Owen Anderson0e275dc2009-08-13 23:27:32 +0000136 Ty = Type::getInt8Ty(P->getContext());
Torok Edwin969f28d2009-07-14 18:44:28 +0000137 // realloc allocates arg1 bytes.
138 return SE->getSCEVAtScope(CS.getArgument(1), L);
139 }
140 }
141
142 return SE->getCouldNotCompute();
143}
144
145// Calculates the number of elements of type Ty allocated for P.
146const SCEV *PointerTracking::computeAllocationCountForType(Value *P,
147 const Type *Ty)
148 const {
149 const Type *elementTy;
150 const SCEV *Count = computeAllocationCount(P, elementTy);
151 if (isa<SCEVCouldNotCompute>(Count))
152 return Count;
153 if (elementTy == Ty)
154 return Count;
155
156 if (!TD) // need TargetData from this point forward
157 return SE->getCouldNotCompute();
158
159 uint64_t elementSize = TD->getTypeAllocSize(elementTy);
160 uint64_t wantSize = TD->getTypeAllocSize(Ty);
161 if (elementSize == wantSize)
162 return Count;
163 if (elementSize % wantSize) //fractional counts not possible
164 return SE->getCouldNotCompute();
165 return SE->getMulExpr(Count, SE->getConstant(Count->getType(),
166 elementSize/wantSize));
167}
168
169const SCEV *PointerTracking::getAllocationElementCount(Value *V) const {
170 // We only deal with pointers.
171 const PointerType *PTy = cast<PointerType>(V->getType());
172 return computeAllocationCountForType(V, PTy->getElementType());
173}
174
175const SCEV *PointerTracking::getAllocationSizeInBytes(Value *V) const {
Owen Anderson1d0be152009-08-13 21:58:54 +0000176 return computeAllocationCountForType(V, Type::getInt8Ty(V->getContext()));
Torok Edwin969f28d2009-07-14 18:44:28 +0000177}
178
179// Helper for isLoopGuardedBy that checks the swapped and inverted predicate too
180enum SolverResult PointerTracking::isLoopGuardedBy(const Loop *L,
181 Predicate Pred,
182 const SCEV *A,
183 const SCEV *B) const {
184 if (SE->isLoopGuardedByCond(L, Pred, A, B))
185 return AlwaysTrue;
186 Pred = ICmpInst::getSwappedPredicate(Pred);
187 if (SE->isLoopGuardedByCond(L, Pred, B, A))
188 return AlwaysTrue;
189
190 Pred = ICmpInst::getInversePredicate(Pred);
191 if (SE->isLoopGuardedByCond(L, Pred, B, A))
192 return AlwaysFalse;
193 Pred = ICmpInst::getSwappedPredicate(Pred);
194 if (SE->isLoopGuardedByCond(L, Pred, A, B))
195 return AlwaysTrue;
196 return Unknown;
197}
198
199enum SolverResult PointerTracking::checkLimits(const SCEV *Offset,
200 const SCEV *Limit,
201 BasicBlock *BB)
202{
203 //FIXME: merge implementation
204 return Unknown;
205}
206
207void PointerTracking::getPointerOffset(Value *Pointer, Value *&Base,
208 const SCEV *&Limit,
209 const SCEV *&Offset) const
210{
211 Pointer = Pointer->stripPointerCasts();
212 Base = Pointer->getUnderlyingObject();
213 Limit = getAllocationSizeInBytes(Base);
214 if (isa<SCEVCouldNotCompute>(Limit)) {
215 Base = 0;
216 Offset = Limit;
217 return;
218 }
219
220 Offset = SE->getMinusSCEV(SE->getSCEV(Pointer), SE->getSCEV(Base));
221 if (isa<SCEVCouldNotCompute>(Offset)) {
222 Base = 0;
223 Limit = Offset;
224 }
225}
226
227void PointerTracking::print(raw_ostream &OS, const Module* M) const {
228 // Calling some PT methods may cause caches to be updated, however
229 // this should be safe for the same reason its safe for SCEV.
230 PointerTracking &PT = *const_cast<PointerTracking*>(this);
231 for (inst_iterator I=inst_begin(*FF), E=inst_end(*FF); I != E; ++I) {
232 if (!isa<PointerType>(I->getType()))
233 continue;
234 Value *Base;
235 const SCEV *Limit, *Offset;
236 getPointerOffset(&*I, Base, Limit, Offset);
237 if (!Base)
238 continue;
239
240 if (Base == &*I) {
241 const SCEV *S = getAllocationElementCount(Base);
242 OS << *Base << " ==> " << *S << " elements, ";
243 OS << *Limit << " bytes allocated\n";
244 continue;
245 }
246 OS << &*I << " -- base: " << *Base;
247 OS << " offset: " << *Offset;
248
249 enum SolverResult res = PT.checkLimits(Offset, Limit, I->getParent());
250 switch (res) {
251 case AlwaysTrue:
252 OS << " always safe\n";
253 break;
254 case AlwaysFalse:
255 OS << " always unsafe\n";
256 break;
257 case Unknown:
258 OS << " <<unknown>>\n";
259 break;
260 }
261 }
262}
263
Torok Edwin969f28d2009-07-14 18:44:28 +0000264static RegisterPass<PointerTracking> X("pointertracking",
265 "Track pointer bounds", false, true);