1 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions identifies calls to builtin functions that allocate
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/MemoryBuiltins.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/Local.h"
32 #define DEBUG_TYPE "memory-builtins"
34 enum AllocType : uint8_t {
35 OpNewLike = 1<<0, // allocates; never returns null
36 MallocLike = 1<<1 | OpNewLike, // allocates; may return null
37 CallocLike = 1<<2, // allocates + bzero
38 ReallocLike = 1<<3, // reallocates
40 AllocLike = MallocLike | CallocLike | StrDupLike,
41 AnyAlloc = AllocLike | ReallocLike
47 unsigned char NumParams;
48 // First and Second size parameters (or -1 if unused)
49 signed char FstParam, SndParam;
52 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
53 // know which functions are nounwind, noalias, nocapture parameters, etc.
54 static const AllocFnsTy AllocationFnData[] = {
55 {LibFunc::malloc, MallocLike, 1, 0, -1},
56 {LibFunc::valloc, MallocLike, 1, 0, -1},
57 {LibFunc::Znwj, OpNewLike, 1, 0, -1}, // new(unsigned int)
58 {LibFunc::ZnwjRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
59 {LibFunc::Znwm, OpNewLike, 1, 0, -1}, // new(unsigned long)
60 {LibFunc::ZnwmRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned long, nothrow)
61 {LibFunc::Znaj, OpNewLike, 1, 0, -1}, // new[](unsigned int)
62 {LibFunc::ZnajRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
63 {LibFunc::Znam, OpNewLike, 1, 0, -1}, // new[](unsigned long)
64 {LibFunc::ZnamRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned long, nothrow)
65 {LibFunc::msvc_new_int, OpNewLike, 1, 0, -1}, // new(unsigned int)
66 {LibFunc::msvc_new_int_nothrow, MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
67 {LibFunc::msvc_new_longlong, OpNewLike, 1, 0, -1}, // new(unsigned long long)
68 {LibFunc::msvc_new_longlong_nothrow, MallocLike, 2, 0, -1}, // new(unsigned long long, nothrow)
69 {LibFunc::msvc_new_array_int, OpNewLike, 1, 0, -1}, // new[](unsigned int)
70 {LibFunc::msvc_new_array_int_nothrow, MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
71 {LibFunc::msvc_new_array_longlong, OpNewLike, 1, 0, -1}, // new[](unsigned long long)
72 {LibFunc::msvc_new_array_longlong_nothrow, MallocLike, 2, 0, -1}, // new[](unsigned long long, nothrow)
73 {LibFunc::calloc, CallocLike, 2, 0, 1},
74 {LibFunc::realloc, ReallocLike, 2, 1, -1},
75 {LibFunc::reallocf, ReallocLike, 2, 1, -1},
76 {LibFunc::strdup, StrDupLike, 1, -1, -1},
77 {LibFunc::strndup, StrDupLike, 2, 1, -1}
78 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
82 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
83 if (LookThroughBitCast)
84 V = V->stripPointerCasts();
86 CallSite CS(const_cast<Value*>(V));
87 if (!CS.getInstruction())
93 Function *Callee = CS.getCalledFunction();
94 if (!Callee || !Callee->isDeclaration())
99 /// \brief Returns the allocation data for the given value if it is a call to a
100 /// known allocation function, and NULL otherwise.
101 static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
102 const TargetLibraryInfo *TLI,
103 bool LookThroughBitCast = false) {
105 if (isa<IntrinsicInst>(V))
108 Function *Callee = getCalledFunction(V, LookThroughBitCast);
112 // Make sure that the function is available.
113 StringRef FnName = Callee->getName();
115 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
118 const AllocFnsTy *FnData =
119 std::find_if(std::begin(AllocationFnData), std::end(AllocationFnData),
120 [TLIFn](const AllocFnsTy &Fn) { return Fn.Func == TLIFn; });
122 if (FnData == std::end(AllocationFnData))
125 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
128 // Check function prototype.
129 int FstParam = FnData->FstParam;
130 int SndParam = FnData->SndParam;
131 FunctionType *FTy = Callee->getFunctionType();
133 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
134 FTy->getNumParams() == FnData->NumParams &&
136 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
137 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
139 FTy->getParamType(SndParam)->isIntegerTy(32) ||
140 FTy->getParamType(SndParam)->isIntegerTy(64)))
145 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
146 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
147 return CS && CS.hasFnAttr(Attribute::NoAlias);
151 /// \brief Tests if a value is a call or invoke to a library function that
152 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
154 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
155 bool LookThroughBitCast) {
156 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
159 /// \brief Tests if a value is a call or invoke to a function that returns a
160 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
161 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
162 bool LookThroughBitCast) {
163 // it's safe to consider realloc as noalias since accessing the original
164 // pointer is undefined behavior
165 return isAllocationFn(V, TLI, LookThroughBitCast) ||
166 hasNoAliasAttr(V, LookThroughBitCast);
169 /// \brief Tests if a value is a call or invoke to a library function that
170 /// allocates uninitialized memory (such as malloc).
171 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
172 bool LookThroughBitCast) {
173 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
176 /// \brief Tests if a value is a call or invoke to a library function that
177 /// allocates zero-filled memory (such as calloc).
178 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
179 bool LookThroughBitCast) {
180 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
183 /// \brief Tests if a value is a call or invoke to a library function that
184 /// allocates memory (either malloc, calloc, or strdup like).
185 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
186 bool LookThroughBitCast) {
187 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
190 /// extractMallocCall - Returns the corresponding CallInst if the instruction
191 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
192 /// ignore InvokeInst here.
193 const CallInst *llvm::extractMallocCall(const Value *I,
194 const TargetLibraryInfo *TLI) {
195 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
198 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
199 const TargetLibraryInfo *TLI,
200 bool LookThroughSExt = false) {
204 // The size of the malloc's result type must be known to determine array size.
205 Type *T = getMallocAllocatedType(CI, TLI);
206 if (!T || !T->isSized())
209 unsigned ElementSize = DL.getTypeAllocSize(T);
210 if (StructType *ST = dyn_cast<StructType>(T))
211 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
213 // If malloc call's arg can be determined to be a multiple of ElementSize,
214 // return the multiple. Otherwise, return NULL.
215 Value *MallocArg = CI->getArgOperand(0);
216 Value *Multiple = nullptr;
217 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
224 /// getMallocType - Returns the PointerType resulting from the malloc call.
225 /// The PointerType depends on the number of bitcast uses of the malloc call:
226 /// 0: PointerType is the calls' return type.
227 /// 1: PointerType is the bitcast's result type.
228 /// >1: Unique PointerType cannot be determined, return NULL.
229 PointerType *llvm::getMallocType(const CallInst *CI,
230 const TargetLibraryInfo *TLI) {
231 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
233 PointerType *MallocType = nullptr;
234 unsigned NumOfBitCastUses = 0;
236 // Determine if CallInst has a bitcast use.
237 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
239 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
240 MallocType = cast<PointerType>(BCI->getDestTy());
244 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
245 if (NumOfBitCastUses == 1)
248 // Malloc call was not bitcast, so type is the malloc function's return type.
249 if (NumOfBitCastUses == 0)
250 return cast<PointerType>(CI->getType());
252 // Type could not be determined.
256 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
257 /// The Type depends on the number of bitcast uses of the malloc call:
258 /// 0: PointerType is the malloc calls' return type.
259 /// 1: PointerType is the bitcast's result type.
260 /// >1: Unique PointerType cannot be determined, return NULL.
261 Type *llvm::getMallocAllocatedType(const CallInst *CI,
262 const TargetLibraryInfo *TLI) {
263 PointerType *PT = getMallocType(CI, TLI);
264 return PT ? PT->getElementType() : nullptr;
267 /// getMallocArraySize - Returns the array size of a malloc call. If the
268 /// argument passed to malloc is a multiple of the size of the malloced type,
269 /// then return that multiple. For non-array mallocs, the multiple is
270 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
272 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
273 const TargetLibraryInfo *TLI,
274 bool LookThroughSExt) {
275 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
276 return computeArraySize(CI, DL, TLI, LookThroughSExt);
280 /// extractCallocCall - Returns the corresponding CallInst if the instruction
281 /// is a calloc call.
282 const CallInst *llvm::extractCallocCall(const Value *I,
283 const TargetLibraryInfo *TLI) {
284 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
288 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
289 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
290 const CallInst *CI = dyn_cast<CallInst>(I);
291 if (!CI || isa<IntrinsicInst>(CI))
293 Function *Callee = CI->getCalledFunction();
294 if (Callee == nullptr)
297 StringRef FnName = Callee->getName();
299 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
302 unsigned ExpectedNumParams;
303 if (TLIFn == LibFunc::free ||
304 TLIFn == LibFunc::ZdlPv || // operator delete(void*)
305 TLIFn == LibFunc::ZdaPv || // operator delete[](void*)
306 TLIFn == LibFunc::msvc_delete_ptr32 || // operator delete(void*)
307 TLIFn == LibFunc::msvc_delete_ptr64 || // operator delete(void*)
308 TLIFn == LibFunc::msvc_delete_array_ptr32 || // operator delete[](void*)
309 TLIFn == LibFunc::msvc_delete_array_ptr64) // operator delete[](void*)
310 ExpectedNumParams = 1;
311 else if (TLIFn == LibFunc::ZdlPvj || // delete(void*, uint)
312 TLIFn == LibFunc::ZdlPvm || // delete(void*, ulong)
313 TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
314 TLIFn == LibFunc::ZdaPvj || // delete[](void*, uint)
315 TLIFn == LibFunc::ZdaPvm || // delete[](void*, ulong)
316 TLIFn == LibFunc::ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
317 TLIFn == LibFunc::msvc_delete_ptr32_int || // delete(void*, uint)
318 TLIFn == LibFunc::msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
319 TLIFn == LibFunc::msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
320 TLIFn == LibFunc::msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
321 TLIFn == LibFunc::msvc_delete_array_ptr32_int || // delete[](void*, uint)
322 TLIFn == LibFunc::msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
323 TLIFn == LibFunc::msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
324 TLIFn == LibFunc::msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
325 ExpectedNumParams = 2;
329 // Check free prototype.
330 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
331 // attribute will exist.
332 FunctionType *FTy = Callee->getFunctionType();
333 if (!FTy->getReturnType()->isVoidTy())
335 if (FTy->getNumParams() != ExpectedNumParams)
337 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
345 //===----------------------------------------------------------------------===//
346 // Utility functions to compute size of objects.
350 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
351 /// object size in Size if successful, and false otherwise.
352 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
353 /// byval arguments, and global variables.
354 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
355 const TargetLibraryInfo *TLI, bool RoundToAlign) {
356 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), RoundToAlign);
357 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
358 if (!Visitor.bothKnown(Data))
361 APInt ObjSize = Data.first, Offset = Data.second;
362 // check for overflow
363 if (Offset.slt(0) || ObjSize.ult(Offset))
366 Size = (ObjSize - Offset).getZExtValue();
371 STATISTIC(ObjectVisitorArgument,
372 "Number of arguments with unsolved size and offset");
373 STATISTIC(ObjectVisitorLoad,
374 "Number of load instructions with unsolved size and offset");
377 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
378 if (RoundToAlign && Align)
379 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
383 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
384 const TargetLibraryInfo *TLI,
385 LLVMContext &Context,
387 : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign) {
388 // Pointer size must be rechecked for each object visited since it could have
389 // a different address space.
392 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
393 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
394 Zero = APInt::getNullValue(IntTyBits);
396 V = V->stripPointerCasts();
397 if (Instruction *I = dyn_cast<Instruction>(V)) {
398 // If we have already seen this instruction, bail out. Cycles can happen in
399 // unreachable code after constant propagation.
400 if (!SeenInsts.insert(I).second)
403 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
404 return visitGEPOperator(*GEP);
407 if (Argument *A = dyn_cast<Argument>(V))
408 return visitArgument(*A);
409 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
410 return visitConstantPointerNull(*P);
411 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
412 return visitGlobalAlias(*GA);
413 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
414 return visitGlobalVariable(*GV);
415 if (UndefValue *UV = dyn_cast<UndefValue>(V))
416 return visitUndefValue(*UV);
417 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
418 if (CE->getOpcode() == Instruction::IntToPtr)
419 return unknown(); // clueless
420 if (CE->getOpcode() == Instruction::GetElementPtr)
421 return visitGEPOperator(cast<GEPOperator>(*CE));
424 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
429 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
430 if (!I.getAllocatedType()->isSized())
433 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
434 if (!I.isArrayAllocation())
435 return std::make_pair(align(Size, I.getAlignment()), Zero);
437 Value *ArraySize = I.getArraySize();
438 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
439 Size *= C->getValue().zextOrSelf(IntTyBits);
440 return std::make_pair(align(Size, I.getAlignment()), Zero);
445 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
446 // no interprocedural analysis is done at the moment
447 if (!A.hasByValOrInAllocaAttr()) {
448 ++ObjectVisitorArgument;
451 PointerType *PT = cast<PointerType>(A.getType());
452 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
453 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
456 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
457 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
462 // handle strdup-like functions separately
463 if (FnData->AllocTy == StrDupLike) {
464 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
468 // strndup limits strlen
469 if (FnData->FstParam > 0) {
470 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
474 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
475 if (Size.ugt(MaxSize))
478 return std::make_pair(Size, Zero);
481 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
485 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
486 // size determined by just 1 parameter
487 if (FnData->SndParam < 0)
488 return std::make_pair(Size, Zero);
490 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
494 Size *= Arg->getValue().zextOrSelf(IntTyBits);
495 return std::make_pair(Size, Zero);
497 // TODO: handle more standard functions (+ wchar cousins):
498 // - strdup / strndup
499 // - strcpy / strncpy
500 // - strcat / strncat
501 // - memcpy / memmove
502 // - strcat / strncat
507 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
508 return std::make_pair(Zero, Zero);
512 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
517 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
518 // Easy cases were already folded by previous passes.
522 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
523 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
524 APInt Offset(IntTyBits, 0);
525 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
528 return std::make_pair(PtrData.first, PtrData.second + Offset);
531 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
532 if (GA.mayBeOverridden())
534 return compute(GA.getAliasee());
537 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
538 if (!GV.hasDefinitiveInitializer())
541 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
542 return std::make_pair(align(Size, GV.getAlignment()), Zero);
545 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
550 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
555 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
556 // too complex to analyze statically.
560 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
561 SizeOffsetType TrueSide = compute(I.getTrueValue());
562 SizeOffsetType FalseSide = compute(I.getFalseValue());
563 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
568 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
569 return std::make_pair(Zero, Zero);
572 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
573 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
577 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
578 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
580 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
581 RoundToAlign(RoundToAlign) {
582 // IntTy and Zero must be set for each compute() since the address space may
583 // be different for later objects.
586 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
587 // XXX - Are vectors of pointers possible here?
588 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
589 Zero = ConstantInt::get(IntTy, 0);
591 SizeOffsetEvalType Result = compute_(V);
593 if (!bothKnown(Result)) {
594 // erase everything that was computed in this iteration from the cache, so
595 // that no dangling references are left behind. We could be a bit smarter if
596 // we kept a dependency graph. It's probably not worth the complexity.
597 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
598 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
599 // non-computable results can be safely cached
600 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
601 CacheMap.erase(CacheIt);
609 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
610 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
611 SizeOffsetType Const = Visitor.compute(V);
612 if (Visitor.bothKnown(Const))
613 return std::make_pair(ConstantInt::get(Context, Const.first),
614 ConstantInt::get(Context, Const.second));
616 V = V->stripPointerCasts();
619 CacheMapTy::iterator CacheIt = CacheMap.find(V);
620 if (CacheIt != CacheMap.end())
621 return CacheIt->second;
623 // always generate code immediately before the instruction being
624 // processed, so that the generated code dominates the same BBs
625 BuilderTy::InsertPointGuard Guard(Builder);
626 if (Instruction *I = dyn_cast<Instruction>(V))
627 Builder.SetInsertPoint(I);
629 // now compute the size and offset
630 SizeOffsetEvalType Result;
632 // Record the pointers that were handled in this run, so that they can be
633 // cleaned later if something fails. We also use this set to break cycles that
634 // can occur in dead code.
635 if (!SeenVals.insert(V).second) {
637 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
638 Result = visitGEPOperator(*GEP);
639 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
641 } else if (isa<Argument>(V) ||
642 (isa<ConstantExpr>(V) &&
643 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
644 isa<GlobalAlias>(V) ||
645 isa<GlobalVariable>(V)) {
646 // ignore values where we cannot do more than what ObjectSizeVisitor can
649 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
654 // Don't reuse CacheIt since it may be invalid at this point.
655 CacheMap[V] = Result;
659 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
660 if (!I.getAllocatedType()->isSized())
664 assert(I.isArrayAllocation());
665 Value *ArraySize = I.getArraySize();
666 Value *Size = ConstantInt::get(ArraySize->getType(),
667 DL.getTypeAllocSize(I.getAllocatedType()));
668 Size = Builder.CreateMul(Size, ArraySize);
669 return std::make_pair(Size, Zero);
672 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
673 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
678 // handle strdup-like functions separately
679 if (FnData->AllocTy == StrDupLike) {
684 Value *FirstArg = CS.getArgument(FnData->FstParam);
685 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
686 if (FnData->SndParam < 0)
687 return std::make_pair(FirstArg, Zero);
689 Value *SecondArg = CS.getArgument(FnData->SndParam);
690 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
691 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
692 return std::make_pair(Size, Zero);
694 // TODO: handle more standard functions (+ wchar cousins):
695 // - strdup / strndup
696 // - strcpy / strncpy
697 // - strcat / strncat
698 // - memcpy / memmove
699 // - strcat / strncat
704 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
709 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
714 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
715 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
716 if (!bothKnown(PtrData))
719 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
720 Offset = Builder.CreateAdd(PtrData.second, Offset);
721 return std::make_pair(PtrData.first, Offset);
724 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
729 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
733 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
734 // create 2 PHIs: one for size and another for offset
735 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
736 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
738 // insert right away in the cache to handle recursive PHIs
739 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
741 // compute offset/size for each PHI incoming pointer
742 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
743 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
744 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
746 if (!bothKnown(EdgeData)) {
747 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
748 OffsetPHI->eraseFromParent();
749 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
750 SizePHI->eraseFromParent();
753 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
754 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
757 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
758 if ((Tmp = SizePHI->hasConstantValue())) {
760 SizePHI->replaceAllUsesWith(Size);
761 SizePHI->eraseFromParent();
763 if ((Tmp = OffsetPHI->hasConstantValue())) {
765 OffsetPHI->replaceAllUsesWith(Offset);
766 OffsetPHI->eraseFromParent();
768 return std::make_pair(Size, Offset);
771 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
772 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
773 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
775 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
777 if (TrueSide == FalseSide)
780 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
782 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
784 return std::make_pair(Size, Offset);
787 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
788 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');