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