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