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