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 #define DEBUG_TYPE "memory-builtins"
16 #include "llvm/Analysis/MemoryBuiltins.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Statistic.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/Target/TargetLibraryInfo.h"
30 #include "llvm/Transforms/Utils/Local.h"
34 MallocLike = 1<<0, // allocates
35 CallocLike = 1<<1, // allocates + bzero
36 ReallocLike = 1<<2, // reallocates
38 AllocLike = MallocLike | CallocLike | StrDupLike,
39 AnyAlloc = MallocLike | CallocLike | ReallocLike | StrDupLike
45 unsigned char NumParams;
46 // First and Second size parameters (or -1 if unused)
47 signed char FstParam, SndParam;
50 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
51 // know which functions are nounwind, noalias, nocapture parameters, etc.
52 static const AllocFnsTy AllocationFnData[] = {
53 {LibFunc::malloc, MallocLike, 1, 0, -1},
54 {LibFunc::valloc, MallocLike, 1, 0, -1},
55 {LibFunc::posix_memalign, MallocLike, 3, 2, -1},
56 {LibFunc::calloc, CallocLike, 2, 0, 1},
57 {LibFunc::realloc, ReallocLike, 2, 1, -1},
58 {LibFunc::reallocf, ReallocLike, 2, 1, -1},
59 {LibFunc::strdup, StrDupLike, 1, -1, -1},
60 {LibFunc::strndup, StrDupLike, 2, 1, -1}
64 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
65 if (LookThroughBitCast)
66 V = V->stripPointerCasts();
68 CallSite CS(const_cast<Value*>(V));
69 if (!CS.getInstruction())
72 Function *Callee = CS.getCalledFunction();
73 if (!Callee || !Callee->isDeclaration())
78 /// \brief Returns the allocation data for the given value if it is a call to a
79 /// known allocation function, and NULL otherwise.
80 static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
81 const TargetLibraryInfo *TLI,
82 bool LookThroughBitCast = false) {
84 if (isa<IntrinsicInst>(V))
87 Function *Callee = getCalledFunction(V, LookThroughBitCast);
91 // Make sure that the function is available.
92 StringRef FnName = Callee->getName();
94 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
99 for ( ; i < array_lengthof(AllocationFnData); ++i) {
100 if (AllocationFnData[i].Func == TLIFn) {
108 const AllocFnsTy *FnData = &AllocationFnData[i];
109 if ((FnData->AllocTy & AllocTy) == 0)
112 // Check function prototype.
113 int FstParam = FnData->FstParam;
114 int SndParam = FnData->SndParam;
115 FunctionType *FTy = Callee->getFunctionType();
117 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
118 FTy->getNumParams() == FnData->NumParams &&
120 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
121 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
123 FTy->getParamType(SndParam)->isIntegerTy(32) ||
124 FTy->getParamType(SndParam)->isIntegerTy(64)))
129 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
130 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
131 return CS && CS.hasFnAttr(Attribute::NoAlias);
135 /// \brief Tests if a value is a call or invoke to a library function that
136 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
138 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
139 bool LookThroughBitCast) {
140 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
143 /// \brief Tests if a value is a call or invoke to a function that returns a
144 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
145 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
146 bool LookThroughBitCast) {
147 // it's safe to consider realloc as noalias since accessing the original
148 // pointer is undefined behavior
149 return isAllocationFn(V, TLI, LookThroughBitCast) ||
150 hasNoAliasAttr(V, LookThroughBitCast);
153 /// \brief Tests if a value is a call or invoke to a library function that
154 /// allocates uninitialized memory (such as malloc).
155 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
156 bool LookThroughBitCast) {
157 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
160 /// \brief Tests if a value is a call or invoke to a library function that
161 /// allocates zero-filled memory (such as calloc).
162 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
163 bool LookThroughBitCast) {
164 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
167 /// \brief Tests if a value is a call or invoke to a library function that
168 /// allocates memory (either malloc, calloc, or strdup like).
169 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
170 bool LookThroughBitCast) {
171 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
174 /// \brief Tests if a value is a call or invoke to a library function that
175 /// reallocates memory (such as realloc).
176 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
177 bool LookThroughBitCast) {
178 return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast);
181 /// extractMallocCall - Returns the corresponding CallInst if the instruction
182 /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
183 /// ignore InvokeInst here.
184 const CallInst *llvm::extractMallocCall(const Value *I,
185 const TargetLibraryInfo *TLI) {
186 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : 0;
189 static Value *computeArraySize(const CallInst *CI, const DataLayout *TD,
190 const TargetLibraryInfo *TLI,
191 bool LookThroughSExt = false) {
195 // The size of the malloc's result type must be known to determine array size.
196 Type *T = getMallocAllocatedType(CI, TLI);
197 if (!T || !T->isSized() || !TD)
200 unsigned ElementSize = TD->getTypeAllocSize(T);
201 if (StructType *ST = dyn_cast<StructType>(T))
202 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
204 // If malloc call's arg can be determined to be a multiple of ElementSize,
205 // return the multiple. Otherwise, return NULL.
206 Value *MallocArg = CI->getArgOperand(0);
208 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
215 /// isArrayMalloc - Returns the corresponding CallInst if the instruction
216 /// is a call to malloc whose array size can be determined and the array size
217 /// is not constant 1. Otherwise, return NULL.
218 const CallInst *llvm::isArrayMalloc(const Value *I,
219 const DataLayout *TD,
220 const TargetLibraryInfo *TLI) {
221 const CallInst *CI = extractMallocCall(I, TLI);
222 Value *ArraySize = computeArraySize(CI, TD, TLI);
224 if (ConstantInt *ConstSize = dyn_cast_or_null<ConstantInt>(ArraySize))
225 if (ConstSize->isOne())
228 // CI is a non-array malloc or we can't figure out that it is an array malloc.
232 /// getMallocType - Returns the PointerType resulting from the malloc call.
233 /// The PointerType depends on the number of bitcast uses of the malloc call:
234 /// 0: PointerType is the calls' return type.
235 /// 1: PointerType is the bitcast's result type.
236 /// >1: Unique PointerType cannot be determined, return NULL.
237 PointerType *llvm::getMallocType(const CallInst *CI,
238 const TargetLibraryInfo *TLI) {
239 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
241 PointerType *MallocType = 0;
242 unsigned NumOfBitCastUses = 0;
244 // Determine if CallInst has a bitcast use.
245 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
247 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
248 MallocType = cast<PointerType>(BCI->getDestTy());
252 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
253 if (NumOfBitCastUses == 1)
256 // Malloc call was not bitcast, so type is the malloc function's return type.
257 if (NumOfBitCastUses == 0)
258 return cast<PointerType>(CI->getType());
260 // Type could not be determined.
264 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
265 /// The Type depends on the number of bitcast uses of the malloc call:
266 /// 0: PointerType is the malloc calls' return type.
267 /// 1: PointerType is the bitcast's result type.
268 /// >1: Unique PointerType cannot be determined, return NULL.
269 Type *llvm::getMallocAllocatedType(const CallInst *CI,
270 const TargetLibraryInfo *TLI) {
271 PointerType *PT = getMallocType(CI, TLI);
272 return PT ? PT->getElementType() : 0;
275 /// getMallocArraySize - Returns the array size of a malloc call. If the
276 /// argument passed to malloc is a multiple of the size of the malloced type,
277 /// then return that multiple. For non-array mallocs, the multiple is
278 /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
280 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout *TD,
281 const TargetLibraryInfo *TLI,
282 bool LookThroughSExt) {
283 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
284 return computeArraySize(CI, TD, TLI, LookThroughSExt);
288 /// extractCallocCall - Returns the corresponding CallInst if the instruction
289 /// is a calloc call.
290 const CallInst *llvm::extractCallocCall(const Value *I,
291 const TargetLibraryInfo *TLI) {
292 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : 0;
296 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
297 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
298 const CallInst *CI = dyn_cast<CallInst>(I);
299 if (!CI || isa<IntrinsicInst>(CI))
301 Function *Callee = CI->getCalledFunction();
302 if (Callee == 0 || !Callee->isDeclaration())
305 StringRef FnName = Callee->getName();
307 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
310 if (TLIFn != LibFunc::free &&
311 TLIFn != LibFunc::ZdlPv && // operator delete(void*)
312 TLIFn != LibFunc::ZdaPv) // operator delete[](void*)
315 // Check free prototype.
316 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
317 // attribute will exist.
318 FunctionType *FTy = Callee->getFunctionType();
319 if (!FTy->getReturnType()->isVoidTy())
321 if (FTy->getNumParams() != 1)
323 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
331 //===----------------------------------------------------------------------===//
332 // Utility functions to compute size of objects.
336 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
337 /// object size in Size if successful, and false otherwise.
338 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
339 /// byval arguments, and global variables.
340 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout *TD,
341 const TargetLibraryInfo *TLI, bool RoundToAlign) {
345 ObjectSizeOffsetVisitor Visitor(TD, TLI, Ptr->getContext(), RoundToAlign);
346 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
347 if (!Visitor.bothKnown(Data))
350 APInt ObjSize = Data.first, Offset = Data.second;
351 // check for overflow
352 if (Offset.slt(0) || ObjSize.ult(Offset))
355 Size = (ObjSize - Offset).getZExtValue();
359 /// \brief Compute the size of the underlying object pointed by Ptr. Returns
360 /// true and the object size in Size if successful, and false otherwise.
361 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
362 /// byval arguments, and global variables.
363 bool llvm::getUnderlyingObjectSize(const Value *Ptr, uint64_t &Size,
364 const DataLayout *TD,
365 const TargetLibraryInfo *TLI,
370 ObjectSizeOffsetVisitor Visitor(TD, TLI, Ptr->getContext(), RoundToAlign);
371 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
372 if (!Visitor.knownSize(Data))
375 Size = Data.first.getZExtValue();
380 STATISTIC(ObjectVisitorArgument,
381 "Number of arguments with unsolved size and offset");
382 STATISTIC(ObjectVisitorLoad,
383 "Number of load instructions with unsolved size and offset");
386 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
387 if (RoundToAlign && Align)
388 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
392 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout *TD,
393 const TargetLibraryInfo *TLI,
394 LLVMContext &Context,
396 : TD(TD), TLI(TLI), RoundToAlign(RoundToAlign) {
397 IntegerType *IntTy = TD->getIntPtrType(Context);
398 IntTyBits = IntTy->getBitWidth();
399 Zero = APInt::getNullValue(IntTyBits);
402 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
403 V = V->stripPointerCasts();
405 if (isa<Instruction>(V) || isa<GEPOperator>(V)) {
406 // Return cached value or insert unknown in cache if size of V was not
407 // computed yet in order to avoid recursions in PHis.
408 std::pair<CacheMapTy::iterator, bool> CacheVal =
409 CacheMap.insert(std::make_pair(V, unknown()));
410 if (!CacheVal.second)
411 return CacheVal.first->second;
413 SizeOffsetType Result;
414 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
415 Result = visitGEPOperator(*GEP);
417 Result = visit(cast<Instruction>(*V));
418 return CacheMap[V] = Result;
421 if (Argument *A = dyn_cast<Argument>(V))
422 return visitArgument(*A);
423 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
424 return visitConstantPointerNull(*P);
425 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
426 return visitGlobalAlias(*GA);
427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
428 return visitGlobalVariable(*GV);
429 if (UndefValue *UV = dyn_cast<UndefValue>(V))
430 return visitUndefValue(*UV);
431 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
432 if (CE->getOpcode() == Instruction::IntToPtr)
433 return unknown(); // clueless
436 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
441 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
442 if (!I.getAllocatedType()->isSized())
445 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
446 if (!I.isArrayAllocation())
447 return std::make_pair(align(Size, I.getAlignment()), Zero);
449 Value *ArraySize = I.getArraySize();
450 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
451 Size *= C->getValue().zextOrSelf(IntTyBits);
452 return std::make_pair(align(Size, I.getAlignment()), Zero);
457 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
458 // no interprocedural analysis is done at the moment
459 if (!A.hasByValAttr()) {
460 ++ObjectVisitorArgument;
463 PointerType *PT = cast<PointerType>(A.getType());
464 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
465 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
468 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
469 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
474 // handle strdup-like functions separately
475 if (FnData->AllocTy == StrDupLike) {
476 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
480 // strndup limits strlen
481 if (FnData->FstParam > 0) {
482 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
486 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
487 if (Size.ugt(MaxSize))
490 return std::make_pair(Size, Zero);
493 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
497 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
498 // size determined by just 1 parameter
499 if (FnData->SndParam < 0)
500 return std::make_pair(Size, Zero);
502 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
506 Size *= Arg->getValue().zextOrSelf(IntTyBits);
507 return std::make_pair(Size, Zero);
509 // TODO: handle more standard functions (+ wchar cousins):
510 // - strdup / strndup
511 // - strcpy / strncpy
512 // - strcat / strncat
513 // - memcpy / memmove
514 // - strcat / strncat
519 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
520 return std::make_pair(Zero, Zero);
524 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
529 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
530 // Easy cases were already folded by previous passes.
534 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
535 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
536 APInt Offset(IntTyBits, 0);
537 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(*TD, Offset))
540 return std::make_pair(PtrData.first, PtrData.second + Offset);
543 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
544 if (GA.mayBeOverridden())
546 return compute(GA.getAliasee());
549 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
550 if (!GV.hasDefinitiveInitializer())
553 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
554 return std::make_pair(align(Size, GV.getAlignment()), Zero);
557 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
562 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
567 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode &PHI) {
568 if (PHI.getNumIncomingValues() == 0)
571 SizeOffsetType Ret = compute(PHI.getIncomingValue(0));
575 // Verify that all PHI incoming pointers have the same size and offset.
576 for (unsigned i = 1, e = PHI.getNumIncomingValues(); i != e; ++i) {
577 SizeOffsetType EdgeData = compute(PHI.getIncomingValue(i));
578 if (!bothKnown(EdgeData) || EdgeData != Ret)
584 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
585 SizeOffsetType TrueSide = compute(I.getTrueValue());
586 SizeOffsetType FalseSide = compute(I.getFalseValue());
587 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
592 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
593 return std::make_pair(Zero, Zero);
596 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
597 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
602 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const DataLayout *TD,
603 const TargetLibraryInfo *TLI,
604 LLVMContext &Context)
605 : TD(TD), TLI(TLI), Context(Context), Builder(Context, TargetFolder(TD)) {
606 IntTy = TD->getIntPtrType(Context);
607 Zero = ConstantInt::get(IntTy, 0);
610 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
611 SizeOffsetEvalType Result = compute_(V);
613 if (!bothKnown(Result)) {
614 // erase everything that was computed in this iteration from the cache, so
615 // that no dangling references are left behind. We could be a bit smarter if
616 // we kept a dependency graph. It's probably not worth the complexity.
617 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
618 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
619 // non-computable results can be safely cached
620 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
621 CacheMap.erase(CacheIt);
629 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
630 ObjectSizeOffsetVisitor Visitor(TD, TLI, Context);
631 SizeOffsetType Const = Visitor.compute(V);
632 if (Visitor.bothKnown(Const))
633 return std::make_pair(ConstantInt::get(Context, Const.first),
634 ConstantInt::get(Context, Const.second));
636 V = V->stripPointerCasts();
639 CacheMapTy::iterator CacheIt = CacheMap.find(V);
640 if (CacheIt != CacheMap.end())
641 return CacheIt->second;
643 // always generate code immediately before the instruction being
644 // processed, so that the generated code dominates the same BBs
645 Instruction *PrevInsertPoint = Builder.GetInsertPoint();
646 if (Instruction *I = dyn_cast<Instruction>(V))
647 Builder.SetInsertPoint(I);
649 // record the pointers that were handled in this run, so that they can be
650 // cleaned later if something fails
653 // now compute the size and offset
654 SizeOffsetEvalType Result;
655 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
656 Result = visitGEPOperator(*GEP);
657 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
659 } else if (isa<Argument>(V) ||
660 (isa<ConstantExpr>(V) &&
661 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
662 isa<GlobalAlias>(V) ||
663 isa<GlobalVariable>(V)) {
664 // ignore values where we cannot do more than what ObjectSizeVisitor can
667 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
673 Builder.SetInsertPoint(PrevInsertPoint);
675 // Don't reuse CacheIt since it may be invalid at this point.
676 CacheMap[V] = Result;
680 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
681 if (!I.getAllocatedType()->isSized())
685 assert(I.isArrayAllocation());
686 Value *ArraySize = I.getArraySize();
687 Value *Size = ConstantInt::get(ArraySize->getType(),
688 TD->getTypeAllocSize(I.getAllocatedType()));
689 Size = Builder.CreateMul(Size, ArraySize);
690 return std::make_pair(Size, Zero);
693 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
694 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
699 // handle strdup-like functions separately
700 if (FnData->AllocTy == StrDupLike) {
705 Value *FirstArg = CS.getArgument(FnData->FstParam);
706 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
707 if (FnData->SndParam < 0)
708 return std::make_pair(FirstArg, Zero);
710 Value *SecondArg = CS.getArgument(FnData->SndParam);
711 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
712 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
713 return std::make_pair(Size, Zero);
715 // TODO: handle more standard functions (+ wchar cousins):
716 // - strdup / strndup
717 // - strcpy / strncpy
718 // - strcat / strncat
719 // - memcpy / memmove
720 // - strcat / strncat
725 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
730 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
735 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
736 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
737 if (!bothKnown(PtrData))
740 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
741 Offset = Builder.CreateAdd(PtrData.second, Offset);
742 return std::make_pair(PtrData.first, Offset);
745 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
750 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
754 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
755 // create 2 PHIs: one for size and another for offset
756 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
757 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
759 // insert right away in the cache to handle recursive PHIs
760 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
762 // compute offset/size for each PHI incoming pointer
763 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
764 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
765 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
767 if (!bothKnown(EdgeData)) {
768 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
769 OffsetPHI->eraseFromParent();
770 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
771 SizePHI->eraseFromParent();
774 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
775 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
778 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
779 if ((Tmp = SizePHI->hasConstantValue())) {
781 SizePHI->replaceAllUsesWith(Size);
782 SizePHI->eraseFromParent();
784 if ((Tmp = OffsetPHI->hasConstantValue())) {
786 OffsetPHI->replaceAllUsesWith(Offset);
787 OffsetPHI->eraseFromParent();
789 return std::make_pair(Size, Offset);
792 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
793 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
794 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
796 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
798 if (TrueSide == FalseSide)
801 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
803 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
805 return std::make_pair(Size, Offset);
808 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
809 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');