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