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