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