blob: f23477622bec69823ca39df5936b2ecef1b45f03 [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 {
Nuno Lopes55fff832012-06-21 15:45:28 +000045 AllocType AllocTy;
George Burgess IV278199f2016-04-12 01:05:35 +000046 unsigned NumParams;
Nuno Lopes55fff832012-06-21 15:45:28 +000047 // First and Second size parameters (or -1 if unused)
George Burgess IV278199f2016-04-12 01:05:35 +000048 int FstParam, SndParam;
Nuno Lopes55fff832012-06-21 15:45:28 +000049};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000050
Nuno Lopes181d67e2012-06-28 16:34:03 +000051// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
52// know which functions are nounwind, noalias, nocapture parameters, etc.
George Burgess IV278199f2016-04-12 01:05:35 +000053static const std::pair<LibFunc::Func, AllocFnsTy> AllocationFnData[] = {
54 {LibFunc::malloc, {MallocLike, 1, 0, -1}},
55 {LibFunc::valloc, {MallocLike, 1, 0, -1}},
56 {LibFunc::Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
57 {LibFunc::ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
58 {LibFunc::Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
59 {LibFunc::ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
60 {LibFunc::Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
61 {LibFunc::ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
62 {LibFunc::Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
63 {LibFunc::ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
64 {LibFunc::msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
65 {LibFunc::msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
66 {LibFunc::msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
67 {LibFunc::msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
68 {LibFunc::msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
69 {LibFunc::msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
70 {LibFunc::msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
71 {LibFunc::msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
72 {LibFunc::calloc, {CallocLike, 2, 0, 1}},
73 {LibFunc::realloc, {ReallocLike, 2, 1, -1}},
74 {LibFunc::reallocf, {ReallocLike, 2, 1, -1}},
75 {LibFunc::strdup, {StrDupLike, 1, -1, -1}},
76 {LibFunc::strndup, {StrDupLike, 2, 1, -1}}
Benjamin Kramer01df8172013-09-24 17:49:08 +000077 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes55fff832012-06-21 15:45:28 +000078};
79
80
81static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
82 if (LookThroughBitCast)
83 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +000084
Nuno Lopes15dbcb42012-06-22 15:50:53 +000085 CallSite CS(const_cast<Value*>(V));
86 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +000087 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000088
Michael Gottesman41748d72013-06-27 00:25:01 +000089 if (CS.isNoBuiltin())
Craig Topper9f008862014-04-15 04:59:12 +000090 return nullptr;
Richard Smithe04f0d32013-05-16 04:12:04 +000091
Nuno Lopesdc6085e2012-06-21 21:25:05 +000092 Function *Callee = CS.getCalledFunction();
Nuno Lopes55fff832012-06-21 15:45:28 +000093 if (!Callee || !Callee->isDeclaration())
Craig Topper9f008862014-04-15 04:59:12 +000094 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +000095 return Callee;
96}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000097
George Burgess IV278199f2016-04-12 01:05:35 +000098/// Returns the allocation data for the given value if it's either a call to a
99/// known allocation function, or a call to a function with the allocsize
100/// attribute.
101static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
102 const TargetLibraryInfo *TLI,
103 bool LookThroughBitCast = false) {
Michael Ilseman74ffc272013-03-08 21:15:00 +0000104 // Skip intrinsics
105 if (isa<IntrinsicInst>(V))
George Burgess IV278199f2016-04-12 01:05:35 +0000106 return None;
Michael Ilseman74ffc272013-03-08 21:15:00 +0000107
George Burgess IV278199f2016-04-12 01:05:35 +0000108 const Function *Callee = getCalledFunction(V, LookThroughBitCast);
Nuno Lopes55fff832012-06-21 15:45:28 +0000109 if (!Callee)
George Burgess IV278199f2016-04-12 01:05:35 +0000110 return None;
111
112 // If it has allocsize, we can skip checking if it's a known function.
113 //
114 // MallocLike is chosen here because allocsize makes no guarantees about the
115 // nullness of the result of the function, nor does it deal with strings, nor
116 // does it require that the memory returned is zeroed out.
117 LLVM_CONSTEXPR auto AllocSizeAllocTy = MallocLike;
118 if ((AllocTy & AllocSizeAllocTy) == AllocSizeAllocTy &&
119 Callee->hasFnAttribute(Attribute::AllocSize)) {
120 Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
121 std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
122
123 AllocFnsTy Result;
124 Result.AllocTy = AllocSizeAllocTy;
125 Result.NumParams = Callee->getNumOperands();
126 Result.FstParam = Args.first;
127 Result.SndParam = Args.second.getValueOr(-1);
128 return Result;
129 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000130
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000131 // Make sure that the function is available.
132 StringRef FnName = Callee->getName();
133 LibFunc::Func TLIFn;
134 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
George Burgess IV278199f2016-04-12 01:05:35 +0000135 return None;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000136
George Burgess IV278199f2016-04-12 01:05:35 +0000137 const auto *Iter =
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000138 std::find_if(std::begin(AllocationFnData), std::end(AllocationFnData),
George Burgess IV278199f2016-04-12 01:05:35 +0000139 [TLIFn](const std::pair<LibFunc::Func, AllocFnsTy> &P) {
140 return P.first == TLIFn;
141 });
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000142
George Burgess IV278199f2016-04-12 01:05:35 +0000143 if (Iter == std::end(AllocationFnData))
144 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000145
George Burgess IV278199f2016-04-12 01:05:35 +0000146 const AllocFnsTy *FnData = &Iter->second;
Benjamin Kramer2939dd32013-09-24 17:34:29 +0000147 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
George Burgess IV278199f2016-04-12 01:05:35 +0000148 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000149
150 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000151 int FstParam = FnData->FstParam;
152 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000153 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000154
155 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
156 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000157 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000158 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
159 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000160 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000161 FTy->getParamType(SndParam)->isIntegerTy(32) ||
162 FTy->getParamType(SndParam)->isIntegerTy(64)))
George Burgess IV278199f2016-04-12 01:05:35 +0000163 return *FnData;
164 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000165}
166
167static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000168 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Sanjoy Dasef8ed0c2016-02-09 21:54:18 +0000169 return CS && CS.paramHasAttr(AttributeSet::ReturnIndex, Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000170}
171
172
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000173/// \brief Tests if a value is a call or invoke to a library function that
174/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
175/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000176bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
177 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000178 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000179}
180
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000181/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000182/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000183bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
184 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000185 // it's safe to consider realloc as noalias since accessing the original
186 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000187 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000188 hasNoAliasAttr(V, LookThroughBitCast);
189}
190
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000191/// \brief Tests if a value is a call or invoke to a library function that
192/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000193bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
194 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000195 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000196}
197
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000198/// \brief Tests if a value is a call or invoke to a library function that
199/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000200bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
201 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000202 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000203}
204
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000205/// \brief Tests if a value is a call or invoke to a library function that
206/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000207bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
208 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000209 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000210}
211
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000212/// extractMallocCall - Returns the corresponding CallInst if the instruction
213/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
214/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000215const CallInst *llvm::extractMallocCall(const Value *I,
216 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000217 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000218}
219
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000220static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000221 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000222 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000223 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000224 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000225
Victor Hernandezf3db9152009-11-07 00:16:28 +0000226 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000227 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000228 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000229 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000230
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000231 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000232 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000234
Gabor Greifad7884a2010-06-23 21:41:47 +0000235 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000236 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000237 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000238 Value *Multiple = nullptr;
Sanjay Patel490193d2016-07-07 16:19:09 +0000239 if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000240 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000241
Craig Topper9f008862014-04-15 04:59:12 +0000242 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000243}
244
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000245/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000246/// The PointerType depends on the number of bitcast uses of the malloc call:
247/// 0: PointerType is the calls' return type.
248/// 1: PointerType is the bitcast's result type.
249/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000250PointerType *llvm::getMallocType(const CallInst *CI,
251 const TargetLibraryInfo *TLI) {
252 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000253
Craig Topper9f008862014-04-15 04:59:12 +0000254 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000255 unsigned NumOfBitCastUses = 0;
256
Victor Hernandez788eaab2009-09-18 19:20:02 +0000257 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000258 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
259 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000260 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
261 MallocType = cast<PointerType>(BCI->getDestTy());
262 NumOfBitCastUses++;
263 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000264
Victor Hernandezf3db9152009-11-07 00:16:28 +0000265 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
266 if (NumOfBitCastUses == 1)
267 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000268
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000269 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000270 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000271 return cast<PointerType>(CI->getType());
272
273 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000274 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000275}
276
Victor Hernandezf3db9152009-11-07 00:16:28 +0000277/// getMallocAllocatedType - Returns the Type allocated by malloc call.
278/// The Type depends on the number of bitcast uses of the malloc call:
279/// 0: PointerType is the malloc calls' return type.
280/// 1: PointerType is the bitcast's result type.
281/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000282Type *llvm::getMallocAllocatedType(const CallInst *CI,
283 const TargetLibraryInfo *TLI) {
284 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000285 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000286}
287
Michael Ilsemand9745242013-03-08 21:03:09 +0000288/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000289/// argument passed to malloc is a multiple of the size of the malloced type,
290/// then return that multiple. For non-array mallocs, the multiple is
291/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000292/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000293Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000294 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000295 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000296 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000297 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000298}
Victor Hernandeze2971492009-10-24 04:23:03 +0000299
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000300
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000301/// extractCallocCall - Returns the corresponding CallInst if the instruction
302/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000303const CallInst *llvm::extractCallocCall(const Value *I,
304 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000305 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000306}
307
Victor Hernandezde5ad422009-10-26 23:43:48 +0000308
Gabor Greif5f5a8642010-06-23 21:51:12 +0000309/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000310const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000311 const CallInst *CI = dyn_cast<CallInst>(I);
Michael Ilseman74ffc272013-03-08 21:15:00 +0000312 if (!CI || isa<IntrinsicInst>(CI))
Craig Topper9f008862014-04-15 04:59:12 +0000313 return nullptr;
Victor Hernandez33188582009-11-03 20:39:35 +0000314 Function *Callee = CI->getCalledFunction();
Richard Smithe78bb122015-01-15 01:00:33 +0000315 if (Callee == nullptr)
Craig Topper9f008862014-04-15 04:59:12 +0000316 return nullptr;
Nick Lewyckyc1f86582011-03-15 07:31:32 +0000317
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000318 StringRef FnName = Callee->getName();
319 LibFunc::Func TLIFn;
320 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000321 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000322
Richard Smith70523c72013-07-21 23:11:42 +0000323 unsigned ExpectedNumParams;
324 if (TLIFn == LibFunc::free ||
325 TLIFn == LibFunc::ZdlPv || // operator delete(void*)
David Majnemerf6665f62015-12-03 22:45:19 +0000326 TLIFn == LibFunc::ZdaPv || // operator delete[](void*)
327 TLIFn == LibFunc::msvc_delete_ptr32 || // operator delete(void*)
328 TLIFn == LibFunc::msvc_delete_ptr64 || // operator delete(void*)
329 TLIFn == LibFunc::msvc_delete_array_ptr32 || // operator delete[](void*)
330 TLIFn == LibFunc::msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000331 ExpectedNumParams = 1;
Richard Smith1ed42292014-10-03 20:17:06 +0000332 else if (TLIFn == LibFunc::ZdlPvj || // delete(void*, uint)
333 TLIFn == LibFunc::ZdlPvm || // delete(void*, ulong)
334 TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
335 TLIFn == LibFunc::ZdaPvj || // delete[](void*, uint)
336 TLIFn == LibFunc::ZdaPvm || // delete[](void*, ulong)
David Majnemerf6665f62015-12-03 22:45:19 +0000337 TLIFn == LibFunc::ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
338 TLIFn == LibFunc::msvc_delete_ptr32_int || // delete(void*, uint)
339 TLIFn == LibFunc::msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
340 TLIFn == LibFunc::msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
341 TLIFn == LibFunc::msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
342 TLIFn == LibFunc::msvc_delete_array_ptr32_int || // delete[](void*, uint)
343 TLIFn == LibFunc::msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
344 TLIFn == LibFunc::msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
345 TLIFn == LibFunc::msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000346 ExpectedNumParams = 2;
347 else
Craig Topper9f008862014-04-15 04:59:12 +0000348 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000349
350 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000351 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000352 // attribute will exist.
Chris Lattner229907c2011-07-18 04:54:35 +0000353 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000354 if (!FTy->getReturnType()->isVoidTy())
Craig Topper9f008862014-04-15 04:59:12 +0000355 return nullptr;
Richard Smith70523c72013-07-21 23:11:42 +0000356 if (FTy->getNumParams() != ExpectedNumParams)
Craig Topper9f008862014-04-15 04:59:12 +0000357 return nullptr;
Chris Lattner67733f62011-06-18 21:46:23 +0000358 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Craig Topper9f008862014-04-15 04:59:12 +0000359 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000360
Gabor Greif5f5a8642010-06-23 21:51:12 +0000361 return CI;
Victor Hernandeze2971492009-10-24 04:23:03 +0000362}
Nuno Lopes55fff832012-06-21 15:45:28 +0000363
364
365
366//===----------------------------------------------------------------------===//
367// Utility functions to compute size of objects.
368//
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000369static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
370 if (Data.second.isNegative() || Data.first.ult(Data.second))
371 return APInt(Data.first.getBitWidth(), 0);
372 return Data.first - Data.second;
373}
Nuno Lopes55fff832012-06-21 15:45:28 +0000374
375/// \brief Compute the size of the object pointed by Ptr. Returns true and the
376/// object size in Size if successful, and false otherwise.
377/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
378/// byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000379bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000380 const TargetLibraryInfo *TLI, bool RoundToAlign,
381 llvm::ObjSizeMode Mode) {
382 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(),
383 RoundToAlign, Mode);
Nuno Lopes55fff832012-06-21 15:45:28 +0000384 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
385 if (!Visitor.bothKnown(Data))
386 return false;
387
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000388 Size = getSizeWithOverflow(Data).getZExtValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000389 return true;
390}
391
Nuno Lopes55fff832012-06-21 15:45:28 +0000392STATISTIC(ObjectVisitorArgument,
393 "Number of arguments with unsolved size and offset");
394STATISTIC(ObjectVisitorLoad,
395 "Number of load instructions with unsolved size and offset");
396
397
398APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
399 if (RoundToAlign && Align)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000400 return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
Nuno Lopes55fff832012-06-21 15:45:28 +0000401 return Size;
402}
403
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000404ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000405 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000406 LLVMContext &Context,
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000407 bool RoundToAlign,
408 ObjSizeMode Mode)
409 : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign), Mode(Mode) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000410 // Pointer size must be rechecked for each object visited since it could have
411 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000412}
413
414SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000415 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000416 Zero = APInt::getNullValue(IntTyBits);
417
Nuno Lopes55fff832012-06-21 15:45:28 +0000418 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000419 if (Instruction *I = dyn_cast<Instruction>(V)) {
420 // If we have already seen this instruction, bail out. Cycles can happen in
421 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000422 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000423 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000424
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000425 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000426 return visitGEPOperator(*GEP);
427 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000428 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000429 if (Argument *A = dyn_cast<Argument>(V))
430 return visitArgument(*A);
431 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
432 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000433 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
434 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000435 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
436 return visitGlobalVariable(*GV);
437 if (UndefValue *UV = dyn_cast<UndefValue>(V))
438 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000440 if (CE->getOpcode() == Instruction::IntToPtr)
441 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000442 if (CE->getOpcode() == Instruction::GetElementPtr)
443 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000444 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000445
446 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
447 << '\n');
448 return unknown();
449}
450
451SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
452 if (!I.getAllocatedType()->isSized())
453 return unknown();
454
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000455 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000456 if (!I.isArrayAllocation())
457 return std::make_pair(align(Size, I.getAlignment()), Zero);
458
459 Value *ArraySize = I.getArraySize();
460 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
461 Size *= C->getValue().zextOrSelf(IntTyBits);
462 return std::make_pair(align(Size, I.getAlignment()), Zero);
463 }
464 return unknown();
465}
466
467SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000468 // No interprocedural analysis is done at the moment.
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000469 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000470 ++ObjectVisitorArgument;
471 return unknown();
472 }
473 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000475 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
476}
477
478SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
George Burgess IV278199f2016-04-12 01:05:35 +0000479 Optional<AllocFnsTy> FnData =
480 getAllocationData(CS.getInstruction(), AnyAlloc, TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000481 if (!FnData)
482 return unknown();
483
Sanjay Patel490193d2016-07-07 16:19:09 +0000484 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000485 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000486 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
487 if (!Size)
488 return unknown();
489
Sanjay Patel490193d2016-07-07 16:19:09 +0000490 // Strndup limits strlen.
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000491 if (FnData->FstParam > 0) {
George Burgess IV278199f2016-04-12 01:05:35 +0000492 ConstantInt *Arg =
493 dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000494 if (!Arg)
495 return unknown();
496
497 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
498 if (Size.ugt(MaxSize))
499 Size = MaxSize + 1;
500 }
501 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000502 }
503
504 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
505 if (!Arg)
506 return unknown();
507
George Burgess IV278199f2016-04-12 01:05:35 +0000508 // When we're compiling N-bit code, and the user uses parameters that are
509 // greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
510 // trouble with APInt size issues. This function handles resizing + overflow
511 // checks for us.
512 auto CheckedZextOrTrunc = [&](APInt &I) {
513 // More bits than we can handle. Checking the bit width isn't necessary, but
514 // it's faster than checking active bits, and should give `false` in the
515 // vast majority of cases.
516 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
517 return false;
518 if (I.getBitWidth() != IntTyBits)
519 I = I.zextOrTrunc(IntTyBits);
520 return true;
521 };
522
523 APInt Size = Arg->getValue();
524 if (!CheckedZextOrTrunc(Size))
525 return unknown();
526
Sanjay Patel490193d2016-07-07 16:19:09 +0000527 // Size is determined by just 1 parameter.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000528 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000529 return std::make_pair(Size, Zero);
530
531 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
532 if (!Arg)
533 return unknown();
534
George Burgess IV278199f2016-04-12 01:05:35 +0000535 APInt NumElems = Arg->getValue();
536 if (!CheckedZextOrTrunc(NumElems))
537 return unknown();
538
539 bool Overflow;
540 Size = Size.umul_ov(NumElems, Overflow);
541 return Overflow ? unknown() : std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000542
543 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000544 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000545 // - strcpy / strncpy
546 // - strcat / strncat
547 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000548 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000549 // - memset
550}
551
552SizeOffsetType
553ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
554 return std::make_pair(Zero, Zero);
555}
556
557SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000558ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
559 return unknown();
560}
561
562SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000563ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
564 // Easy cases were already folded by previous passes.
565 return unknown();
566}
567
568SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
569 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000570 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000571 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000572 return unknown();
573
Nuno Lopes55fff832012-06-21 15:45:28 +0000574 return std::make_pair(PtrData.first, PtrData.second + Offset);
575}
576
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000577SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000578 if (GA.isInterposable())
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000579 return unknown();
580 return compute(GA.getAliasee());
581}
582
Nuno Lopes55fff832012-06-21 15:45:28 +0000583SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
584 if (!GV.hasDefinitiveInitializer())
585 return unknown();
586
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000587 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000588 return std::make_pair(align(Size, GV.getAlignment()), Zero);
589}
590
591SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
592 // clueless
593 return unknown();
594}
595
596SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
597 ++ObjectVisitorLoad;
598 return unknown();
599}
600
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000601SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
602 // too complex to analyze statically.
603 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000604}
605
606SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
607 SizeOffsetType TrueSide = compute(I.getTrueValue());
608 SizeOffsetType FalseSide = compute(I.getFalseValue());
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000609 if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
610 if (TrueSide == FalseSide) {
611 return TrueSide;
612 }
613
614 APInt TrueResult = getSizeWithOverflow(TrueSide);
615 APInt FalseResult = getSizeWithOverflow(FalseSide);
616
617 if (TrueResult == FalseResult) {
618 return TrueSide;
619 }
620 if (Mode == ObjSizeMode::Min) {
621 if (TrueResult.slt(FalseResult))
622 return TrueSide;
623 return FalseSide;
624 }
625 if (Mode == ObjSizeMode::Max) {
626 if (TrueResult.sgt(FalseResult))
627 return TrueSide;
628 return FalseSide;
629 }
630 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000631 return unknown();
632}
633
634SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
635 return std::make_pair(Zero, Zero);
636}
637
638SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
639 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
640 return unknown();
641}
642
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000643ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
644 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
645 bool RoundToAlign)
646 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
647 RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000648 // IntTy and Zero must be set for each compute() since the address space may
649 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000650}
651
652SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000653 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000654 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000655 Zero = ConstantInt::get(IntTy, 0);
656
Nuno Lopes55fff832012-06-21 15:45:28 +0000657 SizeOffsetEvalType Result = compute_(V);
658
659 if (!bothKnown(Result)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000660 // Erase everything that was computed in this iteration from the cache, so
Nuno Lopes55fff832012-06-21 15:45:28 +0000661 // that no dangling references are left behind. We could be a bit smarter if
662 // we kept a dependency graph. It's probably not worth the complexity.
Benjamin Krameraa209152016-06-26 17:27:42 +0000663 for (const Value *SeenVal : SeenVals) {
664 CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
Nuno Lopes55fff832012-06-21 15:45:28 +0000665 // non-computable results can be safely cached
666 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
667 CacheMap.erase(CacheIt);
668 }
669 }
670
671 SeenVals.clear();
672 return Result;
673}
674
675SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
Nuno Lopes340b0462013-10-24 09:17:24 +0000676 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
Nuno Lopes55fff832012-06-21 15:45:28 +0000677 SizeOffsetType Const = Visitor.compute(V);
678 if (Visitor.bothKnown(Const))
679 return std::make_pair(ConstantInt::get(Context, Const.first),
680 ConstantInt::get(Context, Const.second));
681
682 V = V->stripPointerCasts();
683
Sanjay Patel490193d2016-07-07 16:19:09 +0000684 // Check cache.
Nuno Lopes55fff832012-06-21 15:45:28 +0000685 CacheMapTy::iterator CacheIt = CacheMap.find(V);
686 if (CacheIt != CacheMap.end())
687 return CacheIt->second;
688
Sanjay Patel490193d2016-07-07 16:19:09 +0000689 // Always generate code immediately before the instruction being
690 // processed, so that the generated code dominates the same BBs.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000691 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000692 if (Instruction *I = dyn_cast<Instruction>(V))
693 Builder.SetInsertPoint(I);
694
Sanjay Patel490193d2016-07-07 16:19:09 +0000695 // Now compute the size and offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000696 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000697
698 // Record the pointers that were handled in this run, so that they can be
699 // cleaned later if something fails. We also use this set to break cycles that
700 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000701 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000702 Result = unknown();
703 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000704 Result = visitGEPOperator(*GEP);
705 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
706 Result = visit(*I);
707 } else if (isa<Argument>(V) ||
708 (isa<ConstantExpr>(V) &&
709 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000710 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000711 isa<GlobalVariable>(V)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000712 // Ignore values where we cannot do more than ObjectSizeVisitor.
Nuno Lopes55fff832012-06-21 15:45:28 +0000713 Result = unknown();
714 } else {
715 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
716 << *V << '\n');
717 Result = unknown();
718 }
719
Nuno Lopes55fff832012-06-21 15:45:28 +0000720 // Don't reuse CacheIt since it may be invalid at this point.
721 CacheMap[V] = Result;
722 return Result;
723}
724
725SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
726 if (!I.getAllocatedType()->isSized())
727 return unknown();
728
729 // must be a VLA
730 assert(I.isArrayAllocation());
731 Value *ArraySize = I.getArraySize();
732 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000733 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000734 Size = Builder.CreateMul(Size, ArraySize);
735 return std::make_pair(Size, Zero);
736}
737
738SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
George Burgess IV278199f2016-04-12 01:05:35 +0000739 Optional<AllocFnsTy> FnData =
740 getAllocationData(CS.getInstruction(), AnyAlloc, TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000741 if (!FnData)
742 return unknown();
743
Sanjay Patel490193d2016-07-07 16:19:09 +0000744 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000745 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000746 // TODO
747 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000748 }
749
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000750 Value *FirstArg = CS.getArgument(FnData->FstParam);
751 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000752 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000753 return std::make_pair(FirstArg, Zero);
754
755 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000756 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000757 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
758 return std::make_pair(Size, Zero);
759
760 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000761 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000762 // - strcpy / strncpy
763 // - strcat / strncat
764 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000765 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000766 // - memset
767}
768
769SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000770ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
771 return unknown();
772}
773
774SizeOffsetEvalType
775ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
776 return unknown();
777}
778
779SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000780ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
781 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
782 if (!bothKnown(PtrData))
783 return unknown();
784
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000785 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000786 Offset = Builder.CreateAdd(PtrData.second, Offset);
787 return std::make_pair(PtrData.first, Offset);
788}
789
790SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
791 // clueless
792 return unknown();
793}
794
795SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
796 return unknown();
797}
798
799SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000800 // Create 2 PHIs: one for size and another for offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000801 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
802 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
803
Sanjay Patel490193d2016-07-07 16:19:09 +0000804 // Insert right away in the cache to handle recursive PHIs.
Nuno Lopes55fff832012-06-21 15:45:28 +0000805 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
806
Sanjay Patel490193d2016-07-07 16:19:09 +0000807 // Compute offset/size for each PHI incoming pointer.
Nuno Lopes55fff832012-06-21 15:45:28 +0000808 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000809 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000810 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
811
812 if (!bothKnown(EdgeData)) {
813 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
814 OffsetPHI->eraseFromParent();
815 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
816 SizePHI->eraseFromParent();
817 return unknown();
818 }
819 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
820 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
821 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000822
823 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
824 if ((Tmp = SizePHI->hasConstantValue())) {
825 Size = Tmp;
826 SizePHI->replaceAllUsesWith(Size);
827 SizePHI->eraseFromParent();
828 }
829 if ((Tmp = OffsetPHI->hasConstantValue())) {
830 Offset = Tmp;
831 OffsetPHI->replaceAllUsesWith(Offset);
832 OffsetPHI->eraseFromParent();
833 }
834 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000835}
836
837SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
838 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
839 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
840
841 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
842 return unknown();
843 if (TrueSide == FalseSide)
844 return TrueSide;
845
846 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
847 FalseSide.first);
848 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
849 FalseSide.second);
850 return std::make_pair(Size, Offset);
851}
852
853SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
854 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
855 return unknown();
856}