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