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/ADT/StringRef.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 <utility>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "memory-builtins"
51 
52 enum AllocType : uint8_t {
53   OpNewLike          = 1<<0, // allocates; never returns null
54   MallocLike         = 1<<1 | OpNewLike, // allocates; may return null
55   AlignedAllocLike   = 1<<2, // allocates with alignment; may return null
56   CallocLike         = 1<<3, // allocates + bzero
57   ReallocLike        = 1<<4, // reallocates
58   StrDupLike         = 1<<5,
59   MallocOrCallocLike = MallocLike | CallocLike | AlignedAllocLike,
60   AllocLike          = MallocOrCallocLike | StrDupLike,
61   AnyAlloc           = AllocLike | ReallocLike
62 };
63 
64 struct AllocFnsTy {
65   AllocType AllocTy;
66   unsigned NumParams;
67   // First and Second size parameters (or -1 if unused)
68   int FstParam, SndParam;
69 };
70 
71 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
72 // know which functions are nounwind, noalias, nocapture parameters, etc.
73 static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
74   {LibFunc_malloc,              {MallocLike,  1, 0,  -1}},
75   {LibFunc_vec_malloc,          {MallocLike,  1, 0,  -1}},
76   {LibFunc_valloc,              {MallocLike,  1, 0,  -1}},
77   {LibFunc_Znwj,                {OpNewLike,   1, 0,  -1}}, // new(unsigned int)
78   {LibFunc_ZnwjRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new(unsigned int, nothrow)
79   {LibFunc_ZnwjSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new(unsigned int, align_val_t)
80   {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow)
81                                 {MallocLike,  3, 0,  -1}},
82   {LibFunc_Znwm,                {OpNewLike,   1, 0,  -1}}, // new(unsigned long)
83   {LibFunc_ZnwmRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new(unsigned long, nothrow)
84   {LibFunc_ZnwmSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new(unsigned long, align_val_t)
85   {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow)
86                                 {MallocLike,  3, 0,  -1}},
87   {LibFunc_Znaj,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned int)
88   {LibFunc_ZnajRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned int, nothrow)
89   {LibFunc_ZnajSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new[](unsigned int, align_val_t)
90   {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow)
91                                 {MallocLike,  3, 0,  -1}},
92   {LibFunc_Znam,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned long)
93   {LibFunc_ZnamRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned long, nothrow)
94   {LibFunc_ZnamSt11align_val_t, {OpNewLike,   2, 0,  -1}}, // new[](unsigned long, align_val_t)
95   {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow)
96                                  {MallocLike,  3, 0,  -1}},
97   {LibFunc_msvc_new_int,         {OpNewLike,   1, 0,  -1}}, // new(unsigned int)
98   {LibFunc_msvc_new_int_nothrow, {MallocLike,  2, 0,  -1}}, // new(unsigned int, nothrow)
99   {LibFunc_msvc_new_longlong,         {OpNewLike,   1, 0,  -1}}, // new(unsigned long long)
100   {LibFunc_msvc_new_longlong_nothrow, {MallocLike,  2, 0,  -1}}, // new(unsigned long long, nothrow)
101   {LibFunc_msvc_new_array_int,         {OpNewLike,   1, 0,  -1}}, // new[](unsigned int)
102   {LibFunc_msvc_new_array_int_nothrow, {MallocLike,  2, 0,  -1}}, // new[](unsigned int, nothrow)
103   {LibFunc_msvc_new_array_longlong,         {OpNewLike,   1, 0,  -1}}, // new[](unsigned long long)
104   {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike,  2, 0,  -1}}, // new[](unsigned long long, nothrow)
105   {LibFunc_aligned_alloc,       {AlignedAllocLike, 2, 1,  -1}},
106   {LibFunc_memalign,            {AlignedAllocLike, 2, 1,  -1}},
107   {LibFunc_calloc,              {CallocLike,  2, 0,   1}},
108   {LibFunc_vec_calloc,          {CallocLike,  2, 0,   1}},
109   {LibFunc_realloc,             {ReallocLike, 2, 1,  -1}},
110   {LibFunc_vec_realloc,         {ReallocLike, 2, 1,  -1}},
111   {LibFunc_reallocf,            {ReallocLike, 2, 1,  -1}},
112   {LibFunc_strdup,              {StrDupLike,  1, -1, -1}},
113   {LibFunc_strndup,             {StrDupLike,  2, 1,  -1}},
114   {LibFunc___kmpc_alloc_shared, {MallocLike,  1, 0,  -1}},
115   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
116 };
117 
118 static const Function *getCalledFunction(const Value *V,
119                                          bool &IsNoBuiltin) {
120   // Don't care about intrinsics in this case.
121   if (isa<IntrinsicInst>(V))
122     return nullptr;
123 
124   const auto *CB = dyn_cast<CallBase>(V);
125   if (!CB)
126     return nullptr;
127 
128   IsNoBuiltin = CB->isNoBuiltin();
129 
130   if (const Function *Callee = CB->getCalledFunction())
131     return Callee;
132   return nullptr;
133 }
134 
135 /// Returns the allocation data for the given value if it's a call to a known
136 /// allocation function.
137 static Optional<AllocFnsTy>
138 getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
139                              const TargetLibraryInfo *TLI) {
140   // Make sure that the function is available.
141   LibFunc TLIFn;
142   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
143     return None;
144 
145   const auto *Iter = find_if(
146       AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
147         return P.first == TLIFn;
148       });
149 
150   if (Iter == std::end(AllocationFnData))
151     return None;
152 
153   const AllocFnsTy *FnData = &Iter->second;
154   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
155     return None;
156 
157   // Check function prototype.
158   int FstParam = FnData->FstParam;
159   int SndParam = FnData->SndParam;
160   FunctionType *FTy = Callee->getFunctionType();
161 
162   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
163       FTy->getNumParams() == FnData->NumParams &&
164       (FstParam < 0 ||
165        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
166         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
167       (SndParam < 0 ||
168        FTy->getParamType(SndParam)->isIntegerTy(32) ||
169        FTy->getParamType(SndParam)->isIntegerTy(64)))
170     return *FnData;
171   return None;
172 }
173 
174 static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
175                                               const TargetLibraryInfo *TLI) {
176   bool IsNoBuiltinCall;
177   if (const Function *Callee = getCalledFunction(V, IsNoBuiltinCall))
178     if (!IsNoBuiltinCall)
179       return getAllocationDataForFunction(Callee, AllocTy, TLI);
180   return None;
181 }
182 
183 static Optional<AllocFnsTy>
184 getAllocationData(const Value *V, AllocType AllocTy,
185                   function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
186   bool IsNoBuiltinCall;
187   if (const Function *Callee = getCalledFunction(V, IsNoBuiltinCall))
188     if (!IsNoBuiltinCall)
189       return getAllocationDataForFunction(
190           Callee, AllocTy, &GetTLI(const_cast<Function &>(*Callee)));
191   return None;
192 }
193 
194 static Optional<AllocFnsTy> getAllocationSize(const Value *V,
195                                               const TargetLibraryInfo *TLI) {
196   bool IsNoBuiltinCall;
197   const Function *Callee =
198       getCalledFunction(V, IsNoBuiltinCall);
199   if (!Callee)
200     return None;
201 
202   // Prefer to use existing information over allocsize. This will give us an
203   // accurate AllocTy.
204   if (!IsNoBuiltinCall)
205     if (Optional<AllocFnsTy> Data =
206             getAllocationDataForFunction(Callee, AnyAlloc, TLI))
207       return Data;
208 
209   Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
210   if (Attr == Attribute())
211     return None;
212 
213   std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
214 
215   AllocFnsTy Result;
216   // Because allocsize only tells us how many bytes are allocated, we're not
217   // really allowed to assume anything, so we use MallocLike.
218   Result.AllocTy = MallocLike;
219   Result.NumParams = Callee->getNumOperands();
220   Result.FstParam = Args.first;
221   Result.SndParam = Args.second.getValueOr(-1);
222   return Result;
223 }
224 
225 /// Tests if a value is a call or invoke to a library function that
226 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
227 /// like).
228 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI) {
229   return getAllocationData(V, AnyAlloc, TLI).hasValue();
230 }
231 bool llvm::isAllocationFn(
232     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
233   return getAllocationData(V, AnyAlloc, GetTLI).hasValue();
234 }
235 
236 /// Tests if a value is a call or invoke to a library function that
237 /// allocates uninitialized memory (such as malloc).
238 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
239   return getAllocationData(V, MallocLike, TLI).hasValue();
240 }
241 bool llvm::isMallocLikeFn(
242     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
243   return getAllocationData(V, MallocLike, GetTLI)
244       .hasValue();
245 }
246 
247 /// Tests if a value is a call or invoke to a library function that
248 /// allocates uninitialized memory with alignment (such as aligned_alloc).
249 bool llvm::isAlignedAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
250   return getAllocationData(V, AlignedAllocLike, TLI)
251       .hasValue();
252 }
253 bool llvm::isAlignedAllocLikeFn(
254     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
255   return getAllocationData(V, AlignedAllocLike, GetTLI)
256       .hasValue();
257 }
258 
259 /// Tests if a value is a call or invoke to a library function that
260 /// allocates zero-filled memory (such as calloc).
261 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
262   return getAllocationData(V, CallocLike, TLI).hasValue();
263 }
264 
265 /// Tests if a value is a call or invoke to a library function that
266 /// allocates memory similar to malloc or calloc.
267 bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
268   return getAllocationData(V, MallocOrCallocLike, TLI).hasValue();
269 }
270 
271 /// Tests if a value is a call or invoke to a library function that
272 /// allocates memory (either malloc, calloc, or strdup like).
273 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
274   return getAllocationData(V, AllocLike, TLI).hasValue();
275 }
276 
277 /// Tests if a value is a call or invoke to a library function that
278 /// reallocates memory (e.g., realloc).
279 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
280   return getAllocationData(V, ReallocLike, TLI).hasValue();
281 }
282 
283 /// Tests if a functions is a call or invoke to a library function that
284 /// reallocates memory (e.g., realloc).
285 bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
286   return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
287 }
288 
289 /// Tests if a value is a call or invoke to a library function that
290 /// allocates memory and throws if an allocation failed (e.g., new).
291 bool llvm::isOpNewLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
292   return getAllocationData(V, OpNewLike, TLI).hasValue();
293 }
294 
295 /// Tests if a value is a call or invoke to a library function that
296 /// allocates memory (strdup, strndup).
297 bool llvm::isStrdupLikeFn(const Value *V, const TargetLibraryInfo *TLI) {
298   return getAllocationData(V, StrDupLike, TLI).hasValue();
299 }
300 
301 Constant *llvm::getInitialValueOfAllocation(const CallBase *Alloc,
302                                             const TargetLibraryInfo *TLI,
303                                             Type *Ty) {
304   assert(isAllocationFn(Alloc, TLI));
305 
306   // malloc and aligned_alloc are uninitialized (undef)
307   if (isMallocLikeFn(Alloc, TLI) || isAlignedAllocLikeFn(Alloc, TLI))
308     return UndefValue::get(Ty);
309 
310   // calloc zero initializes
311   if (isCallocLikeFn(Alloc, TLI))
312     return Constant::getNullValue(Ty);
313 
314   return nullptr;
315 }
316 
317 /// isLibFreeFunction - Returns true if the function is a builtin free()
318 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
319   unsigned ExpectedNumParams;
320   if (TLIFn == LibFunc_free ||
321       TLIFn == LibFunc_ZdlPv || // operator delete(void*)
322       TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
323       TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
324       TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
325       TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
326       TLIFn == LibFunc_msvc_delete_array_ptr64)   // operator delete[](void*)
327     ExpectedNumParams = 1;
328   else if (TLIFn == LibFunc_ZdlPvj ||              // delete(void*, uint)
329            TLIFn == LibFunc_ZdlPvm ||              // delete(void*, ulong)
330            TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
331            TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
332            TLIFn == LibFunc_ZdaPvj ||              // delete[](void*, uint)
333            TLIFn == LibFunc_ZdaPvm ||              // delete[](void*, ulong)
334            TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
335            TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
336            TLIFn == LibFunc_msvc_delete_ptr32_int ||      // delete(void*, uint)
337            TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
338            TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
339            TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
340            TLIFn == LibFunc_msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
341            TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
342            TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
343            TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow || // delete[](void*, nothrow)
344            TLIFn == LibFunc___kmpc_free_shared) // OpenMP Offloading RTL free
345     ExpectedNumParams = 2;
346   else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
347            TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t || // delete[](void*, align_val_t, nothrow)
348            TLIFn == LibFunc_ZdlPvjSt11align_val_t || // delete(void*, unsigned long, align_val_t)
349            TLIFn == LibFunc_ZdlPvmSt11align_val_t || // delete(void*, unsigned long, align_val_t)
350            TLIFn == LibFunc_ZdaPvjSt11align_val_t || // delete[](void*, unsigned int, align_val_t)
351            TLIFn == LibFunc_ZdaPvmSt11align_val_t) // delete[](void*, unsigned long, align_val_t)
352     ExpectedNumParams = 3;
353   else
354     return false;
355 
356   // Check free prototype.
357   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
358   // attribute will exist.
359   FunctionType *FTy = F->getFunctionType();
360   if (!FTy->getReturnType()->isVoidTy())
361     return false;
362   if (FTy->getNumParams() != ExpectedNumParams)
363     return false;
364   if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
365     return false;
366 
367   return true;
368 }
369 
370 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
371 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
372   bool IsNoBuiltinCall;
373   const Function *Callee = getCalledFunction(I, IsNoBuiltinCall);
374   if (Callee == nullptr || IsNoBuiltinCall)
375     return nullptr;
376 
377   LibFunc TLIFn;
378   if (!TLI || !TLI->getLibFunc(*Callee, TLIFn) || !TLI->has(TLIFn))
379     return nullptr;
380 
381   return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
382 }
383 
384 
385 //===----------------------------------------------------------------------===//
386 //  Utility functions to compute size of objects.
387 //
388 static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
389   if (Data.second.isNegative() || Data.first.ult(Data.second))
390     return APInt(Data.first.getBitWidth(), 0);
391   return Data.first - Data.second;
392 }
393 
394 /// Compute the size of the object pointed by Ptr. Returns true and the
395 /// object size in Size if successful, and false otherwise.
396 /// If RoundToAlign is true, then Size is rounded up to the alignment of
397 /// allocas, byval arguments, and global variables.
398 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
399                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
400   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
401   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
402   if (!Visitor.bothKnown(Data))
403     return false;
404 
405   Size = getSizeWithOverflow(Data).getZExtValue();
406   return true;
407 }
408 
409 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
410                                  const DataLayout &DL,
411                                  const TargetLibraryInfo *TLI,
412                                  bool MustSucceed) {
413   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
414          "ObjectSize must be a call to llvm.objectsize!");
415 
416   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
417   ObjectSizeOpts EvalOptions;
418   // Unless we have to fold this to something, try to be as accurate as
419   // possible.
420   if (MustSucceed)
421     EvalOptions.EvalMode =
422         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
423   else
424     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
425 
426   EvalOptions.NullIsUnknownSize =
427       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
428 
429   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
430   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
431   if (StaticOnly) {
432     // FIXME: Does it make sense to just return a failure value if the size won't
433     // fit in the output and `!MustSucceed`?
434     uint64_t Size;
435     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
436         isUIntN(ResultType->getBitWidth(), Size))
437       return ConstantInt::get(ResultType, Size);
438   } else {
439     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
440     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
441     SizeOffsetEvalType SizeOffsetPair =
442         Eval.compute(ObjectSize->getArgOperand(0));
443 
444     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
445       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
446       Builder.SetInsertPoint(ObjectSize);
447 
448       // If we've outside the end of the object, then we can always access
449       // exactly 0 bytes.
450       Value *ResultSize =
451           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
452       Value *UseZero =
453           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
454       ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
455       Value *Ret = Builder.CreateSelect(
456           UseZero, ConstantInt::get(ResultType, 0), ResultSize);
457 
458       // The non-constant size expression cannot evaluate to -1.
459       if (!isa<Constant>(SizeOffsetPair.first) ||
460           !isa<Constant>(SizeOffsetPair.second))
461         Builder.CreateAssumption(
462             Builder.CreateICmpNE(Ret, ConstantInt::get(ResultType, -1)));
463 
464       return Ret;
465     }
466   }
467 
468   if (!MustSucceed)
469     return nullptr;
470 
471   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
472 }
473 
474 STATISTIC(ObjectVisitorArgument,
475           "Number of arguments with unsolved size and offset");
476 STATISTIC(ObjectVisitorLoad,
477           "Number of load instructions with unsolved size and offset");
478 
479 APInt ObjectSizeOffsetVisitor::align(APInt Size, MaybeAlign Alignment) {
480   if (Options.RoundToAlign && Alignment)
481     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Alignment));
482   return Size;
483 }
484 
485 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
486                                                  const TargetLibraryInfo *TLI,
487                                                  LLVMContext &Context,
488                                                  ObjectSizeOpts Options)
489     : DL(DL), TLI(TLI), Options(Options) {
490   // Pointer size must be rechecked for each object visited since it could have
491   // a different address space.
492 }
493 
494 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
495   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
496   Zero = APInt::getZero(IntTyBits);
497 
498   V = V->stripPointerCasts();
499   if (Instruction *I = dyn_cast<Instruction>(V)) {
500     // If we have already seen this instruction, bail out. Cycles can happen in
501     // unreachable code after constant propagation.
502     if (!SeenInsts.insert(I).second)
503       return unknown();
504 
505     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
506       return visitGEPOperator(*GEP);
507     return visit(*I);
508   }
509   if (Argument *A = dyn_cast<Argument>(V))
510     return visitArgument(*A);
511   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
512     return visitConstantPointerNull(*P);
513   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
514     return visitGlobalAlias(*GA);
515   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
516     return visitGlobalVariable(*GV);
517   if (UndefValue *UV = dyn_cast<UndefValue>(V))
518     return visitUndefValue(*UV);
519   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
520     if (CE->getOpcode() == Instruction::IntToPtr)
521       return unknown(); // clueless
522     if (CE->getOpcode() == Instruction::GetElementPtr)
523       return visitGEPOperator(cast<GEPOperator>(*CE));
524   }
525 
526   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
527                     << *V << '\n');
528   return unknown();
529 }
530 
531 /// When we're compiling N-bit code, and the user uses parameters that are
532 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
533 /// trouble with APInt size issues. This function handles resizing + overflow
534 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
535 /// I's value.
536 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
537   // More bits than we can handle. Checking the bit width isn't necessary, but
538   // it's faster than checking active bits, and should give `false` in the
539   // vast majority of cases.
540   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
541     return false;
542   if (I.getBitWidth() != IntTyBits)
543     I = I.zextOrTrunc(IntTyBits);
544   return true;
545 }
546 
547 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
548   if (!I.getAllocatedType()->isSized())
549     return unknown();
550 
551   if (isa<ScalableVectorType>(I.getAllocatedType()))
552     return unknown();
553 
554   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
555   if (!I.isArrayAllocation())
556     return std::make_pair(align(Size, I.getAlign()), Zero);
557 
558   Value *ArraySize = I.getArraySize();
559   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
560     APInt NumElems = C->getValue();
561     if (!CheckedZextOrTrunc(NumElems))
562       return unknown();
563 
564     bool Overflow;
565     Size = Size.umul_ov(NumElems, Overflow);
566     return Overflow ? unknown()
567                     : std::make_pair(align(Size, I.getAlign()), Zero);
568   }
569   return unknown();
570 }
571 
572 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
573   Type *MemoryTy = A.getPointeeInMemoryValueType();
574   // No interprocedural analysis is done at the moment.
575   if (!MemoryTy|| !MemoryTy->isSized()) {
576     ++ObjectVisitorArgument;
577     return unknown();
578   }
579 
580   APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
581   return std::make_pair(align(Size, A.getParamAlign()), Zero);
582 }
583 
584 SizeOffsetType ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
585   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
586   if (!FnData)
587     return unknown();
588 
589   // Handle strdup-like functions separately.
590   if (FnData->AllocTy == StrDupLike) {
591     APInt Size(IntTyBits, GetStringLength(CB.getArgOperand(0)));
592     if (!Size)
593       return unknown();
594 
595     // Strndup limits strlen.
596     if (FnData->FstParam > 0) {
597       ConstantInt *Arg =
598           dyn_cast<ConstantInt>(CB.getArgOperand(FnData->FstParam));
599       if (!Arg)
600         return unknown();
601 
602       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
603       if (Size.ugt(MaxSize))
604         Size = MaxSize + 1;
605     }
606     return std::make_pair(Size, Zero);
607   }
608 
609   ConstantInt *Arg = dyn_cast<ConstantInt>(CB.getArgOperand(FnData->FstParam));
610   if (!Arg)
611     return unknown();
612 
613   APInt Size = Arg->getValue();
614   if (!CheckedZextOrTrunc(Size))
615     return unknown();
616 
617   // Size is determined by just 1 parameter.
618   if (FnData->SndParam < 0)
619     return std::make_pair(Size, Zero);
620 
621   Arg = dyn_cast<ConstantInt>(CB.getArgOperand(FnData->SndParam));
622   if (!Arg)
623     return unknown();
624 
625   APInt NumElems = Arg->getValue();
626   if (!CheckedZextOrTrunc(NumElems))
627     return unknown();
628 
629   bool Overflow;
630   Size = Size.umul_ov(NumElems, Overflow);
631   return Overflow ? unknown() : std::make_pair(Size, Zero);
632 }
633 
634 SizeOffsetType
635 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
636   // If null is unknown, there's nothing we can do. Additionally, non-zero
637   // address spaces can make use of null, so we don't presume to know anything
638   // about that.
639   //
640   // TODO: How should this work with address space casts? We currently just drop
641   // them on the floor, but it's unclear what we should do when a NULL from
642   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
643   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
644     return unknown();
645   return std::make_pair(Zero, Zero);
646 }
647 
648 SizeOffsetType
649 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
650   return unknown();
651 }
652 
653 SizeOffsetType
654 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
655   // Easy cases were already folded by previous passes.
656   return unknown();
657 }
658 
659 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
660   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
661   APInt Offset(DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()), 0);
662   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
663     return unknown();
664 
665   return std::make_pair(PtrData.first, PtrData.second + Offset);
666 }
667 
668 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
669   if (GA.isInterposable())
670     return unknown();
671   return compute(GA.getAliasee());
672 }
673 
674 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
675   if (!GV.hasDefinitiveInitializer())
676     return unknown();
677 
678   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
679   return std::make_pair(align(Size, GV.getAlign()), Zero);
680 }
681 
682 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
683   // clueless
684   return unknown();
685 }
686 
687 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
688   ++ObjectVisitorLoad;
689   return unknown();
690 }
691 
692 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
693   // too complex to analyze statically.
694   return unknown();
695 }
696 
697 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
698   SizeOffsetType TrueSide  = compute(I.getTrueValue());
699   SizeOffsetType FalseSide = compute(I.getFalseValue());
700   if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
701     if (TrueSide == FalseSide) {
702         return TrueSide;
703     }
704 
705     APInt TrueResult = getSizeWithOverflow(TrueSide);
706     APInt FalseResult = getSizeWithOverflow(FalseSide);
707 
708     if (TrueResult == FalseResult) {
709       return TrueSide;
710     }
711     if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
712       if (TrueResult.slt(FalseResult))
713         return TrueSide;
714       return FalseSide;
715     }
716     if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
717       if (TrueResult.sgt(FalseResult))
718         return TrueSide;
719       return FalseSide;
720     }
721   }
722   return unknown();
723 }
724 
725 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
726   return std::make_pair(Zero, Zero);
727 }
728 
729 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
730   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
731                     << '\n');
732   return unknown();
733 }
734 
735 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
736     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
737     ObjectSizeOpts EvalOpts)
738     : DL(DL), TLI(TLI), Context(Context),
739       Builder(Context, TargetFolder(DL),
740               IRBuilderCallbackInserter(
741                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
742       EvalOpts(EvalOpts) {
743   // IntTy and Zero must be set for each compute() since the address space may
744   // be different for later objects.
745 }
746 
747 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
748   // XXX - Are vectors of pointers possible here?
749   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
750   Zero = ConstantInt::get(IntTy, 0);
751 
752   SizeOffsetEvalType Result = compute_(V);
753 
754   if (!bothKnown(Result)) {
755     // Erase everything that was computed in this iteration from the cache, so
756     // that no dangling references are left behind. We could be a bit smarter if
757     // we kept a dependency graph. It's probably not worth the complexity.
758     for (const Value *SeenVal : SeenVals) {
759       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
760       // non-computable results can be safely cached
761       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
762         CacheMap.erase(CacheIt);
763     }
764 
765     // Erase any instructions we inserted as part of the traversal.
766     for (Instruction *I : InsertedInstructions) {
767       I->replaceAllUsesWith(UndefValue::get(I->getType()));
768       I->eraseFromParent();
769     }
770   }
771 
772   SeenVals.clear();
773   InsertedInstructions.clear();
774   return Result;
775 }
776 
777 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
778   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
779   SizeOffsetType Const = Visitor.compute(V);
780   if (Visitor.bothKnown(Const))
781     return std::make_pair(ConstantInt::get(Context, Const.first),
782                           ConstantInt::get(Context, Const.second));
783 
784   V = V->stripPointerCasts();
785 
786   // Check cache.
787   CacheMapTy::iterator CacheIt = CacheMap.find(V);
788   if (CacheIt != CacheMap.end())
789     return CacheIt->second;
790 
791   // Always generate code immediately before the instruction being
792   // processed, so that the generated code dominates the same BBs.
793   BuilderTy::InsertPointGuard Guard(Builder);
794   if (Instruction *I = dyn_cast<Instruction>(V))
795     Builder.SetInsertPoint(I);
796 
797   // Now compute the size and offset.
798   SizeOffsetEvalType Result;
799 
800   // Record the pointers that were handled in this run, so that they can be
801   // cleaned later if something fails. We also use this set to break cycles that
802   // can occur in dead code.
803   if (!SeenVals.insert(V).second) {
804     Result = unknown();
805   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
806     Result = visitGEPOperator(*GEP);
807   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
808     Result = visit(*I);
809   } else if (isa<Argument>(V) ||
810              (isa<ConstantExpr>(V) &&
811               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
812              isa<GlobalAlias>(V) ||
813              isa<GlobalVariable>(V)) {
814     // Ignore values where we cannot do more than ObjectSizeVisitor.
815     Result = unknown();
816   } else {
817     LLVM_DEBUG(
818         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
819                << '\n');
820     Result = unknown();
821   }
822 
823   // Don't reuse CacheIt since it may be invalid at this point.
824   CacheMap[V] = Result;
825   return Result;
826 }
827 
828 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
829   if (!I.getAllocatedType()->isSized())
830     return unknown();
831 
832   // must be a VLA
833   assert(I.isArrayAllocation());
834 
835   // If needed, adjust the alloca's operand size to match the pointer size.
836   // Subsequent math operations expect the types to match.
837   Value *ArraySize = Builder.CreateZExtOrTrunc(
838       I.getArraySize(), DL.getIntPtrType(I.getContext()));
839   assert(ArraySize->getType() == Zero->getType() &&
840          "Expected zero constant to have pointer type");
841 
842   Value *Size = ConstantInt::get(ArraySize->getType(),
843                                  DL.getTypeAllocSize(I.getAllocatedType()));
844   Size = Builder.CreateMul(Size, ArraySize);
845   return std::make_pair(Size, Zero);
846 }
847 
848 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallBase(CallBase &CB) {
849   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
850   if (!FnData)
851     return unknown();
852 
853   // Handle strdup-like functions separately.
854   if (FnData->AllocTy == StrDupLike) {
855     // TODO: implement evaluation of strdup/strndup
856     return unknown();
857   }
858 
859   Value *FirstArg = CB.getArgOperand(FnData->FstParam);
860   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
861   if (FnData->SndParam < 0)
862     return std::make_pair(FirstArg, Zero);
863 
864   Value *SecondArg = CB.getArgOperand(FnData->SndParam);
865   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
866   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
867   return std::make_pair(Size, Zero);
868 }
869 
870 SizeOffsetEvalType
871 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
872   return unknown();
873 }
874 
875 SizeOffsetEvalType
876 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
877   return unknown();
878 }
879 
880 SizeOffsetEvalType
881 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
882   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
883   if (!bothKnown(PtrData))
884     return unknown();
885 
886   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
887   Offset = Builder.CreateAdd(PtrData.second, Offset);
888   return std::make_pair(PtrData.first, Offset);
889 }
890 
891 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
892   // clueless
893   return unknown();
894 }
895 
896 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
897   return unknown();
898 }
899 
900 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
901   // Create 2 PHIs: one for size and another for offset.
902   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
903   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
904 
905   // Insert right away in the cache to handle recursive PHIs.
906   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
907 
908   // Compute offset/size for each PHI incoming pointer.
909   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
910     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
911     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
912 
913     if (!bothKnown(EdgeData)) {
914       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
915       OffsetPHI->eraseFromParent();
916       InsertedInstructions.erase(OffsetPHI);
917       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
918       SizePHI->eraseFromParent();
919       InsertedInstructions.erase(SizePHI);
920       return unknown();
921     }
922     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
923     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
924   }
925 
926   Value *Size = SizePHI, *Offset = OffsetPHI;
927   if (Value *Tmp = SizePHI->hasConstantValue()) {
928     Size = Tmp;
929     SizePHI->replaceAllUsesWith(Size);
930     SizePHI->eraseFromParent();
931     InsertedInstructions.erase(SizePHI);
932   }
933   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
934     Offset = Tmp;
935     OffsetPHI->replaceAllUsesWith(Offset);
936     OffsetPHI->eraseFromParent();
937     InsertedInstructions.erase(OffsetPHI);
938   }
939   return std::make_pair(Size, Offset);
940 }
941 
942 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
943   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
944   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
945 
946   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
947     return unknown();
948   if (TrueSide == FalseSide)
949     return TrueSide;
950 
951   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
952                                      FalseSide.first);
953   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
954                                        FalseSide.second);
955   return std::make_pair(Size, Offset);
956 }
957 
958 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
959   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
960                     << '\n');
961   return unknown();
962 }
963