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