MemoryBuiltins: add support to determine the size of strdup'ed non-constant strings
[oota-llvm.git] / lib / Analysis / MemoryBuiltins.cpp
1 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
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 family of functions identifies calls to builtin functions that allocate
11 // or free memory.  
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "memory-builtins"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/Metadata.h"
23 #include "llvm/Module.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/Utils/BuildLibCalls.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 using namespace llvm;
32
33 enum AllocType {
34   MallocLike         = 1<<0, // allocates
35   CallocLike         = 1<<1, // allocates + bzero
36   ReallocLike        = 1<<2, // reallocates
37   StrDupLike         = 1<<3,
38   AllocLike          = MallocLike | CallocLike | StrDupLike,
39   AnyAlloc           = MallocLike | CallocLike | ReallocLike | StrDupLike
40 };
41
42 struct AllocFnsTy {
43   const char *Name;
44   AllocType AllocTy;
45   unsigned char NumParams;
46   // First and Second size parameters (or -1 if unused)
47   signed char FstParam, SndParam;
48 };
49
50 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
51 // know which functions are nounwind, noalias, nocapture parameters, etc.
52 static const AllocFnsTy AllocationFnData[] = {
53   {"malloc",              MallocLike,  1, 0,  -1},
54   {"valloc",              MallocLike,  1, 0,  -1},
55   {"_Znwj",               MallocLike,  1, 0,  -1}, // new(unsigned int)
56   {"_ZnwjRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
57   {"_Znwm",               MallocLike,  1, 0,  -1}, // new(unsigned long)
58   {"_ZnwmRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new(unsigned long, nothrow)
59   {"_Znaj",               MallocLike,  1, 0,  -1}, // new[](unsigned int)
60   {"_ZnajRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
61   {"_Znam",               MallocLike,  1, 0,  -1}, // new[](unsigned long)
62   {"_ZnamRKSt9nothrow_t", MallocLike,  2, 0,  -1}, // new[](unsigned long, nothrow)
63   {"posix_memalign",      MallocLike,  3, 2,  -1},
64   {"calloc",              CallocLike,  2, 0,  1},
65   {"realloc",             ReallocLike, 2, 1,  -1},
66   {"reallocf",            ReallocLike, 2, 1,  -1},
67   {"strdup",              StrDupLike,  1, -1, -1},
68   {"strndup",             StrDupLike,  2, 1,  -1}
69 };
70
71
72 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
73   if (LookThroughBitCast)
74     V = V->stripPointerCasts();
75
76   CallSite CS(const_cast<Value*>(V));
77   if (!CS.getInstruction())
78     return 0;
79
80   Function *Callee = CS.getCalledFunction();
81   if (!Callee || !Callee->isDeclaration())
82     return 0;
83   return Callee;
84 }
85
86 /// \brief Returns the allocation data for the given value if it is a call to a
87 /// known allocation function, and NULL otherwise.
88 static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
89                                            bool LookThroughBitCast = false) {
90   Function *Callee = getCalledFunction(V, LookThroughBitCast);
91   if (!Callee)
92     return 0;
93
94   unsigned i = 0;
95   bool found = false;
96   for ( ; i < array_lengthof(AllocationFnData); ++i) {
97     if (Callee->getName() == AllocationFnData[i].Name) {
98       found = true;
99       break;
100     }
101   }
102   if (!found)
103     return 0;
104
105   const AllocFnsTy *FnData = &AllocationFnData[i];
106   if ((FnData->AllocTy & AllocTy) == 0)
107     return 0;
108
109   // Check function prototype.
110   // FIXME: Check the nobuiltin metadata?? (PR5130)
111   int FstParam = FnData->FstParam;
112   int SndParam = FnData->SndParam;
113   FunctionType *FTy = Callee->getFunctionType();
114
115   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
116       FTy->getNumParams() == FnData->NumParams &&
117       (FstParam < 0 ||
118        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
119         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
120       (SndParam < 0 ||
121        FTy->getParamType(SndParam)->isIntegerTy(32) ||
122        FTy->getParamType(SndParam)->isIntegerTy(64)))
123     return FnData;
124   return 0;
125 }
126
127 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
128   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
129   return CS && CS.hasFnAttr(Attribute::NoAlias);
130 }
131
132
133 /// \brief Tests if a value is a call or invoke to a library function that
134 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
135 /// like).
136 bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
137   return getAllocationData(V, AnyAlloc, LookThroughBitCast);
138 }
139
140 /// \brief Tests if a value is a call or invoke to a function that returns a
141 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
142 bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
143   // it's safe to consider realloc as noalias since accessing the original
144   // pointer is undefined behavior
145   return isAllocationFn(V, LookThroughBitCast) ||
146          hasNoAliasAttr(V, LookThroughBitCast);
147 }
148
149 /// \brief Tests if a value is a call or invoke to a library function that
150 /// allocates uninitialized memory (such as malloc).
151 bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
152   return getAllocationData(V, MallocLike, LookThroughBitCast);
153 }
154
155 /// \brief Tests if a value is a call or invoke to a library function that
156 /// allocates zero-filled memory (such as calloc).
157 bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
158   return getAllocationData(V, CallocLike, LookThroughBitCast);
159 }
160
161 /// \brief Tests if a value is a call or invoke to a library function that
162 /// allocates memory (either malloc, calloc, or strdup like).
163 bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
164   return getAllocationData(V, AllocLike, LookThroughBitCast);
165 }
166
167 /// \brief Tests if a value is a call or invoke to a library function that
168 /// reallocates memory (such as realloc).
169 bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
170   return getAllocationData(V, ReallocLike, LookThroughBitCast);
171 }
172
173 /// extractMallocCall - Returns the corresponding CallInst if the instruction
174 /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
175 /// ignore InvokeInst here.
176 const CallInst *llvm::extractMallocCall(const Value *I) {
177   return isMallocLikeFn(I) ? dyn_cast<CallInst>(I) : 0;
178 }
179
180 static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
181                                bool LookThroughSExt = false) {
182   if (!CI)
183     return NULL;
184
185   // The size of the malloc's result type must be known to determine array size.
186   Type *T = getMallocAllocatedType(CI);
187   if (!T || !T->isSized() || !TD)
188     return NULL;
189
190   unsigned ElementSize = TD->getTypeAllocSize(T);
191   if (StructType *ST = dyn_cast<StructType>(T))
192     ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
193
194   // If malloc call's arg can be determined to be a multiple of ElementSize,
195   // return the multiple.  Otherwise, return NULL.
196   Value *MallocArg = CI->getArgOperand(0);
197   Value *Multiple = NULL;
198   if (ComputeMultiple(MallocArg, ElementSize, Multiple,
199                       LookThroughSExt))
200     return Multiple;
201
202   return NULL;
203 }
204
205 /// isArrayMalloc - Returns the corresponding CallInst if the instruction 
206 /// is a call to malloc whose array size can be determined and the array size
207 /// is not constant 1.  Otherwise, return NULL.
208 const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
209   const CallInst *CI = extractMallocCall(I);
210   Value *ArraySize = computeArraySize(CI, TD);
211
212   if (ArraySize &&
213       ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
214     return CI;
215
216   // CI is a non-array malloc or we can't figure out that it is an array malloc.
217   return NULL;
218 }
219
220 /// getMallocType - Returns the PointerType resulting from the malloc call.
221 /// The PointerType depends on the number of bitcast uses of the malloc call:
222 ///   0: PointerType is the calls' return type.
223 ///   1: PointerType is the bitcast's result type.
224 ///  >1: Unique PointerType cannot be determined, return NULL.
225 PointerType *llvm::getMallocType(const CallInst *CI) {
226   assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
227   
228   PointerType *MallocType = NULL;
229   unsigned NumOfBitCastUses = 0;
230
231   // Determine if CallInst has a bitcast use.
232   for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
233        UI != E; )
234     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
235       MallocType = cast<PointerType>(BCI->getDestTy());
236       NumOfBitCastUses++;
237     }
238
239   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
240   if (NumOfBitCastUses == 1)
241     return MallocType;
242
243   // Malloc call was not bitcast, so type is the malloc function's return type.
244   if (NumOfBitCastUses == 0)
245     return cast<PointerType>(CI->getType());
246
247   // Type could not be determined.
248   return NULL;
249 }
250
251 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
252 /// The Type depends on the number of bitcast uses of the malloc call:
253 ///   0: PointerType is the malloc calls' return type.
254 ///   1: PointerType is the bitcast's result type.
255 ///  >1: Unique PointerType cannot be determined, return NULL.
256 Type *llvm::getMallocAllocatedType(const CallInst *CI) {
257   PointerType *PT = getMallocType(CI);
258   return PT ? PT->getElementType() : NULL;
259 }
260
261 /// getMallocArraySize - Returns the array size of a malloc call.  If the 
262 /// argument passed to malloc is a multiple of the size of the malloced type,
263 /// then return that multiple.  For non-array mallocs, the multiple is
264 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
265 /// determined.
266 Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
267                                 bool LookThroughSExt) {
268   assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
269   return computeArraySize(CI, TD, LookThroughSExt);
270 }
271
272
273 /// extractCallocCall - Returns the corresponding CallInst if the instruction
274 /// is a calloc call.
275 const CallInst *llvm::extractCallocCall(const Value *I) {
276   return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
277 }
278
279
280 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
281 const CallInst *llvm::isFreeCall(const Value *I) {
282   const CallInst *CI = dyn_cast<CallInst>(I);
283   if (!CI)
284     return 0;
285   Function *Callee = CI->getCalledFunction();
286   if (Callee == 0 || !Callee->isDeclaration())
287     return 0;
288
289   if (Callee->getName() != "free" &&
290       Callee->getName() != "_ZdlPv" && // operator delete(void*)
291       Callee->getName() != "_ZdaPv")   // operator delete[](void*)
292     return 0;
293
294   // Check free prototype.
295   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin 
296   // attribute will exist.
297   FunctionType *FTy = Callee->getFunctionType();
298   if (!FTy->getReturnType()->isVoidTy())
299     return 0;
300   if (FTy->getNumParams() != 1)
301     return 0;
302   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
303     return 0;
304
305   return CI;
306 }
307
308
309
310 //===----------------------------------------------------------------------===//
311 //  Utility functions to compute size of objects.
312 //
313
314
315 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
316 /// object size in Size if successful, and false otherwise.
317 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
318 /// byval arguments, and global variables.
319 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
320                          bool RoundToAlign) {
321   if (!TD)
322     return false;
323
324   ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
325   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
326   if (!Visitor.bothKnown(Data))
327     return false;
328
329   APInt ObjSize = Data.first, Offset = Data.second;
330   // check for overflow
331   if (Offset.slt(0) || ObjSize.ult(Offset))
332     Size = 0;
333   else
334     Size = (ObjSize - Offset).getZExtValue();
335   return true;
336 }
337
338
339 STATISTIC(ObjectVisitorArgument,
340           "Number of arguments with unsolved size and offset");
341 STATISTIC(ObjectVisitorLoad,
342           "Number of load instructions with unsolved size and offset");
343
344
345 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
346   if (RoundToAlign && Align)
347     return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
348   return Size;
349 }
350
351 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
352                                                  LLVMContext &Context,
353                                                  bool RoundToAlign)
354 : TD(TD), RoundToAlign(RoundToAlign) {
355   IntegerType *IntTy = TD->getIntPtrType(Context);
356   IntTyBits = IntTy->getBitWidth();
357   Zero = APInt::getNullValue(IntTyBits);
358 }
359
360 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
361   V = V->stripPointerCasts();
362
363   if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
364     return visitGEPOperator(*GEP);
365   if (Instruction *I = dyn_cast<Instruction>(V))
366     return visit(*I);
367   if (Argument *A = dyn_cast<Argument>(V))
368     return visitArgument(*A);
369   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
370     return visitConstantPointerNull(*P);
371   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
372     return visitGlobalVariable(*GV);
373   if (UndefValue *UV = dyn_cast<UndefValue>(V))
374     return visitUndefValue(*UV);
375   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
376     if (CE->getOpcode() == Instruction::IntToPtr)
377       return unknown(); // clueless
378
379   DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
380         << '\n');
381   return unknown();
382 }
383
384 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
385   if (!I.getAllocatedType()->isSized())
386     return unknown();
387
388   APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
389   if (!I.isArrayAllocation())
390     return std::make_pair(align(Size, I.getAlignment()), Zero);
391
392   Value *ArraySize = I.getArraySize();
393   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
394     Size *= C->getValue().zextOrSelf(IntTyBits);
395     return std::make_pair(align(Size, I.getAlignment()), Zero);
396   }
397   return unknown();
398 }
399
400 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
401   // no interprocedural analysis is done at the moment
402   if (!A.hasByValAttr()) {
403     ++ObjectVisitorArgument;
404     return unknown();
405   }
406   PointerType *PT = cast<PointerType>(A.getType());
407   APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
408   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
409 }
410
411 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
412   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
413   if (!FnData)
414     return unknown();
415
416   // handle strdup-like functions separately
417   if (FnData->AllocTy == StrDupLike) {
418     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
419     if (!Size)
420       return unknown();
421
422     // strndup limits strlen
423     if (FnData->FstParam > 0) {
424       ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
425       if (!Arg)
426         return unknown();
427
428       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
429       if (Size.ugt(MaxSize))
430         Size = MaxSize + 1;
431     }
432     return std::make_pair(Size, Zero);
433   }
434
435   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
436   if (!Arg)
437     return unknown();
438
439   APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
440   // size determined by just 1 parameter
441   if (FnData->SndParam < 0)
442     return std::make_pair(Size, Zero);
443
444   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
445   if (!Arg)
446     return unknown();
447
448   Size *= Arg->getValue().zextOrSelf(IntTyBits);
449   return std::make_pair(Size, Zero);
450
451   // TODO: handle more standard functions (+ wchar cousins):
452   // - strcpy / strncpy
453   // - strcat / strncat
454   // - memcpy / memmove
455   // - memset
456 }
457
458 SizeOffsetType
459 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
460   return std::make_pair(Zero, Zero);
461 }
462
463 SizeOffsetType
464 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
465   return unknown();
466 }
467
468 SizeOffsetType
469 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
470   // Easy cases were already folded by previous passes.
471   return unknown();
472 }
473
474 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
475   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
476   if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
477     return unknown();
478
479   SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
480   APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
481   return std::make_pair(PtrData.first, PtrData.second + Offset);
482 }
483
484 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
485   if (!GV.hasDefinitiveInitializer())
486     return unknown();
487
488   APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
489   return std::make_pair(align(Size, GV.getAlignment()), Zero);
490 }
491
492 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
493   // clueless
494   return unknown();
495 }
496
497 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
498   ++ObjectVisitorLoad;
499   return unknown();
500 }
501
502 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
503   // too complex to analyze statically.
504   return unknown();
505 }
506
507 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
508   SizeOffsetType TrueSide  = compute(I.getTrueValue());
509   SizeOffsetType FalseSide = compute(I.getFalseValue());
510   if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
511     return TrueSide;
512   return unknown();
513 }
514
515 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
516   return std::make_pair(Zero, Zero);
517 }
518
519 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
520   DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
521   return unknown();
522 }
523
524
525 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
526                                                      const TargetLibraryInfo *TLI,
527                                                      LLVMContext &Context)
528 : TD(TD), TLI(TLI), Context(Context), Builder(Context, TargetFolder(TD)),
529 Visitor(TD, Context) {
530   IntTy = TD->getIntPtrType(Context);
531   Zero = ConstantInt::get(IntTy, 0);
532 }
533
534 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
535   SizeOffsetEvalType Result = compute_(V);
536
537   if (!bothKnown(Result)) {
538     // erase everything that was computed in this iteration from the cache, so
539     // that no dangling references are left behind. We could be a bit smarter if
540     // we kept a dependency graph. It's probably not worth the complexity.
541     for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
542       CacheMapTy::iterator CacheIt = CacheMap.find(*I);
543       // non-computable results can be safely cached
544       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
545         CacheMap.erase(CacheIt);
546     }
547   }
548
549   SeenVals.clear();
550   return Result;
551 }
552
553 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
554   SizeOffsetType Const = Visitor.compute(V);
555   if (Visitor.bothKnown(Const))
556     return std::make_pair(ConstantInt::get(Context, Const.first),
557                           ConstantInt::get(Context, Const.second));
558
559   V = V->stripPointerCasts();
560
561   // check cache
562   CacheMapTy::iterator CacheIt = CacheMap.find(V);
563   if (CacheIt != CacheMap.end())
564     return CacheIt->second;
565
566   // always generate code immediately before the instruction being
567   // processed, so that the generated code dominates the same BBs
568   Instruction *PrevInsertPoint = Builder.GetInsertPoint();
569   if (Instruction *I = dyn_cast<Instruction>(V))
570     Builder.SetInsertPoint(I);
571
572   // record the pointers that were handled in this run, so that they can be
573   // cleaned later if something fails
574   SeenVals.insert(V);
575
576   // now compute the size and offset
577   SizeOffsetEvalType Result;
578   if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
579     Result = visitGEPOperator(*GEP);
580   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
581     Result = visit(*I);
582   } else if (isa<Argument>(V) ||
583              (isa<ConstantExpr>(V) &&
584               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
585              isa<GlobalVariable>(V)) {
586     // ignore values where we cannot do more than what ObjectSizeVisitor can
587     Result = unknown();
588   } else {
589     DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
590           << *V << '\n');
591     Result = unknown();
592   }
593
594   if (PrevInsertPoint)
595     Builder.SetInsertPoint(PrevInsertPoint);
596
597   // Don't reuse CacheIt since it may be invalid at this point.
598   CacheMap[V] = Result;
599   return Result;
600 }
601
602 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
603   if (!I.getAllocatedType()->isSized())
604     return unknown();
605
606   // must be a VLA
607   assert(I.isArrayAllocation());
608   Value *ArraySize = I.getArraySize();
609   Value *Size = ConstantInt::get(ArraySize->getType(),
610                                  TD->getTypeAllocSize(I.getAllocatedType()));
611   Size = Builder.CreateMul(Size, ArraySize);
612   return std::make_pair(Size, Zero);
613 }
614
615 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
616   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
617   if (!FnData)
618     return unknown();
619
620   // handle strdup-like functions separately
621   if (FnData->AllocTy == StrDupLike) {
622     IRBuilder<> StdBuilder(Builder.GetInsertPoint());
623     Value *Size;
624
625     // strdup(str): size =  strlen(str)+1
626     if (FnData->FstParam < 0)
627       Size = EmitStrLen(CS.getArgument(0), StdBuilder, TD, TLI);
628     else
629       // strndup(str, maxlen): size = strnlen(str, maxlen)+1
630       Size = EmitStrNLen(CS.getArgument(0), CS.getArgument(FnData->FstParam),
631                          StdBuilder, TD, TLI);
632     if (!Size)
633       return unknown();
634     Builder.SetInsertPoint(StdBuilder.GetInsertPoint());
635     Size = Builder.CreateNUWAdd(Size, ConstantInt::get(IntTy, 1));
636     return std::make_pair(Size, Zero);
637   }
638
639   Value *FirstArg = CS.getArgument(FnData->FstParam);
640   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
641   if (FnData->SndParam < 0)
642     return std::make_pair(FirstArg, Zero);
643
644   Value *SecondArg = CS.getArgument(FnData->SndParam);
645   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
646   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
647   return std::make_pair(Size, Zero);
648
649   // TODO: handle more standard functions (+ wchar cousins):
650   // - strcpy / strncpy
651   // - strcat / strncat
652   // - memcpy / memmove
653   // - memset
654 }
655
656 SizeOffsetEvalType
657 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
658   return unknown();
659 }
660
661 SizeOffsetEvalType
662 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
663   return unknown();
664 }
665
666 SizeOffsetEvalType
667 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
668   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
669   if (!bothKnown(PtrData))
670     return unknown();
671
672   Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
673   Offset = Builder.CreateAdd(PtrData.second, Offset);
674   return std::make_pair(PtrData.first, Offset);
675 }
676
677 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
678   // clueless
679   return unknown();
680 }
681
682 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
683   return unknown();
684 }
685
686 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
687   // create 2 PHIs: one for size and another for offset
688   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
689   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
690
691   // insert right away in the cache to handle recursive PHIs
692   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
693
694   // compute offset/size for each PHI incoming pointer
695   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
696     Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
697     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
698
699     if (!bothKnown(EdgeData)) {
700       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
701       OffsetPHI->eraseFromParent();
702       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
703       SizePHI->eraseFromParent();
704       return unknown();
705     }
706     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
707     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
708   }
709
710   Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
711   if ((Tmp = SizePHI->hasConstantValue())) {
712     Size = Tmp;
713     SizePHI->replaceAllUsesWith(Size);
714     SizePHI->eraseFromParent();
715   }
716   if ((Tmp = OffsetPHI->hasConstantValue())) {
717     Offset = Tmp;
718     OffsetPHI->replaceAllUsesWith(Offset);
719     OffsetPHI->eraseFromParent();
720   }
721   return std::make_pair(Size, Offset);
722 }
723
724 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
725   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
726   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
727
728   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
729     return unknown();
730   if (TrueSide == FalseSide)
731     return TrueSide;
732
733   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
734                                      FalseSide.first);
735   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
736                                        FalseSide.second);
737   return std::make_pair(Size, Offset);
738 }
739
740 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
741   DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
742   return unknown();
743 }