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