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