LCOV - code coverage report
Current view: top level - lib/Analysis - MemoryBuiltins.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 294 320 91.9 %
Date: 2018-05-20 00:06:23 Functions: 45 53 84.9 %
Legend: Lines: hit not hit

          Line data    Source code
       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/APInt.h"
      17             : #include "llvm/ADT/None.h"
      18             : #include "llvm/ADT/Optional.h"
      19             : #include "llvm/ADT/STLExtras.h"
      20             : #include "llvm/ADT/Statistic.h"
      21             : #include "llvm/ADT/StringRef.h"
      22             : #include "llvm/Analysis/TargetFolder.h"
      23             : #include "llvm/Analysis/TargetLibraryInfo.h"
      24             : #include "llvm/Analysis/Utils/Local.h"
      25             : #include "llvm/Analysis/ValueTracking.h"
      26             : #include "llvm/IR/Argument.h"
      27             : #include "llvm/IR/Attributes.h"
      28             : #include "llvm/IR/Constants.h"
      29             : #include "llvm/IR/DataLayout.h"
      30             : #include "llvm/IR/DerivedTypes.h"
      31             : #include "llvm/IR/Function.h"
      32             : #include "llvm/IR/GlobalAlias.h"
      33             : #include "llvm/IR/GlobalVariable.h"
      34             : #include "llvm/IR/Instruction.h"
      35             : #include "llvm/IR/Instructions.h"
      36             : #include "llvm/IR/IntrinsicInst.h"
      37             : #include "llvm/IR/Operator.h"
      38             : #include "llvm/IR/Type.h"
      39             : #include "llvm/IR/Value.h"
      40             : #include "llvm/Support/Casting.h"
      41             : #include "llvm/Support/Debug.h"
      42             : #include "llvm/Support/MathExtras.h"
      43             : #include "llvm/Support/raw_ostream.h"
      44             : #include <cassert>
      45             : #include <cstdint>
      46             : #include <iterator>
      47             : #include <utility>
      48             : 
      49             : using namespace llvm;
      50             : 
      51             : #define DEBUG_TYPE "memory-builtins"
      52             : 
      53             : enum AllocType : uint8_t {
      54             :   OpNewLike          = 1<<0, // allocates; never returns null
      55             :   MallocLike         = 1<<1 | OpNewLike, // allocates; may return null
      56             :   CallocLike         = 1<<2, // allocates + bzero
      57             :   ReallocLike        = 1<<3, // reallocates
      58             :   StrDupLike         = 1<<4,
      59             :   MallocOrCallocLike = MallocLike | CallocLike,
      60             :   AllocLike          = MallocLike | CallocLike | StrDupLike,
      61             :   AnyAlloc           = AllocLike | ReallocLike
      62             : };
      63             : 
      64             : struct AllocFnsTy {
      65             :   AllocType AllocTy;
      66             :   unsigned NumParams;
      67             :   // First and Second size parameters (or -1 if unused)
      68             :   int FstParam, SndParam;
      69             : };
      70             : 
      71             : // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
      72             : // know which functions are nounwind, noalias, nocapture parameters, etc.
      73             : static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
      74             :   {LibFunc_malloc,              {MallocLike,  1, 0,  -1}},
      75             :   {LibFunc_valloc,              {MallocLike,  1, 0,  -1}},
      76             :   {LibFunc_Znwj,                {OpNewLike,   1, 0,  -1}}, // new(unsigned int)
      77             :   {LibFunc_ZnwjRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new(unsigned int, nothrow)
      78             :   {LibFunc_ZnwjSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new(unsigned int, align_val_t)
      79             :   {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow)
      80             :                                 {MallocLike,  3, 0,  -1}},
      81             :   {LibFunc_Znwm,                {OpNewLike,   1, 0,  -1}}, // new(unsigned long)
      82             :   {LibFunc_ZnwmRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new(unsigned long, nothrow)
      83             :   {LibFunc_ZnwmSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new(unsigned long, align_val_t)
      84             :   {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow)
      85             :                                 {MallocLike,  3, 0,  -1}},
      86             :   {LibFunc_Znaj,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned int)
      87             :   {LibFunc_ZnajRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned int, nothrow)
      88             :   {LibFunc_ZnajSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new[](unsigned int, align_val_t)
      89             :   {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow)
      90             :                                 {MallocLike,  3, 0,  -1}},
      91             :   {LibFunc_Znam,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned long)
      92             :   {LibFunc_ZnamRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned long, nothrow)
      93             :   {LibFunc_ZnamSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new[](unsigned long, align_val_t)
      94             :   {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow)
      95             :                                  {MallocLike,  3, 0,  -1}},
      96             :   {LibFunc_msvc_new_int,         {OpNewLike,   1, 0,  -1}}, // new(unsigned int)
      97             :   {LibFunc_msvc_new_int_nothrow, {MallocLike,  2, 0,  -1}}, // new(unsigned int, nothrow)
      98             :   {LibFunc_msvc_new_longlong,         {OpNewLike,   1, 0,  -1}}, // new(unsigned long long)
      99             :   {LibFunc_msvc_new_longlong_nothrow, {MallocLike,  2, 0,  -1}}, // new(unsigned long long, nothrow)
     100             :   {LibFunc_msvc_new_array_int,         {OpNewLike,   1, 0,  -1}}, // new[](unsigned int)
     101             :   {LibFunc_msvc_new_array_int_nothrow, {MallocLike,  2, 0,  -1}}, // new[](unsigned int, nothrow)
     102             :   {LibFunc_msvc_new_array_longlong,         {OpNewLike,   1, 0,  -1}}, // new[](unsigned long long)
     103             :   {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike,  2, 0,  -1}}, // new[](unsigned long long, nothrow)
     104             :   {LibFunc_calloc,              {CallocLike,  2, 0,   1}},
     105             :   {LibFunc_realloc,             {ReallocLike, 2, 1,  -1}},
     106             :   {LibFunc_reallocf,            {ReallocLike, 2, 1,  -1}},
     107             :   {LibFunc_strdup,              {StrDupLike,  1, -1, -1}},
     108             :   {LibFunc_strndup,             {StrDupLike,  2, 1,  -1}}
     109             :   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
     110             : };
     111             : 
     112    52246117 : static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
     113             :                                          bool &IsNoBuiltin) {
     114             :   // Don't care about intrinsics in this case.
     115             :   if (isa<IntrinsicInst>(V))
     116             :     return nullptr;
     117             : 
     118    44907097 :   if (LookThroughBitCast)
     119           0 :     V = V->stripPointerCasts();
     120             : 
     121             :   ImmutableCallSite CS(V);
     122    44907097 :   if (!CS.getInstruction())
     123             :     return nullptr;
     124             : 
     125    12558296 :   IsNoBuiltin = CS.isNoBuiltin();
     126             : 
     127             :   if (const Function *Callee = CS.getCalledFunction())
     128             :     return Callee;
     129      121898 :   return nullptr;
     130             : }
     131             : 
     132             : /// Returns the allocation data for the given value if it's either a call to a
     133             : /// known allocation function, or a call to a function with the allocsize
     134             : /// attribute.
     135             : static Optional<AllocFnsTy>
     136     7179826 : getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
     137             :                              const TargetLibraryInfo *TLI) {
     138             :   // Make sure that the function is available.
     139     7179826 :   StringRef FnName = Callee->getName();
     140             :   LibFunc TLIFn;
     141    14436345 :   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
     142             :     return None;
     143             : 
     144             :   const auto *Iter = find_if(
     145             :       AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
     146             :         return P.first == TLIFn;
     147             :       });
     148             : 
     149      191267 :   if (Iter == std::end(AllocationFnData))
     150             :     return None;
     151             : 
     152             :   const AllocFnsTy *FnData = &Iter->second;
     153       29294 :   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
     154             :     return None;
     155             : 
     156             :   // Check function prototype.
     157       28993 :   int FstParam = FnData->FstParam;
     158       28993 :   int SndParam = FnData->SndParam;
     159             :   FunctionType *FTy = Callee->getFunctionType();
     160             : 
     161       86977 :   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
     162       86956 :       FTy->getNumParams() == FnData->NumParams &&
     163       28832 :       (FstParam < 0 ||
     164       74282 :        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
     165       91203 :         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
     166         100 :       (SndParam < 0 ||
     167         289 :        FTy->getParamType(SndParam)->isIntegerTy(32) ||
     168         178 :        FTy->getParamType(SndParam)->isIntegerTy(64)))
     169             :     return *FnData;
     170             :   return None;
     171             : }
     172             : 
     173    31150316 : static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
     174             :                                               const TargetLibraryInfo *TLI,
     175             :                                               bool LookThroughBitCast = false) {
     176             :   bool IsNoBuiltinCall;
     177    31150317 :   if (const Function *Callee =
     178    31150316 :           getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
     179     7258289 :     if (!IsNoBuiltinCall)
     180     7177258 :       return getAllocationDataForFunction(Callee, AllocTy, TLI);
     181             :   return None;
     182             : }
     183             : 
     184        7445 : static Optional<AllocFnsTy> getAllocationSize(const Value *V,
     185             :                                               const TargetLibraryInfo *TLI) {
     186             :   bool IsNoBuiltinCall;
     187             :   const Function *Callee =
     188        7445 :       getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
     189        7445 :   if (!Callee)
     190             :     return None;
     191             : 
     192             :   // Prefer to use existing information over allocsize. This will give us an
     193             :   // accurate AllocTy.
     194        6866 :   if (!IsNoBuiltinCall)
     195        2568 :     if (Optional<AllocFnsTy> Data =
     196        2568 :             getAllocationDataForFunction(Callee, AnyAlloc, TLI))
     197             :       return Data;
     198             : 
     199        4715 :   Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
     200        4715 :   if (Attr == Attribute())
     201             :     return None;
     202             : 
     203          18 :   std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
     204             : 
     205             :   AllocFnsTy Result;
     206             :   // Because allocsize only tells us how many bytes are allocated, we're not
     207             :   // really allowed to assume anything, so we use MallocLike.
     208             :   Result.AllocTy = MallocLike;
     209             :   Result.NumParams = Callee->getNumOperands();
     210          18 :   Result.FstParam = Args.first;
     211          18 :   Result.SndParam = Args.second.getValueOr(-1);
     212             :   return Result;
     213             : }
     214             : 
     215     8110810 : static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
     216     8110810 :   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
     217     8110810 :   return CS && CS.hasRetAttr(Attribute::NoAlias);
     218             : }
     219             : 
     220             : /// Tests if a value is a call or invoke to a library function that
     221             : /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
     222             : /// like).
     223     8117620 : bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
     224             :                           bool LookThroughBitCast) {
     225     8117620 :   return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
     226             : }
     227             : 
     228             : /// Tests if a value is a call or invoke to a function that returns a
     229             : /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
     230     8112485 : bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
     231             :                        bool LookThroughBitCast) {
     232             :   // it's safe to consider realloc as noalias since accessing the original
     233             :   // pointer is undefined behavior
     234    16223295 :   return isAllocationFn(V, TLI, LookThroughBitCast) ||
     235    16223295 :          hasNoAliasAttr(V, LookThroughBitCast);
     236             : }
     237             : 
     238             : /// Tests if a value is a call or invoke to a library function that
     239             : /// allocates uninitialized memory (such as malloc).
     240       24553 : bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
     241             :                           bool LookThroughBitCast) {
     242       24553 :   return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
     243             : }
     244             : 
     245             : /// Tests if a value is a call or invoke to a library function that
     246             : /// allocates zero-filled memory (such as calloc).
     247       31911 : bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
     248             :                           bool LookThroughBitCast) {
     249       31911 :   return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
     250             : }
     251             : 
     252             : /// Tests if a value is a call or invoke to a library function that
     253             : /// allocates memory similar to malloc or calloc.
     254     4317267 : bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
     255             :                                   bool LookThroughBitCast) {
     256     8634534 :   return getAllocationData(V, MallocOrCallocLike, TLI,
     257     8634534 :                            LookThroughBitCast).hasValue();
     258             : }
     259             : 
     260             : /// Tests if a value is a call or invoke to a library function that
     261             : /// allocates memory (either malloc, calloc, or strdup like).
     262    18658965 : bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
     263             :                          bool LookThroughBitCast) {
     264    18658965 :   return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
     265             : }
     266             : 
     267             : /// extractMallocCall - Returns the corresponding CallInst if the instruction
     268             : /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
     269             : /// ignore InvokeInst here.
     270          86 : const CallInst *llvm::extractMallocCall(const Value *I,
     271             :                                         const TargetLibraryInfo *TLI) {
     272         172 :   return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
     273             : }
     274             : 
     275          26 : static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
     276             :                                const TargetLibraryInfo *TLI,
     277             :                                bool LookThroughSExt = false) {
     278          26 :   if (!CI)
     279             :     return nullptr;
     280             : 
     281             :   // The size of the malloc's result type must be known to determine array size.
     282          26 :   Type *T = getMallocAllocatedType(CI, TLI);
     283          26 :   if (!T || !T->isSized())
     284             :     return nullptr;
     285             : 
     286          26 :   unsigned ElementSize = DL.getTypeAllocSize(T);
     287             :   if (StructType *ST = dyn_cast<StructType>(T))
     288          14 :     ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
     289             : 
     290             :   // If malloc call's arg can be determined to be a multiple of ElementSize,
     291             :   // return the multiple.  Otherwise, return NULL.
     292          26 :   Value *MallocArg = CI->getArgOperand(0);
     293          26 :   Value *Multiple = nullptr;
     294          26 :   if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
     295          18 :     return Multiple;
     296             : 
     297             :   return nullptr;
     298             : }
     299             : 
     300             : /// getMallocType - Returns the PointerType resulting from the malloc call.
     301             : /// The PointerType depends on the number of bitcast uses of the malloc call:
     302             : ///   0: PointerType is the calls' return type.
     303             : ///   1: PointerType is the bitcast's result type.
     304             : ///  >1: Unique PointerType cannot be determined, return NULL.
     305          81 : PointerType *llvm::getMallocType(const CallInst *CI,
     306             :                                  const TargetLibraryInfo *TLI) {
     307             :   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
     308             : 
     309             :   PointerType *MallocType = nullptr;
     310             :   unsigned NumOfBitCastUses = 0;
     311             : 
     312             :   // Determine if CallInst has a bitcast use.
     313             :   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
     314         162 :        UI != E;)
     315             :     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
     316             :       MallocType = cast<PointerType>(BCI->getDestTy());
     317          81 :       NumOfBitCastUses++;
     318             :     }
     319             : 
     320             :   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
     321          81 :   if (NumOfBitCastUses == 1)
     322             :     return MallocType;
     323             : 
     324             :   // Malloc call was not bitcast, so type is the malloc function's return type.
     325           0 :   if (NumOfBitCastUses == 0)
     326           0 :     return cast<PointerType>(CI->getType());
     327             : 
     328             :   // Type could not be determined.
     329             :   return nullptr;
     330             : }
     331             : 
     332             : /// getMallocAllocatedType - Returns the Type allocated by malloc call.
     333             : /// The Type depends on the number of bitcast uses of the malloc call:
     334             : ///   0: PointerType is the malloc calls' return type.
     335             : ///   1: PointerType is the bitcast's result type.
     336             : ///  >1: Unique PointerType cannot be determined, return NULL.
     337          81 : Type *llvm::getMallocAllocatedType(const CallInst *CI,
     338             :                                    const TargetLibraryInfo *TLI) {
     339          81 :   PointerType *PT = getMallocType(CI, TLI);
     340          81 :   return PT ? PT->getElementType() : nullptr;
     341             : }
     342             : 
     343             : /// getMallocArraySize - Returns the array size of a malloc call.  If the
     344             : /// argument passed to malloc is a multiple of the size of the malloced type,
     345             : /// then return that multiple.  For non-array mallocs, the multiple is
     346             : /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
     347             : /// determined.
     348          26 : Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
     349             :                                 const TargetLibraryInfo *TLI,
     350             :                                 bool LookThroughSExt) {
     351             :   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
     352          26 :   return computeArraySize(CI, DL, TLI, LookThroughSExt);
     353             : }
     354             : 
     355             : /// extractCallocCall - Returns the corresponding CallInst if the instruction
     356             : /// is a calloc call.
     357           0 : const CallInst *llvm::extractCallocCall(const Value *I,
     358             :                                         const TargetLibraryInfo *TLI) {
     359           0 :   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
     360             : }
     361             : 
     362             : /// isFreeCall - Returns non-null if the value is a call to the builtin free()
     363    21088356 : const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
     364             :   bool IsNoBuiltinCall;
     365             :   const Function *Callee =
     366    21088356 :       getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
     367    21088357 :   if (Callee == nullptr || IsNoBuiltinCall)
     368             :     return nullptr;
     369             : 
     370     5099038 :   StringRef FnName = Callee->getName();
     371             :   LibFunc TLIFn;
     372    10265956 :   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
     373             :     return nullptr;
     374             : 
     375             :   unsigned ExpectedNumParams;
     376      181835 :   if (TLIFn == LibFunc_free ||
     377       38402 :       TLIFn == LibFunc_ZdlPv || // operator delete(void*)
     378       37941 :       TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
     379       37916 :       TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
     380       37914 :       TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
     381       37914 :       TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
     382             :       TLIFn == LibFunc_msvc_delete_array_ptr64)   // operator delete[](void*)
     383             :     ExpectedNumParams = 1;
     384       37914 :   else if (TLIFn == LibFunc_ZdlPvj ||              // delete(void*, uint)
     385       37910 :            TLIFn == LibFunc_ZdlPvm ||              // delete(void*, ulong)
     386       37907 :            TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
     387       37903 :            TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
     388       37901 :            TLIFn == LibFunc_ZdaPvj ||              // delete[](void*, uint)
     389       37899 :            TLIFn == LibFunc_ZdaPvm ||              // delete[](void*, ulong)
     390       37899 :            TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
     391       37895 :            TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
     392       37895 :            TLIFn == LibFunc_msvc_delete_ptr32_int ||      // delete(void*, uint)
     393       37895 :            TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
     394       37895 :            TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
     395       37895 :            TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
     396       37895 :            TLIFn == LibFunc_msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
     397       37895 :            TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
     398       37895 :            TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
     399             :            TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow)   // delete[](void*, nothrow)
     400             :     ExpectedNumParams = 2;
     401       37895 :   else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
     402             :            TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow)
     403             :     ExpectedNumParams = 3;
     404             :   else
     405             :     return nullptr;
     406             : 
     407             :   // Check free prototype.
     408             :   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
     409             :   // attribute will exist.
     410             :   FunctionType *FTy = Callee->getFunctionType();
     411      287904 :   if (!FTy->getReturnType()->isVoidTy())
     412             :     return nullptr;
     413      287904 :   if (FTy->getNumParams() != ExpectedNumParams)
     414             :     return nullptr;
     415      143951 :   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
     416             :     return nullptr;
     417             : 
     418             :   return dyn_cast<CallInst>(I);
     419             : }
     420             : 
     421             : //===----------------------------------------------------------------------===//
     422             : //  Utility functions to compute size of objects.
     423             : //
     424     5773536 : static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
     425    17320608 :   if (Data.second.isNegative() || Data.first.ult(Data.second))
     426           0 :     return APInt(Data.first.getBitWidth(), 0);
     427     5773536 :   return Data.first - Data.second;
     428             : }
     429             : 
     430             : /// Compute the size of the object pointed by Ptr. Returns true and the
     431             : /// object size in Size if successful, and false otherwise.
     432             : /// If RoundToAlign is true, then Size is rounded up to the alignment of
     433             : /// allocas, byval arguments, and global variables.
     434     5952148 : bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
     435             :                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
     436    11904296 :   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
     437    11904296 :   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
     438             :   if (!Visitor.bothKnown(Data))
     439             :     return false;
     440             : 
     441    17320584 :   Size = getSizeWithOverflow(Data).getZExtValue();
     442     5773528 :   return true;
     443             : }
     444             : 
     445         119 : ConstantInt *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
     446             :                                        const DataLayout &DL,
     447             :                                        const TargetLibraryInfo *TLI,
     448             :                                        bool MustSucceed) {
     449             :   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
     450             :          "ObjectSize must be a call to llvm.objectsize!");
     451             : 
     452         119 :   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
     453         119 :   ObjectSizeOpts EvalOptions;
     454             :   // Unless we have to fold this to something, try to be as accurate as
     455             :   // possible.
     456         119 :   if (MustSucceed)
     457          30 :     EvalOptions.EvalMode =
     458          30 :         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
     459             :   else
     460             :     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
     461             : 
     462         119 :   EvalOptions.NullIsUnknownSize =
     463             :       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
     464             : 
     465             :   // FIXME: Does it make sense to just return a failure value if the size won't
     466             :   // fit in the output and `!MustSucceed`?
     467             :   uint64_t Size;
     468         119 :   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
     469         119 :   if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
     470          61 :       isUIntN(ResultType->getBitWidth(), Size))
     471          56 :     return ConstantInt::get(ResultType, Size);
     472             : 
     473          63 :   if (!MustSucceed)
     474             :     return nullptr;
     475             : 
     476          18 :   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
     477             : }
     478             : 
     479             : STATISTIC(ObjectVisitorArgument,
     480             :           "Number of arguments with unsolved size and offset");
     481             : STATISTIC(ObjectVisitorLoad,
     482             :           "Number of load instructions with unsolved size and offset");
     483             : 
     484     5771571 : APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
     485     5771571 :   if (Options.RoundToAlign && Align)
     486      538931 :     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
     487             :   return Size;
     488             : }
     489             : 
     490     5952962 : ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
     491             :                                                  const TargetLibraryInfo *TLI,
     492             :                                                  LLVMContext &Context,
     493     5952962 :                                                  ObjectSizeOpts Options)
     494     5952962 :     : DL(DL), TLI(TLI), Options(Options) {
     495             :   // Pointer size must be rechecked for each object visited since it could have
     496             :   // a different address space.
     497     5952962 : }
     498             : 
     499     5952417 : SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
     500     5952417 :   IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
     501    11904834 :   Zero = APInt::getNullValue(IntTyBits);
     502             : 
     503             :   V = V->stripPointerCasts();
     504             :   if (Instruction *I = dyn_cast<Instruction>(V)) {
     505             :     // If we have already seen this instruction, bail out. Cycles can happen in
     506             :     // unreachable code after constant propagation.
     507      563762 :     if (!SeenInsts.insert(I).second)
     508             :       return unknown();
     509             : 
     510             :     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
     511          57 :       return visitGEPOperator(*GEP);
     512      563698 :     return visit(*I);
     513             :   }
     514             :   if (Argument *A = dyn_cast<Argument>(V))
     515       27790 :     return visitArgument(*A);
     516             :   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
     517          15 :     return visitConstantPointerNull(*P);
     518             :   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
     519           2 :     return visitGlobalAlias(*GA);
     520             :   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
     521     5360789 :     return visitGlobalVariable(*GV);
     522             :   if (UndefValue *UV = dyn_cast<UndefValue>(V))
     523          10 :     return visitUndefValue(*UV);
     524             :   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
     525          12 :     if (CE->getOpcode() == Instruction::IntToPtr)
     526             :       return unknown(); // clueless
     527          12 :     if (CE->getOpcode() == Instruction::GetElementPtr)
     528          12 :       return visitGEPOperator(cast<GEPOperator>(*CE));
     529             :   }
     530             : 
     531             :   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
     532             :                     << *V << '\n');
     533             :   return unknown();
     534             : }
     535             : 
     536             : /// When we're compiling N-bit code, and the user uses parameters that are
     537             : /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
     538             : /// trouble with APInt size issues. This function handles resizing + overflow
     539             : /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
     540             : /// I's value.
     541        2125 : bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
     542             :   // More bits than we can handle. Checking the bit width isn't necessary, but
     543             :   // it's faster than checking active bits, and should give `false` in the
     544             :   // vast majority of cases.
     545        2130 :   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
     546             :     return false;
     547        2122 :   if (I.getBitWidth() != IntTyBits)
     548          82 :     I = I.zextOrTrunc(IntTyBits);
     549             :   return true;
     550             : }
     551             : 
     552      552511 : SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
     553      552511 :   if (!I.getAllocatedType()->isSized())
     554             :     return unknown();
     555             : 
     556      552511 :   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
     557      552511 :   if (!I.isArrayAllocation())
     558     2762080 :     return std::make_pair(align(Size, I.getAlignment()), Zero);
     559             : 
     560             :   Value *ArraySize = I.getArraySize();
     561             :   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
     562             :     APInt NumElems = C->getValue();
     563          53 :     if (!CheckedZextOrTrunc(NumElems))
     564             :       return unknown();
     565             : 
     566             :     bool Overflow;
     567         104 :     Size = Size.umul_ov(NumElems, Overflow);
     568         208 :     return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
     569         104 :                                                  Zero);
     570             :   }
     571             :   return unknown();
     572             : }
     573             : 
     574       27790 : SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
     575             :   // No interprocedural analysis is done at the moment.
     576       27790 :   if (!A.hasByValOrInAllocaAttr()) {
     577             :     ++ObjectVisitorArgument;
     578             :     return unknown();
     579             :   }
     580        1858 :   PointerType *PT = cast<PointerType>(A.getType());
     581        1858 :   APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
     582        7432 :   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
     583             : }
     584             : 
     585        7439 : SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
     586       14878 :   Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
     587        7439 :   if (!FnData)
     588             :     return unknown();
     589             : 
     590             :   // Handle strdup-like functions separately.
     591        2163 :   if (FnData->AllocTy == StrDupLike) {
     592           5 :     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
     593           5 :     if (!Size)
     594             :       return unknown();
     595             : 
     596             :     // Strndup limits strlen.
     597           5 :     if (FnData->FstParam > 0) {
     598             :       ConstantInt *Arg =
     599           4 :           dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
     600             :       if (!Arg)
     601           0 :         return unknown();
     602             : 
     603           4 :       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
     604           4 :       if (Size.ugt(MaxSize))
     605           2 :         Size = MaxSize + 1;
     606             :     }
     607           5 :     return std::make_pair(Size, Zero);
     608             :   }
     609             : 
     610        2158 :   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
     611             :   if (!Arg)
     612             :     return unknown();
     613             : 
     614             :   APInt Size = Arg->getValue();
     615        2064 :   if (!CheckedZextOrTrunc(Size))
     616             :     return unknown();
     617             : 
     618             :   // Size is determined by just 1 parameter.
     619        2062 :   if (FnData->SndParam < 0)
     620        2045 :     return std::make_pair(Size, Zero);
     621             : 
     622          17 :   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
     623             :   if (!Arg)
     624             :     return unknown();
     625             : 
     626             :   APInt NumElems = Arg->getValue();
     627           8 :   if (!CheckedZextOrTrunc(NumElems))
     628             :     return unknown();
     629             : 
     630             :   bool Overflow;
     631          16 :   Size = Size.umul_ov(NumElems, Overflow);
     632          16 :   return Overflow ? unknown() : std::make_pair(Size, Zero);
     633             : 
     634             :   // TODO: handle more standard functions (+ wchar cousins):
     635             :   // - strdup / strndup
     636             :   // - strcpy / strncpy
     637             :   // - strcat / strncat
     638             :   // - memcpy / memmove
     639             :   // - strcat / strncat
     640             :   // - memset
     641             : }
     642             : 
     643             : SizeOffsetType
     644          15 : ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
     645          23 :   if (Options.NullIsUnknownSize && CPN.getType()->getAddressSpace() == 0)
     646             :     return unknown();
     647          11 :   return std::make_pair(Zero, Zero);
     648             : }
     649             : 
     650             : SizeOffsetType
     651           0 : ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
     652           0 :   return unknown();
     653             : }
     654             : 
     655             : SizeOffsetType
     656           0 : ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
     657             :   // Easy cases were already folded by previous passes.
     658           0 :   return unknown();
     659             : }
     660             : 
     661          69 : SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
     662         138 :   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
     663          69 :   APInt Offset(IntTyBits, 0);
     664          43 :   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
     665             :     return unknown();
     666             : 
     667          36 :   return std::make_pair(PtrData.first, PtrData.second + Offset);
     668             : }
     669             : 
     670           2 : SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
     671             :   if (GA.isInterposable())
     672             :     return unknown();
     673           0 :   return compute(GA.getAliasee());
     674             : }
     675             : 
     676     5360789 : SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
     677     5360789 :   if (!GV.hasDefinitiveInitializer())
     678             :     return unknown();
     679             : 
     680    10434490 :   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
     681    26086225 :   return std::make_pair(align(Size, GV.getAlignment()), Zero);
     682             : }
     683             : 
     684          13 : SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
     685             :   // clueless
     686          13 :   return unknown();
     687             : }
     688             : 
     689         801 : SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
     690             :   ++ObjectVisitorLoad;
     691         801 :   return unknown();
     692             : }
     693             : 
     694        2922 : SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
     695             :   // too complex to analyze statically.
     696        2922 :   return unknown();
     697             : }
     698             : 
     699          12 : SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
     700          24 :   SizeOffsetType TrueSide  = compute(I.getTrueValue());
     701          24 :   SizeOffsetType FalseSide = compute(I.getFalseValue());
     702             :   if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
     703           6 :     if (TrueSide == FalseSide) {
     704           6 :         return TrueSide;
     705             :     }
     706             : 
     707           4 :     APInt TrueResult = getSizeWithOverflow(TrueSide);
     708           4 :     APInt FalseResult = getSizeWithOverflow(FalseSide);
     709             : 
     710           4 :     if (TrueResult == FalseResult) {
     711             :       return TrueSide;
     712             :     }
     713           3 :     if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
     714           1 :       if (TrueResult.slt(FalseResult))
     715             :         return TrueSide;
     716             :       return FalseSide;
     717             :     }
     718           2 :     if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
     719           2 :       if (TrueResult.sgt(FalseResult))
     720             :         return TrueSide;
     721             :       return FalseSide;
     722             :     }
     723             :   }
     724             :   return unknown();
     725             : }
     726             : 
     727          10 : SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
     728          20 :   return std::make_pair(Zero, Zero);
     729             : }
     730             : 
     731           0 : SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
     732             :   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
     733             :                     << '\n');
     734           0 :   return unknown();
     735             : }
     736             : 
     737          44 : ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
     738             :     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
     739          44 :     bool RoundToAlign)
     740             :     : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
     741         132 :       RoundToAlign(RoundToAlign) {
     742             :   // IntTy and Zero must be set for each compute() since the address space may
     743             :   // be different for later objects.
     744          44 : }
     745             : 
     746          76 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
     747             :   // XXX - Are vectors of pointers possible here?
     748          76 :   IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
     749          76 :   Zero = ConstantInt::get(IntTy, 0);
     750             : 
     751          76 :   SizeOffsetEvalType Result = compute_(V);
     752             : 
     753             :   if (!bothKnown(Result)) {
     754             :     // Erase everything that was computed in this iteration from the cache, so
     755             :     // that no dangling references are left behind. We could be a bit smarter if
     756             :     // we kept a dependency graph. It's probably not worth the complexity.
     757          12 :     for (const Value *SeenVal : SeenVals) {
     758          18 :       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
     759             :       // non-computable results can be safely cached
     760          18 :       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
     761             :         CacheMap.erase(CacheIt);
     762             :     }
     763             :   }
     764             : 
     765          76 :   SeenVals.clear();
     766          76 :   return Result;
     767             : }
     768             : 
     769         114 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
     770         114 :   ObjectSizeOpts ObjSizeOptions;
     771         114 :   ObjSizeOptions.RoundToAlign = RoundToAlign;
     772             : 
     773         228 :   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
     774         228 :   SizeOffsetType Const = Visitor.compute(V);
     775             :   if (Visitor.bothKnown(Const))
     776          48 :     return std::make_pair(ConstantInt::get(Context, Const.first),
     777          96 :                           ConstantInt::get(Context, Const.second));
     778             : 
     779             :   V = V->stripPointerCasts();
     780             : 
     781             :   // Check cache.
     782          66 :   CacheMapTy::iterator CacheIt = CacheMap.find(V);
     783          66 :   if (CacheIt != CacheMap.end())
     784          12 :     return CacheIt->second;
     785             : 
     786             :   // Always generate code immediately before the instruction being
     787             :   // processed, so that the generated code dominates the same BBs.
     788         108 :   BuilderTy::InsertPointGuard Guard(Builder);
     789             :   if (Instruction *I = dyn_cast<Instruction>(V))
     790          50 :     Builder.SetInsertPoint(I);
     791             : 
     792             :   // Now compute the size and offset.
     793             :   SizeOffsetEvalType Result;
     794             : 
     795             :   // Record the pointers that were handled in this run, so that they can be
     796             :   // cleaned later if something fails. We also use this set to break cycles that
     797             :   // can occur in dead code.
     798          54 :   if (!SeenVals.insert(V).second) {
     799             :     Result = unknown();
     800             :   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
     801          44 :     Result = visitGEPOperator(*GEP);
     802             :   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
     803          52 :     Result = visit(*I);
     804           0 :   } else if (isa<Argument>(V) ||
     805             :              (isa<ConstantExpr>(V) &&
     806             :               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
     807           4 :              isa<GlobalAlias>(V) ||
     808             :              isa<GlobalVariable>(V)) {
     809             :     // Ignore values where we cannot do more than ObjectSizeVisitor.
     810             :     Result = unknown();
     811             :   } else {
     812             :     LLVM_DEBUG(
     813             :         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
     814             :                << '\n');
     815             :     Result = unknown();
     816             :   }
     817             : 
     818             :   // Don't reuse CacheIt since it may be invalid at this point.
     819         108 :   CacheMap[V] = Result;
     820          54 :   return Result;
     821             : }
     822             : 
     823          10 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
     824          10 :   if (!I.getAllocatedType()->isSized())
     825             :     return unknown();
     826             : 
     827             :   // must be a VLA
     828             :   assert(I.isArrayAllocation());
     829             :   Value *ArraySize = I.getArraySize();
     830          10 :   Value *Size = ConstantInt::get(ArraySize->getType(),
     831          10 :                                  DL.getTypeAllocSize(I.getAllocatedType()));
     832          20 :   Size = Builder.CreateMul(Size, ArraySize);
     833          10 :   return std::make_pair(Size, Zero);
     834             : }
     835             : 
     836           6 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
     837          12 :   Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
     838           6 :   if (!FnData)
     839             :     return unknown();
     840             : 
     841             :   // Handle strdup-like functions separately.
     842           6 :   if (FnData->AllocTy == StrDupLike) {
     843             :     // TODO
     844             :     return unknown();
     845             :   }
     846             : 
     847           6 :   Value *FirstArg = CS.getArgument(FnData->FstParam);
     848          18 :   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
     849           6 :   if (FnData->SndParam < 0)
     850           2 :     return std::make_pair(FirstArg, Zero);
     851             : 
     852           4 :   Value *SecondArg = CS.getArgument(FnData->SndParam);
     853           8 :   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
     854           4 :   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
     855           4 :   return std::make_pair(Size, Zero);
     856             : 
     857             :   // TODO: handle more standard functions (+ wchar cousins):
     858             :   // - strdup / strndup
     859             :   // - strcpy / strncpy
     860             :   // - strcat / strncat
     861             :   // - memcpy / memmove
     862             :   // - strcat / strncat
     863             :   // - memset
     864             : }
     865             : 
     866             : SizeOffsetEvalType
     867           0 : ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
     868           0 :   return unknown();
     869             : }
     870             : 
     871             : SizeOffsetEvalType
     872           0 : ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
     873           0 :   return unknown();
     874             : }
     875             : 
     876             : SizeOffsetEvalType
     877          22 : ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
     878          22 :   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
     879             :   if (!bothKnown(PtrData))
     880             :     return unknown();
     881             : 
     882          16 :   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
     883          16 :   Offset = Builder.CreateAdd(PtrData.second, Offset);
     884             :   return std::make_pair(PtrData.first, Offset);
     885             : }
     886             : 
     887           0 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
     888             :   // clueless
     889           0 :   return unknown();
     890             : }
     891             : 
     892           2 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
     893           2 :   return unknown();
     894             : }
     895             : 
     896           4 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
     897             :   // Create 2 PHIs: one for size and another for offset.
     898           8 :   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
     899           4 :   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
     900             : 
     901             :   // Insert right away in the cache to handle recursive PHIs.
     902           8 :   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
     903             : 
     904             :   // Compute offset/size for each PHI incoming pointer.
     905          16 :   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
     906          16 :     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
     907           8 :     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
     908             : 
     909             :     if (!bothKnown(EdgeData)) {
     910           2 :       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
     911           2 :       OffsetPHI->eraseFromParent();
     912           2 :       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
     913           2 :       SizePHI->eraseFromParent();
     914             :       return unknown();
     915             :     }
     916           6 :     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
     917           6 :     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
     918             :   }
     919             : 
     920             :   Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
     921           2 :   if ((Tmp = SizePHI->hasConstantValue())) {
     922             :     Size = Tmp;
     923           2 :     SizePHI->replaceAllUsesWith(Size);
     924           2 :     SizePHI->eraseFromParent();
     925             :   }
     926           2 :   if ((Tmp = OffsetPHI->hasConstantValue())) {
     927             :     Offset = Tmp;
     928           0 :     OffsetPHI->replaceAllUsesWith(Offset);
     929           0 :     OffsetPHI->eraseFromParent();
     930             :   }
     931             :   return std::make_pair(Size, Offset);
     932             : }
     933             : 
     934           4 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
     935           4 :   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
     936           4 :   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
     937             : 
     938             :   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
     939             :     return unknown();
     940             :   if (TrueSide == FalseSide)
     941           0 :     return TrueSide;
     942             : 
     943           4 :   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
     944             :                                      FalseSide.first);
     945           2 :   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
     946             :                                        FalseSide.second);
     947             :   return std::make_pair(Size, Offset);
     948             : }
     949             : 
     950           0 : SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
     951             :   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
     952             :                     << '\n');
     953           0 :   return unknown();
     954             : }

Generated by: LCOV version 1.13