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