blob: f99d3b3fbda324da88029db521dacc41c9c2ffc7 [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.
David L. Jonesd21529f2017-01-23 23:16:46 +000053static const std::pair<LibFunc, 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
George Burgess IVed160242016-12-27 06:32:14 +000080static Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
81 bool &IsNoBuiltin) {
George Burgess IVce044892016-12-27 06:10:50 +000082 // Don't care about intrinsics in this case.
83 if (isa<IntrinsicInst>(V))
84 return nullptr;
85
Nuno Lopes55fff832012-06-21 15:45:28 +000086 if (LookThroughBitCast)
87 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +000088
Nuno Lopes15dbcb42012-06-22 15:50:53 +000089 CallSite CS(const_cast<Value*>(V));
90 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +000091 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000092
George Burgess IVed160242016-12-27 06:32:14 +000093 IsNoBuiltin = CS.isNoBuiltin();
Richard Smithe04f0d32013-05-16 04:12:04 +000094
Nuno Lopesdc6085e2012-06-21 21:25:05 +000095 Function *Callee = CS.getCalledFunction();
Nuno Lopes55fff832012-06-21 15:45:28 +000096 if (!Callee || !Callee->isDeclaration())
Craig Topper9f008862014-04-15 04:59:12 +000097 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +000098 return Callee;
99}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000100
George Burgess IV278199f2016-04-12 01:05:35 +0000101/// Returns the allocation data for the given value if it's either a call to a
102/// known allocation function, or a call to a function with the allocsize
103/// attribute.
George Burgess IVce044892016-12-27 06:10:50 +0000104static Optional<AllocFnsTy>
105getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
106 const TargetLibraryInfo *TLI) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000107 // Make sure that the function is available.
108 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000109 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000110 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
George Burgess IV278199f2016-04-12 01:05:35 +0000111 return None;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000112
George Burgess IV45a540f2016-12-20 18:46:27 +0000113 const auto *Iter = find_if(
David L. Jonesd21529f2017-01-23 23:16:46 +0000114 AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
George Burgess IV45a540f2016-12-20 18:46:27 +0000115 return P.first == TLIFn;
116 });
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000117
George Burgess IV278199f2016-04-12 01:05:35 +0000118 if (Iter == std::end(AllocationFnData))
119 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000120
George Burgess IV278199f2016-04-12 01:05:35 +0000121 const AllocFnsTy *FnData = &Iter->second;
Benjamin Kramer2939dd32013-09-24 17:34:29 +0000122 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
George Burgess IV278199f2016-04-12 01:05:35 +0000123 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000124
125 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000126 int FstParam = FnData->FstParam;
127 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000128 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000129
130 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
131 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000132 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000133 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
134 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000135 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000136 FTy->getParamType(SndParam)->isIntegerTy(32) ||
137 FTy->getParamType(SndParam)->isIntegerTy(64)))
George Burgess IV278199f2016-04-12 01:05:35 +0000138 return *FnData;
139 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000140}
141
George Burgess IVce044892016-12-27 06:10:50 +0000142static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
143 const TargetLibraryInfo *TLI,
144 bool LookThroughBitCast = false) {
George Burgess IVed160242016-12-27 06:32:14 +0000145 bool IsNoBuiltinCall;
146 if (const Function *Callee =
147 getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
148 if (!IsNoBuiltinCall)
149 return getAllocationDataForFunction(Callee, AllocTy, TLI);
George Burgess IVce044892016-12-27 06:10:50 +0000150 return None;
151}
152
George Burgess IVccae43a2016-12-23 01:18:09 +0000153static Optional<AllocFnsTy> getAllocationSize(const Value *V,
154 const TargetLibraryInfo *TLI) {
George Burgess IVed160242016-12-27 06:32:14 +0000155 bool IsNoBuiltinCall;
156 const Function *Callee =
157 getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
George Burgess IVce044892016-12-27 06:10:50 +0000158 if (!Callee)
159 return None;
160
George Burgess IVccae43a2016-12-23 01:18:09 +0000161 // Prefer to use existing information over allocsize. This will give us an
162 // accurate AllocTy.
George Burgess IVed160242016-12-27 06:32:14 +0000163 if (!IsNoBuiltinCall)
164 if (Optional<AllocFnsTy> Data =
165 getAllocationDataForFunction(Callee, AnyAlloc, TLI))
166 return Data;
George Burgess IVccae43a2016-12-23 01:18:09 +0000167
George Burgess IVce044892016-12-27 06:10:50 +0000168 Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
169 if (Attr == Attribute())
George Burgess IVccae43a2016-12-23 01:18:09 +0000170 return None;
171
George Burgess IVccae43a2016-12-23 01:18:09 +0000172 std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
173
174 AllocFnsTy Result;
175 // Because allocsize only tells us how many bytes are allocated, we're not
176 // really allowed to assume anything, so we use MallocLike.
177 Result.AllocTy = MallocLike;
178 Result.NumParams = Callee->getNumOperands();
179 Result.FstParam = Args.first;
180 Result.SndParam = Args.second.getValueOr(-1);
181 return Result;
182}
183
Nuno Lopes55fff832012-06-21 15:45:28 +0000184static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000185 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Reid Klecknerb5180542017-03-21 16:57:19 +0000186 return CS && CS.paramHasAttr(AttributeList::ReturnIndex, Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000187}
188
189
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000190/// \brief Tests if a value is a call or invoke to a library function that
191/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
192/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000193bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
194 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000195 return getAllocationData(V, AnyAlloc, 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 function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000199/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000200bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
201 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000202 // it's safe to consider realloc as noalias since accessing the original
203 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000204 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000205 hasNoAliasAttr(V, LookThroughBitCast);
206}
207
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000208/// \brief Tests if a value is a call or invoke to a library function that
209/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000210bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
211 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000212 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000213}
214
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000215/// \brief Tests if a value is a call or invoke to a library function that
216/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000217bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
218 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000219 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000220}
221
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000222/// \brief Tests if a value is a call or invoke to a library function that
223/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000224bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
225 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000226 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000227}
228
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000229/// extractMallocCall - Returns the corresponding CallInst if the instruction
230/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
231/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000232const CallInst *llvm::extractMallocCall(const Value *I,
233 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000234 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000235}
236
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000238 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000239 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000240 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000241 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000242
Victor Hernandezf3db9152009-11-07 00:16:28 +0000243 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000244 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000245 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000246 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000247
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000249 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000250 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000251
Gabor Greifad7884a2010-06-23 21:41:47 +0000252 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000253 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000254 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000255 Value *Multiple = nullptr;
Sanjay Patel490193d2016-07-07 16:19:09 +0000256 if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000257 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000258
Craig Topper9f008862014-04-15 04:59:12 +0000259 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000260}
261
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000262/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000263/// The PointerType depends on the number of bitcast uses of the malloc call:
264/// 0: PointerType is the calls' return type.
265/// 1: PointerType is the bitcast's result type.
266/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000267PointerType *llvm::getMallocType(const CallInst *CI,
268 const TargetLibraryInfo *TLI) {
269 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000270
Craig Topper9f008862014-04-15 04:59:12 +0000271 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000272 unsigned NumOfBitCastUses = 0;
273
Victor Hernandez788eaab2009-09-18 19:20:02 +0000274 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000275 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
276 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000277 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
278 MallocType = cast<PointerType>(BCI->getDestTy());
279 NumOfBitCastUses++;
280 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000281
Victor Hernandezf3db9152009-11-07 00:16:28 +0000282 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
283 if (NumOfBitCastUses == 1)
284 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000285
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000286 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000287 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000288 return cast<PointerType>(CI->getType());
289
290 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000291 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000292}
293
Victor Hernandezf3db9152009-11-07 00:16:28 +0000294/// getMallocAllocatedType - Returns the Type allocated by malloc call.
295/// The Type depends on the number of bitcast uses of the malloc call:
296/// 0: PointerType is the malloc calls' return type.
297/// 1: PointerType is the bitcast's result type.
298/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000299Type *llvm::getMallocAllocatedType(const CallInst *CI,
300 const TargetLibraryInfo *TLI) {
301 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000302 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000303}
304
Michael Ilsemand9745242013-03-08 21:03:09 +0000305/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000306/// argument passed to malloc is a multiple of the size of the malloced type,
307/// then return that multiple. For non-array mallocs, the multiple is
308/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000309/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000310Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000311 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000312 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000313 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000314 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000315}
Victor Hernandeze2971492009-10-24 04:23:03 +0000316
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000317
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000318/// extractCallocCall - Returns the corresponding CallInst if the instruction
319/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000320const CallInst *llvm::extractCallocCall(const Value *I,
321 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000322 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000323}
324
Victor Hernandezde5ad422009-10-26 23:43:48 +0000325
Gabor Greif5f5a8642010-06-23 21:51:12 +0000326/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000327const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000328 const CallInst *CI = dyn_cast<CallInst>(I);
Michael Ilseman74ffc272013-03-08 21:15:00 +0000329 if (!CI || isa<IntrinsicInst>(CI))
Craig Topper9f008862014-04-15 04:59:12 +0000330 return nullptr;
Victor Hernandez33188582009-11-03 20:39:35 +0000331 Function *Callee = CI->getCalledFunction();
Richard Smithe78bb122015-01-15 01:00:33 +0000332 if (Callee == nullptr)
Craig Topper9f008862014-04-15 04:59:12 +0000333 return nullptr;
Nick Lewyckyc1f86582011-03-15 07:31:32 +0000334
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000335 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000336 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000337 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000338 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000339
Richard Smith70523c72013-07-21 23:11:42 +0000340 unsigned ExpectedNumParams;
David L. Jonesd21529f2017-01-23 23:16:46 +0000341 if (TLIFn == LibFunc_free ||
342 TLIFn == LibFunc_ZdlPv || // operator delete(void*)
343 TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
344 TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
345 TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
346 TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
347 TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000348 ExpectedNumParams = 1;
David L. Jonesd21529f2017-01-23 23:16:46 +0000349 else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
350 TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
351 TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
352 TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
353 TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
354 TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
355 TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
356 TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
357 TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
358 TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
359 TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
360 TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
361 TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
362 TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000363 ExpectedNumParams = 2;
364 else
Craig Topper9f008862014-04-15 04:59:12 +0000365 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000366
367 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000368 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000369 // attribute will exist.
Chris Lattner229907c2011-07-18 04:54:35 +0000370 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000371 if (!FTy->getReturnType()->isVoidTy())
Craig Topper9f008862014-04-15 04:59:12 +0000372 return nullptr;
Richard Smith70523c72013-07-21 23:11:42 +0000373 if (FTy->getNumParams() != ExpectedNumParams)
Craig Topper9f008862014-04-15 04:59:12 +0000374 return nullptr;
Chris Lattner67733f62011-06-18 21:46:23 +0000375 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Craig Topper9f008862014-04-15 04:59:12 +0000376 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000377
Gabor Greif5f5a8642010-06-23 21:51:12 +0000378 return CI;
Victor Hernandeze2971492009-10-24 04:23:03 +0000379}
Nuno Lopes55fff832012-06-21 15:45:28 +0000380
381
382
383//===----------------------------------------------------------------------===//
384// Utility functions to compute size of objects.
385//
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000386static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
387 if (Data.second.isNegative() || Data.first.ult(Data.second))
388 return APInt(Data.first.getBitWidth(), 0);
389 return Data.first - Data.second;
390}
Nuno Lopes55fff832012-06-21 15:45:28 +0000391
392/// \brief Compute the size of the object pointed by Ptr. Returns true and the
393/// object size in Size if successful, and false otherwise.
394/// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
395/// byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
George Burgess IV56c7e882017-03-21 20:08:59 +0000397 const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
398 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
Nuno Lopes55fff832012-06-21 15:45:28 +0000399 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
400 if (!Visitor.bothKnown(Data))
401 return false;
402
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000403 Size = getSizeWithOverflow(Data).getZExtValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000404 return true;
405}
406
George Burgess IV3f089142016-12-20 23:46:36 +0000407ConstantInt *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
408 const DataLayout &DL,
409 const TargetLibraryInfo *TLI,
410 bool MustSucceed) {
411 assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
412 "ObjectSize must be a call to llvm.objectsize!");
413
414 bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
George Burgess IV56c7e882017-03-21 20:08:59 +0000415 ObjectSizeOpts EvalOptions;
George Burgess IV3f089142016-12-20 23:46:36 +0000416 // Unless we have to fold this to something, try to be as accurate as
417 // possible.
418 if (MustSucceed)
George Burgess IV56c7e882017-03-21 20:08:59 +0000419 EvalOptions.EvalMode =
420 MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
George Burgess IV3f089142016-12-20 23:46:36 +0000421 else
George Burgess IV56c7e882017-03-21 20:08:59 +0000422 EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
423
424 EvalOptions.NullIsUnknownSize =
425 cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
George Burgess IV3f089142016-12-20 23:46:36 +0000426
427 // FIXME: Does it make sense to just return a failure value if the size won't
428 // fit in the output and `!MustSucceed`?
429 uint64_t Size;
430 auto *ResultType = cast<IntegerType>(ObjectSize->getType());
George Burgess IV56c7e882017-03-21 20:08:59 +0000431 if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
George Burgess IV3f089142016-12-20 23:46:36 +0000432 isUIntN(ResultType->getBitWidth(), Size))
433 return ConstantInt::get(ResultType, Size);
434
435 if (!MustSucceed)
436 return nullptr;
437
438 return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
439}
440
Nuno Lopes55fff832012-06-21 15:45:28 +0000441STATISTIC(ObjectVisitorArgument,
442 "Number of arguments with unsolved size and offset");
443STATISTIC(ObjectVisitorLoad,
444 "Number of load instructions with unsolved size and offset");
445
446
447APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000448 if (Options.RoundToAlign && Align)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000449 return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
Nuno Lopes55fff832012-06-21 15:45:28 +0000450 return Size;
451}
452
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000453ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000454 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000455 LLVMContext &Context,
George Burgess IV56c7e882017-03-21 20:08:59 +0000456 ObjectSizeOpts Options)
457 : DL(DL), TLI(TLI), Options(Options) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000458 // Pointer size must be rechecked for each object visited since it could have
459 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000460}
461
462SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000463 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000464 Zero = APInt::getNullValue(IntTyBits);
465
Nuno Lopes55fff832012-06-21 15:45:28 +0000466 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000467 if (Instruction *I = dyn_cast<Instruction>(V)) {
468 // If we have already seen this instruction, bail out. Cycles can happen in
469 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000470 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000471 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000472
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000473 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000474 return visitGEPOperator(*GEP);
475 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000476 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000477 if (Argument *A = dyn_cast<Argument>(V))
478 return visitArgument(*A);
479 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
480 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000481 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
482 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000483 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
484 return visitGlobalVariable(*GV);
485 if (UndefValue *UV = dyn_cast<UndefValue>(V))
486 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000487 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000488 if (CE->getOpcode() == Instruction::IntToPtr)
489 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000490 if (CE->getOpcode() == Instruction::GetElementPtr)
491 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000492 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000493
494 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
495 << '\n');
496 return unknown();
497}
498
499SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
500 if (!I.getAllocatedType()->isSized())
501 return unknown();
502
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000503 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000504 if (!I.isArrayAllocation())
505 return std::make_pair(align(Size, I.getAlignment()), Zero);
506
507 Value *ArraySize = I.getArraySize();
508 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
509 Size *= C->getValue().zextOrSelf(IntTyBits);
510 return std::make_pair(align(Size, I.getAlignment()), Zero);
511 }
512 return unknown();
513}
514
515SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000516 // No interprocedural analysis is done at the moment.
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000517 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000518 ++ObjectVisitorArgument;
519 return unknown();
520 }
521 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000522 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000523 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
524}
525
526SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000527 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000528 if (!FnData)
529 return unknown();
530
Sanjay Patel490193d2016-07-07 16:19:09 +0000531 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000532 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000533 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
534 if (!Size)
535 return unknown();
536
Sanjay Patel490193d2016-07-07 16:19:09 +0000537 // Strndup limits strlen.
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000538 if (FnData->FstParam > 0) {
George Burgess IV278199f2016-04-12 01:05:35 +0000539 ConstantInt *Arg =
540 dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000541 if (!Arg)
542 return unknown();
543
544 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
545 if (Size.ugt(MaxSize))
546 Size = MaxSize + 1;
547 }
548 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000549 }
550
551 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
552 if (!Arg)
553 return unknown();
554
George Burgess IV278199f2016-04-12 01:05:35 +0000555 // When we're compiling N-bit code, and the user uses parameters that are
556 // greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
557 // trouble with APInt size issues. This function handles resizing + overflow
558 // checks for us.
559 auto CheckedZextOrTrunc = [&](APInt &I) {
560 // More bits than we can handle. Checking the bit width isn't necessary, but
561 // it's faster than checking active bits, and should give `false` in the
562 // vast majority of cases.
563 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
564 return false;
565 if (I.getBitWidth() != IntTyBits)
566 I = I.zextOrTrunc(IntTyBits);
567 return true;
568 };
569
570 APInt Size = Arg->getValue();
571 if (!CheckedZextOrTrunc(Size))
572 return unknown();
573
Sanjay Patel490193d2016-07-07 16:19:09 +0000574 // Size is determined by just 1 parameter.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000575 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000576 return std::make_pair(Size, Zero);
577
578 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
579 if (!Arg)
580 return unknown();
581
George Burgess IV278199f2016-04-12 01:05:35 +0000582 APInt NumElems = Arg->getValue();
583 if (!CheckedZextOrTrunc(NumElems))
584 return unknown();
585
586 bool Overflow;
587 Size = Size.umul_ov(NumElems, Overflow);
588 return Overflow ? unknown() : std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000589
590 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000591 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000592 // - strcpy / strncpy
593 // - strcat / strncat
594 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000595 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000596 // - memset
597}
598
599SizeOffsetType
George Burgess IV56c7e882017-03-21 20:08:59 +0000600ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
601 if (Options.NullIsUnknownSize && CPN.getType()->getAddressSpace() == 0)
602 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000603 return std::make_pair(Zero, Zero);
604}
605
606SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000607ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
608 return unknown();
609}
610
611SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000612ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
613 // Easy cases were already folded by previous passes.
614 return unknown();
615}
616
617SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
618 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000619 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000620 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000621 return unknown();
622
Nuno Lopes55fff832012-06-21 15:45:28 +0000623 return std::make_pair(PtrData.first, PtrData.second + Offset);
624}
625
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000626SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000627 if (GA.isInterposable())
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000628 return unknown();
629 return compute(GA.getAliasee());
630}
631
Nuno Lopes55fff832012-06-21 15:45:28 +0000632SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
633 if (!GV.hasDefinitiveInitializer())
634 return unknown();
635
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000636 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000637 return std::make_pair(align(Size, GV.getAlignment()), Zero);
638}
639
640SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
641 // clueless
642 return unknown();
643}
644
645SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
646 ++ObjectVisitorLoad;
647 return unknown();
648}
649
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000650SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
651 // too complex to analyze statically.
652 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000653}
654
655SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
656 SizeOffsetType TrueSide = compute(I.getTrueValue());
657 SizeOffsetType FalseSide = compute(I.getFalseValue());
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000658 if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
659 if (TrueSide == FalseSide) {
660 return TrueSide;
661 }
662
663 APInt TrueResult = getSizeWithOverflow(TrueSide);
664 APInt FalseResult = getSizeWithOverflow(FalseSide);
665
666 if (TrueResult == FalseResult) {
667 return TrueSide;
668 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000669 if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000670 if (TrueResult.slt(FalseResult))
671 return TrueSide;
672 return FalseSide;
673 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000674 if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000675 if (TrueResult.sgt(FalseResult))
676 return TrueSide;
677 return FalseSide;
678 }
679 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000680 return unknown();
681}
682
683SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
684 return std::make_pair(Zero, Zero);
685}
686
687SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
688 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
689 return unknown();
690}
691
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000692ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
693 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
694 bool RoundToAlign)
695 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
696 RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000697 // IntTy and Zero must be set for each compute() since the address space may
698 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000699}
700
701SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000702 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000703 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000704 Zero = ConstantInt::get(IntTy, 0);
705
Nuno Lopes55fff832012-06-21 15:45:28 +0000706 SizeOffsetEvalType Result = compute_(V);
707
708 if (!bothKnown(Result)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000709 // Erase everything that was computed in this iteration from the cache, so
Nuno Lopes55fff832012-06-21 15:45:28 +0000710 // that no dangling references are left behind. We could be a bit smarter if
711 // we kept a dependency graph. It's probably not worth the complexity.
Benjamin Krameraa209152016-06-26 17:27:42 +0000712 for (const Value *SeenVal : SeenVals) {
713 CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
Nuno Lopes55fff832012-06-21 15:45:28 +0000714 // non-computable results can be safely cached
715 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
716 CacheMap.erase(CacheIt);
717 }
718 }
719
720 SeenVals.clear();
721 return Result;
722}
723
724SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000725 ObjectSizeOpts ObjSizeOptions;
726 ObjSizeOptions.RoundToAlign = RoundToAlign;
727
728 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
Nuno Lopes55fff832012-06-21 15:45:28 +0000729 SizeOffsetType Const = Visitor.compute(V);
730 if (Visitor.bothKnown(Const))
731 return std::make_pair(ConstantInt::get(Context, Const.first),
732 ConstantInt::get(Context, Const.second));
733
734 V = V->stripPointerCasts();
735
Sanjay Patel490193d2016-07-07 16:19:09 +0000736 // Check cache.
Nuno Lopes55fff832012-06-21 15:45:28 +0000737 CacheMapTy::iterator CacheIt = CacheMap.find(V);
738 if (CacheIt != CacheMap.end())
739 return CacheIt->second;
740
Sanjay Patel490193d2016-07-07 16:19:09 +0000741 // Always generate code immediately before the instruction being
742 // processed, so that the generated code dominates the same BBs.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000743 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000744 if (Instruction *I = dyn_cast<Instruction>(V))
745 Builder.SetInsertPoint(I);
746
Sanjay Patel490193d2016-07-07 16:19:09 +0000747 // Now compute the size and offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000748 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000749
750 // Record the pointers that were handled in this run, so that they can be
751 // cleaned later if something fails. We also use this set to break cycles that
752 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000753 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000754 Result = unknown();
755 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000756 Result = visitGEPOperator(*GEP);
757 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
758 Result = visit(*I);
759 } else if (isa<Argument>(V) ||
760 (isa<ConstantExpr>(V) &&
761 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000762 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000763 isa<GlobalVariable>(V)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000764 // Ignore values where we cannot do more than ObjectSizeVisitor.
Nuno Lopes55fff832012-06-21 15:45:28 +0000765 Result = unknown();
766 } else {
767 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
768 << *V << '\n');
769 Result = unknown();
770 }
771
Nuno Lopes55fff832012-06-21 15:45:28 +0000772 // Don't reuse CacheIt since it may be invalid at this point.
773 CacheMap[V] = Result;
774 return Result;
775}
776
777SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
778 if (!I.getAllocatedType()->isSized())
779 return unknown();
780
781 // must be a VLA
782 assert(I.isArrayAllocation());
783 Value *ArraySize = I.getArraySize();
784 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000785 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000786 Size = Builder.CreateMul(Size, ArraySize);
787 return std::make_pair(Size, Zero);
788}
789
790SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000791 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000792 if (!FnData)
793 return unknown();
794
Sanjay Patel490193d2016-07-07 16:19:09 +0000795 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000796 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000797 // TODO
798 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000799 }
800
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000801 Value *FirstArg = CS.getArgument(FnData->FstParam);
802 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000803 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000804 return std::make_pair(FirstArg, Zero);
805
806 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000807 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000808 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
809 return std::make_pair(Size, Zero);
810
811 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000812 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000813 // - strcpy / strncpy
814 // - strcat / strncat
815 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000816 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000817 // - memset
818}
819
820SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000821ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
822 return unknown();
823}
824
825SizeOffsetEvalType
826ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
827 return unknown();
828}
829
830SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000831ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
832 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
833 if (!bothKnown(PtrData))
834 return unknown();
835
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000836 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000837 Offset = Builder.CreateAdd(PtrData.second, Offset);
838 return std::make_pair(PtrData.first, Offset);
839}
840
841SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
842 // clueless
843 return unknown();
844}
845
846SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
847 return unknown();
848}
849
850SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000851 // Create 2 PHIs: one for size and another for offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000852 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
853 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
854
Sanjay Patel490193d2016-07-07 16:19:09 +0000855 // Insert right away in the cache to handle recursive PHIs.
Nuno Lopes55fff832012-06-21 15:45:28 +0000856 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
857
Sanjay Patel490193d2016-07-07 16:19:09 +0000858 // Compute offset/size for each PHI incoming pointer.
Nuno Lopes55fff832012-06-21 15:45:28 +0000859 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000860 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000861 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
862
863 if (!bothKnown(EdgeData)) {
864 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
865 OffsetPHI->eraseFromParent();
866 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
867 SizePHI->eraseFromParent();
868 return unknown();
869 }
870 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
871 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
872 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000873
874 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
875 if ((Tmp = SizePHI->hasConstantValue())) {
876 Size = Tmp;
877 SizePHI->replaceAllUsesWith(Size);
878 SizePHI->eraseFromParent();
879 }
880 if ((Tmp = OffsetPHI->hasConstantValue())) {
881 Offset = Tmp;
882 OffsetPHI->replaceAllUsesWith(Offset);
883 OffsetPHI->eraseFromParent();
884 }
885 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000886}
887
888SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
889 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
890 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
891
892 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
893 return unknown();
894 if (TrueSide == FalseSide)
895 return TrueSide;
896
897 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
898 FalseSide.first);
899 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
900 FalseSide.second);
901 return std::make_pair(Size, Offset);
902}
903
904SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
905 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
906 return unknown();
907}