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.value_or(-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 && 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().zext(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 Value *V,
424                                             const TargetLibraryInfo *TLI,
425                                             Type *Ty) {
426   auto *Alloc = dyn_cast<CallBase>(V);
427   if (!Alloc)
428     return nullptr;
429 
430   // malloc and aligned_alloc are uninitialized (undef)
431   if (isMallocLikeFn(Alloc, TLI) || isAlignedAllocLikeFn(Alloc, TLI))
432     return UndefValue::get(Ty);
433 
434   // calloc zero initializes
435   if (isCallocLikeFn(Alloc, TLI))
436     return Constant::getNullValue(Ty);
437 
438   return nullptr;
439 }
440 
441 struct FreeFnsTy {
442   unsigned NumParams;
443   // Name of default allocator function to group malloc/free calls by family
444   MallocFamily Family;
445 };
446 
447 // clang-format off
448 static const std::pair<LibFunc, FreeFnsTy> FreeFnData[] = {
449     {LibFunc_free,                               {1, MallocFamily::Malloc}},
450     {LibFunc_vec_free,                           {1, MallocFamily::VecMalloc}},
451     {LibFunc_ZdlPv,                              {1, MallocFamily::CPPNew}},             // operator delete(void*)
452     {LibFunc_ZdaPv,                              {1, MallocFamily::CPPNewArray}},        // operator delete[](void*)
453     {LibFunc_msvc_delete_ptr32,                  {1, MallocFamily::MSVCNew}},            // operator delete(void*)
454     {LibFunc_msvc_delete_ptr64,                  {1, MallocFamily::MSVCNew}},            // operator delete(void*)
455     {LibFunc_msvc_delete_array_ptr32,            {1, MallocFamily::MSVCArrayNew}},       // operator delete[](void*)
456     {LibFunc_msvc_delete_array_ptr64,            {1, MallocFamily::MSVCArrayNew}},       // operator delete[](void*)
457     {LibFunc_ZdlPvj,                             {2, MallocFamily::CPPNew}},             // delete(void*, uint)
458     {LibFunc_ZdlPvm,                             {2, MallocFamily::CPPNew}},             // delete(void*, ulong)
459     {LibFunc_ZdlPvRKSt9nothrow_t,                {2, MallocFamily::CPPNew}},             // delete(void*, nothrow)
460     {LibFunc_ZdlPvSt11align_val_t,               {2, MallocFamily::CPPNewAligned}},      // delete(void*, align_val_t)
461     {LibFunc_ZdaPvj,                             {2, MallocFamily::CPPNewArray}},        // delete[](void*, uint)
462     {LibFunc_ZdaPvm,                             {2, MallocFamily::CPPNewArray}},        // delete[](void*, ulong)
463     {LibFunc_ZdaPvRKSt9nothrow_t,                {2, MallocFamily::CPPNewArray}},        // delete[](void*, nothrow)
464     {LibFunc_ZdaPvSt11align_val_t,               {2, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, align_val_t)
465     {LibFunc_msvc_delete_ptr32_int,              {2, MallocFamily::MSVCNew}},            // delete(void*, uint)
466     {LibFunc_msvc_delete_ptr64_longlong,         {2, MallocFamily::MSVCNew}},            // delete(void*, ulonglong)
467     {LibFunc_msvc_delete_ptr32_nothrow,          {2, MallocFamily::MSVCNew}},            // delete(void*, nothrow)
468     {LibFunc_msvc_delete_ptr64_nothrow,          {2, MallocFamily::MSVCNew}},            // delete(void*, nothrow)
469     {LibFunc_msvc_delete_array_ptr32_int,        {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, uint)
470     {LibFunc_msvc_delete_array_ptr64_longlong,   {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, ulonglong)
471     {LibFunc_msvc_delete_array_ptr32_nothrow,    {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, nothrow)
472     {LibFunc_msvc_delete_array_ptr64_nothrow,    {2, MallocFamily::MSVCArrayNew}},       // delete[](void*, nothrow)
473     {LibFunc___kmpc_free_shared,                 {2, MallocFamily::KmpcAllocShared}},    // OpenMP Offloading RTL free
474     {LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t, {3, MallocFamily::CPPNewAligned}},      // delete(void*, align_val_t, nothrow)
475     {LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t, {3, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, align_val_t, nothrow)
476     {LibFunc_ZdlPvjSt11align_val_t,              {3, MallocFamily::CPPNewAligned}},      // delete(void*, unsigned int, align_val_t)
477     {LibFunc_ZdlPvmSt11align_val_t,              {3, MallocFamily::CPPNewAligned}},      // delete(void*, unsigned long, align_val_t)
478     {LibFunc_ZdaPvjSt11align_val_t,              {3, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, unsigned int, align_val_t)
479     {LibFunc_ZdaPvmSt11align_val_t,              {3, MallocFamily::CPPNewArrayAligned}}, // delete[](void*, unsigned long, align_val_t)
480 };
481 // clang-format on
482 
483 Optional<FreeFnsTy> getFreeFunctionDataForFunction(const Function *Callee,
484                                                    const LibFunc TLIFn) {
485   const auto *Iter =
486       find_if(FreeFnData, [TLIFn](const std::pair<LibFunc, FreeFnsTy> &P) {
487         return P.first == TLIFn;
488       });
489   if (Iter == std::end(FreeFnData))
490     return None;
491   return Iter->second;
492 }
493 
494 Optional<StringRef> llvm::getAllocationFamily(const Value *I,
495                                               const TargetLibraryInfo *TLI) {
496   bool IsNoBuiltin;
497   const Function *Callee = getCalledFunction(I, IsNoBuiltin);
498   if (Callee == nullptr || IsNoBuiltin)
499     return None;
500   LibFunc TLIFn;
501   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
502     return None;
503   const auto AllocData = getAllocationDataForFunction(Callee, AnyAlloc, TLI);
504   if (AllocData.hasValue())
505     return mangledNameForMallocFamily(AllocData.getValue().Family);
506   const auto FreeData = getFreeFunctionDataForFunction(Callee, TLIFn);
507   if (FreeData.hasValue())
508     return mangledNameForMallocFamily(FreeData.getValue().Family);
509   return None;
510 }
511 
512 /// isLibFreeFunction - Returns true if the function is a builtin free()
513 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
514   Optional<FreeFnsTy> FnData = getFreeFunctionDataForFunction(F, TLIFn);
515   if (!FnData.hasValue())
516     return false;
517 
518   // Check free prototype.
519   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
520   // attribute will exist.
521   FunctionType *FTy = F->getFunctionType();
522   if (!FTy->getReturnType()->isVoidTy())
523     return false;
524   if (FTy->getNumParams() != FnData->NumParams)
525     return false;
526   if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
527     return false;
528 
529   return true;
530 }
531 
532 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
533 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
534   bool IsNoBuiltinCall;
535   const Function *Callee = getCalledFunction(I, IsNoBuiltinCall);
536   if (Callee == nullptr || IsNoBuiltinCall)
537     return nullptr;
538 
539   LibFunc TLIFn;
540   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
541     return nullptr;
542 
543   return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
544 }
545 
546 
547 //===----------------------------------------------------------------------===//
548 //  Utility functions to compute size of objects.
549 //
550 static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
551   if (Data.second.isNegative() || Data.first.ult(Data.second))
552     return APInt(Data.first.getBitWidth(), 0);
553   return Data.first - Data.second;
554 }
555 
556 /// Compute the size of the object pointed by Ptr. Returns true and the
557 /// object size in Size if successful, and false otherwise.
558 /// If RoundToAlign is true, then Size is rounded up to the alignment of
559 /// allocas, byval arguments, and global variables.
560 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
561                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
562   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
563   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
564   if (!Visitor.bothKnown(Data))
565     return false;
566 
567   Size = getSizeWithOverflow(Data).getZExtValue();
568   return true;
569 }
570 
571 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
572                                  const DataLayout &DL,
573                                  const TargetLibraryInfo *TLI,
574                                  bool MustSucceed) {
575   return lowerObjectSizeCall(ObjectSize, DL, TLI, /*AAResults=*/nullptr,
576                              MustSucceed);
577 }
578 
579 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
580                                  const DataLayout &DL,
581                                  const TargetLibraryInfo *TLI, AAResults *AA,
582                                  bool MustSucceed) {
583   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
584          "ObjectSize must be a call to llvm.objectsize!");
585 
586   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
587   ObjectSizeOpts EvalOptions;
588   EvalOptions.AA = AA;
589 
590   // Unless we have to fold this to something, try to be as accurate as
591   // possible.
592   if (MustSucceed)
593     EvalOptions.EvalMode =
594         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
595   else
596     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
597 
598   EvalOptions.NullIsUnknownSize =
599       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
600 
601   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
602   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
603   if (StaticOnly) {
604     // FIXME: Does it make sense to just return a failure value if the size won't
605     // fit in the output and `!MustSucceed`?
606     uint64_t Size;
607     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
608         isUIntN(ResultType->getBitWidth(), Size))
609       return ConstantInt::get(ResultType, Size);
610   } else {
611     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
612     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
613     SizeOffsetEvalType SizeOffsetPair =
614         Eval.compute(ObjectSize->getArgOperand(0));
615 
616     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
617       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
618       Builder.SetInsertPoint(ObjectSize);
619 
620       // If we've outside the end of the object, then we can always access
621       // exactly 0 bytes.
622       Value *ResultSize =
623           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
624       Value *UseZero =
625           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
626       ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
627       Value *Ret = Builder.CreateSelect(
628           UseZero, ConstantInt::get(ResultType, 0), ResultSize);
629 
630       // The non-constant size expression cannot evaluate to -1.
631       if (!isa<Constant>(SizeOffsetPair.first) ||
632           !isa<Constant>(SizeOffsetPair.second))
633         Builder.CreateAssumption(
634             Builder.CreateICmpNE(Ret, ConstantInt::get(ResultType, -1)));
635 
636       return Ret;
637     }
638   }
639 
640   if (!MustSucceed)
641     return nullptr;
642 
643   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
644 }
645 
646 STATISTIC(ObjectVisitorArgument,
647           "Number of arguments with unsolved size and offset");
648 STATISTIC(ObjectVisitorLoad,
649           "Number of load instructions with unsolved size and offset");
650 
651 APInt ObjectSizeOffsetVisitor::align(APInt Size, MaybeAlign Alignment) {
652   if (Options.RoundToAlign && Alignment)
653     return APInt(IntTyBits, alignTo(Size.getZExtValue(), *Alignment));
654   return Size;
655 }
656 
657 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
658                                                  const TargetLibraryInfo *TLI,
659                                                  LLVMContext &Context,
660                                                  ObjectSizeOpts Options)
661     : DL(DL), TLI(TLI), Options(Options) {
662   // Pointer size must be rechecked for each object visited since it could have
663   // a different address space.
664 }
665 
666 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
667   unsigned InitialIntTyBits = DL.getIndexTypeSizeInBits(V->getType());
668 
669   // Stripping pointer casts can strip address space casts which can change the
670   // index type size. The invariant is that we use the value type to determine
671   // the index type size and if we stripped address space casts we have to
672   // readjust the APInt as we pass it upwards in order for the APInt to match
673   // the type the caller passed in.
674   APInt Offset(InitialIntTyBits, 0);
675   V = V->stripAndAccumulateConstantOffsets(
676       DL, Offset, /* AllowNonInbounds */ true, /* AllowInvariantGroup */ true);
677 
678   // Later we use the index type size and zero but it will match the type of the
679   // value that is passed to computeImpl.
680   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
681   Zero = APInt::getZero(IntTyBits);
682 
683   bool IndexTypeSizeChanged = InitialIntTyBits != IntTyBits;
684   if (!IndexTypeSizeChanged && Offset.isZero())
685     return computeImpl(V);
686 
687   // We stripped an address space cast that changed the index type size or we
688   // accumulated some constant offset (or both). Readjust the bit width to match
689   // the argument index type size and apply the offset, as required.
690   SizeOffsetType SOT = computeImpl(V);
691   if (IndexTypeSizeChanged) {
692     if (knownSize(SOT) && !::CheckedZextOrTrunc(SOT.first, InitialIntTyBits))
693       SOT.first = APInt();
694     if (knownOffset(SOT) && !::CheckedZextOrTrunc(SOT.second, InitialIntTyBits))
695       SOT.second = APInt();
696   }
697   // If the computed offset is "unknown" we cannot add the stripped offset.
698   return {SOT.first,
699           SOT.second.getBitWidth() > 1 ? SOT.second + Offset : SOT.second};
700 }
701 
702 SizeOffsetType ObjectSizeOffsetVisitor::computeImpl(Value *V) {
703   if (Instruction *I = dyn_cast<Instruction>(V)) {
704     // If we have already seen this instruction, bail out. Cycles can happen in
705     // unreachable code after constant propagation.
706     if (!SeenInsts.insert(I).second)
707       return unknown();
708 
709     return visit(*I);
710   }
711   if (Argument *A = dyn_cast<Argument>(V))
712     return visitArgument(*A);
713   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
714     return visitConstantPointerNull(*P);
715   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
716     return visitGlobalAlias(*GA);
717   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
718     return visitGlobalVariable(*GV);
719   if (UndefValue *UV = dyn_cast<UndefValue>(V))
720     return visitUndefValue(*UV);
721 
722   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
723                     << *V << '\n');
724   return unknown();
725 }
726 
727 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
728   return ::CheckedZextOrTrunc(I, IntTyBits);
729 }
730 
731 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
732   if (!I.getAllocatedType()->isSized())
733     return unknown();
734 
735   TypeSize ElemSize = DL.getTypeAllocSize(I.getAllocatedType());
736   if (ElemSize.isScalable() && Options.EvalMode != ObjectSizeOpts::Mode::Min)
737     return unknown();
738   APInt Size(IntTyBits, ElemSize.getKnownMinSize());
739   if (!I.isArrayAllocation())
740     return std::make_pair(align(Size, I.getAlign()), Zero);
741 
742   Value *ArraySize = I.getArraySize();
743   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
744     APInt NumElems = C->getValue();
745     if (!CheckedZextOrTrunc(NumElems))
746       return unknown();
747 
748     bool Overflow;
749     Size = Size.umul_ov(NumElems, Overflow);
750     return Overflow ? unknown()
751                     : std::make_pair(align(Size, I.getAlign()), Zero);
752   }
753   return unknown();
754 }
755 
756 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
757   Type *MemoryTy = A.getPointeeInMemoryValueType();
758   // No interprocedural analysis is done at the moment.
759   if (!MemoryTy|| !MemoryTy->isSized()) {
760     ++ObjectVisitorArgument;
761     return unknown();
762   }
763 
764   APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
765   return std::make_pair(align(Size, A.getParamAlign()), Zero);
766 }
767 
768 SizeOffsetType ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
769   auto Mapper = [](const Value *V) { return V; };
770   if (Optional<APInt> Size = getAllocSize(&CB, TLI, Mapper))
771     return std::make_pair(*Size, Zero);
772   return unknown();
773 }
774 
775 SizeOffsetType
776 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
777   // If null is unknown, there's nothing we can do. Additionally, non-zero
778   // address spaces can make use of null, so we don't presume to know anything
779   // about that.
780   //
781   // TODO: How should this work with address space casts? We currently just drop
782   // them on the floor, but it's unclear what we should do when a NULL from
783   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
784   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
785     return unknown();
786   return std::make_pair(Zero, Zero);
787 }
788 
789 SizeOffsetType
790 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
791   return unknown();
792 }
793 
794 SizeOffsetType
795 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
796   // Easy cases were already folded by previous passes.
797   return unknown();
798 }
799 
800 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
801   if (GA.isInterposable())
802     return unknown();
803   return compute(GA.getAliasee());
804 }
805 
806 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
807   if (!GV.hasDefinitiveInitializer())
808     return unknown();
809 
810   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
811   return std::make_pair(align(Size, GV.getAlign()), Zero);
812 }
813 
814 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
815   // clueless
816   return unknown();
817 }
818 
819 SizeOffsetType ObjectSizeOffsetVisitor::findLoadSizeOffset(
820     LoadInst &Load, BasicBlock &BB, BasicBlock::iterator From,
821     SmallDenseMap<BasicBlock *, SizeOffsetType, 8> &VisitedBlocks,
822     unsigned &ScannedInstCount) {
823   constexpr unsigned MaxInstsToScan = 128;
824 
825   auto Where = VisitedBlocks.find(&BB);
826   if (Where != VisitedBlocks.end())
827     return Where->second;
828 
829   auto Unknown = [this, &BB, &VisitedBlocks]() {
830     return VisitedBlocks[&BB] = unknown();
831   };
832   auto Known = [&BB, &VisitedBlocks](SizeOffsetType SO) {
833     return VisitedBlocks[&BB] = SO;
834   };
835 
836   do {
837     Instruction &I = *From;
838 
839     if (I.isDebugOrPseudoInst())
840       continue;
841 
842     if (++ScannedInstCount > MaxInstsToScan)
843       return Unknown();
844 
845     if (!I.mayWriteToMemory())
846       continue;
847 
848     if (auto *SI = dyn_cast<StoreInst>(&I)) {
849       AliasResult AR =
850           Options.AA->alias(SI->getPointerOperand(), Load.getPointerOperand());
851       switch ((AliasResult::Kind)AR) {
852       case AliasResult::NoAlias:
853         continue;
854       case AliasResult::MustAlias:
855         if (SI->getValueOperand()->getType()->isPointerTy())
856           return Known(compute(SI->getValueOperand()));
857         else
858           return Unknown(); // No handling of non-pointer values by `compute`.
859       default:
860         return Unknown();
861       }
862     }
863 
864     if (auto *CB = dyn_cast<CallBase>(&I)) {
865       Function *Callee = CB->getCalledFunction();
866       // Bail out on indirect call.
867       if (!Callee)
868         return Unknown();
869 
870       LibFunc TLIFn;
871       if (!TLI || !TLI->getLibFunc(*CB->getCalledFunction(), TLIFn) ||
872           !TLI->has(TLIFn))
873         return Unknown();
874 
875       // TODO: There's probably more interesting case to support here.
876       if (TLIFn != LibFunc_posix_memalign)
877         return Unknown();
878 
879       AliasResult AR =
880           Options.AA->alias(CB->getOperand(0), Load.getPointerOperand());
881       switch ((AliasResult::Kind)AR) {
882       case AliasResult::NoAlias:
883         continue;
884       case AliasResult::MustAlias:
885         break;
886       default:
887         return Unknown();
888       }
889 
890       // Is the error status of posix_memalign correctly checked? If not it
891       // would be incorrect to assume it succeeds and load doesn't see the
892       // previous value.
893       Optional<bool> Checked = isImpliedByDomCondition(
894           ICmpInst::ICMP_EQ, CB, ConstantInt::get(CB->getType(), 0), &Load, DL);
895       if (!Checked || !*Checked)
896         return Unknown();
897 
898       Value *Size = CB->getOperand(2);
899       auto *C = dyn_cast<ConstantInt>(Size);
900       if (!C)
901         return Unknown();
902 
903       return Known({C->getValue(), APInt(C->getValue().getBitWidth(), 0)});
904     }
905 
906     return Unknown();
907   } while (From-- != BB.begin());
908 
909   SmallVector<SizeOffsetType> PredecessorSizeOffsets;
910   for (auto *PredBB : predecessors(&BB)) {
911     PredecessorSizeOffsets.push_back(findLoadSizeOffset(
912         Load, *PredBB, BasicBlock::iterator(PredBB->getTerminator()),
913         VisitedBlocks, ScannedInstCount));
914     if (!bothKnown(PredecessorSizeOffsets.back()))
915       return Unknown();
916   }
917 
918   if (PredecessorSizeOffsets.empty())
919     return Unknown();
920 
921   return Known(std::accumulate(PredecessorSizeOffsets.begin() + 1,
922                                PredecessorSizeOffsets.end(),
923                                PredecessorSizeOffsets.front(),
924                                [this](SizeOffsetType LHS, SizeOffsetType RHS) {
925                                  return combineSizeOffset(LHS, RHS);
926                                }));
927 }
928 
929 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst &LI) {
930   if (!Options.AA) {
931     ++ObjectVisitorLoad;
932     return unknown();
933   }
934 
935   SmallDenseMap<BasicBlock *, SizeOffsetType, 8> VisitedBlocks;
936   unsigned ScannedInstCount = 0;
937   SizeOffsetType SO =
938       findLoadSizeOffset(LI, *LI.getParent(), BasicBlock::iterator(LI),
939                          VisitedBlocks, ScannedInstCount);
940   if (!bothKnown(SO))
941     ++ObjectVisitorLoad;
942   return SO;
943 }
944 
945 SizeOffsetType ObjectSizeOffsetVisitor::combineSizeOffset(SizeOffsetType LHS,
946                                                           SizeOffsetType RHS) {
947   if (!bothKnown(LHS) || !bothKnown(RHS))
948     return unknown();
949 
950   switch (Options.EvalMode) {
951   case ObjectSizeOpts::Mode::Min:
952     return (getSizeWithOverflow(LHS).slt(getSizeWithOverflow(RHS))) ? LHS : RHS;
953   case ObjectSizeOpts::Mode::Max:
954     return (getSizeWithOverflow(LHS).sgt(getSizeWithOverflow(RHS))) ? LHS : RHS;
955   case ObjectSizeOpts::Mode::Exact:
956     return (getSizeWithOverflow(LHS).eq(getSizeWithOverflow(RHS))) ? LHS
957                                                                    : unknown();
958   }
959   llvm_unreachable("missing an eval mode");
960 }
961 
962 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode &PN) {
963   auto IncomingValues = PN.incoming_values();
964   return std::accumulate(IncomingValues.begin() + 1, IncomingValues.end(),
965                          compute(*IncomingValues.begin()),
966                          [this](SizeOffsetType LHS, Value *VRHS) {
967                            return combineSizeOffset(LHS, compute(VRHS));
968                          });
969 }
970 
971 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
972   return combineSizeOffset(compute(I.getTrueValue()),
973                            compute(I.getFalseValue()));
974 }
975 
976 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
977   return std::make_pair(Zero, Zero);
978 }
979 
980 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
981   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
982                     << '\n');
983   return unknown();
984 }
985 
986 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
987     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
988     ObjectSizeOpts EvalOpts)
989     : DL(DL), TLI(TLI), Context(Context),
990       Builder(Context, TargetFolder(DL),
991               IRBuilderCallbackInserter(
992                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
993       EvalOpts(EvalOpts) {
994   // IntTy and Zero must be set for each compute() since the address space may
995   // be different for later objects.
996 }
997 
998 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
999   // XXX - Are vectors of pointers possible here?
1000   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
1001   Zero = ConstantInt::get(IntTy, 0);
1002 
1003   SizeOffsetEvalType Result = compute_(V);
1004 
1005   if (!bothKnown(Result)) {
1006     // Erase everything that was computed in this iteration from the cache, so
1007     // that no dangling references are left behind. We could be a bit smarter if
1008     // we kept a dependency graph. It's probably not worth the complexity.
1009     for (const Value *SeenVal : SeenVals) {
1010       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
1011       // non-computable results can be safely cached
1012       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
1013         CacheMap.erase(CacheIt);
1014     }
1015 
1016     // Erase any instructions we inserted as part of the traversal.
1017     for (Instruction *I : InsertedInstructions) {
1018       I->replaceAllUsesWith(UndefValue::get(I->getType()));
1019       I->eraseFromParent();
1020     }
1021   }
1022 
1023   SeenVals.clear();
1024   InsertedInstructions.clear();
1025   return Result;
1026 }
1027 
1028 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
1029   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
1030   SizeOffsetType Const = Visitor.compute(V);
1031   if (Visitor.bothKnown(Const))
1032     return std::make_pair(ConstantInt::get(Context, Const.first),
1033                           ConstantInt::get(Context, Const.second));
1034 
1035   V = V->stripPointerCasts();
1036 
1037   // Check cache.
1038   CacheMapTy::iterator CacheIt = CacheMap.find(V);
1039   if (CacheIt != CacheMap.end())
1040     return CacheIt->second;
1041 
1042   // Always generate code immediately before the instruction being
1043   // processed, so that the generated code dominates the same BBs.
1044   BuilderTy::InsertPointGuard Guard(Builder);
1045   if (Instruction *I = dyn_cast<Instruction>(V))
1046     Builder.SetInsertPoint(I);
1047 
1048   // Now compute the size and offset.
1049   SizeOffsetEvalType Result;
1050 
1051   // Record the pointers that were handled in this run, so that they can be
1052   // cleaned later if something fails. We also use this set to break cycles that
1053   // can occur in dead code.
1054   if (!SeenVals.insert(V).second) {
1055     Result = unknown();
1056   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1057     Result = visitGEPOperator(*GEP);
1058   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
1059     Result = visit(*I);
1060   } else if (isa<Argument>(V) ||
1061              (isa<ConstantExpr>(V) &&
1062               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
1063              isa<GlobalAlias>(V) ||
1064              isa<GlobalVariable>(V)) {
1065     // Ignore values where we cannot do more than ObjectSizeVisitor.
1066     Result = unknown();
1067   } else {
1068     LLVM_DEBUG(
1069         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
1070                << '\n');
1071     Result = unknown();
1072   }
1073 
1074   // Don't reuse CacheIt since it may be invalid at this point.
1075   CacheMap[V] = Result;
1076   return Result;
1077 }
1078 
1079 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
1080   if (!I.getAllocatedType()->isSized())
1081     return unknown();
1082 
1083   // must be a VLA
1084   assert(I.isArrayAllocation());
1085 
1086   // If needed, adjust the alloca's operand size to match the pointer size.
1087   // Subsequent math operations expect the types to match.
1088   Value *ArraySize = Builder.CreateZExtOrTrunc(
1089       I.getArraySize(), DL.getIntPtrType(I.getContext()));
1090   assert(ArraySize->getType() == Zero->getType() &&
1091          "Expected zero constant to have pointer type");
1092 
1093   Value *Size = ConstantInt::get(ArraySize->getType(),
1094                                  DL.getTypeAllocSize(I.getAllocatedType()));
1095   Size = Builder.CreateMul(Size, ArraySize);
1096   return std::make_pair(Size, Zero);
1097 }
1098 
1099 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallBase(CallBase &CB) {
1100   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
1101   if (!FnData)
1102     return unknown();
1103 
1104   // Handle strdup-like functions separately.
1105   if (FnData->AllocTy == StrDupLike) {
1106     // TODO: implement evaluation of strdup/strndup
1107     return unknown();
1108   }
1109 
1110   Value *FirstArg = CB.getArgOperand(FnData->FstParam);
1111   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
1112   if (FnData->SndParam < 0)
1113     return std::make_pair(FirstArg, Zero);
1114 
1115   Value *SecondArg = CB.getArgOperand(FnData->SndParam);
1116   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
1117   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
1118   return std::make_pair(Size, Zero);
1119 }
1120 
1121 SizeOffsetEvalType
1122 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
1123   return unknown();
1124 }
1125 
1126 SizeOffsetEvalType
1127 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
1128   return unknown();
1129 }
1130 
1131 SizeOffsetEvalType
1132 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
1133   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
1134   if (!bothKnown(PtrData))
1135     return unknown();
1136 
1137   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
1138   Offset = Builder.CreateAdd(PtrData.second, Offset);
1139   return std::make_pair(PtrData.first, Offset);
1140 }
1141 
1142 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
1143   // clueless
1144   return unknown();
1145 }
1146 
1147 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst &LI) {
1148   return unknown();
1149 }
1150 
1151 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
1152   // Create 2 PHIs: one for size and another for offset.
1153   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1154   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1155 
1156   // Insert right away in the cache to handle recursive PHIs.
1157   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
1158 
1159   // Compute offset/size for each PHI incoming pointer.
1160   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1161     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
1162     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
1163 
1164     if (!bothKnown(EdgeData)) {
1165       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
1166       OffsetPHI->eraseFromParent();
1167       InsertedInstructions.erase(OffsetPHI);
1168       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
1169       SizePHI->eraseFromParent();
1170       InsertedInstructions.erase(SizePHI);
1171       return unknown();
1172     }
1173     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1174     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1175   }
1176 
1177   Value *Size = SizePHI, *Offset = OffsetPHI;
1178   if (Value *Tmp = SizePHI->hasConstantValue()) {
1179     Size = Tmp;
1180     SizePHI->replaceAllUsesWith(Size);
1181     SizePHI->eraseFromParent();
1182     InsertedInstructions.erase(SizePHI);
1183   }
1184   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1185     Offset = Tmp;
1186     OffsetPHI->replaceAllUsesWith(Offset);
1187     OffsetPHI->eraseFromParent();
1188     InsertedInstructions.erase(OffsetPHI);
1189   }
1190   return std::make_pair(Size, Offset);
1191 }
1192 
1193 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
1194   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
1195   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1196 
1197   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1198     return unknown();
1199   if (TrueSide == FalseSide)
1200     return TrueSide;
1201 
1202   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1203                                      FalseSide.first);
1204   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1205                                        FalseSide.second);
1206   return std::make_pair(Size, Offset);
1207 }
1208 
1209 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1210   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1211                     << '\n');
1212   return unknown();
1213 }
1214