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