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