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