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