blob: 9e896aed0dce574d138f06071501655dab69fe2e [file] [log] [blame]
Victor Hernandezf390e042009-10-27 20:05:49 +00001//===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
Evan Cheng1d9d4bd2009-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 Hernandezf390e042009-10-27 20:05:49 +000010// This family of functions identifies calls to builtin functions that allocate
Michael Ilsemand9745242013-03-08 21:03:09 +000011// or free memory.
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000012//
13//===----------------------------------------------------------------------===//
14
Victor Hernandezf390e042009-10-27 20:05:49 +000015#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/Statistic.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#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"
Nuno Lopes55fff832012-06-21 15:45:28 +000026#include "llvm/Support/Debug.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/raw_ostream.h"
Nuno Lopes55fff832012-06-21 15:45:28 +000029#include "llvm/Transforms/Utils/Local.h"
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000030using namespace llvm;
31
Chandler Carruthf1221bd2014-04-22 02:48:03 +000032#define DEBUG_TYPE "memory-builtins"
33
George Burgess IV2ae15e02015-11-17 19:48:06 +000034enum AllocType : uint8_t {
Benjamin Kramer2939dd32013-09-24 17:34:29 +000035 OpNewLike = 1<<0, // allocates; never returns null
36 MallocLike = 1<<1 | OpNewLike, // allocates; may return null
37 CallocLike = 1<<2, // allocates + bzero
38 ReallocLike = 1<<3, // reallocates
39 StrDupLike = 1<<4,
40 AllocLike = MallocLike | CallocLike | StrDupLike,
Benjamin Kramer4d4df042013-09-24 17:15:14 +000041 AnyAlloc = AllocLike | ReallocLike
Nuno Lopes55fff832012-06-21 15:45:28 +000042};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000043
Nuno Lopes55fff832012-06-21 15:45:28 +000044struct AllocFnsTy {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000045 LibFunc::Func Func;
Nuno Lopes55fff832012-06-21 15:45:28 +000046 AllocType AllocTy;
47 unsigned char NumParams;
48 // First and Second size parameters (or -1 if unused)
Nuno Lopesf06b7312012-06-21 18:38:26 +000049 signed char FstParam, SndParam;
Nuno Lopes55fff832012-06-21 15:45:28 +000050};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000051
Nuno Lopes181d67e2012-06-28 16:34:03 +000052// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
53// know which functions are nounwind, noalias, nocapture parameters, etc.
Nuno Lopes55fff832012-06-21 15:45:28 +000054static const AllocFnsTy AllocationFnData[] = {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000055 {LibFunc::malloc, MallocLike, 1, 0, -1},
56 {LibFunc::valloc, MallocLike, 1, 0, -1},
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000057 {LibFunc::Znwj, OpNewLike, 1, 0, -1}, // new(unsigned int)
Nadav Rotem7b7585d2013-04-09 04:43:46 +000058 {LibFunc::ZnwjRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000059 {LibFunc::Znwm, OpNewLike, 1, 0, -1}, // new(unsigned long)
Nadav Rotem7b7585d2013-04-09 04:43:46 +000060 {LibFunc::ZnwmRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new(unsigned long, nothrow)
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000061 {LibFunc::Znaj, OpNewLike, 1, 0, -1}, // new[](unsigned int)
Nadav Rotem7b7585d2013-04-09 04:43:46 +000062 {LibFunc::ZnajRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000063 {LibFunc::Znam, OpNewLike, 1, 0, -1}, // new[](unsigned long)
Nadav Rotem7b7585d2013-04-09 04:43:46 +000064 {LibFunc::ZnamRKSt9nothrow_t, MallocLike, 2, 0, -1}, // new[](unsigned long, nothrow)
David Majnemerf6665f62015-12-03 22:45:19 +000065 {LibFunc::msvc_new_int, OpNewLike, 1, 0, -1}, // new(unsigned int)
66 {LibFunc::msvc_new_int_nothrow, MallocLike, 2, 0, -1}, // new(unsigned int, nothrow)
67 {LibFunc::msvc_new_longlong, OpNewLike, 1, 0, -1}, // new(unsigned long long)
68 {LibFunc::msvc_new_longlong_nothrow, MallocLike, 2, 0, -1}, // new(unsigned long long, nothrow)
69 {LibFunc::msvc_new_array_int, OpNewLike, 1, 0, -1}, // new[](unsigned int)
70 {LibFunc::msvc_new_array_int_nothrow, MallocLike, 2, 0, -1}, // new[](unsigned int, nothrow)
71 {LibFunc::msvc_new_array_longlong, OpNewLike, 1, 0, -1}, // new[](unsigned long long)
72 {LibFunc::msvc_new_array_longlong_nothrow, MallocLike, 2, 0, -1}, // new[](unsigned long long, nothrow)
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000073 {LibFunc::calloc, CallocLike, 2, 0, 1},
74 {LibFunc::realloc, ReallocLike, 2, 1, -1},
75 {LibFunc::reallocf, ReallocLike, 2, 1, -1},
76 {LibFunc::strdup, StrDupLike, 1, -1, -1},
77 {LibFunc::strndup, StrDupLike, 2, 1, -1}
Benjamin Kramer01df8172013-09-24 17:49:08 +000078 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes55fff832012-06-21 15:45:28 +000079};
80
81
82static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
83 if (LookThroughBitCast)
84 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +000085
Nuno Lopes15dbcb42012-06-22 15:50:53 +000086 CallSite CS(const_cast<Value*>(V));
87 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +000088 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000089
Michael Gottesman41748d72013-06-27 00:25:01 +000090 if (CS.isNoBuiltin())
Craig Topper9f008862014-04-15 04:59:12 +000091 return nullptr;
Richard Smithe04f0d32013-05-16 04:12:04 +000092
Nuno Lopesdc6085e2012-06-21 21:25:05 +000093 Function *Callee = CS.getCalledFunction();
Nuno Lopes55fff832012-06-21 15:45:28 +000094 if (!Callee || !Callee->isDeclaration())
Craig Topper9f008862014-04-15 04:59:12 +000095 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +000096 return Callee;
97}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000098
Nuno Lopes55fff832012-06-21 15:45:28 +000099/// \brief Returns the allocation data for the given value if it is a call to a
100/// known allocation function, and NULL otherwise.
101static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000102 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000103 bool LookThroughBitCast = false) {
Michael Ilseman74ffc272013-03-08 21:15:00 +0000104 // Skip intrinsics
105 if (isa<IntrinsicInst>(V))
Craig Topper9f008862014-04-15 04:59:12 +0000106 return nullptr;
Michael Ilseman74ffc272013-03-08 21:15:00 +0000107
Nuno Lopes55fff832012-06-21 15:45:28 +0000108 Function *Callee = getCalledFunction(V, LookThroughBitCast);
109 if (!Callee)
Craig Topper9f008862014-04-15 04:59:12 +0000110 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +0000111
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000112 // Make sure that the function is available.
113 StringRef FnName = Callee->getName();
114 LibFunc::Func TLIFn;
115 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000116 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000117
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000118 const AllocFnsTy *FnData =
119 std::find_if(std::begin(AllocationFnData), std::end(AllocationFnData),
120 [TLIFn](const AllocFnsTy &Fn) { return Fn.Func == TLIFn; });
121
122 if (FnData == std::end(AllocationFnData))
Craig Topper9f008862014-04-15 04:59:12 +0000123 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +0000124
Benjamin Kramer2939dd32013-09-24 17:34:29 +0000125 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
Craig Topper9f008862014-04-15 04:59:12 +0000126 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +0000127
128 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000129 int FstParam = FnData->FstParam;
130 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000131 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000132
133 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
134 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000135 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000136 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
137 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000138 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000139 FTy->getParamType(SndParam)->isIntegerTy(32) ||
140 FTy->getParamType(SndParam)->isIntegerTy(64)))
141 return FnData;
Craig Topper9f008862014-04-15 04:59:12 +0000142 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +0000143}
144
145static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000146 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000147 return CS && CS.hasFnAttr(Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000148}
149
150
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000151/// \brief Tests if a value is a call or invoke to a library function that
152/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
153/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000154bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
155 bool LookThroughBitCast) {
156 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
Nuno Lopes55fff832012-06-21 15:45:28 +0000157}
158
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000159/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000160/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000161bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
162 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000163 // it's safe to consider realloc as noalias since accessing the original
164 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000165 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000166 hasNoAliasAttr(V, LookThroughBitCast);
167}
168
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000169/// \brief Tests if a value is a call or invoke to a library function that
170/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000171bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
172 bool LookThroughBitCast) {
173 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
Nuno Lopes55fff832012-06-21 15:45:28 +0000174}
175
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000176/// \brief Tests if a value is a call or invoke to a library function that
177/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000178bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
179 bool LookThroughBitCast) {
180 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
Nuno Lopes55fff832012-06-21 15:45:28 +0000181}
182
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000183/// \brief Tests if a value is a call or invoke to a library function that
184/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000185bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
186 bool LookThroughBitCast) {
187 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
Nuno Lopes55fff832012-06-21 15:45:28 +0000188}
189
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000190/// extractMallocCall - Returns the corresponding CallInst if the instruction
191/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
192/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000193const CallInst *llvm::extractMallocCall(const Value *I,
194 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000195 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000196}
197
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000198static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000199 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000200 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000201 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000202 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000203
Victor Hernandezf3db9152009-11-07 00:16:28 +0000204 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000205 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000206 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000207 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000208
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000209 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000210 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000211 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000212
Gabor Greifad7884a2010-06-23 21:41:47 +0000213 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000214 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000215 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000216 Value *Multiple = nullptr;
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000217 if (ComputeMultiple(MallocArg, ElementSize, Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +0000218 LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000219 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000220
Craig Topper9f008862014-04-15 04:59:12 +0000221 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000222}
223
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000224/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000225/// The PointerType depends on the number of bitcast uses of the malloc call:
226/// 0: PointerType is the calls' return type.
227/// 1: PointerType is the bitcast's result type.
228/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000229PointerType *llvm::getMallocType(const CallInst *CI,
230 const TargetLibraryInfo *TLI) {
231 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000232
Craig Topper9f008862014-04-15 04:59:12 +0000233 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000234 unsigned NumOfBitCastUses = 0;
235
Victor Hernandez788eaab2009-09-18 19:20:02 +0000236 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000237 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
238 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000239 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
240 MallocType = cast<PointerType>(BCI->getDestTy());
241 NumOfBitCastUses++;
242 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000243
Victor Hernandezf3db9152009-11-07 00:16:28 +0000244 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
245 if (NumOfBitCastUses == 1)
246 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000247
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000248 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000249 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000250 return cast<PointerType>(CI->getType());
251
252 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000253 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000254}
255
Victor Hernandezf3db9152009-11-07 00:16:28 +0000256/// getMallocAllocatedType - Returns the Type allocated by malloc call.
257/// The Type depends on the number of bitcast uses of the malloc call:
258/// 0: PointerType is the malloc calls' return type.
259/// 1: PointerType is the bitcast's result type.
260/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000261Type *llvm::getMallocAllocatedType(const CallInst *CI,
262 const TargetLibraryInfo *TLI) {
263 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000264 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000265}
266
Michael Ilsemand9745242013-03-08 21:03:09 +0000267/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000268/// argument passed to malloc is a multiple of the size of the malloced type,
269/// then return that multiple. For non-array mallocs, the multiple is
270/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000271/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000272Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000273 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000274 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000275 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000276 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000277}
Victor Hernandeze2971492009-10-24 04:23:03 +0000278
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000279
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000280/// extractCallocCall - Returns the corresponding CallInst if the instruction
281/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000282const CallInst *llvm::extractCallocCall(const Value *I,
283 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000284 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000285}
286
Victor Hernandezde5ad422009-10-26 23:43:48 +0000287
Gabor Greif5f5a8642010-06-23 21:51:12 +0000288/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000289const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000290 const CallInst *CI = dyn_cast<CallInst>(I);
Michael Ilseman74ffc272013-03-08 21:15:00 +0000291 if (!CI || isa<IntrinsicInst>(CI))
Craig Topper9f008862014-04-15 04:59:12 +0000292 return nullptr;
Victor Hernandez33188582009-11-03 20:39:35 +0000293 Function *Callee = CI->getCalledFunction();
Richard Smithe78bb122015-01-15 01:00:33 +0000294 if (Callee == nullptr)
Craig Topper9f008862014-04-15 04:59:12 +0000295 return nullptr;
Nick Lewyckyc1f86582011-03-15 07:31:32 +0000296
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000297 StringRef FnName = Callee->getName();
298 LibFunc::Func TLIFn;
299 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000300 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000301
Richard Smith70523c72013-07-21 23:11:42 +0000302 unsigned ExpectedNumParams;
303 if (TLIFn == LibFunc::free ||
304 TLIFn == LibFunc::ZdlPv || // operator delete(void*)
David Majnemerf6665f62015-12-03 22:45:19 +0000305 TLIFn == LibFunc::ZdaPv || // operator delete[](void*)
306 TLIFn == LibFunc::msvc_delete_ptr32 || // operator delete(void*)
307 TLIFn == LibFunc::msvc_delete_ptr64 || // operator delete(void*)
308 TLIFn == LibFunc::msvc_delete_array_ptr32 || // operator delete[](void*)
309 TLIFn == LibFunc::msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000310 ExpectedNumParams = 1;
Richard Smith1ed42292014-10-03 20:17:06 +0000311 else if (TLIFn == LibFunc::ZdlPvj || // delete(void*, uint)
312 TLIFn == LibFunc::ZdlPvm || // delete(void*, ulong)
313 TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
314 TLIFn == LibFunc::ZdaPvj || // delete[](void*, uint)
315 TLIFn == LibFunc::ZdaPvm || // delete[](void*, ulong)
David Majnemerf6665f62015-12-03 22:45:19 +0000316 TLIFn == LibFunc::ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
317 TLIFn == LibFunc::msvc_delete_ptr32_int || // delete(void*, uint)
318 TLIFn == LibFunc::msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
319 TLIFn == LibFunc::msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
320 TLIFn == LibFunc::msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
321 TLIFn == LibFunc::msvc_delete_array_ptr32_int || // delete[](void*, uint)
322 TLIFn == LibFunc::msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
323 TLIFn == LibFunc::msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
324 TLIFn == LibFunc::msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000325 ExpectedNumParams = 2;
326 else
Craig Topper9f008862014-04-15 04:59:12 +0000327 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000328
329 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000330 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000331 // attribute will exist.
Chris Lattner229907c2011-07-18 04:54:35 +0000332 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000333 if (!FTy->getReturnType()->isVoidTy())
Craig Topper9f008862014-04-15 04:59:12 +0000334 return nullptr;
Richard Smith70523c72013-07-21 23:11:42 +0000335 if (FTy->getNumParams() != ExpectedNumParams)
Craig Topper9f008862014-04-15 04:59:12 +0000336 return nullptr;
Chris Lattner67733f62011-06-18 21:46:23 +0000337 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Craig Topper9f008862014-04-15 04:59:12 +0000338 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000339
Gabor Greif5f5a8642010-06-23 21:51:12 +0000340 return CI;
Victor Hernandeze2971492009-10-24 04:23:03 +0000341}
Nuno Lopes55fff832012-06-21 15:45:28 +0000342
343
344
345//===----------------------------------------------------------------------===//
346// Utility functions to compute size of objects.
347//
348
349
350/// \brief Compute the size of the object pointed by Ptr. Returns true and the
351/// object size in Size if successful, and false otherwise.
352/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
353/// byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000354bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000355 const TargetLibraryInfo *TLI, bool RoundToAlign) {
Matt Arsenault40dddd72013-10-03 19:50:01 +0000356 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), RoundToAlign);
Nuno Lopes55fff832012-06-21 15:45:28 +0000357 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
358 if (!Visitor.bothKnown(Data))
359 return false;
360
361 APInt ObjSize = Data.first, Offset = Data.second;
362 // check for overflow
363 if (Offset.slt(0) || ObjSize.ult(Offset))
364 Size = 0;
365 else
366 Size = (ObjSize - Offset).getZExtValue();
367 return true;
368}
369
370
371STATISTIC(ObjectVisitorArgument,
372 "Number of arguments with unsolved size and offset");
373STATISTIC(ObjectVisitorLoad,
374 "Number of load instructions with unsolved size and offset");
375
376
377APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
378 if (RoundToAlign && Align)
379 return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
380 return Size;
381}
382
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000383ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000384 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000385 LLVMContext &Context,
Chandler Carruth7ec50852012-11-01 08:07:29 +0000386 bool RoundToAlign)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000387 : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000388 // Pointer size must be rechecked for each object visited since it could have
389 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000390}
391
392SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000393 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000394 Zero = APInt::getNullValue(IntTyBits);
395
Nuno Lopes55fff832012-06-21 15:45:28 +0000396 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000397 if (Instruction *I = dyn_cast<Instruction>(V)) {
398 // If we have already seen this instruction, bail out. Cycles can happen in
399 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000400 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000401 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000402
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000403 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000404 return visitGEPOperator(*GEP);
405 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000406 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000407 if (Argument *A = dyn_cast<Argument>(V))
408 return visitArgument(*A);
409 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
410 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000411 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
412 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000413 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
414 return visitGlobalVariable(*GV);
415 if (UndefValue *UV = dyn_cast<UndefValue>(V))
416 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000417 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000418 if (CE->getOpcode() == Instruction::IntToPtr)
419 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000420 if (CE->getOpcode() == Instruction::GetElementPtr)
421 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000422 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000423
424 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
425 << '\n');
426 return unknown();
427}
428
429SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
430 if (!I.getAllocatedType()->isSized())
431 return unknown();
432
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000433 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000434 if (!I.isArrayAllocation())
435 return std::make_pair(align(Size, I.getAlignment()), Zero);
436
437 Value *ArraySize = I.getArraySize();
438 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
439 Size *= C->getValue().zextOrSelf(IntTyBits);
440 return std::make_pair(align(Size, I.getAlignment()), Zero);
441 }
442 return unknown();
443}
444
445SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
446 // no interprocedural analysis is done at the moment
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000447 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000448 ++ObjectVisitorArgument;
449 return unknown();
450 }
451 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000452 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000453 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
454}
455
456SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000457 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
458 TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000459 if (!FnData)
460 return unknown();
461
462 // handle strdup-like functions separately
463 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000464 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
465 if (!Size)
466 return unknown();
467
468 // strndup limits strlen
469 if (FnData->FstParam > 0) {
470 ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
471 if (!Arg)
472 return unknown();
473
474 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
475 if (Size.ugt(MaxSize))
476 Size = MaxSize + 1;
477 }
478 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000479 }
480
481 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
482 if (!Arg)
483 return unknown();
484
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000485 APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes55fff832012-06-21 15:45:28 +0000486 // size determined by just 1 parameter
Nuno Lopesf06b7312012-06-21 18:38:26 +0000487 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000488 return std::make_pair(Size, Zero);
489
490 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
491 if (!Arg)
492 return unknown();
493
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000494 Size *= Arg->getValue().zextOrSelf(IntTyBits);
Nuno Lopes55fff832012-06-21 15:45:28 +0000495 return std::make_pair(Size, Zero);
496
497 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000498 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000499 // - strcpy / strncpy
500 // - strcat / strncat
501 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000502 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000503 // - memset
504}
505
506SizeOffsetType
507ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
508 return std::make_pair(Zero, Zero);
509}
510
511SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000512ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
513 return unknown();
514}
515
516SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000517ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
518 // Easy cases were already folded by previous passes.
519 return unknown();
520}
521
522SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
523 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000524 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000525 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000526 return unknown();
527
Nuno Lopes55fff832012-06-21 15:45:28 +0000528 return std::make_pair(PtrData.first, PtrData.second + Offset);
529}
530
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000531SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
532 if (GA.mayBeOverridden())
533 return unknown();
534 return compute(GA.getAliasee());
535}
536
Nuno Lopes55fff832012-06-21 15:45:28 +0000537SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
538 if (!GV.hasDefinitiveInitializer())
539 return unknown();
540
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000541 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000542 return std::make_pair(align(Size, GV.getAlignment()), Zero);
543}
544
545SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
546 // clueless
547 return unknown();
548}
549
550SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
551 ++ObjectVisitorLoad;
552 return unknown();
553}
554
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000555SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
556 // too complex to analyze statically.
557 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000558}
559
560SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
561 SizeOffsetType TrueSide = compute(I.getTrueValue());
562 SizeOffsetType FalseSide = compute(I.getFalseValue());
Nuno Lopes4b47f822012-12-31 18:01:36 +0000563 if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
Nuno Lopes55fff832012-06-21 15:45:28 +0000564 return TrueSide;
565 return unknown();
566}
567
568SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
569 return std::make_pair(Zero, Zero);
570}
571
572SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
573 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
574 return unknown();
575}
576
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000577ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
578 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
579 bool RoundToAlign)
580 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
581 RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000582 // IntTy and Zero must be set for each compute() since the address space may
583 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000584}
585
586SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000587 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000589 Zero = ConstantInt::get(IntTy, 0);
590
Nuno Lopes55fff832012-06-21 15:45:28 +0000591 SizeOffsetEvalType Result = compute_(V);
592
593 if (!bothKnown(Result)) {
594 // erase everything that was computed in this iteration from the cache, so
595 // that no dangling references are left behind. We could be a bit smarter if
596 // we kept a dependency graph. It's probably not worth the complexity.
597 for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
598 CacheMapTy::iterator CacheIt = CacheMap.find(*I);
599 // non-computable results can be safely cached
600 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
601 CacheMap.erase(CacheIt);
602 }
603 }
604
605 SeenVals.clear();
606 return Result;
607}
608
609SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
Nuno Lopes340b0462013-10-24 09:17:24 +0000610 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
Nuno Lopes55fff832012-06-21 15:45:28 +0000611 SizeOffsetType Const = Visitor.compute(V);
612 if (Visitor.bothKnown(Const))
613 return std::make_pair(ConstantInt::get(Context, Const.first),
614 ConstantInt::get(Context, Const.second));
615
616 V = V->stripPointerCasts();
617
618 // check cache
619 CacheMapTy::iterator CacheIt = CacheMap.find(V);
620 if (CacheIt != CacheMap.end())
621 return CacheIt->second;
622
623 // always generate code immediately before the instruction being
624 // processed, so that the generated code dominates the same BBs
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000625 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000626 if (Instruction *I = dyn_cast<Instruction>(V))
627 Builder.SetInsertPoint(I);
628
Nuno Lopes55fff832012-06-21 15:45:28 +0000629 // now compute the size and offset
630 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000631
632 // Record the pointers that were handled in this run, so that they can be
633 // cleaned later if something fails. We also use this set to break cycles that
634 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000635 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000636 Result = unknown();
637 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000638 Result = visitGEPOperator(*GEP);
639 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
640 Result = visit(*I);
641 } else if (isa<Argument>(V) ||
642 (isa<ConstantExpr>(V) &&
643 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000644 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000645 isa<GlobalVariable>(V)) {
646 // ignore values where we cannot do more than what ObjectSizeVisitor can
647 Result = unknown();
648 } else {
649 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
650 << *V << '\n');
651 Result = unknown();
652 }
653
Nuno Lopes55fff832012-06-21 15:45:28 +0000654 // Don't reuse CacheIt since it may be invalid at this point.
655 CacheMap[V] = Result;
656 return Result;
657}
658
659SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
660 if (!I.getAllocatedType()->isSized())
661 return unknown();
662
663 // must be a VLA
664 assert(I.isArrayAllocation());
665 Value *ArraySize = I.getArraySize();
666 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000667 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000668 Size = Builder.CreateMul(Size, ArraySize);
669 return std::make_pair(Size, Zero);
670}
671
672SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000673 const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
674 TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000675 if (!FnData)
676 return unknown();
677
678 // handle strdup-like functions separately
679 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000680 // TODO
681 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000682 }
683
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000684 Value *FirstArg = CS.getArgument(FnData->FstParam);
685 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000686 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000687 return std::make_pair(FirstArg, Zero);
688
689 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000690 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000691 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
692 return std::make_pair(Size, Zero);
693
694 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000695 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000696 // - strcpy / strncpy
697 // - strcat / strncat
698 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000699 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000700 // - memset
701}
702
703SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000704ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
705 return unknown();
706}
707
708SizeOffsetEvalType
709ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
710 return unknown();
711}
712
713SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000714ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
715 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
716 if (!bothKnown(PtrData))
717 return unknown();
718
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000719 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000720 Offset = Builder.CreateAdd(PtrData.second, Offset);
721 return std::make_pair(PtrData.first, Offset);
722}
723
724SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
725 // clueless
726 return unknown();
727}
728
729SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
730 return unknown();
731}
732
733SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
734 // create 2 PHIs: one for size and another for offset
735 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
736 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
737
738 // insert right away in the cache to handle recursive PHIs
739 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
740
741 // compute offset/size for each PHI incoming pointer
742 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000743 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000744 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
745
746 if (!bothKnown(EdgeData)) {
747 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
748 OffsetPHI->eraseFromParent();
749 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
750 SizePHI->eraseFromParent();
751 return unknown();
752 }
753 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
754 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
755 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000756
757 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
758 if ((Tmp = SizePHI->hasConstantValue())) {
759 Size = Tmp;
760 SizePHI->replaceAllUsesWith(Size);
761 SizePHI->eraseFromParent();
762 }
763 if ((Tmp = OffsetPHI->hasConstantValue())) {
764 Offset = Tmp;
765 OffsetPHI->replaceAllUsesWith(Offset);
766 OffsetPHI->eraseFromParent();
767 }
768 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000769}
770
771SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
772 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
773 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
774
775 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
776 return unknown();
777 if (TrueSide == FalseSide)
778 return TrueSide;
779
780 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
781 FalseSide.first);
782 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
783 FalseSide.second);
784 return std::make_pair(Size, Offset);
785}
786
787SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
788 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
789 return unknown();
790}