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