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