blob: 6b21b73f22f831dd27aa3aa5349dcc72d15ec0e3 [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"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/ADT/STLExtras.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000018#include "llvm/Analysis/MemoryBuiltins.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000019#include "llvm/GlobalVariable.h"
Evan Chengfabcb912009-09-10 04:36:43 +000020#include "llvm/Instructions.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000021#include "llvm/Intrinsics.h"
22#include "llvm/Metadata.h"
Evan Chengfabcb912009-09-10 04:36:43 +000023#include "llvm/Module.h"
Victor Hernandez8e345a12009-11-10 08:32:25 +000024#include "llvm/Analysis/ValueTracking.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/raw_ostream.h"
Victor Hernandez9d0b7042009-11-07 00:16:28 +000028#include "llvm/Target/TargetData.h"
Nuno Lopes9e72a792012-06-21 15:45:28 +000029#include "llvm/Transforms/Utils/Local.h"
Evan Chengfabcb912009-09-10 04:36:43 +000030using namespace llvm;
31
Nuno Lopes9e72a792012-06-21 15:45:28 +000032enum AllocType {
33 MallocLike = 1<<0, // allocates
34 CallocLike = 1<<1, // allocates + bzero
35 ReallocLike = 1<<2, // reallocates
36 StrDupLike = 1<<3,
37 AllocLike = MallocLike | CallocLike | StrDupLike,
38 AnyAlloc = MallocLike | CallocLike | ReallocLike | StrDupLike
39};
Evan Chengfabcb912009-09-10 04:36:43 +000040
Nuno Lopes9e72a792012-06-21 15:45:28 +000041struct AllocFnsTy {
42 const char *Name;
43 AllocType AllocTy;
44 unsigned char NumParams;
45 // First and Second size parameters (or -1 if unused)
Nuno Lopesef22f042012-06-21 18:38:26 +000046 signed char FstParam, SndParam;
Nuno Lopes9e72a792012-06-21 15:45:28 +000047};
Evan Chengfabcb912009-09-10 04:36:43 +000048
Nuno Lopes9e72a792012-06-21 15:45:28 +000049static const AllocFnsTy AllocationFnData[] = {
50 {"malloc", MallocLike, 1, 0, -1},
51 {"valloc", MallocLike, 1, 0, -1},
52 {"_Znwj", MallocLike, 1, 0, -1}, // operator new(unsigned int)
53 {"_Znwm", MallocLike, 1, 0, -1}, // operator new(unsigned long)
54 {"_Znaj", MallocLike, 1, 0, -1}, // operator new[](unsigned int)
55 {"_Znam", MallocLike, 1, 0, -1}, // operator new[](unsigned long)
56 {"posix_memalign", MallocLike, 3, 2, -1},
57 {"calloc", CallocLike, 2, 0, 1},
58 {"realloc", ReallocLike, 2, 1, -1},
59 {"reallocf", ReallocLike, 2, 1, -1},
60 {"strdup", StrDupLike, 1, -1, -1},
61 {"strndup", StrDupLike, 2, -1, -1}
62};
63
64
65static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
66 if (LookThroughBitCast)
67 V = V->stripPointerCasts();
Nuno Lopes2b3e9582012-06-21 21:25:05 +000068
Nuno Lopesd845c342012-06-22 15:50:53 +000069 CallSite CS(const_cast<Value*>(V));
70 if (!CS.getInstruction())
Nuno Lopes9e72a792012-06-21 15:45:28 +000071 return 0;
Evan Chengfabcb912009-09-10 04:36:43 +000072
Nuno Lopes2b3e9582012-06-21 21:25:05 +000073 Function *Callee = CS.getCalledFunction();
Nuno Lopes9e72a792012-06-21 15:45:28 +000074 if (!Callee || !Callee->isDeclaration())
75 return 0;
76 return Callee;
77}
Evan Chengfabcb912009-09-10 04:36:43 +000078
Nuno Lopes9e72a792012-06-21 15:45:28 +000079/// \brief Returns the allocation data for the given value if it is a call to a
80/// known allocation function, and NULL otherwise.
81static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
82 bool LookThroughBitCast = false) {
83 Function *Callee = getCalledFunction(V, LookThroughBitCast);
84 if (!Callee)
85 return 0;
86
87 unsigned i = 0;
88 bool found = false;
89 for ( ; i < array_lengthof(AllocationFnData); ++i) {
90 if (Callee->getName() == AllocationFnData[i].Name) {
91 found = true;
92 break;
93 }
94 }
95 if (!found)
96 return 0;
97
98 const AllocFnsTy *FnData = &AllocationFnData[i];
99 if ((FnData->AllocTy & AllocTy) == 0)
100 return 0;
101
102 // Check function prototype.
103 // FIXME: Check the nobuiltin metadata?? (PR5130)
Nuno Lopesef22f042012-06-21 18:38:26 +0000104 int FstParam = FnData->FstParam;
105 int SndParam = FnData->SndParam;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000106 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes9e72a792012-06-21 15:45:28 +0000107
108 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
109 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000110 (FstParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000111 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
112 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesef22f042012-06-21 18:38:26 +0000113 (SndParam < 0 ||
Nuno Lopes9e72a792012-06-21 15:45:28 +0000114 FTy->getParamType(SndParam)->isIntegerTy(32) ||
115 FTy->getParamType(SndParam)->isIntegerTy(64)))
116 return FnData;
117 return 0;
118}
119
120static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopese8742d02012-06-25 16:17:54 +0000121 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
122 return CS && CS.hasFnAttr(Attribute::NoAlias);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000123}
124
125
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000126/// \brief Tests if a value is a call or invoke to a library function that
127/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
128/// like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000129bool llvm::isAllocationFn(const Value *V, bool LookThroughBitCast) {
130 return getAllocationData(V, AnyAlloc, LookThroughBitCast);
131}
132
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000133/// \brief Tests if a value is a call or invoke to a function that returns a
134/// NoAlias pointer (including malloc/calloc/strdup-like functions).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000135bool llvm::isNoAliasFn(const Value *V, bool LookThroughBitCast) {
136 return isAllocLikeFn(V, LookThroughBitCast) ||
137 hasNoAliasAttr(V, LookThroughBitCast);
138}
139
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000140/// \brief Tests if a value is a call or invoke to a library function that
141/// allocates uninitialized memory (such as malloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000142bool llvm::isMallocLikeFn(const Value *V, bool LookThroughBitCast) {
143 return getAllocationData(V, MallocLike, LookThroughBitCast);
144}
145
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000146/// \brief Tests if a value is a call or invoke to a library function that
147/// allocates zero-filled memory (such as calloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000148bool llvm::isCallocLikeFn(const Value *V, bool LookThroughBitCast) {
149 return getAllocationData(V, CallocLike, LookThroughBitCast);
150}
151
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000152/// \brief Tests if a value is a call or invoke to a library function that
153/// allocates memory (either malloc, calloc, or strdup like).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000154bool llvm::isAllocLikeFn(const Value *V, bool LookThroughBitCast) {
155 return getAllocationData(V, AllocLike, LookThroughBitCast);
156}
157
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000158/// \brief Tests if a value is a call or invoke to a library function that
159/// reallocates memory (such as realloc).
Nuno Lopes9e72a792012-06-21 15:45:28 +0000160bool llvm::isReallocLikeFn(const Value *V, bool LookThroughBitCast) {
161 return getAllocationData(V, ReallocLike, LookThroughBitCast);
Evan Chengfabcb912009-09-10 04:36:43 +0000162}
163
164/// extractMallocCall - Returns the corresponding CallInst if the instruction
165/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
166/// ignore InvokeInst here.
Victor Hernandez88efeae2009-11-03 20:02:35 +0000167const CallInst *llvm::extractMallocCall(const Value *I) {
Nuno Lopeseb7c6862012-06-22 00:25:01 +0000168 return isMallocLikeFn(I) ? dyn_cast<CallInst>(I) : 0;
Evan Chengfabcb912009-09-10 04:36:43 +0000169}
170
Victor Hernandez8e345a12009-11-10 08:32:25 +0000171static Value *computeArraySize(const CallInst *CI, const TargetData *TD,
172 bool LookThroughSExt = false) {
Evan Chengfabcb912009-09-10 04:36:43 +0000173 if (!CI)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000174 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000175
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000176 // The size of the malloc's result type must be known to determine array size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000177 Type *T = getMallocAllocatedType(CI);
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000178 if (!T || !T->isSized() || !TD)
Victor Hernandez90f48e72009-10-28 20:18:55 +0000179 return NULL;
Victor Hernandez88d98392009-09-18 19:20:02 +0000180
Victor Hernandez8e345a12009-11-10 08:32:25 +0000181 unsigned ElementSize = TD->getTypeAllocSize(T);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000182 if (StructType *ST = dyn_cast<StructType>(T))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000183 ElementSize = TD->getStructLayout(ST)->getSizeInBytes();
Victor Hernandez88d98392009-09-18 19:20:02 +0000184
Gabor Greife3401c42010-06-23 21:41:47 +0000185 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandez8e345a12009-11-10 08:32:25 +0000186 // return the multiple. Otherwise, return NULL.
Gabor Greife3401c42010-06-23 21:41:47 +0000187 Value *MallocArg = CI->getArgOperand(0);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000188 Value *Multiple = NULL;
Victor Hernandez8e345a12009-11-10 08:32:25 +0000189 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman3dbb9e62009-11-18 00:58:27 +0000190 LookThroughSExt))
Victor Hernandez8e345a12009-11-10 08:32:25 +0000191 return Multiple;
Victor Hernandez88d98392009-09-18 19:20:02 +0000192
Victor Hernandez90f48e72009-10-28 20:18:55 +0000193 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000194}
195
196/// isArrayMalloc - Returns the corresponding CallInst if the instruction
Victor Hernandez90f48e72009-10-28 20:18:55 +0000197/// is a call to malloc whose array size can be determined and the array size
198/// is not constant 1. Otherwise, return NULL.
Chris Lattner7b550cc2009-11-06 04:27:31 +0000199const CallInst *llvm::isArrayMalloc(const Value *I, const TargetData *TD) {
Evan Chengfabcb912009-09-10 04:36:43 +0000200 const CallInst *CI = extractMallocCall(I);
Victor Hernandez8e345a12009-11-10 08:32:25 +0000201 Value *ArraySize = computeArraySize(CI, TD);
Victor Hernandez90f48e72009-10-28 20:18:55 +0000202
203 if (ArraySize &&
Gabor Greife3401c42010-06-23 21:41:47 +0000204 ArraySize != ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
Victor Hernandez90f48e72009-10-28 20:18:55 +0000205 return CI;
206
207 // CI is a non-array malloc or we can't figure out that it is an array malloc.
208 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000209}
210
211/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000212/// The PointerType depends on the number of bitcast uses of the malloc call:
213/// 0: PointerType is the calls' return type.
214/// 1: PointerType is the bitcast's result type.
215/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000216PointerType *llvm::getMallocType(const CallInst *CI) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000217 assert(isMallocLikeFn(CI) && "getMallocType and not malloc call");
Evan Chengfabcb912009-09-10 04:36:43 +0000218
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000219 PointerType *MallocType = NULL;
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000220 unsigned NumOfBitCastUses = 0;
221
Victor Hernandez88d98392009-09-18 19:20:02 +0000222 // Determine if CallInst has a bitcast use.
Gabor Greif60ad7812010-03-25 23:06:16 +0000223 for (Value::const_use_iterator UI = CI->use_begin(), E = CI->use_end();
Victor Hernandez88d98392009-09-18 19:20:02 +0000224 UI != E; )
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000225 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
226 MallocType = cast<PointerType>(BCI->getDestTy());
227 NumOfBitCastUses++;
228 }
Evan Chengfabcb912009-09-10 04:36:43 +0000229
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000230 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
231 if (NumOfBitCastUses == 1)
232 return MallocType;
Evan Chengfabcb912009-09-10 04:36:43 +0000233
Victor Hernandez60cfc032009-09-22 18:50:03 +0000234 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000235 if (NumOfBitCastUses == 0)
Victor Hernandez88d98392009-09-18 19:20:02 +0000236 return cast<PointerType>(CI->getType());
237
238 // Type could not be determined.
239 return NULL;
Evan Chengfabcb912009-09-10 04:36:43 +0000240}
241
Victor Hernandez9d0b7042009-11-07 00:16:28 +0000242/// getMallocAllocatedType - Returns the Type allocated by malloc call.
243/// The Type depends on the number of bitcast uses of the malloc call:
244/// 0: PointerType is the malloc calls' return type.
245/// 1: PointerType is the bitcast's result type.
246/// >1: Unique PointerType cannot be determined, return NULL.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000247Type *llvm::getMallocAllocatedType(const CallInst *CI) {
248 PointerType *PT = getMallocType(CI);
Evan Chengfabcb912009-09-10 04:36:43 +0000249 return PT ? PT->getElementType() : NULL;
250}
251
Victor Hernandez90f48e72009-10-28 20:18:55 +0000252/// getMallocArraySize - Returns the array size of a malloc call. If the
253/// argument passed to malloc is a multiple of the size of the malloced type,
254/// then return that multiple. For non-array mallocs, the multiple is
255/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez2491ce02009-10-15 20:14:52 +0000256/// determined.
Victor Hernandez8e345a12009-11-10 08:32:25 +0000257Value *llvm::getMallocArraySize(CallInst *CI, const TargetData *TD,
258 bool LookThroughSExt) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000259 assert(isMallocLikeFn(CI) && "getMallocArraySize and not malloc call");
Victor Hernandez8e345a12009-11-10 08:32:25 +0000260 return computeArraySize(CI, TD, LookThroughSExt);
Evan Chengfabcb912009-09-10 04:36:43 +0000261}
Victor Hernandez66284e02009-10-24 04:23:03 +0000262
Nuno Lopes252ef562012-05-03 21:19:58 +0000263
Nuno Lopes252ef562012-05-03 21:19:58 +0000264/// extractCallocCall - Returns the corresponding CallInst if the instruction
265/// is a calloc call.
266const CallInst *llvm::extractCallocCall(const Value *I) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000267 return isCallocLikeFn(I) ? cast<CallInst>(I) : 0;
Nuno Lopes252ef562012-05-03 21:19:58 +0000268}
269
Victor Hernandez046e78c2009-10-26 23:43:48 +0000270
Gabor Greif02680f92010-06-23 21:51:12 +0000271/// isFreeCall - Returns non-null if the value is a call to the builtin free()
272const CallInst *llvm::isFreeCall(const Value *I) {
Victor Hernandez66284e02009-10-24 04:23:03 +0000273 const CallInst *CI = dyn_cast<CallInst>(I);
274 if (!CI)
Gabor Greif02680f92010-06-23 21:51:12 +0000275 return 0;
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000276 Function *Callee = CI->getCalledFunction();
Nick Lewycky42e72ca2011-03-15 07:31:32 +0000277 if (Callee == 0 || !Callee->isDeclaration())
278 return 0;
279
280 if (Callee->getName() != "free" &&
Nick Lewycky1ace1692011-03-17 05:20:12 +0000281 Callee->getName() != "_ZdlPv" && // operator delete(void*)
282 Callee->getName() != "_ZdaPv") // operator delete[](void*)
Gabor Greif02680f92010-06-23 21:51:12 +0000283 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000284
285 // Check free prototype.
286 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
287 // attribute will exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000288 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez3ad70d52009-11-03 20:39:35 +0000289 if (!FTy->getReturnType()->isVoidTy())
Gabor Greif02680f92010-06-23 21:51:12 +0000290 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000291 if (FTy->getNumParams() != 1)
Gabor Greif02680f92010-06-23 21:51:12 +0000292 return 0;
Chris Lattnerebb21892011-06-18 21:46:23 +0000293 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Gabor Greif02680f92010-06-23 21:51:12 +0000294 return 0;
Victor Hernandez66284e02009-10-24 04:23:03 +0000295
Gabor Greif02680f92010-06-23 21:51:12 +0000296 return CI;
Victor Hernandez66284e02009-10-24 04:23:03 +0000297}
Nuno Lopes9e72a792012-06-21 15:45:28 +0000298
299
300
301//===----------------------------------------------------------------------===//
302// Utility functions to compute size of objects.
303//
304
305
306/// \brief Compute the size of the object pointed by Ptr. Returns true and the
307/// object size in Size if successful, and false otherwise.
308/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
309/// byval arguments, and global variables.
310bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const TargetData *TD,
311 bool RoundToAlign) {
312 if (!TD)
313 return false;
314
315 ObjectSizeOffsetVisitor Visitor(TD, Ptr->getContext(), RoundToAlign);
316 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
317 if (!Visitor.bothKnown(Data))
318 return false;
319
320 APInt ObjSize = Data.first, Offset = Data.second;
321 // check for overflow
322 if (Offset.slt(0) || ObjSize.ult(Offset))
323 Size = 0;
324 else
325 Size = (ObjSize - Offset).getZExtValue();
326 return true;
327}
328
329
330STATISTIC(ObjectVisitorArgument,
331 "Number of arguments with unsolved size and offset");
332STATISTIC(ObjectVisitorLoad,
333 "Number of load instructions with unsolved size and offset");
334
335
336APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
337 if (RoundToAlign && Align)
338 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
339 return Size;
340}
341
342ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const TargetData *TD,
343 LLVMContext &Context,
344 bool RoundToAlign)
345: TD(TD), RoundToAlign(RoundToAlign) {
346 IntegerType *IntTy = TD->getIntPtrType(Context);
347 IntTyBits = IntTy->getBitWidth();
348 Zero = APInt::getNullValue(IntTyBits);
349}
350
351SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
352 V = V->stripPointerCasts();
353
354 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
355 return visitGEPOperator(*GEP);
356 if (Instruction *I = dyn_cast<Instruction>(V))
357 return visit(*I);
358 if (Argument *A = dyn_cast<Argument>(V))
359 return visitArgument(*A);
360 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
361 return visitConstantPointerNull(*P);
362 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
363 return visitGlobalVariable(*GV);
364 if (UndefValue *UV = dyn_cast<UndefValue>(V))
365 return visitUndefValue(*UV);
366 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
367 if (CE->getOpcode() == Instruction::IntToPtr)
368 return unknown(); // clueless
369
370 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
371 << '\n');
372 return unknown();
373}
374
375SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
376 if (!I.getAllocatedType()->isSized())
377 return unknown();
378
379 APInt Size(IntTyBits, TD->getTypeAllocSize(I.getAllocatedType()));
380 if (!I.isArrayAllocation())
381 return std::make_pair(align(Size, I.getAlignment()), Zero);
382
383 Value *ArraySize = I.getArraySize();
384 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
385 Size *= C->getValue().zextOrSelf(IntTyBits);
386 return std::make_pair(align(Size, I.getAlignment()), Zero);
387 }
388 return unknown();
389}
390
391SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
392 // no interprocedural analysis is done at the moment
393 if (!A.hasByValAttr()) {
394 ++ObjectVisitorArgument;
395 return unknown();
396 }
397 PointerType *PT = cast<PointerType>(A.getType());
398 APInt Size(IntTyBits, TD->getTypeAllocSize(PT->getElementType()));
399 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
400}
401
402SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
403 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
404 if (!FnData)
405 return unknown();
406
407 // handle strdup-like functions separately
408 if (FnData->AllocTy == StrDupLike) {
409 // TODO
410 return unknown();
411 }
412
413 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
414 if (!Arg)
415 return unknown();
416
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000417 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000418 // size determined by just 1 parameter
Nuno Lopesef22f042012-06-21 18:38:26 +0000419 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000420 return std::make_pair(Size, Zero);
421
422 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
423 if (!Arg)
424 return unknown();
425
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000426 Size *= Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000427 return std::make_pair(Size, Zero);
428
429 // TODO: handle more standard functions (+ wchar cousins):
430 // - strdup / strndup
431 // - strcpy / strncpy
432 // - strcat / strncat
433 // - memcpy / memmove
434 // - strcat / strncat
435 // - memset
436}
437
438SizeOffsetType
439ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
440 return std::make_pair(Zero, Zero);
441}
442
443SizeOffsetType
444ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
445 // Easy cases were already folded by previous passes.
446 return unknown();
447}
448
449SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
450 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
451 if (!bothKnown(PtrData) || !GEP.hasAllConstantIndices())
452 return unknown();
453
454 SmallVector<Value*, 8> Ops(GEP.idx_begin(), GEP.idx_end());
455 APInt Offset(IntTyBits,TD->getIndexedOffset(GEP.getPointerOperandType(),Ops));
456 return std::make_pair(PtrData.first, PtrData.second + Offset);
457}
458
459SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
460 if (!GV.hasDefinitiveInitializer())
461 return unknown();
462
463 APInt Size(IntTyBits, TD->getTypeAllocSize(GV.getType()->getElementType()));
464 return std::make_pair(align(Size, GV.getAlignment()), Zero);
465}
466
467SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
468 // clueless
469 return unknown();
470}
471
472SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
473 ++ObjectVisitorLoad;
474 return unknown();
475}
476
477SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
478 // too complex to analyze statically.
479 return unknown();
480}
481
482SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
483 SizeOffsetType TrueSide = compute(I.getTrueValue());
484 SizeOffsetType FalseSide = compute(I.getFalseValue());
485 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
486 return TrueSide;
487 return unknown();
488}
489
490SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
491 return std::make_pair(Zero, Zero);
492}
493
494SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
495 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
496 return unknown();
497}
498
499
500ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const TargetData *TD,
501 LLVMContext &Context)
502: TD(TD), Context(Context), Builder(Context, TargetFolder(TD)),
503Visitor(TD, Context) {
504 IntTy = TD->getIntPtrType(Context);
505 Zero = ConstantInt::get(IntTy, 0);
506}
507
508SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
509 SizeOffsetEvalType Result = compute_(V);
510
511 if (!bothKnown(Result)) {
512 // erase everything that was computed in this iteration from the cache, so
513 // that no dangling references are left behind. We could be a bit smarter if
514 // we kept a dependency graph. It's probably not worth the complexity.
515 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
516 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
517 // non-computable results can be safely cached
518 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
519 CacheMap.erase(CacheIt);
520 }
521 }
522
523 SeenVals.clear();
524 return Result;
525}
526
527SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
528 SizeOffsetType Const = Visitor.compute(V);
529 if (Visitor.bothKnown(Const))
530 return std::make_pair(ConstantInt::get(Context, Const.first),
531 ConstantInt::get(Context, Const.second));
532
533 V = V->stripPointerCasts();
534
535 // check cache
536 CacheMapTy::iterator CacheIt = CacheMap.find(V);
537 if (CacheIt != CacheMap.end())
538 return CacheIt->second;
539
540 // always generate code immediately before the instruction being
541 // processed, so that the generated code dominates the same BBs
542 Instruction *PrevInsertPoint = Builder.GetInsertPoint();
543 if (Instruction *I = dyn_cast<Instruction>(V))
544 Builder.SetInsertPoint(I);
545
546 // record the pointers that were handled in this run, so that they can be
547 // cleaned later if something fails
548 SeenVals.insert(V);
549
550 // now compute the size and offset
551 SizeOffsetEvalType Result;
552 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
553 Result = visitGEPOperator(*GEP);
554 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
555 Result = visit(*I);
556 } else if (isa<Argument>(V) ||
557 (isa<ConstantExpr>(V) &&
558 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
559 isa<GlobalVariable>(V)) {
560 // ignore values where we cannot do more than what ObjectSizeVisitor can
561 Result = unknown();
562 } else {
563 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
564 << *V << '\n');
565 Result = unknown();
566 }
567
568 if (PrevInsertPoint)
569 Builder.SetInsertPoint(PrevInsertPoint);
570
571 // Don't reuse CacheIt since it may be invalid at this point.
572 CacheMap[V] = Result;
573 return Result;
574}
575
576SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
577 if (!I.getAllocatedType()->isSized())
578 return unknown();
579
580 // must be a VLA
581 assert(I.isArrayAllocation());
582 Value *ArraySize = I.getArraySize();
583 Value *Size = ConstantInt::get(ArraySize->getType(),
584 TD->getTypeAllocSize(I.getAllocatedType()));
585 Size = Builder.CreateMul(Size, ArraySize);
586 return std::make_pair(Size, Zero);
587}
588
589SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
590 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc);
591 if (!FnData)
592 return unknown();
593
594 // handle strdup-like functions separately
595 if (FnData->AllocTy == StrDupLike) {
596 // TODO
597 return unknown();
598 }
599
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000600 Value *FirstArg = CS.getArgument(FnData->FstParam);
601 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesef22f042012-06-21 18:38:26 +0000602 if (FnData->SndParam < 0)
Nuno Lopes9e72a792012-06-21 15:45:28 +0000603 return std::make_pair(FirstArg, Zero);
604
605 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopes034dd6c2012-06-21 16:47:58 +0000606 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes9e72a792012-06-21 15:45:28 +0000607 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
608 return std::make_pair(Size, Zero);
609
610 // TODO: handle more standard functions (+ wchar cousins):
611 // - strdup / strndup
612 // - strcpy / strncpy
613 // - strcat / strncat
614 // - memcpy / memmove
615 // - strcat / strncat
616 // - memset
617}
618
619SizeOffsetEvalType
620ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
621 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
622 if (!bothKnown(PtrData))
623 return unknown();
624
625 Value *Offset = EmitGEPOffset(&Builder, *TD, &GEP);
626 Offset = Builder.CreateAdd(PtrData.second, Offset);
627 return std::make_pair(PtrData.first, Offset);
628}
629
630SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
631 // clueless
632 return unknown();
633}
634
635SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
636 return unknown();
637}
638
639SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
640 // create 2 PHIs: one for size and another for offset
641 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
642 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
643
644 // insert right away in the cache to handle recursive PHIs
645 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
646
647 // compute offset/size for each PHI incoming pointer
648 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
649 Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
650 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
651
652 if (!bothKnown(EdgeData)) {
653 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
654 OffsetPHI->eraseFromParent();
655 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
656 SizePHI->eraseFromParent();
657 return unknown();
658 }
659 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
660 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
661 }
662 return std::make_pair(SizePHI, OffsetPHI);
663}
664
665SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
666 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
667 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
668
669 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
670 return unknown();
671 if (TrueSide == FalseSide)
672 return TrueSide;
673
674 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
675 FalseSide.first);
676 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
677 FalseSide.second);
678 return std::make_pair(Size, Offset);
679}
680
681SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
682 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
683 return unknown();
684}