blob: 186fda18886e138b8c43f4f9851aa677270331df [file] [log] [blame]
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +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"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000021#include "llvm/ADT/StringRef.h"
22#include "llvm/Analysis/TargetFolder.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000024#include "llvm/Analysis/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000026#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
28#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/DataLayout.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000030#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/GlobalVariable.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000034#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Operator.h"
38#include "llvm/IR/Type.h"
39#include "llvm/IR/Value.h"
40#include "llvm/Support/Casting.h"
Nuno Lopes55fff832012-06-21 15:45:28 +000041#include "llvm/Support/Debug.h"
42#include "llvm/Support/MathExtras.h"
43#include "llvm/Support/raw_ostream.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000044#include <cassert>
45#include <cstdint>
46#include <iterator>
47#include <utility>
48
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000049using namespace llvm;
50
Chandler Carruthf1221bd2014-04-22 02:48:03 +000051#define DEBUG_TYPE "memory-builtins"
52
George Burgess IV2ae15e02015-11-17 19:48:06 +000053enum AllocType : uint8_t {
Benjamin Kramer2939dd32013-09-24 17:34:29 +000054 OpNewLike = 1<<0, // allocates; never returns null
55 MallocLike = 1<<1 | OpNewLike, // allocates; may return null
56 CallocLike = 1<<2, // allocates + bzero
57 ReallocLike = 1<<3, // reallocates
58 StrDupLike = 1<<4,
Craig Topper09bb7602017-04-18 21:43:46 +000059 MallocOrCallocLike = MallocLike | CallocLike,
Benjamin Kramer2939dd32013-09-24 17:34:29 +000060 AllocLike = MallocLike | CallocLike | StrDupLike,
Benjamin Kramer4d4df042013-09-24 17:15:14 +000061 AnyAlloc = AllocLike | ReallocLike
Nuno Lopes55fff832012-06-21 15:45:28 +000062};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000063
Nuno Lopes55fff832012-06-21 15:45:28 +000064struct AllocFnsTy {
Nuno Lopes55fff832012-06-21 15:45:28 +000065 AllocType AllocTy;
George Burgess IV278199f2016-04-12 01:05:35 +000066 unsigned NumParams;
Nuno Lopes55fff832012-06-21 15:45:28 +000067 // First and Second size parameters (or -1 if unused)
George Burgess IV278199f2016-04-12 01:05:35 +000068 int FstParam, SndParam;
Nuno Lopes55fff832012-06-21 15:45:28 +000069};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000070
Nuno Lopes181d67e2012-06-28 16:34:03 +000071// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
72// know which functions are nounwind, noalias, nocapture parameters, etc.
David L. Jonesd21529f2017-01-23 23:16:46 +000073static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
74 {LibFunc_malloc, {MallocLike, 1, 0, -1}},
75 {LibFunc_valloc, {MallocLike, 1, 0, -1}},
76 {LibFunc_Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
77 {LibFunc_ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000078 {LibFunc_ZnwjSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned int, align_val_t)
79 {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow)
80 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000081 {LibFunc_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
82 {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000083 {LibFunc_ZnwmSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned long, align_val_t)
84 {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow)
85 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000086 {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
87 {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000088 {LibFunc_ZnajSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned int, align_val_t)
89 {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow)
90 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000091 {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
92 {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000093 {LibFunc_ZnamSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned long, align_val_t)
94 {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow)
95 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000096 {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
97 {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
98 {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
99 {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
100 {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
101 {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
102 {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
103 {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
104 {LibFunc_calloc, {CallocLike, 2, 0, 1}},
105 {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
106 {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
107 {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
108 {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
Benjamin Kramer01df8172013-09-24 17:49:08 +0000109 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes55fff832012-06-21 15:45:28 +0000110};
111
Craig Toppereae6db02017-04-18 20:17:23 +0000112static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
113 bool &IsNoBuiltin) {
George Burgess IVce044892016-12-27 06:10:50 +0000114 // Don't care about intrinsics in this case.
115 if (isa<IntrinsicInst>(V))
116 return nullptr;
117
Nuno Lopes55fff832012-06-21 15:45:28 +0000118 if (LookThroughBitCast)
119 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000120
Craig Toppereae6db02017-04-18 20:17:23 +0000121 ImmutableCallSite CS(V);
Nuno Lopes15dbcb42012-06-22 15:50:53 +0000122 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +0000123 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000124
George Burgess IVed160242016-12-27 06:32:14 +0000125 IsNoBuiltin = CS.isNoBuiltin();
Richard Smithe04f0d32013-05-16 04:12:04 +0000126
Benjamin Kramerfd063062018-02-20 22:00:33 +0000127 if (const Function *Callee = CS.getCalledFunction())
128 return Callee;
129 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +0000130}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000131
George Burgess IV278199f2016-04-12 01:05:35 +0000132/// Returns the allocation data for the given value if it's either a call to a
133/// known allocation function, or a call to a function with the allocsize
134/// attribute.
George Burgess IVce044892016-12-27 06:10:50 +0000135static Optional<AllocFnsTy>
136getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
137 const TargetLibraryInfo *TLI) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000138 // Make sure that the function is available.
139 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000140 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000141 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
George Burgess IV278199f2016-04-12 01:05:35 +0000142 return None;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000143
George Burgess IV45a540f2016-12-20 18:46:27 +0000144 const auto *Iter = find_if(
David L. Jonesd21529f2017-01-23 23:16:46 +0000145 AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
George Burgess IV45a540f2016-12-20 18:46:27 +0000146 return P.first == TLIFn;
147 });
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000148
George Burgess IV278199f2016-04-12 01:05:35 +0000149 if (Iter == std::end(AllocationFnData))
150 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000151
George Burgess IV278199f2016-04-12 01:05:35 +0000152 const AllocFnsTy *FnData = &Iter->second;
Benjamin Kramer2939dd32013-09-24 17:34:29 +0000153 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
George Burgess IV278199f2016-04-12 01:05:35 +0000154 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000155
156 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000157 int FstParam = FnData->FstParam;
158 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000159 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000160
161 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
162 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000163 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000164 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
165 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000166 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000167 FTy->getParamType(SndParam)->isIntegerTy(32) ||
168 FTy->getParamType(SndParam)->isIntegerTy(64)))
George Burgess IV278199f2016-04-12 01:05:35 +0000169 return *FnData;
170 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000171}
172
George Burgess IVce044892016-12-27 06:10:50 +0000173static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
174 const TargetLibraryInfo *TLI,
175 bool LookThroughBitCast = false) {
George Burgess IVed160242016-12-27 06:32:14 +0000176 bool IsNoBuiltinCall;
177 if (const Function *Callee =
178 getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
179 if (!IsNoBuiltinCall)
180 return getAllocationDataForFunction(Callee, AllocTy, TLI);
George Burgess IVce044892016-12-27 06:10:50 +0000181 return None;
182}
183
George Burgess IVccae43a2016-12-23 01:18:09 +0000184static Optional<AllocFnsTy> getAllocationSize(const Value *V,
185 const TargetLibraryInfo *TLI) {
George Burgess IVed160242016-12-27 06:32:14 +0000186 bool IsNoBuiltinCall;
187 const Function *Callee =
188 getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
George Burgess IVce044892016-12-27 06:10:50 +0000189 if (!Callee)
190 return None;
191
George Burgess IVccae43a2016-12-23 01:18:09 +0000192 // Prefer to use existing information over allocsize. This will give us an
193 // accurate AllocTy.
George Burgess IVed160242016-12-27 06:32:14 +0000194 if (!IsNoBuiltinCall)
195 if (Optional<AllocFnsTy> Data =
196 getAllocationDataForFunction(Callee, AnyAlloc, TLI))
197 return Data;
George Burgess IVccae43a2016-12-23 01:18:09 +0000198
George Burgess IVce044892016-12-27 06:10:50 +0000199 Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
200 if (Attr == Attribute())
George Burgess IVccae43a2016-12-23 01:18:09 +0000201 return None;
202
George Burgess IVccae43a2016-12-23 01:18:09 +0000203 std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
204
205 AllocFnsTy Result;
206 // Because allocsize only tells us how many bytes are allocated, we're not
207 // really allowed to assume anything, so we use MallocLike.
208 Result.AllocTy = MallocLike;
209 Result.NumParams = Callee->getNumOperands();
210 Result.FstParam = Args.first;
211 Result.SndParam = Args.second.getValueOr(-1);
212 return Result;
213}
214
Nuno Lopes55fff832012-06-21 15:45:28 +0000215static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000216 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000217 return CS && CS.hasRetAttr(Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000218}
219
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000220/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000221/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
222/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000223bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
224 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000225 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000226}
227
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000228/// Tests if a value is a call or invoke to a function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000229/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000230bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
231 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000232 // it's safe to consider realloc as noalias since accessing the original
233 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000234 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000235 hasNoAliasAttr(V, LookThroughBitCast);
236}
237
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000238/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000239/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000240bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
241 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000242 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000243}
244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000245/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000246/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000247bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
248 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000249 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000250}
251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000252/// Tests if a value is a call or invoke to a library function that
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000253/// allocates memory similar to malloc or calloc.
Craig Topper09bb7602017-04-18 21:43:46 +0000254bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
255 bool LookThroughBitCast) {
256 return getAllocationData(V, MallocOrCallocLike, TLI,
257 LookThroughBitCast).hasValue();
258}
259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000260/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000261/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000262bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
263 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000264 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000265}
266
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000267/// extractMallocCall - Returns the corresponding CallInst if the instruction
268/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
269/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000270const CallInst *llvm::extractMallocCall(const Value *I,
271 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000272 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000273}
274
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000275static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000276 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000277 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000278 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000279 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000280
Victor Hernandezf3db9152009-11-07 00:16:28 +0000281 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000282 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000283 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000284 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000285
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000286 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000287 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000289
Gabor Greifad7884a2010-06-23 21:41:47 +0000290 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000291 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000292 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000293 Value *Multiple = nullptr;
Sanjay Patel490193d2016-07-07 16:19:09 +0000294 if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000295 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000296
Craig Topper9f008862014-04-15 04:59:12 +0000297 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000298}
299
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000300/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000301/// The PointerType depends on the number of bitcast uses of the malloc call:
302/// 0: PointerType is the calls' return type.
303/// 1: PointerType is the bitcast's result type.
304/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000305PointerType *llvm::getMallocType(const CallInst *CI,
306 const TargetLibraryInfo *TLI) {
307 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000308
Craig Topper9f008862014-04-15 04:59:12 +0000309 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000310 unsigned NumOfBitCastUses = 0;
311
Victor Hernandez788eaab2009-09-18 19:20:02 +0000312 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000313 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
314 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000315 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
316 MallocType = cast<PointerType>(BCI->getDestTy());
317 NumOfBitCastUses++;
318 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000319
Victor Hernandezf3db9152009-11-07 00:16:28 +0000320 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
321 if (NumOfBitCastUses == 1)
322 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000323
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000324 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000325 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000326 return cast<PointerType>(CI->getType());
327
328 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000329 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000330}
331
Victor Hernandezf3db9152009-11-07 00:16:28 +0000332/// getMallocAllocatedType - Returns the Type allocated by malloc call.
333/// The Type depends on the number of bitcast uses of the malloc call:
334/// 0: PointerType is the malloc calls' return type.
335/// 1: PointerType is the bitcast's result type.
336/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000337Type *llvm::getMallocAllocatedType(const CallInst *CI,
338 const TargetLibraryInfo *TLI) {
339 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000340 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000341}
342
Michael Ilsemand9745242013-03-08 21:03:09 +0000343/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000344/// argument passed to malloc is a multiple of the size of the malloced type,
345/// then return that multiple. For non-array mallocs, the multiple is
346/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000347/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000349 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000350 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000351 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000352 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000353}
Victor Hernandeze2971492009-10-24 04:23:03 +0000354
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000355/// extractCallocCall - Returns the corresponding CallInst if the instruction
356/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000357const CallInst *llvm::extractCallocCall(const Value *I,
358 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000359 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000360}
361
Gabor Greif5f5a8642010-06-23 21:51:12 +0000362/// isFreeCall - Returns non-null if the value is a call to the builtin free()
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000363const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
Benjamin Kramerfd063062018-02-20 22:00:33 +0000364 bool IsNoBuiltinCall;
365 const Function *Callee =
366 getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
367 if (Callee == nullptr || IsNoBuiltinCall)
Craig Topper9f008862014-04-15 04:59:12 +0000368 return nullptr;
Nick Lewyckyc1f86582011-03-15 07:31:32 +0000369
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000370 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000371 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000372 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
Craig Topper9f008862014-04-15 04:59:12 +0000373 return nullptr;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000374
Richard Smith70523c72013-07-21 23:11:42 +0000375 unsigned ExpectedNumParams;
David L. Jonesd21529f2017-01-23 23:16:46 +0000376 if (TLIFn == LibFunc_free ||
377 TLIFn == LibFunc_ZdlPv || // operator delete(void*)
378 TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
379 TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
380 TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
381 TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
382 TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000383 ExpectedNumParams = 1;
David L. Jonesd21529f2017-01-23 23:16:46 +0000384 else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
385 TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
386 TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +0000387 TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
David L. Jonesd21529f2017-01-23 23:16:46 +0000388 TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
389 TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
390 TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +0000391 TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
David L. Jonesd21529f2017-01-23 23:16:46 +0000392 TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
393 TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
394 TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
395 TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
396 TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
397 TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
398 TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
399 TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000400 ExpectedNumParams = 2;
Eric Fiselier96bbec72018-04-04 19:01:51 +0000401 else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
402 TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow)
403 ExpectedNumParams = 3;
Richard Smith70523c72013-07-21 23:11:42 +0000404 else
Craig Topper9f008862014-04-15 04:59:12 +0000405 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000406
407 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000408 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000409 // attribute will exist.
Chris Lattner229907c2011-07-18 04:54:35 +0000410 FunctionType *FTy = Callee->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000411 if (!FTy->getReturnType()->isVoidTy())
Craig Topper9f008862014-04-15 04:59:12 +0000412 return nullptr;
Richard Smith70523c72013-07-21 23:11:42 +0000413 if (FTy->getNumParams() != ExpectedNumParams)
Craig Topper9f008862014-04-15 04:59:12 +0000414 return nullptr;
Chris Lattner67733f62011-06-18 21:46:23 +0000415 if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
Craig Topper9f008862014-04-15 04:59:12 +0000416 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000417
Benjamin Kramerfd063062018-02-20 22:00:33 +0000418 return dyn_cast<CallInst>(I);
Victor Hernandeze2971492009-10-24 04:23:03 +0000419}
Nuno Lopes55fff832012-06-21 15:45:28 +0000420
Nuno Lopes55fff832012-06-21 15:45:28 +0000421//===----------------------------------------------------------------------===//
422// Utility functions to compute size of objects.
423//
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000424static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
425 if (Data.second.isNegative() || Data.first.ult(Data.second))
426 return APInt(Data.first.getBitWidth(), 0);
427 return Data.first - Data.second;
428}
Nuno Lopes55fff832012-06-21 15:45:28 +0000429
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000430/// Compute the size of the object pointed by Ptr. Returns true and the
Nuno Lopes55fff832012-06-21 15:45:28 +0000431/// object size in Size if successful, and false otherwise.
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +0000432/// If RoundToAlign is true, then Size is rounded up to the alignment of
433/// allocas, byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000434bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
George Burgess IV56c7e882017-03-21 20:08:59 +0000435 const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
436 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
Nuno Lopes55fff832012-06-21 15:45:28 +0000437 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
438 if (!Visitor.bothKnown(Data))
439 return false;
440
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000441 Size = getSizeWithOverflow(Data).getZExtValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000442 return true;
443}
444
George Burgess IV3f089142016-12-20 23:46:36 +0000445ConstantInt *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
446 const DataLayout &DL,
447 const TargetLibraryInfo *TLI,
448 bool MustSucceed) {
449 assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
450 "ObjectSize must be a call to llvm.objectsize!");
451
452 bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
George Burgess IV56c7e882017-03-21 20:08:59 +0000453 ObjectSizeOpts EvalOptions;
George Burgess IV3f089142016-12-20 23:46:36 +0000454 // Unless we have to fold this to something, try to be as accurate as
455 // possible.
456 if (MustSucceed)
George Burgess IV56c7e882017-03-21 20:08:59 +0000457 EvalOptions.EvalMode =
458 MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
George Burgess IV3f089142016-12-20 23:46:36 +0000459 else
George Burgess IV56c7e882017-03-21 20:08:59 +0000460 EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
461
462 EvalOptions.NullIsUnknownSize =
463 cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
George Burgess IV3f089142016-12-20 23:46:36 +0000464
465 // FIXME: Does it make sense to just return a failure value if the size won't
466 // fit in the output and `!MustSucceed`?
467 uint64_t Size;
468 auto *ResultType = cast<IntegerType>(ObjectSize->getType());
George Burgess IV56c7e882017-03-21 20:08:59 +0000469 if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
George Burgess IV3f089142016-12-20 23:46:36 +0000470 isUIntN(ResultType->getBitWidth(), Size))
471 return ConstantInt::get(ResultType, Size);
472
473 if (!MustSucceed)
474 return nullptr;
475
476 return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
477}
478
Nuno Lopes55fff832012-06-21 15:45:28 +0000479STATISTIC(ObjectVisitorArgument,
480 "Number of arguments with unsolved size and offset");
481STATISTIC(ObjectVisitorLoad,
482 "Number of load instructions with unsolved size and offset");
483
Nuno Lopes55fff832012-06-21 15:45:28 +0000484APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000485 if (Options.RoundToAlign && Align)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000486 return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
Nuno Lopes55fff832012-06-21 15:45:28 +0000487 return Size;
488}
489
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000491 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000492 LLVMContext &Context,
George Burgess IV56c7e882017-03-21 20:08:59 +0000493 ObjectSizeOpts Options)
494 : DL(DL), TLI(TLI), Options(Options) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000495 // Pointer size must be rechecked for each object visited since it could have
496 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000497}
498
499SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000500 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000501 Zero = APInt::getNullValue(IntTyBits);
502
Nuno Lopes55fff832012-06-21 15:45:28 +0000503 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000504 if (Instruction *I = dyn_cast<Instruction>(V)) {
505 // If we have already seen this instruction, bail out. Cycles can happen in
506 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000507 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000508 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000509
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000510 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000511 return visitGEPOperator(*GEP);
512 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000513 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000514 if (Argument *A = dyn_cast<Argument>(V))
515 return visitArgument(*A);
516 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
517 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000518 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
519 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000520 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
521 return visitGlobalVariable(*GV);
522 if (UndefValue *UV = dyn_cast<UndefValue>(V))
523 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000524 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000525 if (CE->getOpcode() == Instruction::IntToPtr)
526 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000527 if (CE->getOpcode() == Instruction::GetElementPtr)
528 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000529 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000530
531 DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
532 << '\n');
533 return unknown();
534}
535
Mikael Holmenad7e7182017-07-12 06:19:10 +0000536/// When we're compiling N-bit code, and the user uses parameters that are
537/// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
538/// trouble with APInt size issues. This function handles resizing + overflow
539/// checks for us. Check and zext or trunc \p I depending on IntTyBits and
540/// I's value.
541bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
542 // More bits than we can handle. Checking the bit width isn't necessary, but
543 // it's faster than checking active bits, and should give `false` in the
544 // vast majority of cases.
545 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
546 return false;
547 if (I.getBitWidth() != IntTyBits)
548 I = I.zextOrTrunc(IntTyBits);
549 return true;
550}
551
Nuno Lopes55fff832012-06-21 15:45:28 +0000552SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
553 if (!I.getAllocatedType()->isSized())
554 return unknown();
555
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000556 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000557 if (!I.isArrayAllocation())
558 return std::make_pair(align(Size, I.getAlignment()), Zero);
559
560 Value *ArraySize = I.getArraySize();
561 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
Mikael Holmenad7e7182017-07-12 06:19:10 +0000562 APInt NumElems = C->getValue();
563 if (!CheckedZextOrTrunc(NumElems))
564 return unknown();
565
566 bool Overflow;
567 Size = Size.umul_ov(NumElems, Overflow);
568 return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
569 Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000570 }
571 return unknown();
572}
573
574SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000575 // No interprocedural analysis is done at the moment.
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000576 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000577 ++ObjectVisitorArgument;
578 return unknown();
579 }
580 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000581 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000582 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
583}
584
585SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000586 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000587 if (!FnData)
588 return unknown();
589
Sanjay Patel490193d2016-07-07 16:19:09 +0000590 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000591 if (FnData->AllocTy == StrDupLike) {
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000592 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
593 if (!Size)
594 return unknown();
595
Sanjay Patel490193d2016-07-07 16:19:09 +0000596 // Strndup limits strlen.
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000597 if (FnData->FstParam > 0) {
George Burgess IV278199f2016-04-12 01:05:35 +0000598 ConstantInt *Arg =
599 dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000600 if (!Arg)
601 return unknown();
602
603 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
604 if (Size.ugt(MaxSize))
605 Size = MaxSize + 1;
606 }
607 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000608 }
609
610 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
611 if (!Arg)
612 return unknown();
613
George Burgess IV278199f2016-04-12 01:05:35 +0000614 APInt Size = Arg->getValue();
615 if (!CheckedZextOrTrunc(Size))
616 return unknown();
617
Sanjay Patel490193d2016-07-07 16:19:09 +0000618 // Size is determined by just 1 parameter.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000619 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000620 return std::make_pair(Size, Zero);
621
622 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
623 if (!Arg)
624 return unknown();
625
George Burgess IV278199f2016-04-12 01:05:35 +0000626 APInt NumElems = Arg->getValue();
627 if (!CheckedZextOrTrunc(NumElems))
628 return unknown();
629
630 bool Overflow;
631 Size = Size.umul_ov(NumElems, Overflow);
632 return Overflow ? unknown() : std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000633
634 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000635 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000636 // - strcpy / strncpy
637 // - strcat / strncat
638 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000639 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000640 // - memset
641}
642
643SizeOffsetType
George Burgess IV56c7e882017-03-21 20:08:59 +0000644ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
645 if (Options.NullIsUnknownSize && CPN.getType()->getAddressSpace() == 0)
646 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000647 return std::make_pair(Zero, Zero);
648}
649
650SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000651ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
652 return unknown();
653}
654
655SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000656ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
657 // Easy cases were already folded by previous passes.
658 return unknown();
659}
660
661SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
662 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000663 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000664 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000665 return unknown();
666
Nuno Lopes55fff832012-06-21 15:45:28 +0000667 return std::make_pair(PtrData.first, PtrData.second + Offset);
668}
669
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000670SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000671 if (GA.isInterposable())
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000672 return unknown();
673 return compute(GA.getAliasee());
674}
675
Nuno Lopes55fff832012-06-21 15:45:28 +0000676SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
677 if (!GV.hasDefinitiveInitializer())
678 return unknown();
679
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000680 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000681 return std::make_pair(align(Size, GV.getAlignment()), Zero);
682}
683
684SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
685 // clueless
686 return unknown();
687}
688
689SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
690 ++ObjectVisitorLoad;
691 return unknown();
692}
693
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000694SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
695 // too complex to analyze statically.
696 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000697}
698
699SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
700 SizeOffsetType TrueSide = compute(I.getTrueValue());
701 SizeOffsetType FalseSide = compute(I.getFalseValue());
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000702 if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
703 if (TrueSide == FalseSide) {
704 return TrueSide;
705 }
706
707 APInt TrueResult = getSizeWithOverflow(TrueSide);
708 APInt FalseResult = getSizeWithOverflow(FalseSide);
709
710 if (TrueResult == FalseResult) {
711 return TrueSide;
712 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000713 if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000714 if (TrueResult.slt(FalseResult))
715 return TrueSide;
716 return FalseSide;
717 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000718 if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000719 if (TrueResult.sgt(FalseResult))
720 return TrueSide;
721 return FalseSide;
722 }
723 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000724 return unknown();
725}
726
727SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
728 return std::make_pair(Zero, Zero);
729}
730
731SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
732 DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
733 return unknown();
734}
735
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
737 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
738 bool RoundToAlign)
739 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
740 RoundToAlign(RoundToAlign) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000741 // IntTy and Zero must be set for each compute() since the address space may
742 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000743}
744
745SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000746 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000747 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000748 Zero = ConstantInt::get(IntTy, 0);
749
Nuno Lopes55fff832012-06-21 15:45:28 +0000750 SizeOffsetEvalType Result = compute_(V);
751
752 if (!bothKnown(Result)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000753 // Erase everything that was computed in this iteration from the cache, so
Nuno Lopes55fff832012-06-21 15:45:28 +0000754 // that no dangling references are left behind. We could be a bit smarter if
755 // we kept a dependency graph. It's probably not worth the complexity.
Benjamin Krameraa209152016-06-26 17:27:42 +0000756 for (const Value *SeenVal : SeenVals) {
757 CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
Nuno Lopes55fff832012-06-21 15:45:28 +0000758 // non-computable results can be safely cached
759 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
760 CacheMap.erase(CacheIt);
761 }
762 }
763
764 SeenVals.clear();
765 return Result;
766}
767
768SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000769 ObjectSizeOpts ObjSizeOptions;
770 ObjSizeOptions.RoundToAlign = RoundToAlign;
771
772 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, ObjSizeOptions);
Nuno Lopes55fff832012-06-21 15:45:28 +0000773 SizeOffsetType Const = Visitor.compute(V);
774 if (Visitor.bothKnown(Const))
775 return std::make_pair(ConstantInt::get(Context, Const.first),
776 ConstantInt::get(Context, Const.second));
777
778 V = V->stripPointerCasts();
779
Sanjay Patel490193d2016-07-07 16:19:09 +0000780 // Check cache.
Nuno Lopes55fff832012-06-21 15:45:28 +0000781 CacheMapTy::iterator CacheIt = CacheMap.find(V);
782 if (CacheIt != CacheMap.end())
783 return CacheIt->second;
784
Sanjay Patel490193d2016-07-07 16:19:09 +0000785 // Always generate code immediately before the instruction being
786 // processed, so that the generated code dominates the same BBs.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000787 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000788 if (Instruction *I = dyn_cast<Instruction>(V))
789 Builder.SetInsertPoint(I);
790
Sanjay Patel490193d2016-07-07 16:19:09 +0000791 // Now compute the size and offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000792 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000793
794 // Record the pointers that were handled in this run, so that they can be
795 // cleaned later if something fails. We also use this set to break cycles that
796 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000797 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000798 Result = unknown();
799 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000800 Result = visitGEPOperator(*GEP);
801 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
802 Result = visit(*I);
803 } else if (isa<Argument>(V) ||
804 (isa<ConstantExpr>(V) &&
805 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000806 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000807 isa<GlobalVariable>(V)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000808 // Ignore values where we cannot do more than ObjectSizeVisitor.
Nuno Lopes55fff832012-06-21 15:45:28 +0000809 Result = unknown();
810 } else {
811 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
812 << *V << '\n');
813 Result = unknown();
814 }
815
Nuno Lopes55fff832012-06-21 15:45:28 +0000816 // Don't reuse CacheIt since it may be invalid at this point.
817 CacheMap[V] = Result;
818 return Result;
819}
820
821SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
822 if (!I.getAllocatedType()->isSized())
823 return unknown();
824
825 // must be a VLA
826 assert(I.isArrayAllocation());
827 Value *ArraySize = I.getArraySize();
828 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000829 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000830 Size = Builder.CreateMul(Size, ArraySize);
831 return std::make_pair(Size, Zero);
832}
833
834SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000835 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000836 if (!FnData)
837 return unknown();
838
Sanjay Patel490193d2016-07-07 16:19:09 +0000839 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000840 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000841 // TODO
842 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000843 }
844
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000845 Value *FirstArg = CS.getArgument(FnData->FstParam);
846 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000847 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000848 return std::make_pair(FirstArg, Zero);
849
850 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000851 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000852 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
853 return std::make_pair(Size, Zero);
854
855 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000856 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000857 // - strcpy / strncpy
858 // - strcat / strncat
859 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000860 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000861 // - memset
862}
863
864SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000865ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
866 return unknown();
867}
868
869SizeOffsetEvalType
870ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
871 return unknown();
872}
873
874SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000875ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
876 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
877 if (!bothKnown(PtrData))
878 return unknown();
879
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000880 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000881 Offset = Builder.CreateAdd(PtrData.second, Offset);
882 return std::make_pair(PtrData.first, Offset);
883}
884
885SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
886 // clueless
887 return unknown();
888}
889
890SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
891 return unknown();
892}
893
894SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000895 // Create 2 PHIs: one for size and another for offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000896 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
897 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
898
Sanjay Patel490193d2016-07-07 16:19:09 +0000899 // Insert right away in the cache to handle recursive PHIs.
Nuno Lopes55fff832012-06-21 15:45:28 +0000900 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
901
Sanjay Patel490193d2016-07-07 16:19:09 +0000902 // Compute offset/size for each PHI incoming pointer.
Nuno Lopes55fff832012-06-21 15:45:28 +0000903 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000904 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000905 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
906
907 if (!bothKnown(EdgeData)) {
908 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
909 OffsetPHI->eraseFromParent();
910 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
911 SizePHI->eraseFromParent();
912 return unknown();
913 }
914 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
915 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
916 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000917
918 Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
919 if ((Tmp = SizePHI->hasConstantValue())) {
920 Size = Tmp;
921 SizePHI->replaceAllUsesWith(Size);
922 SizePHI->eraseFromParent();
923 }
924 if ((Tmp = OffsetPHI->hasConstantValue())) {
925 Offset = Tmp;
926 OffsetPHI->replaceAllUsesWith(Offset);
927 OffsetPHI->eraseFromParent();
928 }
929 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000930}
931
932SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
933 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
934 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
935
936 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
937 return unknown();
938 if (TrueSide == FalseSide)
939 return TrueSide;
940
941 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
942 FalseSide.first);
943 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
944 FalseSide.second);
945 return std::make_pair(Size, Offset);
946}
947
948SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
949 DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
950 return unknown();
951}