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