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 value is a call or invoke to a library function that
316 /// reallocates memory (e.g., realloc).
317 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
318   return getAllocationData(V, ReallocLike, TLI).has_value();
319 }
320 
321 /// Tests if a functions is a call or invoke to a library function that
322 /// reallocates memory (e.g., realloc).
323 bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
324   return getAllocationDataForFunction(F, ReallocLike, TLI).has_value();
325 }
326 
327 bool llvm::isRemovableAlloc(const CallBase *CB, const TargetLibraryInfo *TLI) {
328   // Note: Removability is highly dependent on the source language.  For
329   // example, recent C++ requires direct calls to the global allocation
330   // [basic.stc.dynamic.allocation] to be observable unless part of a new
331   // expression [expr.new paragraph 13].
332 
333   // Historically we've treated the C family allocation routines and operator
334   // new as removable
335   return isAllocLikeFn(CB, TLI);
336 }
337 
338 Value *llvm::getAllocAlignment(const CallBase *V,
339                                const TargetLibraryInfo *TLI) {
340   const Optional<AllocFnsTy> FnData = getAllocationData(V, AnyAlloc, TLI);
341   if (FnData && FnData->AlignParam >= 0) {
342     return V->getOperand(FnData->AlignParam);
343   }
344   return V->getArgOperandWithAttribute(Attribute::AllocAlign);
345 }
346 
347 /// When we're compiling N-bit code, and the user uses parameters that are
348 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
349 /// trouble with APInt size issues. This function handles resizing + overflow
350 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
351 /// I's value.
352 static bool CheckedZextOrTrunc(APInt &I, unsigned IntTyBits) {
353   // More bits than we can handle. Checking the bit width isn't necessary, but
354   // it's faster than checking active bits, and should give `false` in the
355   // vast majority of cases.
356   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
357     return false;
358   if (I.getBitWidth() != IntTyBits)
359     I = I.zextOrTrunc(IntTyBits);
360   return true;
361 }
362 
363 Optional<APInt>
364 llvm::getAllocSize(const CallBase *CB, const TargetLibraryInfo *TLI,
365                    function_ref<const Value *(const Value *)> Mapper) {
366   // Note: This handles both explicitly listed allocation functions and
367   // allocsize.  The code structure could stand to be cleaned up a bit.
368   Optional<AllocFnsTy> FnData = getAllocationSize(CB, TLI);
369   if (!FnData)
370     return None;
371 
372   // Get the index type for this address space, results and intermediate
373   // computations are performed at that width.
374   auto &DL = CB->getModule()->getDataLayout();
375   const unsigned IntTyBits = DL.getIndexTypeSizeInBits(CB->getType());
376 
377   // Handle strdup-like functions separately.
378   if (FnData->AllocTy == StrDupLike) {
379     APInt Size(IntTyBits, GetStringLength(Mapper(CB->getArgOperand(0))));
380     if (!Size)
381       return None;
382 
383     // Strndup limits strlen.
384     if (FnData->FstParam > 0) {
385       const ConstantInt *Arg =
386         dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->FstParam)));
387       if (!Arg)
388         return None;
389 
390       APInt MaxSize = Arg->getValue().zext(IntTyBits);
391       if (Size.ugt(MaxSize))
392         Size = MaxSize + 1;
393     }
394     return Size;
395   }
396 
397   const ConstantInt *Arg =
398     dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->FstParam)));
399   if (!Arg)
400     return None;
401 
402   APInt Size = Arg->getValue();
403   if (!CheckedZextOrTrunc(Size, IntTyBits))
404     return None;
405 
406   // Size is determined by just 1 parameter.
407   if (FnData->SndParam < 0)
408     return Size;
409 
410   Arg = dyn_cast<ConstantInt>(Mapper(CB->getArgOperand(FnData->SndParam)));
411   if (!Arg)
412     return None;
413 
414   APInt NumElems = Arg->getValue();
415   if (!CheckedZextOrTrunc(NumElems, IntTyBits))
416     return None;
417 
418   bool Overflow;
419   Size = Size.umul_ov(NumElems, Overflow);
420   if (Overflow)
421     return None;
422   return Size;
423 }
424 
425 Constant *llvm::getInitialValueOfAllocation(const Value *V,
426                                             const TargetLibraryInfo *TLI,
427                                             Type *Ty) {
428   auto *Alloc = dyn_cast<CallBase>(V);
429   if (!Alloc)
430     return nullptr;
431 
432   // malloc and aligned_alloc are uninitialized (undef)
433   if (isMallocLikeFn(Alloc, TLI) || isAlignedAllocLikeFn(Alloc, TLI))
434     return UndefValue::get(Ty);
435 
436   // calloc zero initializes
437   if (isCallocLikeFn(Alloc, TLI))
438     return Constant::getNullValue(Ty);
439 
440   return nullptr;
441 }
442 
443 struct FreeFnsTy {
444   unsigned NumParams;
445   // Name of default allocator function to group malloc/free calls by family
446   MallocFamily Family;
447 };
448 
449 // clang-format off
450 static const std::pair<LibFunc, FreeFnsTy> FreeFnData[] = {
451     {LibFunc_free,                               {1, MallocFamily::Malloc}},
452     {LibFunc_vec_free,                           {1, MallocFamily::VecMalloc}},
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 || IsNoBuiltin)
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)
507     return mangledNameForMallocFamily(AllocData.value().Family);
508   const auto FreeData = getFreeFunctionDataForFunction(Callee, TLIFn);
509   if (FreeData)
510     return mangledNameForMallocFamily(FreeData.value().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)
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   return lowerObjectSizeCall(ObjectSize, DL, TLI, /*AAResults=*/nullptr,
578                              MustSucceed);
579 }
580 
581 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
582                                  const DataLayout &DL,
583                                  const TargetLibraryInfo *TLI, AAResults *AA,
584                                  bool MustSucceed) {
585   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
586          "ObjectSize must be a call to llvm.objectsize!");
587 
588   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
589   ObjectSizeOpts EvalOptions;
590   EvalOptions.AA = AA;
591 
592   // Unless we have to fold this to something, try to be as accurate as
593   // possible.
594   if (MustSucceed)
595     EvalOptions.EvalMode =
596         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
597   else
598     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
599 
600   EvalOptions.NullIsUnknownSize =
601       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
602 
603   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
604   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
605   if (StaticOnly) {
606     // FIXME: Does it make sense to just return a failure value if the size won't
607     // fit in the output and `!MustSucceed`?
608     uint64_t Size;
609     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
610         isUIntN(ResultType->getBitWidth(), Size))
611       return ConstantInt::get(ResultType, Size);
612   } else {
613     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
614     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
615     SizeOffsetEvalType SizeOffsetPair =
616         Eval.compute(ObjectSize->getArgOperand(0));
617 
618     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
619       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
620       Builder.SetInsertPoint(ObjectSize);
621 
622       // If we've outside the end of the object, then we can always access
623       // exactly 0 bytes.
624       Value *ResultSize =
625           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
626       Value *UseZero =
627           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
628       ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
629       Value *Ret = Builder.CreateSelect(
630           UseZero, ConstantInt::get(ResultType, 0), ResultSize);
631 
632       // The non-constant size expression cannot evaluate to -1.
633       if (!isa<Constant>(SizeOffsetPair.first) ||
634           !isa<Constant>(SizeOffsetPair.second))
635         Builder.CreateAssumption(
636             Builder.CreateICmpNE(Ret, ConstantInt::get(ResultType, -1)));
637 
638       return Ret;
639     }
640   }
641 
642   if (!MustSucceed)
643     return nullptr;
644 
645   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
646 }
647 
648 STATISTIC(ObjectVisitorArgument,
649           "Number of arguments with unsolved size and offset");
650 STATISTIC(ObjectVisitorLoad,
651           "Number of load instructions with unsolved size and offset");
652 
653 APInt ObjectSizeOffsetVisitor::align(APInt Size, MaybeAlign Alignment) {
654   if (Options.RoundToAlign && Alignment)
655     return APInt(IntTyBits, alignTo(Size.getZExtValue(), *Alignment));
656   return Size;
657 }
658 
659 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
660                                                  const TargetLibraryInfo *TLI,
661                                                  LLVMContext &Context,
662                                                  ObjectSizeOpts Options)
663     : DL(DL), TLI(TLI), Options(Options) {
664   // Pointer size must be rechecked for each object visited since it could have
665   // a different address space.
666 }
667 
668 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
669   unsigned InitialIntTyBits = DL.getIndexTypeSizeInBits(V->getType());
670 
671   // Stripping pointer casts can strip address space casts which can change the
672   // index type size. The invariant is that we use the value type to determine
673   // the index type size and if we stripped address space casts we have to
674   // readjust the APInt as we pass it upwards in order for the APInt to match
675   // the type the caller passed in.
676   APInt Offset(InitialIntTyBits, 0);
677   V = V->stripAndAccumulateConstantOffsets(
678       DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true);
679 
680   // Later we use the index type size and zero but it will match the type of the
681   // value that is passed to computeImpl.
682   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
683   Zero = APInt::getZero(IntTyBits);
684 
685   bool IndexTypeSizeChanged = InitialIntTyBits != IntTyBits;
686   if (!IndexTypeSizeChanged && Offset.isZero())
687     return computeImpl(V);
688 
689   // We stripped an address space cast that changed the index type size or we
690   // accumulated some constant offset (or both). Readjust the bit width to match
691   // the argument index type size and apply the offset, as required.
692   SizeOffsetType SOT = computeImpl(V);
693   if (IndexTypeSizeChanged) {
694     if (knownSize(SOT) && !::CheckedZextOrTrunc(SOT.first, InitialIntTyBits))
695       SOT.first = APInt();
696     if (knownOffset(SOT) && !::CheckedZextOrTrunc(SOT.second, InitialIntTyBits))
697       SOT.second = APInt();
698   }
699   // If the computed offset is "unknown" we cannot add the stripped offset.
700   return {SOT.first,
701           SOT.second.getBitWidth() > 1 ? SOT.second + Offset : SOT.second};
702 }
703 
704 SizeOffsetType ObjectSizeOffsetVisitor::computeImpl(Value *V) {
705   if (Instruction *I = dyn_cast<Instruction>(V)) {
706     // If we have already seen this instruction, bail out. Cycles can happen in
707     // unreachable code after constant propagation.
708     if (!SeenInsts.insert(I).second)
709       return unknown();
710 
711     return visit(*I);
712   }
713   if (Argument *A = dyn_cast<Argument>(V))
714     return visitArgument(*A);
715   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
716     return visitConstantPointerNull(*P);
717   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
718     return visitGlobalAlias(*GA);
719   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
720     return visitGlobalVariable(*GV);
721   if (UndefValue *UV = dyn_cast<UndefValue>(V))
722     return visitUndefValue(*UV);
723 
724   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
725                     << *V << '\n');
726   return unknown();
727 }
728 
729 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
730   return ::CheckedZextOrTrunc(I, IntTyBits);
731 }
732 
733 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
734   if (!I.getAllocatedType()->isSized())
735     return unknown();
736 
737   TypeSize ElemSize = DL.getTypeAllocSize(I.getAllocatedType());
738   if (ElemSize.isScalable() && Options.EvalMode != ObjectSizeOpts::Mode::Min)
739     return unknown();
740   APInt Size(IntTyBits, ElemSize.getKnownMinSize());
741   if (!I.isArrayAllocation())
742     return std::make_pair(align(Size, I.getAlign()), Zero);
743 
744   Value *ArraySize = I.getArraySize();
745   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
746     APInt NumElems = C->getValue();
747     if (!CheckedZextOrTrunc(NumElems))
748       return unknown();
749 
750     bool Overflow;
751     Size = Size.umul_ov(NumElems, Overflow);
752     return Overflow ? unknown()
753                     : std::make_pair(align(Size, I.getAlign()), Zero);
754   }
755   return unknown();
756 }
757 
758 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
759   Type *MemoryTy = A.getPointeeInMemoryValueType();
760   // No interprocedural analysis is done at the moment.
761   if (!MemoryTy|| !MemoryTy->isSized()) {
762     ++ObjectVisitorArgument;
763     return unknown();
764   }
765 
766   APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
767   return std::make_pair(align(Size, A.getParamAlign()), Zero);
768 }
769 
770 SizeOffsetType ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
771   if (Optional<APInt> Size = getAllocSize(&CB, TLI))
772     return std::make_pair(*Size, Zero);
773   return unknown();
774 }
775 
776 SizeOffsetType
777 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
778   // If null is unknown, there's nothing we can do. Additionally, non-zero
779   // address spaces can make use of null, so we don't presume to know anything
780   // about that.
781   //
782   // TODO: How should this work with address space casts? We currently just drop
783   // them on the floor, but it's unclear what we should do when a NULL from
784   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
785   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
786     return unknown();
787   return std::make_pair(Zero, Zero);
788 }
789 
790 SizeOffsetType
791 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
792   return unknown();
793 }
794 
795 SizeOffsetType
796 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
797   // Easy cases were already folded by previous passes.
798   return unknown();
799 }
800 
801 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
802   if (GA.isInterposable())
803     return unknown();
804   return compute(GA.getAliasee());
805 }
806 
807 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
808   if (!GV.hasDefinitiveInitializer())
809     return unknown();
810 
811   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
812   return std::make_pair(align(Size, GV.getAlign()), Zero);
813 }
814 
815 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
816   // clueless
817   return unknown();
818 }
819 
820 SizeOffsetType ObjectSizeOffsetVisitor::findLoadSizeOffset(
821     LoadInst &Load, BasicBlock &BB, BasicBlock::iterator From,
822     SmallDenseMap<BasicBlock *, SizeOffsetType, 8> &VisitedBlocks,
823     unsigned &ScannedInstCount) {
824   constexpr unsigned MaxInstsToScan = 128;
825 
826   auto Where = VisitedBlocks.find(&BB);
827   if (Where != VisitedBlocks.end())
828     return Where->second;
829 
830   auto Unknown = [this, &BB, &VisitedBlocks]() {
831     return VisitedBlocks[&BB] = unknown();
832   };
833   auto Known = [&BB, &VisitedBlocks](SizeOffsetType SO) {
834     return VisitedBlocks[&BB] = SO;
835   };
836 
837   do {
838     Instruction &I = *From;
839 
840     if (I.isDebugOrPseudoInst())
841       continue;
842 
843     if (++ScannedInstCount > MaxInstsToScan)
844       return Unknown();
845 
846     if (!I.mayWriteToMemory())
847       continue;
848 
849     if (auto *SI = dyn_cast<StoreInst>(&I)) {
850       AliasResult AR =
851           Options.AA->alias(SI->getPointerOperand(), Load.getPointerOperand());
852       switch ((AliasResult::Kind)AR) {
853       case AliasResult::NoAlias:
854         continue;
855       case AliasResult::MustAlias:
856         if (SI->getValueOperand()->getType()->isPointerTy())
857           return Known(compute(SI->getValueOperand()));
858         else
859           return Unknown(); // No handling of non-pointer values by `compute`.
860       default:
861         return Unknown();
862       }
863     }
864 
865     if (auto *CB = dyn_cast<CallBase>(&I)) {
866       Function *Callee = CB->getCalledFunction();
867       // Bail out on indirect call.
868       if (!Callee)
869         return Unknown();
870 
871       LibFunc TLIFn;
872       if (!TLI || !TLI->getLibFunc(*CB->getCalledFunction(), TLIFn) ||
873           !TLI->has(TLIFn))
874         return Unknown();
875 
876       // TODO: There's probably more interesting case to support here.
877       if (TLIFn != LibFunc_posix_memalign)
878         return Unknown();
879 
880       AliasResult AR =
881           Options.AA->alias(CB->getOperand(0), Load.getPointerOperand());
882       switch ((AliasResult::Kind)AR) {
883       case AliasResult::NoAlias:
884         continue;
885       case AliasResult::MustAlias:
886         break;
887       default:
888         return Unknown();
889       }
890 
891       // Is the error status of posix_memalign correctly checked? If not it
892       // would be incorrect to assume it succeeds and load doesn't see the
893       // previous value.
894       Optional<bool> Checked = isImpliedByDomCondition(
895           ICmpInst::ICMP_EQ, CB, ConstantInt::get(CB->getType(), 0), &Load, DL);
896       if (!Checked || !*Checked)
897         return Unknown();
898 
899       Value *Size = CB->getOperand(2);
900       auto *C = dyn_cast<ConstantInt>(Size);
901       if (!C)
902         return Unknown();
903 
904       return Known({C->getValue(), APInt(C->getValue().getBitWidth(), 0)});
905     }
906 
907     return Unknown();
908   } while (From-- != BB.begin());
909 
910   SmallVector<SizeOffsetType> PredecessorSizeOffsets;
911   for (auto *PredBB : predecessors(&BB)) {
912     PredecessorSizeOffsets.push_back(findLoadSizeOffset(
913         Load, *PredBB, BasicBlock::iterator(PredBB->getTerminator()),
914         VisitedBlocks, ScannedInstCount));
915     if (!bothKnown(PredecessorSizeOffsets.back()))
916       return Unknown();
917   }
918 
919   if (PredecessorSizeOffsets.empty())
920     return Unknown();
921 
922   return Known(std::accumulate(PredecessorSizeOffsets.begin() + 1,
923                                PredecessorSizeOffsets.end(),
924                                PredecessorSizeOffsets.front(),
925                                [this](SizeOffsetType LHS, SizeOffsetType RHS) {
926                                  return combineSizeOffset(LHS, RHS);
927                                }));
928 }
929 
930 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst &LI) {
931   if (!Options.AA) {
932     ++ObjectVisitorLoad;
933     return unknown();
934   }
935 
936   SmallDenseMap<BasicBlock *, SizeOffsetType, 8> VisitedBlocks;
937   unsigned ScannedInstCount = 0;
938   SizeOffsetType SO =
939       findLoadSizeOffset(LI, *LI.getParent(), BasicBlock::iterator(LI),
940                          VisitedBlocks, ScannedInstCount);
941   if (!bothKnown(SO))
942     ++ObjectVisitorLoad;
943   return SO;
944 }
945 
946 SizeOffsetType ObjectSizeOffsetVisitor::combineSizeOffset(SizeOffsetType LHS,
947                                                           SizeOffsetType RHS) {
948   if (!bothKnown(LHS) || !bothKnown(RHS))
949     return unknown();
950 
951   switch (Options.EvalMode) {
952   case ObjectSizeOpts::Mode::Min:
953     return (getSizeWithOverflow(LHS).slt(getSizeWithOverflow(RHS))) ? LHS : RHS;
954   case ObjectSizeOpts::Mode::Max:
955     return (getSizeWithOverflow(LHS).sgt(getSizeWithOverflow(RHS))) ? LHS : RHS;
956   case ObjectSizeOpts::Mode::Exact:
957     return (getSizeWithOverflow(LHS).eq(getSizeWithOverflow(RHS))) ? LHS
958                                                                    : unknown();
959   }
960   llvm_unreachable("missing an eval mode");
961 }
962 
963 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode &PN) {
964   auto IncomingValues = PN.incoming_values();
965   return std::accumulate(IncomingValues.begin() + 1, IncomingValues.end(),
966                          compute(*IncomingValues.begin()),
967                          [this](SizeOffsetType LHS, Value *VRHS) {
968                            return combineSizeOffset(LHS, compute(VRHS));
969                          });
970 }
971 
972 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
973   return combineSizeOffset(compute(I.getTrueValue()),
974                            compute(I.getFalseValue()));
975 }
976 
977 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
978   return std::make_pair(Zero, Zero);
979 }
980 
981 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
982   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
983                     << '\n');
984   return unknown();
985 }
986 
987 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
988     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
989     ObjectSizeOpts EvalOpts)
990     : DL(DL), TLI(TLI), Context(Context),
991       Builder(Context, TargetFolder(DL),
992               IRBuilderCallbackInserter(
993                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
994       EvalOpts(EvalOpts) {
995   // IntTy and Zero must be set for each compute() since the address space may
996   // be different for later objects.
997 }
998 
999 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
1000   // XXX - Are vectors of pointers possible here?
1001   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
1002   Zero = ConstantInt::get(IntTy, 0);
1003 
1004   SizeOffsetEvalType Result = compute_(V);
1005 
1006   if (!bothKnown(Result)) {
1007     // Erase everything that was computed in this iteration from the cache, so
1008     // that no dangling references are left behind. We could be a bit smarter if
1009     // we kept a dependency graph. It's probably not worth the complexity.
1010     for (const Value *SeenVal : SeenVals) {
1011       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
1012       // non-computable results can be safely cached
1013       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
1014         CacheMap.erase(CacheIt);
1015     }
1016 
1017     // Erase any instructions we inserted as part of the traversal.
1018     for (Instruction *I : InsertedInstructions) {
1019       I->replaceAllUsesWith(PoisonValue::get(I->getType()));
1020       I->eraseFromParent();
1021     }
1022   }
1023 
1024   SeenVals.clear();
1025   InsertedInstructions.clear();
1026   return Result;
1027 }
1028 
1029 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
1030   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
1031   SizeOffsetType Const = Visitor.compute(V);
1032   if (Visitor.bothKnown(Const))
1033     return std::make_pair(ConstantInt::get(Context, Const.first),
1034                           ConstantInt::get(Context, Const.second));
1035 
1036   V = V->stripPointerCasts();
1037 
1038   // Check cache.
1039   CacheMapTy::iterator CacheIt = CacheMap.find(V);
1040   if (CacheIt != CacheMap.end())
1041     return CacheIt->second;
1042 
1043   // Always generate code immediately before the instruction being
1044   // processed, so that the generated code dominates the same BBs.
1045   BuilderTy::InsertPointGuard Guard(Builder);
1046   if (Instruction *I = dyn_cast<Instruction>(V))
1047     Builder.SetInsertPoint(I);
1048 
1049   // Now compute the size and offset.
1050   SizeOffsetEvalType Result;
1051 
1052   // Record the pointers that were handled in this run, so that they can be
1053   // cleaned later if something fails. We also use this set to break cycles that
1054   // can occur in dead code.
1055   if (!SeenVals.insert(V).second) {
1056     Result = unknown();
1057   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1058     Result = visitGEPOperator(*GEP);
1059   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
1060     Result = visit(*I);
1061   } else if (isa<Argument>(V) ||
1062              (isa<ConstantExpr>(V) &&
1063               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
1064              isa<GlobalAlias>(V) ||
1065              isa<GlobalVariable>(V)) {
1066     // Ignore values where we cannot do more than ObjectSizeVisitor.
1067     Result = unknown();
1068   } else {
1069     LLVM_DEBUG(
1070         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
1071                << '\n');
1072     Result = unknown();
1073   }
1074 
1075   // Don't reuse CacheIt since it may be invalid at this point.
1076   CacheMap[V] = Result;
1077   return Result;
1078 }
1079 
1080 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
1081   if (!I.getAllocatedType()->isSized())
1082     return unknown();
1083 
1084   // must be a VLA
1085   assert(I.isArrayAllocation());
1086 
1087   // If needed, adjust the alloca's operand size to match the pointer size.
1088   // Subsequent math operations expect the types to match.
1089   Value *ArraySize = Builder.CreateZExtOrTrunc(
1090       I.getArraySize(), DL.getIntPtrType(I.getContext()));
1091   assert(ArraySize->getType() == Zero->getType() &&
1092          "Expected zero constant to have pointer type");
1093 
1094   Value *Size = ConstantInt::get(ArraySize->getType(),
1095                                  DL.getTypeAllocSize(I.getAllocatedType()));
1096   Size = Builder.CreateMul(Size, ArraySize);
1097   return std::make_pair(Size, Zero);
1098 }
1099 
1100 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallBase(CallBase &CB) {
1101   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
1102   if (!FnData)
1103     return unknown();
1104 
1105   // Handle strdup-like functions separately.
1106   if (FnData->AllocTy == StrDupLike) {
1107     // TODO: implement evaluation of strdup/strndup
1108     return unknown();
1109   }
1110 
1111   Value *FirstArg = CB.getArgOperand(FnData->FstParam);
1112   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
1113   if (FnData->SndParam < 0)
1114     return std::make_pair(FirstArg, Zero);
1115 
1116   Value *SecondArg = CB.getArgOperand(FnData->SndParam);
1117   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
1118   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
1119   return std::make_pair(Size, Zero);
1120 }
1121 
1122 SizeOffsetEvalType
1123 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
1124   return unknown();
1125 }
1126 
1127 SizeOffsetEvalType
1128 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
1129   return unknown();
1130 }
1131 
1132 SizeOffsetEvalType
1133 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
1134   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
1135   if (!bothKnown(PtrData))
1136     return unknown();
1137 
1138   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
1139   Offset = Builder.CreateAdd(PtrData.second, Offset);
1140   return std::make_pair(PtrData.first, Offset);
1141 }
1142 
1143 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
1144   // clueless
1145   return unknown();
1146 }
1147 
1148 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst &LI) {
1149   return unknown();
1150 }
1151 
1152 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
1153   // Create 2 PHIs: one for size and another for offset.
1154   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1155   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1156 
1157   // Insert right away in the cache to handle recursive PHIs.
1158   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
1159 
1160   // Compute offset/size for each PHI incoming pointer.
1161   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1162     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
1163     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
1164 
1165     if (!bothKnown(EdgeData)) {
1166       OffsetPHI->replaceAllUsesWith(PoisonValue::get(IntTy));
1167       OffsetPHI->eraseFromParent();
1168       InsertedInstructions.erase(OffsetPHI);
1169       SizePHI->replaceAllUsesWith(PoisonValue::get(IntTy));
1170       SizePHI->eraseFromParent();
1171       InsertedInstructions.erase(SizePHI);
1172       return unknown();
1173     }
1174     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1175     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1176   }
1177 
1178   Value *Size = SizePHI, *Offset = OffsetPHI;
1179   if (Value *Tmp = SizePHI->hasConstantValue()) {
1180     Size = Tmp;
1181     SizePHI->replaceAllUsesWith(Size);
1182     SizePHI->eraseFromParent();
1183     InsertedInstructions.erase(SizePHI);
1184   }
1185   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1186     Offset = Tmp;
1187     OffsetPHI->replaceAllUsesWith(Offset);
1188     OffsetPHI->eraseFromParent();
1189     InsertedInstructions.erase(OffsetPHI);
1190   }
1191   return std::make_pair(Size, Offset);
1192 }
1193 
1194 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
1195   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
1196   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1197 
1198   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1199     return unknown();
1200   if (TrueSide == FalseSide)
1201     return TrueSide;
1202 
1203   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1204                                      FalseSide.first);
1205   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1206                                        FalseSide.second);
1207   return std::make_pair(Size, Offset);
1208 }
1209 
1210 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1211   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1212                     << '\n');
1213   return unknown();
1214 }
1215