Introduce and use convenience methods for getting pointer types
[oota-llvm.git] / lib / Analysis / PointerTracking.cpp
1 //===- 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"
16 #include "llvm/Analysis/MallocHelper.h"
17 #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"
27 using namespace llvm;
28
29 char PointerTracking::ID = 0;
30 PointerTracking::PointerTracking() : FunctionPass(&ID) {}
31
32 bool 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
43 void PointerTracking::getAnalysisUsage(AnalysisUsage &AU) const {
44   AU.addRequiredTransitive<DominatorTree>();
45   AU.addRequiredTransitive<LoopInfo>();
46   AU.addRequiredTransitive<ScalarEvolution>();
47   AU.setPreservesAll();
48 }
49
50 bool PointerTracking::doInitialization(Module &M) {
51   const Type *PTy = Type::getInt8PtrTy(M.getContext());
52
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;
59     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()));
63     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);
77     args.push_back(Type::getInt64Ty(M.getContext()));
78     args2.push_back(PTy);
79     args2.push_back(Type::getInt32Ty(M.getContext()));
80
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.
93 const 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
103   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
111   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();
116         return SE->getConstant(Type::getInt32Ty(P->getContext()),
117                                ATy->getNumElements());
118       }
119     }
120     Ty = GV->getType();
121     return SE->getConstant(Type::getInt32Ty(P->getContext()), 1);
122     //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) {
130       Ty = Type::getInt8Ty(P->getContext());
131       // 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) {
136       Ty = Type::getInt8Ty(P->getContext());
137       // 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.
146 const 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
169 const 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
175 const SCEV *PointerTracking::getAllocationSizeInBytes(Value *V) const {
176   return computeAllocationCountForType(V, Type::getInt8Ty(V->getContext()));
177 }
178
179 // Helper for isLoopGuardedBy that checks the swapped and inverted predicate too
180 enum 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
199 enum SolverResult PointerTracking::checkLimits(const SCEV *Offset,
200                                                const SCEV *Limit,
201                                                BasicBlock *BB)
202 {
203   //FIXME: merge implementation
204   return Unknown;
205 }
206
207 void 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
227 void 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
264 static RegisterPass<PointerTracking> X("pointertracking",
265                                        "Track pointer bounds", false, true);