blob: 2503bfa2161e168e6b9a2014e7fb4f83addaa3db [file] [log] [blame]
Victor Hernandezf006b182009-10-27 20:05:49 +00001//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
Evan Chengfabcb912009-09-10 04:36:43 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Victor Hernandezf006b182009-10-27 20:05:49 +000010// This family of functions identifies calls to builtin functions that allocate
11// or free memory.
Evan Chengfabcb912009-09-10 04:36:43 +000012//
13//===----------------------------------------------------------------------===//
14
Nuno Lopes9e72a792012-06-21 15:45:28 +000015#define DEBUG_TYPE "memory-builtins"
Victor Hernandezf006b182009-10-27 20:05:49 +000016#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/DataLayout.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000021#include "llvm/GlobalVariable.h"
Evan Chengfabcb912009-09-10 04:36:43 +000022#include "llvm/Instructions.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000023#include "llvm/Intrinsics.h"
24#include "llvm/Metadata.h"
Evan Chengfabcb912009-09-10 04:36:43 +000025#include "llvm/Module.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/raw_ostream.h"
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000029#include "llvm/Target/TargetLibraryInfo.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000030#include "llvm/Transforms/Utils/Local.h"
Evan Chengfabcb912009-09-10 04:36:43 +000031using namespace llvm;
32
Nuno Lopes9e72a792012-06-21 15:45:28 +000033enum AllocType {
34 MallocLike = 1<<0, // allocates
35 CallocLike = 1<<1, // allocates + bzero
36 ReallocLike = 1<<2, // reallocates
37 StrDupLike = 1<<3,
38 AllocLike = MallocLike | CallocLike | StrDupLike,
39 AnyAlloc = MallocLike | CallocLike | ReallocLike | StrDupLike
40};
Evan Chengfabcb912009-09-10 04:36:43 +000041
Nuno Lopes9e72a792012-06-21 15:45:28 +000042struct AllocFnsTy {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000043 LibFunc::Func Func;
Nuno Lopes9e72a792012-06-21 15:45:28 +000044 AllocType AllocTy;
45 unsigned char NumParams;
46 // First and Second size parameters (or -1 if unused)
Nuno Lopesef22f042012-06-21 18:38:26 +000047 signed char FstParam, SndParam;
Nuno Lopes9e72a792012-06-21 15:45:28 +000048};
Evan Chengfabcb912009-09-10 04:36:43 +000049
Nuno Lopes41a3f252012-06-28 16:34:03 +000050// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
51// know which functions are nounwind, noalias, nocapture parameters, etc.
Nuno Lopes9e72a792012-06-21 15:45:28 +000052static const AllocFnsTy AllocationFnData[] = {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000053 {LibFunc::malloc, MallocLike, 1, 0, -1},
54 {LibFunc::valloc, MallocLike, 1, 0, -1},
55 {LibFunc::Znwj, MallocLike, 1, 0, -1}, // new(unsigned int)
56 {LibFunc::ZnwjRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
57 {LibFunc::Znwm, MallocLike, 1, 0, -1}, // new(unsigned long)
58 {LibFunc::ZnwmRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned long, nothrow)
59 {LibFunc::Znaj, MallocLike, 1, 0, -1}, // new[](unsigned int)
60 {LibFunc::ZnajRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
61 {LibFunc::Znam, MallocLike, 1, 0, -1}, // new[](unsigned long)
62 {LibFunc::ZnamRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned long, nothrow)
63 {LibFunc::posix_memalign, MallocLike, 3, 2, -1},
64 {LibFunc::calloc, CallocLike, 2, 0, 1},
65 {LibFunc::realloc, ReallocLike, 2, 1, -1},
66 {LibFunc::reallocf, ReallocLike, 2, 1, -1},
67 {LibFunc::strdup, StrDupLike, 1, -1, -1},
68 {LibFunc::strndup, StrDupLike, 2, 1, -1}
Nuno Lopes9e72a792012-06-21 15:45:28 +000069};
70
71
72static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
73 if (LookThroughBitCast)
74 V = V->stripPointerCasts();
Nuno Lopes2b3e9582012-06-21 21:25:05 +000075
Nuno Lopesd845c342012-06-22 15:50:53 +000076 CallSite CS(const_cast<Value*>(V));
77 if (!CS.getInstruction())
Nuno Lopes9e72a792012-06-21 15:45:28 +000078 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +000079
Nuno Lopes2b3e9582012-06-21 21:25:05 +000080 Function *Callee = CS.getCalledFunction();
Nuno Lopes9e72a792012-06-21 15:45:28 +000081 if (!Callee || !Callee->isDeclaration())
82 return 0;
83 return Callee;
84}
Evan Chengfabcb912009-09-10 04:36:43 +000085
Nuno Lopes9e72a792012-06-21 15:45:28 +000086/// \brief Returns the allocation data for the given value if it is a call to a
87/// known allocation function, and NULL otherwise.
88static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000089 const TargetLibraryInfo *TLI,
Nuno Lopes9e72a792012-06-21 15:45:28 +000090 bool LookThroughBitCast = false) {
91 Function *Callee = getCalledFunction(V, LookThroughBitCast);
92 if (!Callee)
93 return 0;
94
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000095 // Make sure that the function is available.
96 StringRef FnName = Callee->getName();
97 LibFunc::Func TLIFn;
98 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
99 return 0;
100
Nuno Lopes9e72a792012-06-21 15:45:28 +0000101 unsigned i = 0;
102 bool found = false;
103 for ( ; i < array_lengthof(AllocationFnData); ++i) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000104 if (AllocationFnData[i].Func == TLIFn) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000105 found = true;
106 break;
107 }
108 }
109 if (!found)
110 return 0;
111
112 const AllocFnsTy *FnData = &AllocationFnData[i];
113 if ((FnData->AllocTy & AllocTy) == 0)
114 return 0;
115
116 // Check function prototype.
Nuno Lopesef22f042012-06-21 18:38:26 +0000117 int FstParam = FnData->FstParam;
118 int SndParam = FnData->SndParam;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000119 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000120
121 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
122 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000123 (FstParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000124 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
125 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000126 (SndParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000127 FTy->getParamType(SndParam)->isIntegerTy(32) ||
128 FTy->getParamType(SndParam)->isIntegerTy(64)))
129 return FnData;
130 return 0;
131}
132
133static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopese8742d02012-06-25 16:17:54 +0000134 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Bill Wendling034b94b2012-12-19 07:18:57 +0000135 return CS && CS.hasFnAttr(Attribute::NoAlias);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000136}
137
138
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000139/// \brief Tests if a value is a call or invoke to a library function that
140/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
141/// like).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000142bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
143 bool LookThroughBitCast) {
144 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000145}
146
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000147/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes41a3f252012-06-28 16:34:03 +0000148/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000149bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
150 bool LookThroughBitCast) {
Nuno Lopes41a3f252012-06-28 16:34:03 +0000151 // it's safe to consider realloc as noalias since accessing the original
152 // pointer is undefined behavior
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000153 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000154 hasNoAliasAttr(V, LookThroughBitCast);
155}
156
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000157/// \brief Tests if a value is a call or invoke to a library function that
158/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000159bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
160 bool LookThroughBitCast) {
161 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000162}
163
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000164/// \brief Tests if a value is a call or invoke to a library function that
165/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000166bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
167 bool LookThroughBitCast) {
168 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000169}
170
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000171/// \brief Tests if a value is a call or invoke to a library function that
172/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000173bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
174 bool LookThroughBitCast) {
175 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000176}
177
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000178/// \brief Tests if a value is a call or invoke to a library function that
179/// reallocates memory (such as realloc).
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000180bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
181 bool LookThroughBitCast) {
182 return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast);
Evan Chengfabcb912009-09-10 04:36:43 +0000183}
184
185/// extractMallocCall - Returns the corresponding CallInst if the instruction
186/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
187/// ignore InvokeInst here.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000188const CallInst *llvm::extractMallocCall(const Value *I,
189 const TargetLibraryInfo *TLI) {
190 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000191}
192
Micah Villmow3574eca2012-10-08 16:38:25 +0000193static Value *computeArraySize(const CallInst *CI, const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000194 const TargetLibraryInfo *TLI,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000195 bool LookThroughSExt = false) {
Evan Chengfabcb912009-09-10 04:36:43 +0000196 if (!CI)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000197 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000198
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000199 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000200 Type *T = getMallocAllocatedType(CI, TLI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000201 if (!T || !T->isSized() || !TD)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000202 return NULL;
Victor Hernandez88d98392009-09-18 19:20:02 +0000203
Victor Hernandez8e345a12009-11-10 08:32:25 +0000204 unsigned ElementSize = TD->getTypeAllocSize(T);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000205 if (StructType *ST = dyn_cast<StructType>(T))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000206 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez88d98392009-09-18 19:20:02 +0000207
Gabor Greife3401c42010-06-23 21:41:47 +0000208 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000209 // return the multiple. Otherwise, return NULL.
Gabor Greife3401c42010-06-23 21:41:47 +0000210 Value *MallocArg = CI->getArgOperand(0);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000211 Value *Multiple = NULL;
Victor Hernandez8e345a12009-11-10 08:32:25 +0000212 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000213 LookThroughSExt))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000214 return Multiple;
Victor Hernandez88d98392009-09-18 19:20:02 +0000215
Victor Hernandez90f48e72009-10-28 20:18:55 +0000216 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000217}
218
219/// isArrayMalloc - Returns the corresponding CallInst if the instruction
Victor Hernandez90f48e72009-10-28 20:18:55 +0000220/// is a call to malloc whose array size can be determined and the array size
221/// is not constant 1. Otherwise, return NULL.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000222const CallInst *llvm::isArrayMalloc(const Value *I,
Micah Villmow3574eca2012-10-08 16:38:25 +0000223 const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000224 const TargetLibraryInfo *TLI) {
225 const CallInst *CI = extractMallocCall(I, TLI);
226 Value *ArraySize = computeArraySize(CI, TD, TLI);
Victor Hernandez90f48e72009-10-28 20:18:55 +0000227
228 if (ArraySize &&
Gabor Greife3401c42010-06-23 21:41:47 +0000229 ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Victor Hernandez90f48e72009-10-28 20:18:55 +0000230 return CI;
231
232 // CI is a non-array malloc or we can't figure out that it is an array malloc.
233 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000234}
235
236/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000237/// The PointerType depends on the number of bitcast uses of the malloc call:
238/// 0: PointerType is the calls' return type.
239/// 1: PointerType is the bitcast's result type.
240/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000241PointerType *llvm::getMallocType(const CallInst *CI,
242 const TargetLibraryInfo *TLI) {
243 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Evan Chengfabcb912009-09-10 04:36:43 +0000244
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000245 PointerType *MallocType = NULL;
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000246 unsigned NumOfBitCastUses = 0;
247
Victor Hernandez88d98392009-09-18 19:20:02 +0000248 // Determine if CallInst has a bitcast use.
Gabor Greif60ad7812010-03-25 23:06:16 +0000249 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
Victor Hernandez88d98392009-09-18 19:20:02 +0000250 UI != E; )
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000251 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
252 MallocType = cast<PointerType>(BCI->getDestTy());
253 NumOfBitCastUses++;
254 }
Evan Chengfabcb912009-09-10 04:36:43 +0000255
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000256 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
257 if (NumOfBitCastUses == 1)
258 return MallocType;
Evan Chengfabcb912009-09-10 04:36:43 +0000259
Victor Hernandez60cfc032009-09-22 18:50:03 +0000260 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000261 if (NumOfBitCastUses == 0)
Victor Hernandez88d98392009-09-18 19:20:02 +0000262 return cast<PointerType>(CI->getType());
263
264 // Type could not be determined.
265 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000266}
267
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000268/// getMallocAllocatedType - Returns the Type allocated by malloc call.
269/// The Type depends on the number of bitcast uses of the malloc call:
270/// 0: PointerType is the malloc calls' return type.
271/// 1: PointerType is the bitcast's result type.
272/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000273Type *llvm::getMallocAllocatedType(const CallInst *CI,
274 const TargetLibraryInfo *TLI) {
275 PointerType *PT = getMallocType(CI, TLI);
Evan Chengfabcb912009-09-10 04:36:43 +0000276 return PT ? PT->getElementType() : NULL;
277}
278
Victor Hernandez90f48e72009-10-28 20:18:55 +0000279/// getMallocArraySize - Returns the array size of a malloc call. If the
280/// argument passed to malloc is a multiple of the size of the malloced type,
281/// then return that multiple. For non-array mallocs, the multiple is
282/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez2491ce02009-10-15 20:14:52 +0000283/// determined.
Micah Villmow3574eca2012-10-08 16:38:25 +0000284Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000285 const TargetLibraryInfo *TLI,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000286 bool LookThroughSExt) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000287 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
288 return computeArraySize(CI, TD, TLI, LookThroughSExt);
Evan Chengfabcb912009-09-10 04:36:43 +0000289}
Victor Hernandez66284e02009-10-24 04:23:03 +0000290
Nuno Lopes252ef562012-05-03 21:19:58 +0000291
Nuno Lopes252ef562012-05-03 21:19:58 +0000292/// extractCallocCall - Returns the corresponding CallInst if the instruction
293/// is a calloc call.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000294const CallInst *llvm::extractCallocCall(const Value *I,
295 const TargetLibraryInfo *TLI) {
296 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : 0;
Nuno Lopes252ef562012-05-03 21:19:58 +0000297}
298
Victor Hernandez046e78c2009-10-26 23:43:48 +0000299
Gabor Greif02680f92010-06-23 21:51:12 +0000300/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000301const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandez66284e02009-10-24 04:23:03 +0000302 const CallInst *CI = dyn_cast<CallInst>(I);
303 if (!CI)
Gabor Greif02680f92010-06-23 21:51:12 +0000304 return 0;
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000305 Function *Callee = CI->getCalledFunction();
Nick Lewycky42e72ca2011-03-15 07:31:32 +0000306 if (Callee == 0 || !Callee->isDeclaration())
307 return 0;
308
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000309 StringRef FnName = Callee->getName();
310 LibFunc::Func TLIFn;
311 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
312 return 0;
313
314 if (TLIFn != LibFunc::free &&
315 TLIFn != LibFunc::ZdlPv && // operator delete(void*)
316 TLIFn != LibFunc::ZdaPv) // operator delete[](void*)
Gabor Greif02680f92010-06-23 21:51:12 +0000317 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000318
319 // Check free prototype.
320 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
321 // attribute will exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000322 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000323 if (!FTy->getReturnType()->isVoidTy())
Gabor Greif02680f92010-06-23 21:51:12 +0000324 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000325 if (FTy->getNumParams() != 1)
Gabor Greif02680f92010-06-23 21:51:12 +0000326 return 0;
Chris Lattnerebb21892011-06-18 21:46:23 +0000327 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Gabor Greif02680f92010-06-23 21:51:12 +0000328 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000329
Gabor Greif02680f92010-06-23 21:51:12 +0000330 return CI;
Victor Hernandez66284e02009-10-24 04:23:03 +0000331}
Nuno Lopes9e72a792012-06-21 15:45:28 +0000332
333
334
335//===----------------------------------------------------------------------===//
336// Utility functions to compute size of objects.
337//
338
339
340/// \brief Compute the size of the object pointed by Ptr. Returns true and the
341/// object size in Size if successful, and false otherwise.
342/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
343/// byval arguments, and global variables.
Micah Villmow3574eca2012-10-08 16:38:25 +0000344bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000345 const TargetLibraryInfo *TLI, bool RoundToAlign) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000346 if (!TD)
347 return false;
348
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000349 ObjectSizeOffsetVisitor Visitor(TD, TLI, Ptr->getContext(), RoundToAlign);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000350 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
351 if (!Visitor.bothKnown(Data))
352 return false;
353
354 APInt ObjSize = Data.first, Offset = Data.second;
355 // check for overflow
356 if (Offset.slt(0) || ObjSize.ult(Offset))
357 Size = 0;
358 else
359 Size = (ObjSize - Offset).getZExtValue();
360 return true;
361}
362
363
364STATISTIC(ObjectVisitorArgument,
365 "Number of arguments with unsolved size and offset");
366STATISTIC(ObjectVisitorLoad,
367 "Number of load instructions with unsolved size and offset");
368
369
370APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
371 if (RoundToAlign && Align)
372 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
373 return Size;
374}
375
Micah Villmow3574eca2012-10-08 16:38:25 +0000376ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000377 const TargetLibraryInfo *TLI,
Nuno Lopes9e72a792012-06-21 15:45:28 +0000378 LLVMContext &Context,
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000379 bool RoundToAlign)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000380: TD(TD), TLI(TLI), RoundToAlign(RoundToAlign) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000381 IntegerType *IntTy = TD->getIntPtrType(Context);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000382 IntTyBits = IntTy->getBitWidth();
383 Zero = APInt::getNullValue(IntTyBits);
384}
385
386SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
387 V = V->stripPointerCasts();
Benjamin Kramer168843c2012-08-17 19:26:41 +0000388 if (Instruction *I = dyn_cast<Instruction>(V)) {
389 // If we have already seen this instruction, bail out. Cycles can happen in
390 // unreachable code after constant propagation.
391 if (!SeenInsts.insert(I))
392 return unknown();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000393
Benjamin Kramer168843c2012-08-17 19:26:41 +0000394 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
395 return visitGEPOperator(*GEP);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000396 return visit(*I);
Benjamin Kramer168843c2012-08-17 19:26:41 +0000397 }
Nuno Lopes9e72a792012-06-21 15:45:28 +0000398 if (Argument *A = dyn_cast<Argument>(V))
399 return visitArgument(*A);
400 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
401 return visitConstantPointerNull(*P);
402 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
403 return visitGlobalVariable(*GV);
404 if (UndefValue *UV = dyn_cast<UndefValue>(V))
405 return visitUndefValue(*UV);
Benjamin Kramer168843c2012-08-17 19:26:41 +0000406 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000407 if (CE->getOpcode() == Instruction::IntToPtr)
408 return unknown(); // clueless
Benjamin Kramer168843c2012-08-17 19:26:41 +0000409 if (CE->getOpcode() == Instruction::GetElementPtr)
410 return visitGEPOperator(cast<GEPOperator>(*CE));
411 }
Nuno Lopes9e72a792012-06-21 15:45:28 +0000412
413 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
414 << '\n');
415 return unknown();
416}
417
418SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
419 if (!I.getAllocatedType()->isSized())
420 return unknown();
421
422 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
423 if (!I.isArrayAllocation())
424 return std::make_pair(align(Size, I.getAlignment()), Zero);
425
426 Value *ArraySize = I.getArraySize();
427 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
428 Size *= C->getValue().zextOrSelf(IntTyBits);
429 return std::make_pair(align(Size, I.getAlignment()), Zero);
430 }
431 return unknown();
432}
433
434SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
435 // no interprocedural analysis is done at the moment
436 if (!A.hasByValAttr()) {
437 ++ObjectVisitorArgument;
438 return unknown();
439 }
440 PointerType *PT = cast<PointerType>(A.getType());
441 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
442 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
443}
444
445SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000446 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
447 TLI);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000448 if (!FnData)
449 return unknown();
450
451 // handle strdup-like functions separately
452 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes9827c8e2012-07-24 16:28:13 +0000453 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
454 if (!Size)
455 return unknown();
456
457 // strndup limits strlen
458 if (FnData->FstParam > 0) {
459 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
460 if (!Arg)
461 return unknown();
462
463 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
464 if (Size.ugt(MaxSize))
465 Size = MaxSize + 1;
466 }
467 return std::make_pair(Size, Zero);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000468 }
469
470 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
471 if (!Arg)
472 return unknown();
473
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000474 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000475 // size determined by just 1 parameter
Nuno Lopesef22f042012-06-21 18:38:26 +0000476 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000477 return std::make_pair(Size, Zero);
478
479 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
480 if (!Arg)
481 return unknown();
482
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000483 Size *= Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000484 return std::make_pair(Size, Zero);
485
486 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000487 // - strdup / strndup
Nuno Lopes9e72a792012-06-21 15:45:28 +0000488 // - strcpy / strncpy
489 // - strcat / strncat
490 // - memcpy / memmove
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000491 // - strcat / strncat
Nuno Lopes9e72a792012-06-21 15:45:28 +0000492 // - memset
493}
494
495SizeOffsetType
496ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
497 return std::make_pair(Zero, Zero);
498}
499
500SizeOffsetType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000501ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
502 return unknown();
503}
504
505SizeOffsetType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000506ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
507 // Easy cases were already folded by previous passes.
508 return unknown();
509}
510
511SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
512 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopes98281a22012-12-30 16:25:48 +0000513 APInt Offset(IntTyBits, 0);
514 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(*TD, Offset))
Nuno Lopes9e72a792012-06-21 15:45:28 +0000515 return unknown();
516
Nuno Lopes9e72a792012-06-21 15:45:28 +0000517 return std::make_pair(PtrData.first, PtrData.second + Offset);
518}
519
520SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
521 if (!GV.hasDefinitiveInitializer())
522 return unknown();
523
524 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
525 return std::make_pair(align(Size, GV.getAlignment()), Zero);
526}
527
528SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
529 // clueless
530 return unknown();
531}
532
533SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
534 ++ObjectVisitorLoad;
535 return unknown();
536}
537
Nuno Lopes729e6022012-12-31 13:52:36 +0000538SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode &PHI) {
539 if (PHI.getNumIncomingValues() == 0)
540 return unknown();
541
542 SizeOffsetType Ret = compute(PHI.getIncomingValue(0));
543 if (!bothKnown(Ret))
544 return unknown();
545
546 // verify that all PHI incoming pointers have the same size and offset
547 for (unsigned i = 1, e = PHI.getNumIncomingValues(); i != e; ++i) {
548 if (compute(PHI.getIncomingValue(i)) != Ret)
549 return unknown();
550 }
551 return Ret;
Nuno Lopes9e72a792012-06-21 15:45:28 +0000552}
553
554SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
555 SizeOffsetType TrueSide = compute(I.getTrueValue());
556 SizeOffsetType FalseSide = compute(I.getFalseValue());
557 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
558 return TrueSide;
559 return unknown();
560}
561
562SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
563 return std::make_pair(Zero, Zero);
564}
565
566SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
567 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
568 return unknown();
569}
570
571
Micah Villmow3574eca2012-10-08 16:38:25 +0000572ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const DataLayout *TD,
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000573 const TargetLibraryInfo *TLI,
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000574 LLVMContext &Context)
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000575: TD(TD), TLI(TLI), Context(Context), Builder(Context, TargetFolder(TD)) {
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000576 IntTy = TD->getIntPtrType(Context);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000577 Zero = ConstantInt::get(IntTy, 0);
578}
579
580SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
581 SizeOffsetEvalType Result = compute_(V);
582
583 if (!bothKnown(Result)) {
584 // erase everything that was computed in this iteration from the cache, so
585 // that no dangling references are left behind. We could be a bit smarter if
586 // we kept a dependency graph. It's probably not worth the complexity.
587 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
588 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
589 // non-computable results can be safely cached
590 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
591 CacheMap.erase(CacheIt);
592 }
593 }
594
595 SeenVals.clear();
596 return Result;
597}
598
599SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000600 ObjectSizeOffsetVisitor Visitor(TD, TLI, Context);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000601 SizeOffsetType Const = Visitor.compute(V);
602 if (Visitor.bothKnown(Const))
603 return std::make_pair(ConstantInt::get(Context, Const.first),
604 ConstantInt::get(Context, Const.second));
605
606 V = V->stripPointerCasts();
607
608 // check cache
609 CacheMapTy::iterator CacheIt = CacheMap.find(V);
610 if (CacheIt != CacheMap.end())
611 return CacheIt->second;
612
613 // always generate code immediately before the instruction being
614 // processed, so that the generated code dominates the same BBs
615 Instruction *PrevInsertPoint = Builder.GetInsertPoint();
616 if (Instruction *I = dyn_cast<Instruction>(V))
617 Builder.SetInsertPoint(I);
618
619 // record the pointers that were handled in this run, so that they can be
620 // cleaned later if something fails
621 SeenVals.insert(V);
622
623 // now compute the size and offset
624 SizeOffsetEvalType Result;
625 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
626 Result = visitGEPOperator(*GEP);
627 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
628 Result = visit(*I);
629 } else if (isa<Argument>(V) ||
630 (isa<ConstantExpr>(V) &&
631 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
632 isa<GlobalVariable>(V)) {
633 // ignore values where we cannot do more than what ObjectSizeVisitor can
634 Result = unknown();
635 } else {
636 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
637 << *V << '\n');
638 Result = unknown();
639 }
640
641 if (PrevInsertPoint)
642 Builder.SetInsertPoint(PrevInsertPoint);
643
644 // Don't reuse CacheIt since it may be invalid at this point.
645 CacheMap[V] = Result;
646 return Result;
647}
648
649SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
650 if (!I.getAllocatedType()->isSized())
651 return unknown();
652
653 // must be a VLA
654 assert(I.isArrayAllocation());
655 Value *ArraySize = I.getArraySize();
656 Value *Size = ConstantInt::get(ArraySize->getType(),
657 TD->getTypeAllocSize(I.getAllocatedType()));
658 Size = Builder.CreateMul(Size, ArraySize);
659 return std::make_pair(Size, Zero);
660}
661
662SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000663 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
664 TLI);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000665 if (!FnData)
666 return unknown();
667
668 // handle strdup-like functions separately
669 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000670 // TODO
671 return unknown();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000672 }
673
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000674 Value *FirstArg = CS.getArgument(FnData->FstParam);
675 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesef22f042012-06-21 18:38:26 +0000676 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000677 return std::make_pair(FirstArg, Zero);
678
679 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000680 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000681 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
682 return std::make_pair(Size, Zero);
683
684 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000685 // - strdup / strndup
Nuno Lopes9e72a792012-06-21 15:45:28 +0000686 // - strcpy / strncpy
687 // - strcat / strncat
688 // - memcpy / memmove
Nuno Lopes6e699bf2012-07-25 18:49:28 +0000689 // - strcat / strncat
Nuno Lopes9e72a792012-06-21 15:45:28 +0000690 // - memset
691}
692
693SizeOffsetEvalType
Nuno Lopes41a3f252012-06-28 16:34:03 +0000694ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
695 return unknown();
696}
697
698SizeOffsetEvalType
699ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
700 return unknown();
701}
702
703SizeOffsetEvalType
Nuno Lopes9e72a792012-06-21 15:45:28 +0000704ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
705 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
706 if (!bothKnown(PtrData))
707 return unknown();
708
Nuno Lopesc606c3f2012-07-20 23:07:40 +0000709 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP, /*NoAssumptions=*/true);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000710 Offset = Builder.CreateAdd(PtrData.second, Offset);
711 return std::make_pair(PtrData.first, Offset);
712}
713
714SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
715 // clueless
716 return unknown();
717}
718
719SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
720 return unknown();
721}
722
723SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
724 // create 2 PHIs: one for size and another for offset
725 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
726 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
727
728 // insert right away in the cache to handle recursive PHIs
729 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
730
731 // compute offset/size for each PHI incoming pointer
732 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
733 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
734 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
735
736 if (!bothKnown(EdgeData)) {
737 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
738 OffsetPHI->eraseFromParent();
739 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
740 SizePHI->eraseFromParent();
741 return unknown();
742 }
743 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
744 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
745 }
Nuno Lopes0dff5322012-07-03 17:13:25 +0000746
747 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
748 if ((Tmp = SizePHI->hasConstantValue())) {
749 Size = Tmp;
750 SizePHI->replaceAllUsesWith(Size);
751 SizePHI->eraseFromParent();
752 }
753 if ((Tmp = OffsetPHI->hasConstantValue())) {
754 Offset = Tmp;
755 OffsetPHI->replaceAllUsesWith(Offset);
756 OffsetPHI->eraseFromParent();
757 }
758 return std::make_pair(Size, Offset);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000759}
760
761SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
762 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
763 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
764
765 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
766 return unknown();
767 if (TrueSide == FalseSide)
768 return TrueSide;
769
770 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
771 FalseSide.first);
772 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
773 FalseSide.second);
774 return std::make_pair(Size, Offset);
775}
776
777SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
778 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
779 return unknown();
780}