1 //===- MemoryBuiltins.cpp - Identify calls to memory builtins -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This family of functions identifies calls to builtin functions that allocate
10 // or free memory.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/MemoryBuiltins.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/TargetFolder.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/Utils/Local.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/Argument.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <cassert>
43 #include <cstdint>
44 #include <iterator>
45 #include <numeric>
46 #include <type_traits>
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, // allocates; may return null
56   AlignedAllocLike   = 1<<2, // allocates with alignment; may return null
57   CallocLike         = 1<<3, // allocates + bzero
58   ReallocLike        = 1<<4, // reallocates
59   StrDupLike         = 1<<5,
60   MallocOrOpNewLike  = MallocLike | OpNewLike,
61   MallocOrCallocLike = MallocLike | OpNewLike | CallocLike | AlignedAllocLike,
62   AllocLike          = MallocOrCallocLike | StrDupLike,
63   AnyAlloc           = AllocLike | ReallocLike
64 };
65 
66 enum class MallocFamily {
67   Malloc,
68   CPPNew,             // new(unsigned int)
69   CPPNewAligned,      // new(unsigned int, align_val_t)
70   CPPNewArray,        // new[](unsigned int)
71   CPPNewArrayAligned, // new[](unsigned long, align_val_t)
72   MSVCNew,            // new(unsigned int)
73   MSVCArrayNew,       // new[](unsigned int)
74   VecMalloc,
75   KmpcAllocShared,
76 };
77 
78 StringRef mangledNameForMallocFamily(const MallocFamily &Family) {
79   switch (Family) {
80   case MallocFamily::Malloc:
81     return "malloc";
82   case MallocFamily::CPPNew:
83     return "_Znwm";
84   case MallocFamily::CPPNewAligned:
85     return "_ZnwmSt11align_val_t";
86   case MallocFamily::CPPNewArray:
87     return "_Znam";
88   case MallocFamily::CPPNewArrayAligned:
89     return "_ZnamSt11align_val_t";
90   case MallocFamily::MSVCNew:
91     return "??2@YAPAXI@Z";
92   case MallocFamily::MSVCArrayNew:
93     return "??_U@YAPAXI@Z";
94   case MallocFamily::VecMalloc:
95     return "vec_malloc";
96   case MallocFamily::KmpcAllocShared:
97     return "__kmpc_alloc_shared";
98   }
99   llvm_unreachable("missing an alloc family");
100 }
101 
102 struct AllocFnsTy {
103   AllocType AllocTy;
104   unsigned NumParams;
105   // First and Second size parameters (or -1 if unused)
106   int FstParam, SndParam;
107   // Alignment parameter for aligned_alloc and aligned new
108   int AlignParam;
109   // Name of default allocator function to group malloc/free calls by family
110   MallocFamily Family;
111 };
112 
113 // clang-format off
114 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
115 // know which functions are nounwind, noalias, nocapture parameters, etc.
116 static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
117     {LibFunc_malloc,                            {MallocLike,       1,  0, -1, -1, MallocFamily::Malloc}},
118     {LibFunc_vec_malloc,                        {MallocLike,       1,  0, -1, -1, MallocFamily::VecMalloc}},
119     {LibFunc_valloc,                            {MallocLike,       1,  0, -1, -1, MallocFamily::Malloc}},
120     {LibFunc_Znwj,                              {OpNewLike,        1,  0, -1, -1, MallocFamily::CPPNew}},             // new(unsigned int)
121     {LibFunc_ZnwjRKSt9nothrow_t,                {MallocLike,       2,  0, -1, -1, MallocFamily::CPPNew}},             // new(unsigned int, nothrow)
122     {LibFunc_ZnwjSt11align_val_t,               {OpNewLike,        2,  0, -1,  1, MallocFamily::CPPNewAligned}},      // new(unsigned int, align_val_t)
123     {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, {MallocLike,       3,  0, -1,  1, MallocFamily::CPPNewAligned}},      // new(unsigned int, align_val_t, nothrow)
124     {LibFunc_Znwm,                              {OpNewLike,        1,  0, -1, -1, MallocFamily::CPPNew}},             // new(unsigned long)
125     {LibFunc_ZnwmRKSt9nothrow_t,                {MallocLike,       2,  0, -1, -1, MallocFamily::CPPNew}},             // new(unsigned long, nothrow)
126     {LibFunc_ZnwmSt11align_val_t,               {OpNewLike,        2,  0, -1,  1, MallocFamily::CPPNewAligned}},      // new(unsigned long, align_val_t)
127     {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, {MallocLike,       3,  0, -1,  1, MallocFamily::CPPNewAligned}},      // new(unsigned long, align_val_t, nothrow)
128     {LibFunc_Znaj,                              {OpNewLike,        1,  0, -1, -1, MallocFamily::CPPNewArray}},        // new[](unsigned int)
129     {LibFunc_ZnajRKSt9nothrow_t,                {MallocLike,       2,  0, -1, -1, MallocFamily::CPPNewArray}},        // new[](unsigned int, nothrow)
130     {LibFunc_ZnajSt11align_val_t,               {OpNewLike,        2,  0, -1,  1, MallocFamily::CPPNewArrayAligned}}, // new[](unsigned int, align_val_t)
131     {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, {MallocLike,       3,  0, -1,  1, MallocFamily::CPPNewArrayAligned}}, // new[](unsigned int, align_val_t, nothrow)
132     {LibFunc_Znam,                              {OpNewLike,        1,  0, -1, -1, MallocFamily::CPPNewArray}},        // new[](unsigned long)
133     {LibFunc_ZnamRKSt9nothrow_t,                {MallocLike,       2,  0, -1, -1, MallocFamily::CPPNewArray}},        // new[](unsigned long, nothrow)
134     {LibFunc_ZnamSt11align_val_t,               {OpNewLike,        2,  0, -1,  1, MallocFamily::CPPNewArrayAligned}}, // new[](unsigned long, align_val_t)
135     {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, {MallocLike,       3,  0, -1,  1, MallocFamily::CPPNewArrayAligned}}, // new[](unsigned long, align_val_t, nothrow)
136     {LibFunc_msvc_new_int,                      {OpNewLike,        1,  0, -1, -1, MallocFamily::MSVCNew}},            // new(unsigned int)
137     {LibFunc_msvc_new_int_nothrow,              {MallocLike,       2,  0, -1, -1, MallocFamily::MSVCNew}},            // new(unsigned int, nothrow)
138     {LibFunc_msvc_new_longlong,                 {OpNewLike,        1,  0, -1, -1, MallocFamily::MSVCNew}},            // new(unsigned long long)
139     {LibFunc_msvc_new_longlong_nothrow,         {MallocLike,       2,  0, -1, -1, MallocFamily::MSVCNew}},            // new(unsigned long long, nothrow)
140     {LibFunc_msvc_new_array_int,                {OpNewLike,        1,  0, -1, -1, MallocFamily::MSVCArrayNew}},       // new[](unsigned int)
141     {LibFunc_msvc_new_array_int_nothrow,        {MallocLike,       2,  0, -1, -1, MallocFamily::MSVCArrayNew}},       // new[](unsigned int, nothrow)
142     {LibFunc_msvc_new_array_longlong,           {OpNewLike,        1,  0, -1, -1, MallocFamily::MSVCArrayNew}},       // new[](unsigned long long)
143     {LibFunc_msvc_new_array_longlong_nothrow,   {MallocLike,       2,  0, -1, -1, MallocFamily::MSVCArrayNew}},       // new[](unsigned long long, nothrow)
144     {LibFunc_aligned_alloc,                     {AlignedAllocLike, 2,  1, -1,  0, MallocFamily::Malloc}},
145     {LibFunc_memalign,                          {AlignedAllocLike, 2,  1, -1,  0, MallocFamily::Malloc}},
146     {LibFunc_calloc,                            {CallocLike,       2,  0,  1, -1, MallocFamily::Malloc}},
147     {LibFunc_vec_calloc,                        {CallocLike,       2,  0,  1, -1, MallocFamily::VecMalloc}},
148     {LibFunc_realloc,                           {ReallocLike,      2,  1, -1, -1, MallocFamily::Malloc}},
149     {LibFunc_vec_realloc,                       {ReallocLike,      2,  1, -1, -1, MallocFamily::VecMalloc}},
150     {LibFunc_reallocf,                          {ReallocLike,      2,  1, -1, -1, MallocFamily::Malloc}},
151     {LibFunc_strdup,                            {StrDupLike,       1, -1, -1, -1, MallocFamily::Malloc}},
152     {LibFunc_dunder_strdup,                     {StrDupLike,       1, -1, -1, -1, MallocFamily::Malloc}},
153     {LibFunc_strndup,                           {StrDupLike,       2,  1, -1, -1, MallocFamily::Malloc}},
154     {LibFunc_dunder_strndup,                    {StrDupLike,       2,  1, -1, -1, MallocFamily::Malloc}},
155     {LibFunc___kmpc_alloc_shared,               {MallocLike,       1,  0, -1, -1, MallocFamily::KmpcAllocShared}},
156     // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
157 };
158 // clang-format on
159 
160 static const Function *getCalledFunction(const Value *V,
161                                          bool &IsNoBuiltin) {
162   // Don't care about intrinsics in this case.
163   if (isa<IntrinsicInst>(V))
164     return nullptr;
165 
166   const auto *CB = dyn_cast<CallBase>(V);
167   if (!CB)
168     return nullptr;
169 
170   IsNoBuiltin = CB->isNoBuiltin();
171 
172   if (const Function *Callee = CB->getCalledFunction())
173     return Callee;
174   return nullptr;
175 }
176 
177 /// Returns the allocation data for the given value if it's a call to a known
178 /// allocation function.
179 static Optional<AllocFnsTy>
180 getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
181                              const TargetLibraryInfo *TLI) {
182   // Make sure that the function is available.
183   LibFunc TLIFn;
184   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
185     return None;
186 
187   const auto *Iter = find_if(
188       AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
189         return P.first == TLIFn;
190       });
191 
192   if (Iter == std::end(AllocationFnData))
193     return None;
194 
195   const AllocFnsTy *FnData = &Iter->second;
196   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
197     return None;
198 
199   // Check function prototype.
200   int FstParam = FnData->FstParam;
201   int SndParam = FnData->SndParam;
202   FunctionType *FTy = Callee->getFunctionType();
203 
204   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
205       FTy->getNumParams() == FnData->NumParams &&
206       (FstParam < 0 ||
207        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
208         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
209       (SndParam < 0 ||
210        FTy->getParamType(SndParam)->isIntegerTy(32) ||
211        FTy->getParamType(SndParam)->isIntegerTy(64)))
212     return *FnData;
213   return None;
214 }
215 
216 static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
217                                               const TargetLibraryInfo *TLI) {
218   bool IsNoBuiltinCall;
219   if (const Function *Callee = getCalledFunction(V, IsNoBuiltinCall))
220     if (!IsNoBuiltinCall)
221       return getAllocationDataForFunction(Callee, AllocTy, TLI);
222   return None;
223 }
224 
225 static Optional<AllocFnsTy>
226 getAllocationData(const Value *V, AllocType AllocTy,
227                   function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
228   bool IsNoBuiltinCall;
229   if (const Function *Callee = getCalledFunction(V, IsNoBuiltinCall))
230     if (!IsNoBuiltinCall)
231       return getAllocationDataForFunction(
232           Callee, AllocTy, &GetTLI(const_cast<Function &>(*Callee)));
233   return None;
234 }
235 
236 static Optional<AllocFnsTy> getAllocationSize(const Value *V,
237                                               const TargetLibraryInfo *TLI) {
238   bool IsNoBuiltinCall;
239   const Function *Callee =
240       getCalledFunction(V, IsNoBuiltinCall);
241   if (!Callee)
242     return None;
243 
244   // Prefer to use existing information over allocsize. This will give us an
245   // accurate AllocTy.
246   if (!IsNoBuiltinCall)
247     if (Optional<AllocFnsTy> Data =
248             getAllocationDataForFunction(Callee, AnyAlloc, TLI))
249       return Data;
250 
251   Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
252   if (Attr == Attribute())
253     return None;
254 
255   std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
256 
257   AllocFnsTy Result;
258   // Because allocsize only tells us how many bytes are allocated, we're not
259   // really allowed to assume anything, so we use MallocLike.
260   Result.AllocTy = MallocLike;
261   Result.NumParams = Callee->getNumOperands();
262   Result.FstParam = Args.first;
263   Result.SndParam = Args.second.getValueOr(-1);
264   // Allocsize has no way to specify an alignment argument
265   Result.AlignParam = -1;
266   return Result;
267 }
268 
269 /// Tests if a value is a call or invoke to a library function that
270 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
271 /// like).
272 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI) {
273   return getAllocationData(V, AnyAlloc, TLI).hasValue();
274 }
275 bool llvm::isAllocationFn(
276     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
277   return getAllocationData(V, AnyAlloc, GetTLI).hasValue();
278 }
279 
280 /// Tests if a value is a call or invoke to a library function that
281 /// allocates uninitialized memory (such as malloc).
282 static bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
283   return getAllocationData(V, MallocOrOpNewLike, TLI).hasValue();
284 }
285 
286 /// Tests if a value is a call or invoke to a library function that
287 /// allocates uninitialized memory with alignment (such as aligned_alloc).
288 static bool isAlignedAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
289   return getAllocationData(V, AlignedAllocLike, TLI)
290       .hasValue();
291 }
292 
293 /// Tests if a value is a call or invoke to a library function that
294 /// allocates zero-filled memory (such as calloc).
295 static bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
296   return getAllocationData(V, CallocLike, TLI).hasValue();
297 }
298 
299 /// Tests if a value is a call or invoke to a library function that
300 /// allocates memory similar to malloc or calloc.
301 bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
302   return getAllocationData(V, MallocOrCallocLike, TLI).hasValue();
303 }
304 
305 /// Tests if a value is a call or invoke to a library function that
306 /// allocates memory (either malloc, calloc, or strdup like).
307 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
308   return getAllocationData(V, AllocLike, TLI).hasValue();
309 }
310 
311 /// Tests if a value is a call or invoke to a library function that
312 /// reallocates memory (e.g., realloc).
313 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
314   return getAllocationData(V, ReallocLike, TLI).hasValue();
315 }
316 
317 /// Tests if a functions is a call or invoke to a library function that
318 /// reallocates memory (e.g., realloc).
319 bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
320   return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
321 }
322 
323 bool llvm::isAllocRemovable(const CallBase *CB, const TargetLibraryInfo *TLI) {
324   assert(isAllocationFn(CB, TLI));
325 
326   // Note: Removability is highly dependent on the source language.  For
327   // example, recent C++ requires direct calls to the global allocation
328   // [basic.stc.dynamic.allocation] to be observable unless part of a new
329   // expression [expr.new paragraph 13].
330 
331   // Historically we've treated the C family allocation routines as removable
332   return isAllocLikeFn(CB, TLI);
333 }
334 
335 Value *llvm::getAllocAlignment(const CallBase *V,
336                                const TargetLibraryInfo *TLI) {
337   const Optional<AllocFnsTy> FnData = getAllocationData(V, AnyAlloc, TLI);
338   if (FnData.hasValue() && FnData->AlignParam >= 0) {
339     return V->getOperand(FnData->AlignParam);
340   }
341   unsigned AllocAlignParam;
342   if (V->getAttributes().hasAttrSomewhere(Attribute::AllocAlign,
343                                           &AllocAlignParam)) {
344     return V->getOperand(AllocAlignParam-1);
345   }
346   return nullptr;
347 }
348 
349 /// When we're compiling N-bit code, and the user uses parameters that are
350 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
351 /// trouble with APInt size issues. This function handles resizing + overflow
352 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
353 /// I's value.
354 static bool CheckedZextOrTrunc(APInt &I, unsigned IntTyBits) {
355   // More bits than we can handle. Checking the bit width isn't necessary, but
356   // it's faster than checking active bits, and should give `false` in the
357   // vast majority of cases.
358   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
359     return false;
360   if (I.getBitWidth() != IntTyBits)
361     I = I.zextOrTrunc(IntTyBits);
362   return true;
363 }
364 
365 Optional<APInt>
366 llvm::getAllocSize(const CallBase *CB,
367                    const TargetLibraryInfo *TLI,
368                    std::function<const Value*(const Value*)> Mapper) {
369   // Note: This handles both explicitly listed allocation functions and
370   // allocsize.  The code structure could stand to be cleaned up a bit.
371   Optional<AllocFnsTy> FnData = getAllocationSize(CB, TLI);
372   if (!FnData)
373     return None;
374 
375   // Get the index type for this address space, results and intermediate
376   // computations are performed at that width.
377   auto &DL = CB->getModule()->getDataLayout();
378   const unsigned IntTyBits = DL.getIndexTypeSizeInBits(CB->getType());
379 
380   // Handle strdup-like functions separately.
381   if (FnData->AllocTy == StrDupLike) {
382     APInt Size(IntTyBits, GetStringLength(Mapper(CB->getArgOperand(0))));
383     if (!Size)
384       return None;
385 
386     // Strndup limits strlen.
387     if (FnData->FstParam > 0) {
388       const ConstantInt *Arg =
389         dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->FstParam)));
390       if (!Arg)
391         return None;
392 
393       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
394       if (Size.ugt(MaxSize))
395         Size = MaxSize + 1;
396     }
397     return Size;
398   }
399 
400   const ConstantInt *Arg =
401     dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->FstParam)));
402   if (!Arg)
403     return None;
404 
405   APInt Size = Arg->getValue();
406   if (!CheckedZextOrTrunc(Size, IntTyBits))
407     return None;
408 
409   // Size is determined by just 1 parameter.
410   if (FnData->SndParam < 0)
411     return Size;
412 
413   Arg = dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->SndParam)));
414   if (!Arg)
415     return None;
416 
417   APInt NumElems = Arg->getValue();
418   if (!CheckedZextOrTrunc(NumElems, IntTyBits))
419     return None;
420 
421   bool Overflow;
422   Size = Size.umul_ov(NumElems, Overflow);
423   if (Overflow)
424     return None;
425   return Size;
426 }
427 
428 Constant *llvm::getInitialValueOfAllocation(const CallBase *Alloc,
429                                             const TargetLibraryInfo *TLI,
430                                             Type *Ty) {
431   assert(isAllocationFn(Alloc, TLI));
432 
433   // malloc and aligned_alloc are uninitialized (undef)
434   if (isMallocLikeFn(Alloc, TLI) || isAlignedAllocLikeFn(Alloc, TLI))
435     return UndefValue::get(Ty);
436 
437   // calloc zero initializes
438   if (isCallocLikeFn(Alloc, TLI))
439     return Constant::getNullValue(Ty);
440 
441   return nullptr;
442 }
443 
444 struct FreeFnsTy {
445   unsigned NumParams;
446   // Name of default allocator function to group malloc/free calls by family
447   MallocFamily Family;
448 };
449 
450 // clang-format off
451 static const std::pair<LibFunc, FreeFnsTy> FreeFnData[] = {
452     {LibFunc_free,                               {1, MallocFamily::Malloc}},
453     {LibFunc_ZdlPv,                              {1, MallocFamily::CPPNew}},             // operator delete(void*)
454     {LibFunc_ZdaPv,                              {1, MallocFamily::CPPNewArray}},        // operator delete[](void*)
455     {LibFunc_msvc_delete_ptr32,                  {1, MallocFamily::MSVCNew}},            // operator delete(void*)
456     {LibFunc_msvc_delete_ptr64,                  {1, MallocFamily::MSVCNew}},            // operator delete(void*)
457     {LibFunc_msvc_delete_array_ptr32,            {1, MallocFamily::MSVCArrayNew}},       // operator delete[](void*)
458     {LibFunc_msvc_delete_array_ptr64,            {1, MallocFamily::MSVCArrayNew}},       // operator delete[](void*)
459     {LibFunc_ZdlPvj,                             {2, MallocFamily::CPPNew}},             // delete(void*, uint)
460     {LibFunc_ZdlPvm,                             {2, MallocFamily::CPPNew}},             // delete(void*, ulong)
461     {LibFunc_ZdlPvRKSt9nothrow_t,                {2, MallocFamily::CPPNew}},             // delete(void*, nothrow)
462     {LibFunc_ZdlPvSt11align_val_t,               {2, MallocFamily::CPPNewAligned}},      // delete(void*, align_val_t)
463     {LibFunc_ZdaPvj,                             {2, MallocFamily::CPPNewArray}},        // delete[](void*, uint)
464     {LibFunc_ZdaPvm,                             {2, MallocFamily::CPPNewArray}},        // delete[](void*, ulong)
465     {LibFunc_ZdaPvRKSt9nothrow_t,                {2, MallocFamily::CPPNewArray}},        // delete[](void*, nothrow)
466     {LibFunc_ZdaPvSt11align_val_t,               {2, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, align_val_t)
467     {LibFunc_msvc_delete_ptr32_int,              {2, MallocFamily::MSVCNew}},            // delete(void*, uint)
468     {LibFunc_msvc_delete_ptr64_longlong,         {2, MallocFamily::MSVCNew}},            // delete(void*, ulonglong)
469     {LibFunc_msvc_delete_ptr32_nothrow,          {2, MallocFamily::MSVCNew}},            // delete(void*, nothrow)
470     {LibFunc_msvc_delete_ptr64_nothrow,          {2, MallocFamily::MSVCNew}},            // delete(void*, nothrow)
471     {LibFunc_msvc_delete_array_ptr32_int,        {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, uint)
472     {LibFunc_msvc_delete_array_ptr64_longlong,   {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, ulonglong)
473     {LibFunc_msvc_delete_array_ptr32_nothrow,    {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, nothrow)
474     {LibFunc_msvc_delete_array_ptr64_nothrow,    {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, nothrow)
475     {LibFunc___kmpc_free_shared,                 {2, MallocFamily::KmpcAllocShared}},    // OpenMP Offloading RTL free
476     {LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t, {3, MallocFamily::CPPNewAligned}},      // delete(void*, align_val_t, nothrow)
477     {LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t, {3, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, align_val_t, nothrow)
478     {LibFunc_ZdlPvjSt11align_val_t,              {3, MallocFamily::CPPNewAligned}},      // delete(void*, unsigned int, align_val_t)
479     {LibFunc_ZdlPvmSt11align_val_t,              {3, MallocFamily::CPPNewAligned}},      // delete(void*, unsigned long, align_val_t)
480     {LibFunc_ZdaPvjSt11align_val_t,              {3, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, unsigned int, align_val_t)
481     {LibFunc_ZdaPvmSt11align_val_t,              {3, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, unsigned long, align_val_t)
482 };
483 // clang-format on
484 
485 Optional<FreeFnsTy> getFreeFunctionDataForFunction(const Function *Callee,
486                                                    const LibFunc TLIFn) {
487   const auto *Iter =
488       find_if(FreeFnData, [TLIFn](const std::pair<LibFunc, FreeFnsTy> &P) {
489         return P.first == TLIFn;
490       });
491   if (Iter == std::end(FreeFnData))
492     return None;
493   return Iter->second;
494 }
495 
496 Optional<StringRef> llvm::getAllocationFamily(const Value *I,
497                                               const TargetLibraryInfo *TLI) {
498   bool IsNoBuiltin;
499   const Function *Callee = getCalledFunction(I, IsNoBuiltin);
500   if (Callee == nullptr)
501     return None;
502   LibFunc TLIFn;
503   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
504     return None;
505   const auto AllocData = getAllocationDataForFunction(Callee, AnyAlloc, TLI);
506   if (AllocData.hasValue())
507     return mangledNameForMallocFamily(AllocData.getValue().Family);
508   const auto FreeData = getFreeFunctionDataForFunction(Callee, TLIFn);
509   if (FreeData.hasValue())
510     return mangledNameForMallocFamily(FreeData.getValue().Family);
511   return None;
512 }
513 
514 /// isLibFreeFunction - Returns true if the function is a builtin free()
515 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
516   Optional<FreeFnsTy> FnData = getFreeFunctionDataForFunction(F, TLIFn);
517   if (!FnData.hasValue())
518     return false;
519 
520   // Check free prototype.
521   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
522   // attribute will exist.
523   FunctionType *FTy = F->getFunctionType();
524   if (!FTy->getReturnType()->isVoidTy())
525     return false;
526   if (FTy->getNumParams() != FnData->NumParams)
527     return false;
528   if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
529     return false;
530 
531   return true;
532 }
533 
534 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
535 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
536   bool IsNoBuiltinCall;
537   const Function *Callee = getCalledFunction(I, IsNoBuiltinCall);
538   if (Callee == nullptr || IsNoBuiltinCall)
539     return nullptr;
540 
541   LibFunc TLIFn;
542   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
543     return nullptr;
544 
545   return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
546 }
547 
548 
549 //===----------------------------------------------------------------------===//
550 //  Utility functions to compute size of objects.
551 //
552 static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
553   if (Data.second.isNegative() || Data.first.ult(Data.second))
554     return APInt(Data.first.getBitWidth(), 0);
555   return Data.first - Data.second;
556 }
557 
558 /// Compute the size of the object pointed by Ptr. Returns true and the
559 /// object size in Size if successful, and false otherwise.
560 /// If RoundToAlign is true, then Size is rounded up to the alignment of
561 /// allocas, byval arguments, and global variables.
562 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
563                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
564   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
565   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
566   if (!Visitor.bothKnown(Data))
567     return false;
568 
569   Size = getSizeWithOverflow(Data).getZExtValue();
570   return true;
571 }
572 
573 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
574                                  const DataLayout &DL,
575                                  const TargetLibraryInfo *TLI,
576                                  bool MustSucceed) {
577   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
578          "ObjectSize must be a call to llvm.objectsize!");
579 
580   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
581   ObjectSizeOpts EvalOptions;
582   // Unless we have to fold this to something, try to be as accurate as
583   // possible.
584   if (MustSucceed)
585     EvalOptions.EvalMode =
586         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
587   else
588     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
589 
590   EvalOptions.NullIsUnknownSize =
591       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
592 
593   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
594   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
595   if (StaticOnly) {
596     // FIXME: Does it make sense to just return a failure value if the size won't
597     // fit in the output and `!MustSucceed`?
598     uint64_t Size;
599     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
600         isUIntN(ResultType->getBitWidth(), Size))
601       return ConstantInt::get(ResultType, Size);
602   } else {
603     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
604     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
605     SizeOffsetEvalType SizeOffsetPair =
606         Eval.compute(ObjectSize->getArgOperand(0));
607 
608     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
609       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
610       Builder.SetInsertPoint(ObjectSize);
611 
612       // If we've outside the end of the object, then we can always access
613       // exactly 0 bytes.
614       Value *ResultSize =
615           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
616       Value *UseZero =
617           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
618       ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
619       Value *Ret = Builder.CreateSelect(
620           UseZero, ConstantInt::get(ResultType, 0), ResultSize);
621 
622       // The non-constant size expression cannot evaluate to -1.
623       if (!isa<Constant>(SizeOffsetPair.first) ||
624           !isa<Constant>(SizeOffsetPair.second))
625         Builder.CreateAssumption(
626             Builder.CreateICmpNE(Ret, ConstantInt::get(ResultType, -1)));
627 
628       return Ret;
629     }
630   }
631 
632   if (!MustSucceed)
633     return nullptr;
634 
635   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
636 }
637 
638 STATISTIC(ObjectVisitorArgument,
639           "Number of arguments with unsolved size and offset");
640 STATISTIC(ObjectVisitorLoad,
641           "Number of load instructions with unsolved size and offset");
642 
643 APInt ObjectSizeOffsetVisitor::align(APInt Size, MaybeAlign Alignment) {
644   if (Options.RoundToAlign && Alignment)
645     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Alignment));
646   return Size;
647 }
648 
649 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
650                                                  const TargetLibraryInfo *TLI,
651                                                  LLVMContext &Context,
652                                                  ObjectSizeOpts Options)
653     : DL(DL), TLI(TLI), Options(Options) {
654   // Pointer size must be rechecked for each object visited since it could have
655   // a different address space.
656 }
657 
658 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
659   unsigned InitialIntTyBits = DL.getIndexTypeSizeInBits(V->getType());
660 
661   // Stripping pointer casts can strip address space casts which can change the
662   // index type size. The invariant is that we use the value type to determine
663   // the index type size and if we stripped address space casts we have to
664   // readjust the APInt as we pass it upwards in order for the APInt to match
665   // the type the caller passed in.
666   APInt Offset(InitialIntTyBits, 0);
667   V = V->stripAndAccumulateConstantOffsets(
668       DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true);
669 
670   // Later we use the index type size and zero but it will match the type of the
671   // value that is passed to computeImpl.
672   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
673   Zero = APInt::getZero(IntTyBits);
674 
675   bool IndexTypeSizeChanged = InitialIntTyBits != IntTyBits;
676   if (!IndexTypeSizeChanged && Offset.isZero())
677     return computeImpl(V);
678 
679   // We stripped an address space cast that changed the index type size or we
680   // accumulated some constant offset (or both). Readjust the bit width to match
681   // the argument index type size and apply the offset, as required.
682   SizeOffsetType SOT = computeImpl(V);
683   if (IndexTypeSizeChanged) {
684     if (knownSize(SOT) && !::CheckedZextOrTrunc(SOT.first, InitialIntTyBits))
685       SOT.first = APInt();
686     if (knownOffset(SOT) && !::CheckedZextOrTrunc(SOT.second, InitialIntTyBits))
687       SOT.second = APInt();
688   }
689   // If the computed offset is "unknown" we cannot add the stripped offset.
690   return {SOT.first,
691           SOT.second.getBitWidth() > 1 ? SOT.second + Offset : SOT.second};
692 }
693 
694 SizeOffsetType ObjectSizeOffsetVisitor::computeImpl(Value *V) {
695   if (Instruction *I = dyn_cast<Instruction>(V)) {
696     // If we have already seen this instruction, bail out. Cycles can happen in
697     // unreachable code after constant propagation.
698     if (!SeenInsts.insert(I).second)
699       return unknown();
700 
701     return visit(*I);
702   }
703   if (Argument *A = dyn_cast<Argument>(V))
704     return visitArgument(*A);
705   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
706     return visitConstantPointerNull(*P);
707   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
708     return visitGlobalAlias(*GA);
709   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
710     return visitGlobalVariable(*GV);
711   if (UndefValue *UV = dyn_cast<UndefValue>(V))
712     return visitUndefValue(*UV);
713 
714   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
715                     << *V << '\n');
716   return unknown();
717 }
718 
719 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
720   return ::CheckedZextOrTrunc(I, IntTyBits);
721 }
722 
723 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
724   if (!I.getAllocatedType()->isSized())
725     return unknown();
726 
727   TypeSize ElemSize = DL.getTypeAllocSize(I.getAllocatedType());
728   if (ElemSize.isScalable() && Options.EvalMode != ObjectSizeOpts::Mode::Min)
729     return unknown();
730   APInt Size(IntTyBits, ElemSize.getKnownMinSize());
731   if (!I.isArrayAllocation())
732     return std::make_pair(align(Size, I.getAlign()), Zero);
733 
734   Value *ArraySize = I.getArraySize();
735   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
736     APInt NumElems = C->getValue();
737     if (!CheckedZextOrTrunc(NumElems))
738       return unknown();
739 
740     bool Overflow;
741     Size = Size.umul_ov(NumElems, Overflow);
742     return Overflow ? unknown()
743                     : std::make_pair(align(Size, I.getAlign()), Zero);
744   }
745   return unknown();
746 }
747 
748 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
749   Type *MemoryTy = A.getPointeeInMemoryValueType();
750   // No interprocedural analysis is done at the moment.
751   if (!MemoryTy|| !MemoryTy->isSized()) {
752     ++ObjectVisitorArgument;
753     return unknown();
754   }
755 
756   APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
757   return std::make_pair(align(Size, A.getParamAlign()), Zero);
758 }
759 
760 SizeOffsetType ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
761   auto Mapper = [](const Value *V) { return V; };
762   if (Optional<APInt> Size = getAllocSize(&CB, TLI, Mapper))
763     return std::make_pair(*Size, Zero);
764   return unknown();
765 }
766 
767 SizeOffsetType
768 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
769   // If null is unknown, there's nothing we can do. Additionally, non-zero
770   // address spaces can make use of null, so we don't presume to know anything
771   // about that.
772   //
773   // TODO: How should this work with address space casts? We currently just drop
774   // them on the floor, but it's unclear what we should do when a NULL from
775   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
776   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
777     return unknown();
778   return std::make_pair(Zero, Zero);
779 }
780 
781 SizeOffsetType
782 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
783   return unknown();
784 }
785 
786 SizeOffsetType
787 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
788   // Easy cases were already folded by previous passes.
789   return unknown();
790 }
791 
792 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
793   if (GA.isInterposable())
794     return unknown();
795   return compute(GA.getAliasee());
796 }
797 
798 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
799   if (!GV.hasDefinitiveInitializer())
800     return unknown();
801 
802   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
803   return std::make_pair(align(Size, GV.getAlign()), Zero);
804 }
805 
806 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
807   // clueless
808   return unknown();
809 }
810 
811 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
812   ++ObjectVisitorLoad;
813   return unknown();
814 }
815 
816 SizeOffsetType ObjectSizeOffsetVisitor::combineSizeOffset(SizeOffsetType LHS,
817                                                           SizeOffsetType RHS) {
818   if (!bothKnown(LHS) || !bothKnown(RHS))
819     return unknown();
820 
821   switch (Options.EvalMode) {
822   case ObjectSizeOpts::Mode::Min:
823     return (getSizeWithOverflow(LHS).slt(getSizeWithOverflow(RHS))) ? LHS : RHS;
824   case ObjectSizeOpts::Mode::Max:
825     return (getSizeWithOverflow(LHS).sgt(getSizeWithOverflow(RHS))) ? LHS : RHS;
826   case ObjectSizeOpts::Mode::Exact:
827     return (getSizeWithOverflow(LHS).eq(getSizeWithOverflow(RHS))) ? LHS
828                                                                    : unknown();
829   }
830   llvm_unreachable("missing an eval mode");
831 }
832 
833 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode &PN) {
834   auto IncomingValues = PN.incoming_values();
835   return std::accumulate(IncomingValues.begin() + 1, IncomingValues.end(),
836                          compute(*IncomingValues.begin()),
837                          [this](SizeOffsetType LHS, Value *VRHS) {
838                            return combineSizeOffset(LHS, compute(VRHS));
839                          });
840 }
841 
842 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
843   return combineSizeOffset(compute(I.getTrueValue()),
844                            compute(I.getFalseValue()));
845 }
846 
847 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
848   return std::make_pair(Zero, Zero);
849 }
850 
851 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
852   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
853                     << '\n');
854   return unknown();
855 }
856 
857 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
858     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
859     ObjectSizeOpts EvalOpts)
860     : DL(DL), TLI(TLI), Context(Context),
861       Builder(Context, TargetFolder(DL),
862               IRBuilderCallbackInserter(
863                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
864       EvalOpts(EvalOpts) {
865   // IntTy and Zero must be set for each compute() since the address space may
866   // be different for later objects.
867 }
868 
869 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
870   // XXX - Are vectors of pointers possible here?
871   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
872   Zero = ConstantInt::get(IntTy, 0);
873 
874   SizeOffsetEvalType Result = compute_(V);
875 
876   if (!bothKnown(Result)) {
877     // Erase everything that was computed in this iteration from the cache, so
878     // that no dangling references are left behind. We could be a bit smarter if
879     // we kept a dependency graph. It's probably not worth the complexity.
880     for (const Value *SeenVal : SeenVals) {
881       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
882       // non-computable results can be safely cached
883       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
884         CacheMap.erase(CacheIt);
885     }
886 
887     // Erase any instructions we inserted as part of the traversal.
888     for (Instruction *I : InsertedInstructions) {
889       I->replaceAllUsesWith(UndefValue::get(I->getType()));
890       I->eraseFromParent();
891     }
892   }
893 
894   SeenVals.clear();
895   InsertedInstructions.clear();
896   return Result;
897 }
898 
899 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
900   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
901   SizeOffsetType Const = Visitor.compute(V);
902   if (Visitor.bothKnown(Const))
903     return std::make_pair(ConstantInt::get(Context, Const.first),
904                           ConstantInt::get(Context, Const.second));
905 
906   V = V->stripPointerCasts();
907 
908   // Check cache.
909   CacheMapTy::iterator CacheIt = CacheMap.find(V);
910   if (CacheIt != CacheMap.end())
911     return CacheIt->second;
912 
913   // Always generate code immediately before the instruction being
914   // processed, so that the generated code dominates the same BBs.
915   BuilderTy::InsertPointGuard Guard(Builder);
916   if (Instruction *I = dyn_cast<Instruction>(V))
917     Builder.SetInsertPoint(I);
918 
919   // Now compute the size and offset.
920   SizeOffsetEvalType Result;
921 
922   // Record the pointers that were handled in this run, so that they can be
923   // cleaned later if something fails. We also use this set to break cycles that
924   // can occur in dead code.
925   if (!SeenVals.insert(V).second) {
926     Result = unknown();
927   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
928     Result = visitGEPOperator(*GEP);
929   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
930     Result = visit(*I);
931   } else if (isa<Argument>(V) ||
932              (isa<ConstantExpr>(V) &&
933               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
934              isa<GlobalAlias>(V) ||
935              isa<GlobalVariable>(V)) {
936     // Ignore values where we cannot do more than ObjectSizeVisitor.
937     Result = unknown();
938   } else {
939     LLVM_DEBUG(
940         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
941                << '\n');
942     Result = unknown();
943   }
944 
945   // Don't reuse CacheIt since it may be invalid at this point.
946   CacheMap[V] = Result;
947   return Result;
948 }
949 
950 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
951   if (!I.getAllocatedType()->isSized())
952     return unknown();
953 
954   // must be a VLA
955   assert(I.isArrayAllocation());
956 
957   // If needed, adjust the alloca's operand size to match the pointer size.
958   // Subsequent math operations expect the types to match.
959   Value *ArraySize = Builder.CreateZExtOrTrunc(
960       I.getArraySize(), DL.getIntPtrType(I.getContext()));
961   assert(ArraySize->getType() == Zero->getType() &&
962          "Expected zero constant to have pointer type");
963 
964   Value *Size = ConstantInt::get(ArraySize->getType(),
965                                  DL.getTypeAllocSize(I.getAllocatedType()));
966   Size = Builder.CreateMul(Size, ArraySize);
967   return std::make_pair(Size, Zero);
968 }
969 
970 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallBase(CallBase &CB) {
971   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
972   if (!FnData)
973     return unknown();
974 
975   // Handle strdup-like functions separately.
976   if (FnData->AllocTy == StrDupLike) {
977     // TODO: implement evaluation of strdup/strndup
978     return unknown();
979   }
980 
981   Value *FirstArg = CB.getArgOperand(FnData->FstParam);
982   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
983   if (FnData->SndParam < 0)
984     return std::make_pair(FirstArg, Zero);
985 
986   Value *SecondArg = CB.getArgOperand(FnData->SndParam);
987   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
988   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
989   return std::make_pair(Size, Zero);
990 }
991 
992 SizeOffsetEvalType
993 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
994   return unknown();
995 }
996 
997 SizeOffsetEvalType
998 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
999   return unknown();
1000 }
1001 
1002 SizeOffsetEvalType
1003 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
1004   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
1005   if (!bothKnown(PtrData))
1006     return unknown();
1007 
1008   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
1009   Offset = Builder.CreateAdd(PtrData.second, Offset);
1010   return std::make_pair(PtrData.first, Offset);
1011 }
1012 
1013 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
1014   // clueless
1015   return unknown();
1016 }
1017 
1018 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
1019   return unknown();
1020 }
1021 
1022 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
1023   // Create 2 PHIs: one for size and another for offset.
1024   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1025   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1026 
1027   // Insert right away in the cache to handle recursive PHIs.
1028   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
1029 
1030   // Compute offset/size for each PHI incoming pointer.
1031   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1032     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
1033     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
1034 
1035     if (!bothKnown(EdgeData)) {
1036       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
1037       OffsetPHI->eraseFromParent();
1038       InsertedInstructions.erase(OffsetPHI);
1039       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
1040       SizePHI->eraseFromParent();
1041       InsertedInstructions.erase(SizePHI);
1042       return unknown();
1043     }
1044     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1045     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1046   }
1047 
1048   Value *Size = SizePHI, *Offset = OffsetPHI;
1049   if (Value *Tmp = SizePHI->hasConstantValue()) {
1050     Size = Tmp;
1051     SizePHI->replaceAllUsesWith(Size);
1052     SizePHI->eraseFromParent();
1053     InsertedInstructions.erase(SizePHI);
1054   }
1055   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1056     Offset = Tmp;
1057     OffsetPHI->replaceAllUsesWith(Offset);
1058     OffsetPHI->eraseFromParent();
1059     InsertedInstructions.erase(OffsetPHI);
1060   }
1061   return std::make_pair(Size, Offset);
1062 }
1063 
1064 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
1065   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
1066   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1067 
1068   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1069     return unknown();
1070   if (TrueSide == FalseSide)
1071     return TrueSide;
1072 
1073   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1074                                      FalseSide.first);
1075   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1076                                        FalseSide.second);
1077   return std::make_pair(Size, Offset);
1078 }
1079 
1080 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1081   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1082                     << '\n');
1083   return unknown();
1084 }
1085