blob: d73419fad6a95be37eaa3e9fff4092b25cbaa29e [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Evan Cheng1d9d4bd2009-09-10 04:36:43 +00006//
7//===----------------------------------------------------------------------===//
8//
Victor Hernandezf390e042009-10-27 20:05:49 +00009// This family of functions identifies calls to builtin functions that allocate
Michael Ilsemand9745242013-03-08 21:03:09 +000010// or free memory.
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000011//
12//===----------------------------------------------------------------------===//
13
Victor Hernandezf390e042009-10-27 20:05:49 +000014#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/Statistic.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000020#include "llvm/ADT/StringRef.h"
21#include "llvm/Analysis/TargetFolder.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000023#include "llvm/Analysis/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000025#include "llvm/IR/Argument.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000029#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/GlobalVariable.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000033#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000035#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/Operator.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Support/Casting.h"
Nuno Lopes55fff832012-06-21 15:45:28 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/raw_ostream.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000043#include <cassert>
44#include <cstdint>
45#include <iterator>
46#include <utility>
47
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000048using namespace llvm;
49
Chandler Carruthf1221bd2014-04-22 02:48:03 +000050#define DEBUG_TYPE "memory-builtins"
51
George Burgess IV2ae15e02015-11-17 19:48:06 +000052enum AllocType : uint8_t {
Benjamin Kramer2939dd32013-09-24 17:34:29 +000053 OpNewLike = 1<<0, // allocates; never returns null
54 MallocLike = 1<<1 | OpNewLike, // allocates; may return null
55 CallocLike = 1<<2, // allocates + bzero
56 ReallocLike = 1<<3, // reallocates
57 StrDupLike = 1<<4,
Craig Topper09bb7602017-04-18 21:43:46 +000058 MallocOrCallocLike = MallocLike | CallocLike,
Benjamin Kramer2939dd32013-09-24 17:34:29 +000059 AllocLike = MallocLike | CallocLike | StrDupLike,
Benjamin Kramer4d4df042013-09-24 17:15:14 +000060 AnyAlloc = AllocLike | ReallocLike
Nuno Lopes55fff832012-06-21 15:45:28 +000061};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000062
Nuno Lopes55fff832012-06-21 15:45:28 +000063struct AllocFnsTy {
Nuno Lopes55fff832012-06-21 15:45:28 +000064 AllocType AllocTy;
George Burgess IV278199f2016-04-12 01:05:35 +000065 unsigned NumParams;
Nuno Lopes55fff832012-06-21 15:45:28 +000066 // First and Second size parameters (or -1 if unused)
George Burgess IV278199f2016-04-12 01:05:35 +000067 int FstParam, SndParam;
Nuno Lopes55fff832012-06-21 15:45:28 +000068};
Evan Cheng1d9d4bd2009-09-10 04:36:43 +000069
Nuno Lopes181d67e2012-06-28 16:34:03 +000070// FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
71// know which functions are nounwind, noalias, nocapture parameters, etc.
David L. Jonesd21529f2017-01-23 23:16:46 +000072static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = {
73 {LibFunc_malloc, {MallocLike, 1, 0, -1}},
74 {LibFunc_valloc, {MallocLike, 1, 0, -1}},
75 {LibFunc_Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
76 {LibFunc_ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000077 {LibFunc_ZnwjSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned int, align_val_t)
78 {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow)
79 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000080 {LibFunc_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long)
81 {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000082 {LibFunc_ZnwmSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned long, align_val_t)
83 {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow)
84 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000085 {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
86 {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000087 {LibFunc_ZnajSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned int, align_val_t)
88 {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow)
89 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000090 {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long)
91 {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +000092 {LibFunc_ZnamSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned long, align_val_t)
93 {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow)
94 {MallocLike, 3, 0, -1}},
David L. Jonesd21529f2017-01-23 23:16:46 +000095 {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int)
96 {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow)
97 {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long)
98 {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow)
99 {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int)
100 {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow)
101 {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long)
102 {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow)
103 {LibFunc_calloc, {CallocLike, 2, 0, 1}},
104 {LibFunc_realloc, {ReallocLike, 2, 1, -1}},
105 {LibFunc_reallocf, {ReallocLike, 2, 1, -1}},
106 {LibFunc_strdup, {StrDupLike, 1, -1, -1}},
107 {LibFunc_strndup, {StrDupLike, 2, 1, -1}}
Benjamin Kramer01df8172013-09-24 17:49:08 +0000108 // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
Nuno Lopes55fff832012-06-21 15:45:28 +0000109};
110
Craig Toppereae6db02017-04-18 20:17:23 +0000111static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
112 bool &IsNoBuiltin) {
George Burgess IVce044892016-12-27 06:10:50 +0000113 // Don't care about intrinsics in this case.
114 if (isa<IntrinsicInst>(V))
115 return nullptr;
116
Nuno Lopes55fff832012-06-21 15:45:28 +0000117 if (LookThroughBitCast)
118 V = V->stripPointerCasts();
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000119
Craig Toppereae6db02017-04-18 20:17:23 +0000120 ImmutableCallSite CS(V);
Nuno Lopes15dbcb42012-06-22 15:50:53 +0000121 if (!CS.getInstruction())
Craig Topper9f008862014-04-15 04:59:12 +0000122 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000123
George Burgess IVed160242016-12-27 06:32:14 +0000124 IsNoBuiltin = CS.isNoBuiltin();
Richard Smithe04f0d32013-05-16 04:12:04 +0000125
Benjamin Kramerfd063062018-02-20 22:00:33 +0000126 if (const Function *Callee = CS.getCalledFunction())
127 return Callee;
128 return nullptr;
Nuno Lopes55fff832012-06-21 15:45:28 +0000129}
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000130
George Burgess IV278199f2016-04-12 01:05:35 +0000131/// Returns the allocation data for the given value if it's either a call to a
132/// known allocation function, or a call to a function with the allocsize
133/// attribute.
George Burgess IVce044892016-12-27 06:10:50 +0000134static Optional<AllocFnsTy>
135getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
136 const TargetLibraryInfo *TLI) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000137 // Make sure that the function is available.
138 StringRef FnName = Callee->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000139 LibFunc TLIFn;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000140 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
George Burgess IV278199f2016-04-12 01:05:35 +0000141 return None;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000142
George Burgess IV45a540f2016-12-20 18:46:27 +0000143 const auto *Iter = find_if(
David L. Jonesd21529f2017-01-23 23:16:46 +0000144 AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
George Burgess IV45a540f2016-12-20 18:46:27 +0000145 return P.first == TLIFn;
146 });
Benjamin Kramer74b6d3b2015-10-24 19:03:15 +0000147
George Burgess IV278199f2016-04-12 01:05:35 +0000148 if (Iter == std::end(AllocationFnData))
149 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000150
George Burgess IV278199f2016-04-12 01:05:35 +0000151 const AllocFnsTy *FnData = &Iter->second;
Andrew Kaylord9b6b812018-08-30 18:37:18 +0000152 if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
George Burgess IV278199f2016-04-12 01:05:35 +0000153 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000154
155 // Check function prototype.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000156 int FstParam = FnData->FstParam;
157 int SndParam = FnData->SndParam;
Chris Lattner229907c2011-07-18 04:54:35 +0000158 FunctionType *FTy = Callee->getFunctionType();
Nuno Lopes55fff832012-06-21 15:45:28 +0000159
160 if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
161 FTy->getNumParams() == FnData->NumParams &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000162 (FstParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000163 (FTy->getParamType(FstParam)->isIntegerTy(32) ||
164 FTy->getParamType(FstParam)->isIntegerTy(64))) &&
Nuno Lopesf06b7312012-06-21 18:38:26 +0000165 (SndParam < 0 ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000166 FTy->getParamType(SndParam)->isIntegerTy(32) ||
167 FTy->getParamType(SndParam)->isIntegerTy(64)))
George Burgess IV278199f2016-04-12 01:05:35 +0000168 return *FnData;
169 return None;
Nuno Lopes55fff832012-06-21 15:45:28 +0000170}
171
George Burgess IVce044892016-12-27 06:10:50 +0000172static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
173 const TargetLibraryInfo *TLI,
174 bool LookThroughBitCast = false) {
George Burgess IVed160242016-12-27 06:32:14 +0000175 bool IsNoBuiltinCall;
176 if (const Function *Callee =
177 getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
178 if (!IsNoBuiltinCall)
179 return getAllocationDataForFunction(Callee, AllocTy, TLI);
George Burgess IVce044892016-12-27 06:10:50 +0000180 return None;
181}
182
George Burgess IVccae43a2016-12-23 01:18:09 +0000183static Optional<AllocFnsTy> getAllocationSize(const Value *V,
184 const TargetLibraryInfo *TLI) {
George Burgess IVed160242016-12-27 06:32:14 +0000185 bool IsNoBuiltinCall;
186 const Function *Callee =
187 getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
George Burgess IVce044892016-12-27 06:10:50 +0000188 if (!Callee)
189 return None;
190
George Burgess IVccae43a2016-12-23 01:18:09 +0000191 // Prefer to use existing information over allocsize. This will give us an
192 // accurate AllocTy.
George Burgess IVed160242016-12-27 06:32:14 +0000193 if (!IsNoBuiltinCall)
194 if (Optional<AllocFnsTy> Data =
195 getAllocationDataForFunction(Callee, AnyAlloc, TLI))
196 return Data;
George Burgess IVccae43a2016-12-23 01:18:09 +0000197
George Burgess IVce044892016-12-27 06:10:50 +0000198 Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
199 if (Attr == Attribute())
George Burgess IVccae43a2016-12-23 01:18:09 +0000200 return None;
201
George Burgess IVccae43a2016-12-23 01:18:09 +0000202 std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
203
204 AllocFnsTy Result;
205 // Because allocsize only tells us how many bytes are allocated, we're not
206 // really allowed to assume anything, so we use MallocLike.
207 Result.AllocTy = MallocLike;
208 Result.NumParams = Callee->getNumOperands();
209 Result.FstParam = Args.first;
210 Result.SndParam = Args.second.getValueOr(-1);
211 return Result;
212}
213
Nuno Lopes55fff832012-06-21 15:45:28 +0000214static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
Nuno Lopes9ecc8762012-06-25 16:17:54 +0000215 ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
Reid Klecknerfb502d22017-04-14 20:19:02 +0000216 return CS && CS.hasRetAttr(Attribute::NoAlias);
Nuno Lopes55fff832012-06-21 15:45:28 +0000217}
218
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000219/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000220/// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
221/// like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000222bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
223 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000224 return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000225}
226
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000227/// Tests if a value is a call or invoke to a function that returns a
Nuno Lopes181d67e2012-06-28 16:34:03 +0000228/// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000229bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
230 bool LookThroughBitCast) {
Nuno Lopes181d67e2012-06-28 16:34:03 +0000231 // it's safe to consider realloc as noalias since accessing the original
232 // pointer is undefined behavior
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000233 return isAllocationFn(V, TLI, LookThroughBitCast) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000234 hasNoAliasAttr(V, LookThroughBitCast);
235}
236
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000237/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000238/// allocates uninitialized memory (such as malloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000239bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
240 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000241 return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000242}
243
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000244/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000245/// allocates zero-filled memory (such as calloc).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000246bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
247 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000248 return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000249}
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251/// Tests if a value is a call or invoke to a library function that
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000252/// allocates memory similar to malloc or calloc.
Craig Topper09bb7602017-04-18 21:43:46 +0000253bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
254 bool LookThroughBitCast) {
255 return getAllocationData(V, MallocOrCallocLike, TLI,
256 LookThroughBitCast).hasValue();
257}
258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000259/// Tests if a value is a call or invoke to a library function that
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000260/// allocates memory (either malloc, calloc, or strdup like).
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000261bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
262 bool LookThroughBitCast) {
George Burgess IV278199f2016-04-12 01:05:35 +0000263 return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000264}
265
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000266/// Tests if a value is a call or invoke to a library function that
267/// reallocates memory (e.g., realloc).
268bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
269 bool LookThroughBitCast) {
270 return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast).hasValue();
271}
272
273/// Tests if a functions is a call or invoke to a library function that
274/// reallocates memory (e.g., realloc).
275bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
276 return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
277}
278
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000279/// extractMallocCall - Returns the corresponding CallInst if the instruction
280/// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we
281/// ignore InvokeInst here.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000282const CallInst *llvm::extractMallocCall(const Value *I,
283 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000284 return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000285}
286
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000287static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000288 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000289 bool LookThroughSExt = false) {
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000290 if (!CI)
Craig Topper9f008862014-04-15 04:59:12 +0000291 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000292
Victor Hernandezf3db9152009-11-07 00:16:28 +0000293 // The size of the malloc's result type must be known to determine array size.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000294 Type *T = getMallocAllocatedType(CI, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295 if (!T || !T->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000296 return nullptr;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000297
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000298 unsigned ElementSize = DL.getTypeAllocSize(T);
Chris Lattner229907c2011-07-18 04:54:35 +0000299 if (StructType *ST = dyn_cast<StructType>(T))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000300 ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
Victor Hernandez788eaab2009-09-18 19:20:02 +0000301
Gabor Greifad7884a2010-06-23 21:41:47 +0000302 // If malloc call's arg can be determined to be a multiple of ElementSize,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000303 // return the multiple. Otherwise, return NULL.
Gabor Greifad7884a2010-06-23 21:41:47 +0000304 Value *MallocArg = CI->getArgOperand(0);
Craig Topper9f008862014-04-15 04:59:12 +0000305 Value *Multiple = nullptr;
Sanjay Patel490193d2016-07-07 16:19:09 +0000306 if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000307 return Multiple;
Victor Hernandez788eaab2009-09-18 19:20:02 +0000308
Craig Topper9f008862014-04-15 04:59:12 +0000309 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000310}
311
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000312/// getMallocType - Returns the PointerType resulting from the malloc call.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000313/// The PointerType depends on the number of bitcast uses of the malloc call:
314/// 0: PointerType is the calls' return type.
315/// 1: PointerType is the bitcast's result type.
316/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000317PointerType *llvm::getMallocType(const CallInst *CI,
318 const TargetLibraryInfo *TLI) {
319 assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
Michael Ilsemand9745242013-03-08 21:03:09 +0000320
Craig Topper9f008862014-04-15 04:59:12 +0000321 PointerType *MallocType = nullptr;
Victor Hernandezf3db9152009-11-07 00:16:28 +0000322 unsigned NumOfBitCastUses = 0;
323
Victor Hernandez788eaab2009-09-18 19:20:02 +0000324 // Determine if CallInst has a bitcast use.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000325 for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
326 UI != E;)
Victor Hernandezf3db9152009-11-07 00:16:28 +0000327 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
328 MallocType = cast<PointerType>(BCI->getDestTy());
329 NumOfBitCastUses++;
330 }
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000331
Victor Hernandezf3db9152009-11-07 00:16:28 +0000332 // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
333 if (NumOfBitCastUses == 1)
334 return MallocType;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000335
Victor Hernandezddc2ce42009-09-22 18:50:03 +0000336 // Malloc call was not bitcast, so type is the malloc function's return type.
Victor Hernandezf3db9152009-11-07 00:16:28 +0000337 if (NumOfBitCastUses == 0)
Victor Hernandez788eaab2009-09-18 19:20:02 +0000338 return cast<PointerType>(CI->getType());
339
340 // Type could not be determined.
Craig Topper9f008862014-04-15 04:59:12 +0000341 return nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000342}
343
Victor Hernandezf3db9152009-11-07 00:16:28 +0000344/// getMallocAllocatedType - Returns the Type allocated by malloc call.
345/// The Type depends on the number of bitcast uses of the malloc call:
346/// 0: PointerType is the malloc calls' return type.
347/// 1: PointerType is the bitcast's result type.
348/// >1: Unique PointerType cannot be determined, return NULL.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000349Type *llvm::getMallocAllocatedType(const CallInst *CI,
350 const TargetLibraryInfo *TLI) {
351 PointerType *PT = getMallocType(CI, TLI);
Craig Topper9f008862014-04-15 04:59:12 +0000352 return PT ? PT->getElementType() : nullptr;
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000353}
354
Michael Ilsemand9745242013-03-08 21:03:09 +0000355/// getMallocArraySize - Returns the array size of a malloc call. If the
Victor Hernandez0d025422009-10-28 20:18:55 +0000356/// argument passed to malloc is a multiple of the size of the malloced type,
357/// then return that multiple. For non-array mallocs, the multiple is
358/// constant 1. Otherwise, return NULL for mallocs whose array size cannot be
Victor Hernandez13020b12009-10-15 20:14:52 +0000359/// determined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000360Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000361 const TargetLibraryInfo *TLI,
Victor Hernandezfcc77b12009-11-10 08:32:25 +0000362 bool LookThroughSExt) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000363 assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
Matt Arsenault40dddd72013-10-03 19:50:01 +0000364 return computeArraySize(CI, DL, TLI, LookThroughSExt);
Evan Cheng1d9d4bd2009-09-10 04:36:43 +0000365}
Victor Hernandeze2971492009-10-24 04:23:03 +0000366
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000367/// extractCallocCall - Returns the corresponding CallInst if the instruction
368/// is a calloc call.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000369const CallInst *llvm::extractCallocCall(const Value *I,
370 const TargetLibraryInfo *TLI) {
Craig Topper9f008862014-04-15 04:59:12 +0000371 return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
Nuno Lopesd2b71e72012-05-03 21:19:58 +0000372}
373
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000374/// isLibFreeFunction - Returns true if the function is a builtin free()
375bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
Richard Smith70523c72013-07-21 23:11:42 +0000376 unsigned ExpectedNumParams;
David L. Jonesd21529f2017-01-23 23:16:46 +0000377 if (TLIFn == LibFunc_free ||
378 TLIFn == LibFunc_ZdlPv || // operator delete(void*)
379 TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
380 TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
381 TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
382 TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
383 TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*)
Richard Smith70523c72013-07-21 23:11:42 +0000384 ExpectedNumParams = 1;
David L. Jonesd21529f2017-01-23 23:16:46 +0000385 else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint)
386 TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong)
387 TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +0000388 TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
David L. Jonesd21529f2017-01-23 23:16:46 +0000389 TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint)
390 TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong)
391 TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
Eric Fiselier96bbec72018-04-04 19:01:51 +0000392 TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
David L. Jonesd21529f2017-01-23 23:16:46 +0000393 TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint)
394 TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
395 TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
396 TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
397 TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint)
398 TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
399 TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
400 TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow)
Richard Smith70523c72013-07-21 23:11:42 +0000401 ExpectedNumParams = 2;
Eric Fiselier96bbec72018-04-04 19:01:51 +0000402 else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
403 TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow)
404 ExpectedNumParams = 3;
Richard Smith70523c72013-07-21 23:11:42 +0000405 else
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000406 return false;
Victor Hernandeze2971492009-10-24 04:23:03 +0000407
408 // Check free prototype.
Michael Ilsemand9745242013-03-08 21:03:09 +0000409 // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
Victor Hernandeze2971492009-10-24 04:23:03 +0000410 // attribute will exist.
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000411 FunctionType *FTy = F->getFunctionType();
Victor Hernandez33188582009-11-03 20:39:35 +0000412 if (!FTy->getReturnType()->isVoidTy())
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000413 return false;
Richard Smith70523c72013-07-21 23:11:42 +0000414 if (FTy->getNumParams() != ExpectedNumParams)
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000415 return false;
416 if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
417 return false;
418
419 return true;
420}
421
422/// isFreeCall - Returns non-null if the value is a call to the builtin free()
423const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
424 bool IsNoBuiltinCall;
425 const Function *Callee =
426 getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
427 if (Callee == nullptr || IsNoBuiltinCall)
Craig Topper9f008862014-04-15 04:59:12 +0000428 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000429
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000430 StringRef FnName = Callee->getName();
431 LibFunc TLIFn;
432 if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
433 return nullptr;
434
435 return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +0000436}
Nuno Lopes55fff832012-06-21 15:45:28 +0000437
Brian Homerdingb4b21d82019-07-08 15:57:56 +0000438
Nuno Lopes55fff832012-06-21 15:45:28 +0000439//===----------------------------------------------------------------------===//
440// Utility functions to compute size of objects.
441//
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000442static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
443 if (Data.second.isNegative() || Data.first.ult(Data.second))
444 return APInt(Data.first.getBitWidth(), 0);
445 return Data.first - Data.second;
446}
Nuno Lopes55fff832012-06-21 15:45:28 +0000447
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000448/// Compute the size of the object pointed by Ptr. Returns true and the
Nuno Lopes55fff832012-06-21 15:45:28 +0000449/// object size in Size if successful, and false otherwise.
Hiroshi Inoueef1c2ba2017-07-01 07:12:15 +0000450/// If RoundToAlign is true, then Size is rounded up to the alignment of
451/// allocas, byval arguments, and global variables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000452bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
George Burgess IV56c7e882017-03-21 20:08:59 +0000453 const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
454 ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
Nuno Lopes55fff832012-06-21 15:45:28 +0000455 SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
456 if (!Visitor.bothKnown(Data))
457 return false;
458
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000459 Size = getSizeWithOverflow(Data).getZExtValue();
Nuno Lopes55fff832012-06-21 15:45:28 +0000460 return true;
461}
462
Erik Pilkington600e9de2019-01-30 20:34:35 +0000463Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
464 const DataLayout &DL,
465 const TargetLibraryInfo *TLI,
466 bool MustSucceed) {
George Burgess IV3f089142016-12-20 23:46:36 +0000467 assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
468 "ObjectSize must be a call to llvm.objectsize!");
469
470 bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
George Burgess IV56c7e882017-03-21 20:08:59 +0000471 ObjectSizeOpts EvalOptions;
George Burgess IV3f089142016-12-20 23:46:36 +0000472 // Unless we have to fold this to something, try to be as accurate as
473 // possible.
474 if (MustSucceed)
George Burgess IV56c7e882017-03-21 20:08:59 +0000475 EvalOptions.EvalMode =
476 MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
George Burgess IV3f089142016-12-20 23:46:36 +0000477 else
George Burgess IV56c7e882017-03-21 20:08:59 +0000478 EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
479
480 EvalOptions.NullIsUnknownSize =
481 cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
George Burgess IV3f089142016-12-20 23:46:36 +0000482
George Burgess IV3f089142016-12-20 23:46:36 +0000483 auto *ResultType = cast<IntegerType>(ObjectSize->getType());
Erik Pilkington600e9de2019-01-30 20:34:35 +0000484 bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
485 if (StaticOnly) {
486 // FIXME: Does it make sense to just return a failure value if the size won't
487 // fit in the output and `!MustSucceed`?
488 uint64_t Size;
489 if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
490 isUIntN(ResultType->getBitWidth(), Size))
491 return ConstantInt::get(ResultType, Size);
492 } else {
493 LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
494 ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
495 SizeOffsetEvalType SizeOffsetPair =
496 Eval.compute(ObjectSize->getArgOperand(0));
497
498 if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
499 IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
500 Builder.SetInsertPoint(ObjectSize);
501
502 // If we've outside the end of the object, then we can always access
503 // exactly 0 bytes.
504 Value *ResultSize =
505 Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
506 Value *UseZero =
507 Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
508 return Builder.CreateSelect(UseZero, ConstantInt::get(ResultType, 0),
509 ResultSize);
510 }
511 }
George Burgess IV3f089142016-12-20 23:46:36 +0000512
513 if (!MustSucceed)
514 return nullptr;
515
516 return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
517}
518
Nuno Lopes55fff832012-06-21 15:45:28 +0000519STATISTIC(ObjectVisitorArgument,
520 "Number of arguments with unsolved size and offset");
521STATISTIC(ObjectVisitorLoad,
522 "Number of load instructions with unsolved size and offset");
523
Nuno Lopes55fff832012-06-21 15:45:28 +0000524APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
George Burgess IV56c7e882017-03-21 20:08:59 +0000525 if (Options.RoundToAlign && Align)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000526 return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align));
Nuno Lopes55fff832012-06-21 15:45:28 +0000527 return Size;
528}
529
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000530ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000531 const TargetLibraryInfo *TLI,
Nuno Lopes55fff832012-06-21 15:45:28 +0000532 LLVMContext &Context,
George Burgess IV56c7e882017-03-21 20:08:59 +0000533 ObjectSizeOpts Options)
534 : DL(DL), TLI(TLI), Options(Options) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000535 // Pointer size must be rechecked for each object visited since it could have
536 // a different address space.
Nuno Lopes55fff832012-06-21 15:45:28 +0000537}
538
539SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000540 IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000541 Zero = APInt::getNullValue(IntTyBits);
542
Nuno Lopes55fff832012-06-21 15:45:28 +0000543 V = V->stripPointerCasts();
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000544 if (Instruction *I = dyn_cast<Instruction>(V)) {
545 // If we have already seen this instruction, bail out. Cycles can happen in
546 // unreachable code after constant propagation.
David Blaikie70573dc2014-11-19 07:49:26 +0000547 if (!SeenInsts.insert(I).second)
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000548 return unknown();
Nuno Lopesd896a402012-12-31 20:45:10 +0000549
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000550 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000551 return visitGEPOperator(*GEP);
552 return visit(*I);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000553 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000554 if (Argument *A = dyn_cast<Argument>(V))
555 return visitArgument(*A);
556 if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
557 return visitConstantPointerNull(*P);
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000558 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
559 return visitGlobalAlias(*GA);
Nuno Lopes55fff832012-06-21 15:45:28 +0000560 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
561 return visitGlobalVariable(*GV);
562 if (UndefValue *UV = dyn_cast<UndefValue>(V))
563 return visitUndefValue(*UV);
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000564 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000565 if (CE->getOpcode() == Instruction::IntToPtr)
566 return unknown(); // clueless
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000567 if (CE->getOpcode() == Instruction::GetElementPtr)
568 return visitGEPOperator(cast<GEPOperator>(*CE));
Benjamin Kramer34764fe2012-08-17 19:26:41 +0000569 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000570
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000571 LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
572 << *V << '\n');
Nuno Lopes55fff832012-06-21 15:45:28 +0000573 return unknown();
574}
575
Mikael Holmenad7e7182017-07-12 06:19:10 +0000576/// When we're compiling N-bit code, and the user uses parameters that are
577/// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
578/// trouble with APInt size issues. This function handles resizing + overflow
579/// checks for us. Check and zext or trunc \p I depending on IntTyBits and
580/// I's value.
581bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
582 // More bits than we can handle. Checking the bit width isn't necessary, but
583 // it's faster than checking active bits, and should give `false` in the
584 // vast majority of cases.
585 if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
586 return false;
587 if (I.getBitWidth() != IntTyBits)
588 I = I.zextOrTrunc(IntTyBits);
589 return true;
590}
591
Nuno Lopes55fff832012-06-21 15:45:28 +0000592SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
593 if (!I.getAllocatedType()->isSized())
594 return unknown();
595
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000596 APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000597 if (!I.isArrayAllocation())
598 return std::make_pair(align(Size, I.getAlignment()), Zero);
599
600 Value *ArraySize = I.getArraySize();
601 if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
Mikael Holmenad7e7182017-07-12 06:19:10 +0000602 APInt NumElems = C->getValue();
603 if (!CheckedZextOrTrunc(NumElems))
604 return unknown();
605
606 bool Overflow;
607 Size = Size.umul_ov(NumElems, Overflow);
608 return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
609 Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000610 }
611 return unknown();
612}
613
614SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000615 // No interprocedural analysis is done at the moment.
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000616 if (!A.hasByValOrInAllocaAttr()) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000617 ++ObjectVisitorArgument;
618 return unknown();
619 }
620 PointerType *PT = cast<PointerType>(A.getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000621 APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000622 return std::make_pair(align(Size, A.getParamAlignment()), Zero);
623}
624
625SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000626 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000627 if (!FnData)
628 return unknown();
629
Sanjay Patel490193d2016-07-07 16:19:09 +0000630 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000631 if (FnData->AllocTy == StrDupLike) {
David Bolvansky1f343fa2018-05-22 20:27:36 +0000632 APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000633 if (!Size)
634 return unknown();
635
Sanjay Patel490193d2016-07-07 16:19:09 +0000636 // Strndup limits strlen.
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000637 if (FnData->FstParam > 0) {
George Burgess IV278199f2016-04-12 01:05:35 +0000638 ConstantInt *Arg =
639 dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
Nuno Lopes2a4b09c2012-07-24 16:28:13 +0000640 if (!Arg)
641 return unknown();
642
643 APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
644 if (Size.ugt(MaxSize))
645 Size = MaxSize + 1;
646 }
647 return std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000648 }
649
650 ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
651 if (!Arg)
652 return unknown();
653
George Burgess IV278199f2016-04-12 01:05:35 +0000654 APInt Size = Arg->getValue();
655 if (!CheckedZextOrTrunc(Size))
656 return unknown();
657
Sanjay Patel490193d2016-07-07 16:19:09 +0000658 // Size is determined by just 1 parameter.
Nuno Lopesf06b7312012-06-21 18:38:26 +0000659 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000660 return std::make_pair(Size, Zero);
661
662 Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
663 if (!Arg)
664 return unknown();
665
George Burgess IV278199f2016-04-12 01:05:35 +0000666 APInt NumElems = Arg->getValue();
667 if (!CheckedZextOrTrunc(NumElems))
668 return unknown();
669
670 bool Overflow;
671 Size = Size.umul_ov(NumElems, Overflow);
672 return Overflow ? unknown() : std::make_pair(Size, Zero);
Nuno Lopes55fff832012-06-21 15:45:28 +0000673
674 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000675 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000676 // - strcpy / strncpy
677 // - strcat / strncat
678 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000679 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000680 // - memset
681}
682
683SizeOffsetType
George Burgess IV56c7e882017-03-21 20:08:59 +0000684ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
George Burgess IV3fbfa9c42018-07-09 22:21:16 +0000685 // If null is unknown, there's nothing we can do. Additionally, non-zero
686 // address spaces can make use of null, so we don't presume to know anything
687 // about that.
688 //
689 // TODO: How should this work with address space casts? We currently just drop
690 // them on the floor, but it's unclear what we should do when a NULL from
691 // addrspace(1) gets casted to addrspace(0) (or vice-versa).
692 if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
George Burgess IV56c7e882017-03-21 20:08:59 +0000693 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000694 return std::make_pair(Zero, Zero);
695}
696
697SizeOffsetType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000698ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
699 return unknown();
700}
701
702SizeOffsetType
Nuno Lopes55fff832012-06-21 15:45:28 +0000703ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
704 // Easy cases were already folded by previous passes.
705 return unknown();
706}
707
708SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
709 SizeOffsetType PtrData = compute(GEP.getPointerOperand());
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000710 APInt Offset(IntTyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000711 if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
Nuno Lopes55fff832012-06-21 15:45:28 +0000712 return unknown();
713
Nuno Lopes55fff832012-06-21 15:45:28 +0000714 return std::make_pair(PtrData.first, PtrData.second + Offset);
715}
716
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000717SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000718 if (GA.isInterposable())
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000719 return unknown();
720 return compute(GA.getAliasee());
721}
722
Nuno Lopes55fff832012-06-21 15:45:28 +0000723SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
724 if (!GV.hasDefinitiveInitializer())
725 return unknown();
726
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000727 APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000728 return std::make_pair(align(Size, GV.getAlignment()), Zero);
729}
730
731SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
732 // clueless
733 return unknown();
734}
735
736SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
737 ++ObjectVisitorLoad;
738 return unknown();
739}
740
Nadav Rotemabcc64f2013-04-09 18:16:05 +0000741SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
742 // too complex to analyze statically.
743 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000744}
745
746SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
747 SizeOffsetType TrueSide = compute(I.getTrueValue());
748 SizeOffsetType FalseSide = compute(I.getFalseValue());
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000749 if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
750 if (TrueSide == FalseSide) {
751 return TrueSide;
752 }
753
754 APInt TrueResult = getSizeWithOverflow(TrueSide);
755 APInt FalseResult = getSizeWithOverflow(FalseSide);
756
757 if (TrueResult == FalseResult) {
758 return TrueSide;
759 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000760 if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000761 if (TrueResult.slt(FalseResult))
762 return TrueSide;
763 return FalseSide;
764 }
George Burgess IV56c7e882017-03-21 20:08:59 +0000765 if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
Petar Jovanovic644b8c12016-04-13 12:25:25 +0000766 if (TrueResult.sgt(FalseResult))
767 return TrueSide;
768 return FalseSide;
769 }
770 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000771 return unknown();
772}
773
774SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
775 return std::make_pair(Zero, Zero);
776}
777
778SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000779 LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
780 << '\n');
Nuno Lopes55fff832012-06-21 15:45:28 +0000781 return unknown();
782}
783
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000784ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
785 const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
Erik Pilkington600e9de2019-01-30 20:34:35 +0000786 ObjectSizeOpts EvalOpts)
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000787 : DL(DL), TLI(TLI), Context(Context),
788 Builder(Context, TargetFolder(DL),
789 IRBuilderCallbackInserter(
790 [&](Instruction *I) { InsertedInstructions.insert(I); })),
Erik Pilkington600e9de2019-01-30 20:34:35 +0000791 EvalOpts(EvalOpts) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000792 // IntTy and Zero must be set for each compute() since the address space may
793 // be different for later objects.
Nuno Lopes55fff832012-06-21 15:45:28 +0000794}
795
796SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000797 // XXX - Are vectors of pointers possible here?
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000798 IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Matt Arsenaultd3ee7af2013-12-14 00:27:48 +0000799 Zero = ConstantInt::get(IntTy, 0);
800
Nuno Lopes55fff832012-06-21 15:45:28 +0000801 SizeOffsetEvalType Result = compute_(V);
802
803 if (!bothKnown(Result)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000804 // Erase everything that was computed in this iteration from the cache, so
Nuno Lopes55fff832012-06-21 15:45:28 +0000805 // that no dangling references are left behind. We could be a bit smarter if
806 // we kept a dependency graph. It's probably not worth the complexity.
Benjamin Krameraa209152016-06-26 17:27:42 +0000807 for (const Value *SeenVal : SeenVals) {
808 CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
Nuno Lopes55fff832012-06-21 15:45:28 +0000809 // non-computable results can be safely cached
810 if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
811 CacheMap.erase(CacheIt);
812 }
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000813
814 // Erase any instructions we inserted as part of the traversal.
815 for (Instruction *I : InsertedInstructions) {
816 I->replaceAllUsesWith(UndefValue::get(I->getType()));
817 I->eraseFromParent();
818 }
Nuno Lopes55fff832012-06-21 15:45:28 +0000819 }
820
821 SeenVals.clear();
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000822 InsertedInstructions.clear();
Nuno Lopes55fff832012-06-21 15:45:28 +0000823 return Result;
824}
825
826SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
Erik Pilkington600e9de2019-01-30 20:34:35 +0000827 ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
Nuno Lopes55fff832012-06-21 15:45:28 +0000828 SizeOffsetType Const = Visitor.compute(V);
829 if (Visitor.bothKnown(Const))
830 return std::make_pair(ConstantInt::get(Context, Const.first),
831 ConstantInt::get(Context, Const.second));
832
833 V = V->stripPointerCasts();
834
Sanjay Patel490193d2016-07-07 16:19:09 +0000835 // Check cache.
Nuno Lopes55fff832012-06-21 15:45:28 +0000836 CacheMapTy::iterator CacheIt = CacheMap.find(V);
837 if (CacheIt != CacheMap.end())
838 return CacheIt->second;
839
Sanjay Patel490193d2016-07-07 16:19:09 +0000840 // Always generate code immediately before the instruction being
841 // processed, so that the generated code dominates the same BBs.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000842 BuilderTy::InsertPointGuard Guard(Builder);
Nuno Lopes55fff832012-06-21 15:45:28 +0000843 if (Instruction *I = dyn_cast<Instruction>(V))
844 Builder.SetInsertPoint(I);
845
Sanjay Patel490193d2016-07-07 16:19:09 +0000846 // Now compute the size and offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000847 SizeOffsetEvalType Result;
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000848
849 // Record the pointers that were handled in this run, so that they can be
850 // cleaned later if something fails. We also use this set to break cycles that
851 // can occur in dead code.
David Blaikie70573dc2014-11-19 07:49:26 +0000852 if (!SeenVals.insert(V).second) {
Benjamin Kramer155c9d52013-09-29 19:39:13 +0000853 Result = unknown();
854 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000855 Result = visitGEPOperator(*GEP);
856 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
857 Result = visit(*I);
858 } else if (isa<Argument>(V) ||
859 (isa<ConstantExpr>(V) &&
860 cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
Nuno Lopese9d6dbf2012-12-31 16:23:48 +0000861 isa<GlobalAlias>(V) ||
Nuno Lopes55fff832012-06-21 15:45:28 +0000862 isa<GlobalVariable>(V)) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000863 // Ignore values where we cannot do more than ObjectSizeVisitor.
Nuno Lopes55fff832012-06-21 15:45:28 +0000864 Result = unknown();
865 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000866 LLVM_DEBUG(
867 dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
868 << '\n');
Nuno Lopes55fff832012-06-21 15:45:28 +0000869 Result = unknown();
870 }
871
Nuno Lopes55fff832012-06-21 15:45:28 +0000872 // Don't reuse CacheIt since it may be invalid at this point.
873 CacheMap[V] = Result;
874 return Result;
875}
876
877SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
878 if (!I.getAllocatedType()->isSized())
879 return unknown();
880
881 // must be a VLA
882 assert(I.isArrayAllocation());
883 Value *ArraySize = I.getArraySize();
884 Value *Size = ConstantInt::get(ArraySize->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000885 DL.getTypeAllocSize(I.getAllocatedType()));
Nuno Lopes55fff832012-06-21 15:45:28 +0000886 Size = Builder.CreateMul(Size, ArraySize);
887 return std::make_pair(Size, Zero);
888}
889
890SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
George Burgess IVccae43a2016-12-23 01:18:09 +0000891 Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000892 if (!FnData)
893 return unknown();
894
Sanjay Patel490193d2016-07-07 16:19:09 +0000895 // Handle strdup-like functions separately.
Nuno Lopes55fff832012-06-21 15:45:28 +0000896 if (FnData->AllocTy == StrDupLike) {
Nuno Lopesf0626f22012-07-25 18:49:28 +0000897 // TODO
898 return unknown();
Nuno Lopes55fff832012-06-21 15:45:28 +0000899 }
900
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000901 Value *FirstArg = CS.getArgument(FnData->FstParam);
902 FirstArg = Builder.CreateZExt(FirstArg, IntTy);
Nuno Lopesf06b7312012-06-21 18:38:26 +0000903 if (FnData->SndParam < 0)
Nuno Lopes55fff832012-06-21 15:45:28 +0000904 return std::make_pair(FirstArg, Zero);
905
906 Value *SecondArg = CS.getArgument(FnData->SndParam);
Nuno Lopesa6aa3d32012-06-21 16:47:58 +0000907 SecondArg = Builder.CreateZExt(SecondArg, IntTy);
Nuno Lopes55fff832012-06-21 15:45:28 +0000908 Value *Size = Builder.CreateMul(FirstArg, SecondArg);
909 return std::make_pair(Size, Zero);
910
911 // TODO: handle more standard functions (+ wchar cousins):
Nuno Lopesf0626f22012-07-25 18:49:28 +0000912 // - strdup / strndup
Nuno Lopes55fff832012-06-21 15:45:28 +0000913 // - strcpy / strncpy
914 // - strcat / strncat
915 // - memcpy / memmove
Nuno Lopesf0626f22012-07-25 18:49:28 +0000916 // - strcat / strncat
Nuno Lopes55fff832012-06-21 15:45:28 +0000917 // - memset
918}
919
920SizeOffsetEvalType
Nuno Lopes181d67e2012-06-28 16:34:03 +0000921ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
922 return unknown();
923}
924
925SizeOffsetEvalType
926ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
927 return unknown();
928}
929
930SizeOffsetEvalType
Nuno Lopes55fff832012-06-21 15:45:28 +0000931ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
932 SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
933 if (!bothKnown(PtrData))
934 return unknown();
935
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000936 Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
Nuno Lopes55fff832012-06-21 15:45:28 +0000937 Offset = Builder.CreateAdd(PtrData.second, Offset);
938 return std::make_pair(PtrData.first, Offset);
939}
940
941SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
942 // clueless
943 return unknown();
944}
945
946SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
947 return unknown();
948}
949
950SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
Sanjay Patel490193d2016-07-07 16:19:09 +0000951 // Create 2 PHIs: one for size and another for offset.
Nuno Lopes55fff832012-06-21 15:45:28 +0000952 PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
953 PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
954
Sanjay Patel490193d2016-07-07 16:19:09 +0000955 // Insert right away in the cache to handle recursive PHIs.
Nuno Lopes55fff832012-06-21 15:45:28 +0000956 CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
957
Sanjay Patel490193d2016-07-07 16:19:09 +0000958 // Compute offset/size for each PHI incoming pointer.
Nuno Lopes55fff832012-06-21 15:45:28 +0000959 for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000960 Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
Nuno Lopes55fff832012-06-21 15:45:28 +0000961 SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
962
963 if (!bothKnown(EdgeData)) {
964 OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
965 OffsetPHI->eraseFromParent();
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000966 InsertedInstructions.erase(OffsetPHI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000967 SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
968 SizePHI->eraseFromParent();
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000969 InsertedInstructions.erase(SizePHI);
Nuno Lopes55fff832012-06-21 15:45:28 +0000970 return unknown();
971 }
972 SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
973 OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
974 }
Nuno Lopes9291ff42012-07-03 17:13:25 +0000975
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000976 Value *Size = SizePHI, *Offset = OffsetPHI;
977 if (Value *Tmp = SizePHI->hasConstantValue()) {
Nuno Lopes9291ff42012-07-03 17:13:25 +0000978 Size = Tmp;
979 SizePHI->replaceAllUsesWith(Size);
980 SizePHI->eraseFromParent();
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000981 InsertedInstructions.erase(SizePHI);
Nuno Lopes9291ff42012-07-03 17:13:25 +0000982 }
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000983 if (Value *Tmp = OffsetPHI->hasConstantValue()) {
Nuno Lopes9291ff42012-07-03 17:13:25 +0000984 Offset = Tmp;
985 OffsetPHI->replaceAllUsesWith(Offset);
986 OffsetPHI->eraseFromParent();
Erik Pilkingtoncb5c7bd2019-04-10 23:42:11 +0000987 InsertedInstructions.erase(OffsetPHI);
Nuno Lopes9291ff42012-07-03 17:13:25 +0000988 }
989 return std::make_pair(Size, Offset);
Nuno Lopes55fff832012-06-21 15:45:28 +0000990}
991
992SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
993 SizeOffsetEvalType TrueSide = compute_(I.getTrueValue());
994 SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
995
996 if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
997 return unknown();
998 if (TrueSide == FalseSide)
999 return TrueSide;
1000
1001 Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1002 FalseSide.first);
1003 Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1004 FalseSide.second);
1005 return std::make_pair(Size, Offset);
1006}
1007
1008SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001009 LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1010 << '\n');
Nuno Lopes55fff832012-06-21 15:45:28 +00001011 return unknown();
1012}