blob: f88d54b21e1e36dc50615fdbe47bfdd7980c74f2 [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,
Craig Topper09bb7602017-04-18 21:43:46 +000040 MallocOrCallocLike = MallocLike | CallocLike,
Benjamin Kramer2939dd32013-09-24 17:34:29 +000041 AllocLike = MallocLike | CallocLike | StrDupLike,
Benjamin Kramer4d4df042013-09-24 17:15:14 +000042 AnyAlloc = AllocLike | ReallocLike
Nuno Lopes55fff832012-06-21 15:45:28 +000043};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000044
Nuno Lopes55fff832012-06-21 15:45:28 +000045struct AllocFnsTy {
Nuno Lopes55fff832012-06-21 15:45:28 +000046 AllocType AllocTy;
George Burgess IV278199f2016-04-12 01:05:35 +000047 unsigned NumParams;
Nuno Lopes55fff832012-06-21 15:45:28 +000048 // First and Second size parameters (or -1 if unused)
George Burgess IV278199f2016-04-12 01:05:35 +000049 int FstParam, SndParam;
Nuno Lopes55fff832012-06-21 15:45:28 +000050};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000051
Nuno Lopes181d67e2012-06-28 16:34:03 +000052// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
53// know which functions are nounwind, noalias, nocapture parameters, etc.
David L. Jonesd21529f2017-01-23 23:16:46 +000054static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
55 {LibFunc_malloc, {MallocLike, 1, 0, -1}},
56 {LibFunc_valloc, {MallocLike, 1, 0, -1}},
57 {LibFunc_Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
58 {LibFunc_ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
59 {LibFunc_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
60 {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
61 {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
62 {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
63 {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
64 {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
65 {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
66 {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
67 {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
68 {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
69 {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
70 {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
71 {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
72 {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
73 {LibFunc_calloc, {CallocLike, 2, 0, 1}},
74 {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
75 {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
76 {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
77 {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
Benjamin Kramer01df8172013-09-24 17:49:08 +000078 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes55fff832012-06-21 15:45:28 +000079};
80
Craig Toppereae6db02017-04-18 20:17:23 +000081static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
82 bool &IsNoBuiltin) {
George Burgess IVce044892016-12-27 06:10:50 +000083 // Don't care about intrinsics in this case.
84 if (isa<IntrinsicInst>(V))
85 return nullptr;
86
Nuno Lopes55fff832012-06-21 15:45:28 +000087 if (LookThroughBitCast)
88 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +000089
Craig Toppereae6db02017-04-18 20:17:23 +000090 ImmutableCallSite CS(V);
Nuno Lopes15dbcb42012-06-22 15:50:53 +000091 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +000092 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000093
George Burgess IVed160242016-12-27 06:32:14 +000094 IsNoBuiltin = CS.isNoBuiltin();
Richard Smithe04f0d32013-05-16 04:12:04 +000095
Craig Toppereae6db02017-04-18 20:17:23 +000096 const Function *Callee = CS.getCalledFunction();
Nuno Lopes55fff832012-06-21 15:45:28 +000097 if (!Callee || !Callee->isDeclaration())
Craig Topper9f008862014-04-15 04:59:12 +000098 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +000099 return Callee;
100}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000101
George Burgess IV278199f2016-04-12 01:05:35 +0000102/// Returns the allocation data for the given value if it's either a call to a
103/// known allocation function, or a call to a function with the allocsize
104/// attribute.
George Burgess IVce044892016-12-27 06:10:50 +0000105static Optional<AllocFnsTy>
106getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
107 const TargetLibraryInfo *TLI) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000108 // Make sure that the function is available.
109 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000110 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000111 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
George Burgess IV278199f2016-04-12 01:05:35 +0000112 return None;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000113
George Burgess IV45a540f2016-12-20 18:46:27 +0000114 const auto *Iter = find_if(
David L. Jonesd21529f2017-01-23 23:16:46 +0000115 AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
George Burgess IV45a540f2016-12-20 18:46:27 +0000116 return P.first == TLIFn;
117 });
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000118
George Burgess IV278199f2016-04-12 01:05:35 +0000119 if (Iter == std::end(AllocationFnData))
120 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000121
George Burgess IV278199f2016-04-12 01:05:35 +0000122 const AllocFnsTy *FnData = &Iter->second;
Benjamin Kramer2939dd32013-09-24 17:34:29 +0000123 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
George Burgess IV278199f2016-04-12 01:05:35 +0000124 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000125
126 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000127 int FstParam = FnData->FstParam;
128 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000129 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000130
131 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
132 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000133 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000134 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
135 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000136 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000137 FTy->getParamType(SndParam)->isIntegerTy(32) ||
138 FTy->getParamType(SndParam)->isIntegerTy(64)))
George Burgess IV278199f2016-04-12 01:05:35 +0000139 return *FnData;
140 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000141}
142
George Burgess IVce044892016-12-27 06:10:50 +0000143static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
144 const TargetLibraryInfo *TLI,
145 bool LookThroughBitCast = false) {
George Burgess IVed160242016-12-27 06:32:14 +0000146 bool IsNoBuiltinCall;
147 if (const Function *Callee =
148 getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
149 if (!IsNoBuiltinCall)
150 return getAllocationDataForFunction(Callee, AllocTy, TLI);
George Burgess IVce044892016-12-27 06:10:50 +0000151 return None;
152}
153
George Burgess IVccae43a2016-12-23 01:18:09 +0000154static Optional<AllocFnsTy> getAllocationSize(const Value *V,
155 const TargetLibraryInfo *TLI) {
George Burgess IVed160242016-12-27 06:32:14 +0000156 bool IsNoBuiltinCall;
157 const Function *Callee =
158 getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
George Burgess IVce044892016-12-27 06:10:50 +0000159 if (!Callee)
160 return None;
161
George Burgess IVccae43a2016-12-23 01:18:09 +0000162 // Prefer to use existing information over allocsize. This will give us an
163 // accurate AllocTy.
George Burgess IVed160242016-12-27 06:32:14 +0000164 if (!IsNoBuiltinCall)
165 if (Optional<AllocFnsTy> Data =
166 getAllocationDataForFunction(Callee, AnyAlloc, TLI))
167 return Data;
George Burgess IVccae43a2016-12-23 01:18:09 +0000168
George Burgess IVce044892016-12-27 06:10:50 +0000169 Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
170 if (Attr == Attribute())
George Burgess IVccae43a2016-12-23 01:18:09 +0000171 return None;
172
George Burgess IVccae43a2016-12-23 01:18:09 +0000173 std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
174
175 AllocFnsTy Result;
176 // Because allocsize only tells us how many bytes are allocated, we're not
177 // really allowed to assume anything, so we use MallocLike.
178 Result.AllocTy = MallocLike;
179 Result.NumParams = Callee->getNumOperands();
180 Result.FstParam = Args.first;
181 Result.SndParam = Args.second.getValueOr(-1);
182 return Result;
183}
184
Nuno Lopes55fff832012-06-21 15:45:28 +0000185static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000186 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000187 return CS && CS.hasRetAttr(Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000188}
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 or reallocates memory (either malloc, calloc, realloc, or strdup
193/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000194bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
195 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000196 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000197}
198
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000199/// \brief Tests if a value is a call or invoke to a function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000200/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000201bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
202 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000203 // it's safe to consider realloc as noalias since accessing the original
204 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000205 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000206 hasNoAliasAttr(V, LookThroughBitCast);
207}
208
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000209/// \brief Tests if a value is a call or invoke to a library function that
210/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000211bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
212 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000213 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000214}
215
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000216/// \brief Tests if a value is a call or invoke to a library function that
217/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000218bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
219 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000220 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000221}
222
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000223/// \brief Tests if a value is a call or invoke to a library function that
Craig Topper09bb7602017-04-18 21:43:46 +0000224/// allocates memory similiar to malloc or calloc.
225bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
226 bool LookThroughBitCast) {
227 return getAllocationData(V, MallocOrCallocLike, TLI,
228 LookThroughBitCast).hasValue();
229}
230
231/// \brief Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000232/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000233bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
234 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000235 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000236}
237
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000238/// extractMallocCall - Returns the corresponding CallInst if the instruction
239/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
240/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000241const CallInst *llvm::extractMallocCall(const Value *I,
242 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000243 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000244}
245
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000246static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000247 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000248 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000249 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000250 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000251
Victor Hernandezf3db9152009-11-07 00:16:28 +0000252 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000253 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000254 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000255 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000256
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000257 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000258 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000259 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000260
Gabor Greifad7884a2010-06-23 21:41:47 +0000261 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000262 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000263 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000264 Value *Multiple = nullptr;
Sanjay Patel490193d2016-07-07 16:19:09 +0000265 if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000266 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000267
Craig Topper9f008862014-04-15 04:59:12 +0000268 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000269}
270
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000271/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000272/// The PointerType depends on the number of bitcast uses of the malloc call:
273/// 0: PointerType is the calls' return type.
274/// 1: PointerType is the bitcast's result type.
275/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000276PointerType *llvm::getMallocType(const CallInst *CI,
277 const TargetLibraryInfo *TLI) {
278 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000279
Craig Topper9f008862014-04-15 04:59:12 +0000280 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000281 unsigned NumOfBitCastUses = 0;
282
Victor Hernandez788eaab2009-09-18 19:20:02 +0000283 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000284 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
285 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000286 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
287 MallocType = cast<PointerType>(BCI->getDestTy());
288 NumOfBitCastUses++;
289 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000290
Victor Hernandezf3db9152009-11-07 00:16:28 +0000291 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
292 if (NumOfBitCastUses == 1)
293 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000294
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000295 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000296 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000297 return cast<PointerType>(CI->getType());
298
299 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000300 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000301}
302
Victor Hernandezf3db9152009-11-07 00:16:28 +0000303/// getMallocAllocatedType - Returns the Type allocated by malloc call.
304/// The Type depends on the number of bitcast uses of the malloc call:
305/// 0: PointerType is the malloc calls' return type.
306/// 1: PointerType is the bitcast's result type.
307/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000308Type *llvm::getMallocAllocatedType(const CallInst *CI,
309 const TargetLibraryInfo *TLI) {
310 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000311 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000312}
313
Michael Ilsemand9745242013-03-08 21:03:09 +0000314/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000315/// argument passed to malloc is a multiple of the size of the malloced type,
316/// then return that multiple. For non-array mallocs, the multiple is
317/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000318/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000320 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000321 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000322 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000323 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000324}
Victor Hernandeze2971492009-10-24 04:23:03 +0000325
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000326
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000327/// extractCallocCall - Returns the corresponding CallInst if the instruction
328/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000329const CallInst *llvm::extractCallocCall(const Value *I,
330 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000331 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000332}
333
Victor Hernandezde5ad422009-10-26 23:43:48 +0000334
Gabor Greif5f5a8642010-06-23 21:51:12 +0000335/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000336const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000337 const CallInst *CI = dyn_cast<CallInst>(I);
Michael Ilseman74ffc272013-03-08 21:15:00 +0000338 if (!CI || isa<IntrinsicInst>(CI))
Craig Topper9f008862014-04-15 04:59:12 +0000339 return nullptr;
Victor Hernandez33188582009-11-03 20:39:35 +0000340 Function *Callee = CI->getCalledFunction();
Richard Smithe78bb122015-01-15 01:00:33 +0000341 if (Callee == nullptr)
Craig Topper9f008862014-04-15 04:59:12 +0000342 return nullptr;
Nick Lewyckyc1f86582011-03-15 07:31:32 +0000343
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000344 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000345 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000346 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000347 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000348
Richard Smith70523c72013-07-21 23:11:42 +0000349 unsigned ExpectedNumParams;
David L. Jonesd21529f2017-01-23 23:16:46 +0000350 if (TLIFn == LibFunc_free ||
351 TLIFn == LibFunc_ZdlPv || // operator delete(void*)
352 TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
353 TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
354 TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
355 TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
356 TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000357 ExpectedNumParams = 1;
David L. Jonesd21529f2017-01-23 23:16:46 +0000358 else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
359 TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
360 TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
361 TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
362 TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
363 TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
364 TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
365 TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
366 TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
367 TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
368 TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
369 TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
370 TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
371 TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000372 ExpectedNumParams = 2;
373 else
Craig Topper9f008862014-04-15 04:59:12 +0000374 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000375
376 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000377 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000378 // attribute will exist.
Chris Lattner229907c2011-07-18 04:54:35 +0000379 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000380 if (!FTy->getReturnType()->isVoidTy())
Craig Topper9f008862014-04-15 04:59:12 +0000381 return nullptr;
Richard Smith70523c72013-07-21 23:11:42 +0000382 if (FTy->getNumParams() != ExpectedNumParams)
Craig Topper9f008862014-04-15 04:59:12 +0000383 return nullptr;
Chris Lattner67733f62011-06-18 21:46:23 +0000384 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Craig Topper9f008862014-04-15 04:59:12 +0000385 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000386
Gabor Greif5f5a8642010-06-23 21:51:12 +0000387 return CI;
Victor Hernandeze2971492009-10-24 04:23:03 +0000388}
Nuno Lopes55fff832012-06-21 15:45:28 +0000389
390
391
392//===----------------------------------------------------------------------===//
393// Utility functions to compute size of objects.
394//
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000395static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
396 if (Data.second.isNegative() || Data.first.ult(Data.second))
397 return APInt(Data.first.getBitWidth(), 0);
398 return Data.first - Data.second;
399}
Nuno Lopes55fff832012-06-21 15:45:28 +0000400
401/// \brief Compute the size of the object pointed by Ptr. Returns true and the
402/// object size in Size if successful, and false otherwise.
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +0000403/// If RoundToAlign is true, then Size is rounded up to the alignment of
404/// allocas, byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
George Burgess IV56c7e882017-03-21 20:08:59 +0000406 const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
407 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
Nuno Lopes55fff832012-06-21 15:45:28 +0000408 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
409 if (!Visitor.bothKnown(Data))
410 return false;
411
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000412 Size = getSizeWithOverflow(Data).getZExtValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000413 return true;
414}
415
George Burgess IV3f089142016-12-20 23:46:36 +0000416ConstantInt *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
417 const DataLayout &DL,
418 const TargetLibraryInfo *TLI,
419 bool MustSucceed) {
420 assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
421 "ObjectSize must be a call to llvm.objectsize!");
422
423 bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
George Burgess IV56c7e882017-03-21 20:08:59 +0000424 ObjectSizeOpts EvalOptions;
George Burgess IV3f089142016-12-20 23:46:36 +0000425 // Unless we have to fold this to something, try to be as accurate as
426 // possible.
427 if (MustSucceed)
George Burgess IV56c7e882017-03-21 20:08:59 +0000428 EvalOptions.EvalMode =
429 MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
George Burgess IV3f089142016-12-20 23:46:36 +0000430 else
George Burgess IV56c7e882017-03-21 20:08:59 +0000431 EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
432
433 EvalOptions.NullIsUnknownSize =
434 cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
George Burgess IV3f089142016-12-20 23:46:36 +0000435
436 // FIXME: Does it make sense to just return a failure value if the size won't
437 // fit in the output and `!MustSucceed`?
438 uint64_t Size;
439 auto *ResultType = cast<IntegerType>(ObjectSize->getType());
George Burgess IV56c7e882017-03-21 20:08:59 +0000440 if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
George Burgess IV3f089142016-12-20 23:46:36 +0000441 isUIntN(ResultType->getBitWidth(), Size))
442 return ConstantInt::get(ResultType, Size);
443
444 if (!MustSucceed)
445 return nullptr;
446
447 return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
448}
449
Nuno Lopes55fff832012-06-21 15:45:28 +0000450STATISTIC(ObjectVisitorArgument,
451 "Number of arguments with unsolved size and offset");
452STATISTIC(ObjectVisitorLoad,
453 "Number of load instructions with unsolved size and offset");
454
455
456APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000457 if (Options.RoundToAlign && Align)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000458 return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
Nuno Lopes55fff832012-06-21 15:45:28 +0000459 return Size;
460}
461
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000462ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000463 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000464 LLVMContext &Context,
George Burgess IV56c7e882017-03-21 20:08:59 +0000465 ObjectSizeOpts Options)
466 : DL(DL), TLI(TLI), Options(Options) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000467 // Pointer size must be rechecked for each object visited since it could have
468 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000469}
470
471SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000472 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000473 Zero = APInt::getNullValue(IntTyBits);
474
Nuno Lopes55fff832012-06-21 15:45:28 +0000475 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000476 if (Instruction *I = dyn_cast<Instruction>(V)) {
477 // If we have already seen this instruction, bail out. Cycles can happen in
478 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000479 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000480 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000481
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000482 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000483 return visitGEPOperator(*GEP);
484 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000485 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000486 if (Argument *A = dyn_cast<Argument>(V))
487 return visitArgument(*A);
488 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
489 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000490 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
491 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000492 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
493 return visitGlobalVariable(*GV);
494 if (UndefValue *UV = dyn_cast<UndefValue>(V))
495 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000497 if (CE->getOpcode() == Instruction::IntToPtr)
498 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000499 if (CE->getOpcode() == Instruction::GetElementPtr)
500 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000501 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000502
503 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
504 << '\n');
505 return unknown();
506}
507
508SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
509 if (!I.getAllocatedType()->isSized())
510 return unknown();
511
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000512 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000513 if (!I.isArrayAllocation())
514 return std::make_pair(align(Size, I.getAlignment()), Zero);
515
516 Value *ArraySize = I.getArraySize();
517 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
518 Size *= C->getValue().zextOrSelf(IntTyBits);
519 return std::make_pair(align(Size, I.getAlignment()), Zero);
520 }
521 return unknown();
522}
523
524SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000525 // No interprocedural analysis is done at the moment.
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000526 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000527 ++ObjectVisitorArgument;
528 return unknown();
529 }
530 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000531 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000532 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
533}
534
535SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000536 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000537 if (!FnData)
538 return unknown();
539
Sanjay Patel490193d2016-07-07 16:19:09 +0000540 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000541 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000542 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
543 if (!Size)
544 return unknown();
545
Sanjay Patel490193d2016-07-07 16:19:09 +0000546 // Strndup limits strlen.
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000547 if (FnData->FstParam > 0) {
George Burgess IV278199f2016-04-12 01:05:35 +0000548 ConstantInt *Arg =
549 dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000550 if (!Arg)
551 return unknown();
552
553 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
554 if (Size.ugt(MaxSize))
555 Size = MaxSize + 1;
556 }
557 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000558 }
559
560 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
561 if (!Arg)
562 return unknown();
563
George Burgess IV278199f2016-04-12 01:05:35 +0000564 // When we're compiling N-bit code, and the user uses parameters that are
565 // greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
566 // trouble with APInt size issues. This function handles resizing + overflow
567 // checks for us.
568 auto CheckedZextOrTrunc = [&](APInt &I) {
569 // More bits than we can handle. Checking the bit width isn't necessary, but
570 // it's faster than checking active bits, and should give `false` in the
571 // vast majority of cases.
572 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
573 return false;
574 if (I.getBitWidth() != IntTyBits)
575 I = I.zextOrTrunc(IntTyBits);
576 return true;
577 };
578
579 APInt Size = Arg->getValue();
580 if (!CheckedZextOrTrunc(Size))
581 return unknown();
582
Sanjay Patel490193d2016-07-07 16:19:09 +0000583 // Size is determined by just 1 parameter.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000584 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000585 return std::make_pair(Size, Zero);
586
587 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
588 if (!Arg)
589 return unknown();
590
George Burgess IV278199f2016-04-12 01:05:35 +0000591 APInt NumElems = Arg->getValue();
592 if (!CheckedZextOrTrunc(NumElems))
593 return unknown();
594
595 bool Overflow;
596 Size = Size.umul_ov(NumElems, Overflow);
597 return Overflow ? unknown() : std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000598
599 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000600 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000601 // - strcpy / strncpy
602 // - strcat / strncat
603 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000604 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000605 // - memset
606}
607
608SizeOffsetType
George Burgess IV56c7e882017-03-21 20:08:59 +0000609ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
610 if (Options.NullIsUnknownSize && CPN.getType()->getAddressSpace() == 0)
611 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000612 return std::make_pair(Zero, Zero);
613}
614
615SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000616ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
617 return unknown();
618}
619
620SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000621ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
622 // Easy cases were already folded by previous passes.
623 return unknown();
624}
625
626SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
627 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000628 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000629 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000630 return unknown();
631
Nuno Lopes55fff832012-06-21 15:45:28 +0000632 return std::make_pair(PtrData.first, PtrData.second + Offset);
633}
634
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000635SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000636 if (GA.isInterposable())
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000637 return unknown();
638 return compute(GA.getAliasee());
639}
640
Nuno Lopes55fff832012-06-21 15:45:28 +0000641SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
642 if (!GV.hasDefinitiveInitializer())
643 return unknown();
644
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000646 return std::make_pair(align(Size, GV.getAlignment()), Zero);
647}
648
649SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
650 // clueless
651 return unknown();
652}
653
654SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
655 ++ObjectVisitorLoad;
656 return unknown();
657}
658
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000659SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
660 // too complex to analyze statically.
661 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000662}
663
664SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
665 SizeOffsetType TrueSide = compute(I.getTrueValue());
666 SizeOffsetType FalseSide = compute(I.getFalseValue());
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000667 if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
668 if (TrueSide == FalseSide) {
669 return TrueSide;
670 }
671
672 APInt TrueResult = getSizeWithOverflow(TrueSide);
673 APInt FalseResult = getSizeWithOverflow(FalseSide);
674
675 if (TrueResult == FalseResult) {
676 return TrueSide;
677 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000678 if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000679 if (TrueResult.slt(FalseResult))
680 return TrueSide;
681 return FalseSide;
682 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000683 if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000684 if (TrueResult.sgt(FalseResult))
685 return TrueSide;
686 return FalseSide;
687 }
688 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000689 return unknown();
690}
691
692SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
693 return std::make_pair(Zero, Zero);
694}
695
696SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
697 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
698 return unknown();
699}
700
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000701ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
702 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
703 bool RoundToAlign)
704 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
705 RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000706 // IntTy and Zero must be set for each compute() since the address space may
707 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000708}
709
710SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000711 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000712 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000713 Zero = ConstantInt::get(IntTy, 0);
714
Nuno Lopes55fff832012-06-21 15:45:28 +0000715 SizeOffsetEvalType Result = compute_(V);
716
717 if (!bothKnown(Result)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000718 // Erase everything that was computed in this iteration from the cache, so
Nuno Lopes55fff832012-06-21 15:45:28 +0000719 // that no dangling references are left behind. We could be a bit smarter if
720 // we kept a dependency graph. It's probably not worth the complexity.
Benjamin Krameraa209152016-06-26 17:27:42 +0000721 for (const Value *SeenVal : SeenVals) {
722 CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
Nuno Lopes55fff832012-06-21 15:45:28 +0000723 // non-computable results can be safely cached
724 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
725 CacheMap.erase(CacheIt);
726 }
727 }
728
729 SeenVals.clear();
730 return Result;
731}
732
733SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000734 ObjectSizeOpts ObjSizeOptions;
735 ObjSizeOptions.RoundToAlign = RoundToAlign;
736
737 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
Nuno Lopes55fff832012-06-21 15:45:28 +0000738 SizeOffsetType Const = Visitor.compute(V);
739 if (Visitor.bothKnown(Const))
740 return std::make_pair(ConstantInt::get(Context, Const.first),
741 ConstantInt::get(Context, Const.second));
742
743 V = V->stripPointerCasts();
744
Sanjay Patel490193d2016-07-07 16:19:09 +0000745 // Check cache.
Nuno Lopes55fff832012-06-21 15:45:28 +0000746 CacheMapTy::iterator CacheIt = CacheMap.find(V);
747 if (CacheIt != CacheMap.end())
748 return CacheIt->second;
749
Sanjay Patel490193d2016-07-07 16:19:09 +0000750 // Always generate code immediately before the instruction being
751 // processed, so that the generated code dominates the same BBs.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000752 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000753 if (Instruction *I = dyn_cast<Instruction>(V))
754 Builder.SetInsertPoint(I);
755
Sanjay Patel490193d2016-07-07 16:19:09 +0000756 // Now compute the size and offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000757 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000758
759 // Record the pointers that were handled in this run, so that they can be
760 // cleaned later if something fails. We also use this set to break cycles that
761 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000762 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000763 Result = unknown();
764 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000765 Result = visitGEPOperator(*GEP);
766 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
767 Result = visit(*I);
768 } else if (isa<Argument>(V) ||
769 (isa<ConstantExpr>(V) &&
770 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000771 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000772 isa<GlobalVariable>(V)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000773 // Ignore values where we cannot do more than ObjectSizeVisitor.
Nuno Lopes55fff832012-06-21 15:45:28 +0000774 Result = unknown();
775 } else {
776 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
777 << *V << '\n');
778 Result = unknown();
779 }
780
Nuno Lopes55fff832012-06-21 15:45:28 +0000781 // Don't reuse CacheIt since it may be invalid at this point.
782 CacheMap[V] = Result;
783 return Result;
784}
785
786SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
787 if (!I.getAllocatedType()->isSized())
788 return unknown();
789
790 // must be a VLA
791 assert(I.isArrayAllocation());
792 Value *ArraySize = I.getArraySize();
793 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000794 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000795 Size = Builder.CreateMul(Size, ArraySize);
796 return std::make_pair(Size, Zero);
797}
798
799SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000800 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000801 if (!FnData)
802 return unknown();
803
Sanjay Patel490193d2016-07-07 16:19:09 +0000804 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000805 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000806 // TODO
807 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000808 }
809
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000810 Value *FirstArg = CS.getArgument(FnData->FstParam);
811 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000812 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000813 return std::make_pair(FirstArg, Zero);
814
815 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000816 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000817 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
818 return std::make_pair(Size, Zero);
819
820 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000821 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000822 // - strcpy / strncpy
823 // - strcat / strncat
824 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000825 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000826 // - memset
827}
828
829SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000830ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
831 return unknown();
832}
833
834SizeOffsetEvalType
835ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
836 return unknown();
837}
838
839SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000840ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
841 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
842 if (!bothKnown(PtrData))
843 return unknown();
844
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000845 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000846 Offset = Builder.CreateAdd(PtrData.second, Offset);
847 return std::make_pair(PtrData.first, Offset);
848}
849
850SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
851 // clueless
852 return unknown();
853}
854
855SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
856 return unknown();
857}
858
859SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000860 // Create 2 PHIs: one for size and another for offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000861 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
862 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
863
Sanjay Patel490193d2016-07-07 16:19:09 +0000864 // Insert right away in the cache to handle recursive PHIs.
Nuno Lopes55fff832012-06-21 15:45:28 +0000865 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
866
Sanjay Patel490193d2016-07-07 16:19:09 +0000867 // Compute offset/size for each PHI incoming pointer.
Nuno Lopes55fff832012-06-21 15:45:28 +0000868 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000869 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000870 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
871
872 if (!bothKnown(EdgeData)) {
873 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
874 OffsetPHI->eraseFromParent();
875 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
876 SizePHI->eraseFromParent();
877 return unknown();
878 }
879 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
880 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
881 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000882
883 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
884 if ((Tmp = SizePHI->hasConstantValue())) {
885 Size = Tmp;
886 SizePHI->replaceAllUsesWith(Size);
887 SizePHI->eraseFromParent();
888 }
889 if ((Tmp = OffsetPHI->hasConstantValue())) {
890 Offset = Tmp;
891 OffsetPHI->replaceAllUsesWith(Offset);
892 OffsetPHI->eraseFromParent();
893 }
894 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000895}
896
897SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
898 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
899 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
900
901 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
902 return unknown();
903 if (TrueSide == FalseSide)
904 return TrueSide;
905
906 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
907 FalseSide.first);
908 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
909 FalseSide.second);
910 return std::make_pair(Size, Offset);
911}
912
913SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
914 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
915 return unknown();
916}