1 //===- MemoryBuiltins.cpp - Identify calls to memory builtins -------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This family of functions identifies calls to builtin functions that allocate
10 // or free memory.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/MemoryBuiltins.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Analysis/TargetFolder.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/Utils/Local.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/IR/Argument.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #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"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <cassert>
44 #include <cstdint>
45 #include <iterator>
46 #include <utility>
47 
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "memory-builtins"
51 
52 enum AllocType : uint8_t {
53   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,
58   MallocOrCallocLike = MallocLike | CallocLike,
59   AllocLike          = MallocLike | CallocLike | StrDupLike,
60   AnyAlloc           = AllocLike | ReallocLike
61 };
62 
63 struct AllocFnsTy {
64   AllocType AllocTy;
65   unsigned NumParams;
66   // First and Second size parameters (or -1 if unused)
67   int FstParam, SndParam;
68 };
69 
70 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
71 // know which functions are nounwind, noalias, nocapture parameters, etc.
72 static 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)
77   {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}},
80   {LibFunc_Znwm,                {OpNewLike,   1, 0,  -1}}, // new(unsigned long)
81   {LibFunc_ZnwmRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new(unsigned long, nothrow)
82   {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}},
85   {LibFunc_Znaj,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned int)
86   {LibFunc_ZnajRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned int, nothrow)
87   {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}},
90   {LibFunc_Znam,                {OpNewLike,   1, 0,  -1}}, // new[](unsigned long)
91   {LibFunc_ZnamRKSt9nothrow_t,  {MallocLike,  2, 0,  -1}}, // new[](unsigned long, nothrow)
92   {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}},
95   {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}}
108   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
109 };
110 
111 static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast,
112                                          bool &IsNoBuiltin) {
113   // Don't care about intrinsics in this case.
114   if (isa<IntrinsicInst>(V))
115     return nullptr;
116 
117   if (LookThroughBitCast)
118     V = V->stripPointerCasts();
119 
120   ImmutableCallSite CS(V);
121   if (!CS.getInstruction())
122     return nullptr;
123 
124   IsNoBuiltin = CS.isNoBuiltin();
125 
126   if (const Function *Callee = CS.getCalledFunction())
127     return Callee;
128   return nullptr;
129 }
130 
131 /// 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.
134 static Optional<AllocFnsTy>
135 getAllocationDataForFunction(const Function *Callee, AllocType AllocTy,
136                              const TargetLibraryInfo *TLI) {
137   // Make sure that the function is available.
138   StringRef FnName = Callee->getName();
139   LibFunc TLIFn;
140   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
141     return None;
142 
143   const auto *Iter = find_if(
144       AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) {
145         return P.first == TLIFn;
146       });
147 
148   if (Iter == std::end(AllocationFnData))
149     return None;
150 
151   const AllocFnsTy *FnData = &Iter->second;
152   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
153     return None;
154 
155   // Check function prototype.
156   int FstParam = FnData->FstParam;
157   int SndParam = FnData->SndParam;
158   FunctionType *FTy = Callee->getFunctionType();
159 
160   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
161       FTy->getNumParams() == FnData->NumParams &&
162       (FstParam < 0 ||
163        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
164         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
165       (SndParam < 0 ||
166        FTy->getParamType(SndParam)->isIntegerTy(32) ||
167        FTy->getParamType(SndParam)->isIntegerTy(64)))
168     return *FnData;
169   return None;
170 }
171 
172 static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy,
173                                               const TargetLibraryInfo *TLI,
174                                               bool LookThroughBitCast = false) {
175   bool IsNoBuiltinCall;
176   if (const Function *Callee =
177           getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
178     if (!IsNoBuiltinCall)
179       return getAllocationDataForFunction(Callee, AllocTy, TLI);
180   return None;
181 }
182 
183 static Optional<AllocFnsTy>
184 getAllocationData(const Value *V, AllocType AllocTy,
185                   function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
186                   bool LookThroughBitCast = false) {
187   bool IsNoBuiltinCall;
188   if (const Function *Callee =
189           getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall))
190     if (!IsNoBuiltinCall)
191       return getAllocationDataForFunction(
192           Callee, AllocTy, &GetTLI(const_cast<Function &>(*Callee)));
193   return None;
194 }
195 
196 static Optional<AllocFnsTy> getAllocationSize(const Value *V,
197                                               const TargetLibraryInfo *TLI) {
198   bool IsNoBuiltinCall;
199   const Function *Callee =
200       getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
201   if (!Callee)
202     return None;
203 
204   // Prefer to use existing information over allocsize. This will give us an
205   // accurate AllocTy.
206   if (!IsNoBuiltinCall)
207     if (Optional<AllocFnsTy> Data =
208             getAllocationDataForFunction(Callee, AnyAlloc, TLI))
209       return Data;
210 
211   Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize);
212   if (Attr == Attribute())
213     return None;
214 
215   std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs();
216 
217   AllocFnsTy Result;
218   // Because allocsize only tells us how many bytes are allocated, we're not
219   // really allowed to assume anything, so we use MallocLike.
220   Result.AllocTy = MallocLike;
221   Result.NumParams = Callee->getNumOperands();
222   Result.FstParam = Args.first;
223   Result.SndParam = Args.second.getValueOr(-1);
224   return Result;
225 }
226 
227 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
228   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
229   return CS && CS.hasRetAttr(Attribute::NoAlias);
230 }
231 
232 /// Tests if a value is a call or invoke to a library function that
233 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
234 /// like).
235 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
236                           bool LookThroughBitCast) {
237   return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue();
238 }
239 bool llvm::isAllocationFn(
240     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
241     bool LookThroughBitCast) {
242   return getAllocationData(V, AnyAlloc, GetTLI, LookThroughBitCast).hasValue();
243 }
244 
245 /// Tests if a value is a call or invoke to a function that returns a
246 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
247 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
248                        bool LookThroughBitCast) {
249   // it's safe to consider realloc as noalias since accessing the original
250   // pointer is undefined behavior
251   return isAllocationFn(V, TLI, LookThroughBitCast) ||
252          hasNoAliasAttr(V, LookThroughBitCast);
253 }
254 
255 /// Tests if a value is a call or invoke to a library function that
256 /// allocates uninitialized memory (such as malloc).
257 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
258                           bool LookThroughBitCast) {
259   return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue();
260 }
261 bool llvm::isMallocLikeFn(
262     const Value *V, function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
263     bool LookThroughBitCast) {
264   return getAllocationData(V, MallocLike, GetTLI, LookThroughBitCast)
265       .hasValue();
266 }
267 
268 /// Tests if a value is a call or invoke to a library function that
269 /// allocates zero-filled memory (such as calloc).
270 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
271                           bool LookThroughBitCast) {
272   return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue();
273 }
274 
275 /// Tests if a value is a call or invoke to a library function that
276 /// allocates memory similar to malloc or calloc.
277 bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
278                                   bool LookThroughBitCast) {
279   return getAllocationData(V, MallocOrCallocLike, TLI,
280                            LookThroughBitCast).hasValue();
281 }
282 
283 /// Tests if a value is a call or invoke to a library function that
284 /// allocates memory (either malloc, calloc, or strdup like).
285 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
286                          bool LookThroughBitCast) {
287   return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue();
288 }
289 
290 /// Tests if a value is a call or invoke to a library function that
291 /// reallocates memory (e.g., realloc).
292 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
293                      bool LookThroughBitCast) {
294   return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast).hasValue();
295 }
296 
297 /// Tests if a functions is a call or invoke to a library function that
298 /// reallocates memory (e.g., realloc).
299 bool llvm::isReallocLikeFn(const Function *F, const TargetLibraryInfo *TLI) {
300   return getAllocationDataForFunction(F, ReallocLike, TLI).hasValue();
301 }
302 
303 /// Tests if a value is a call or invoke to a library function that
304 /// allocates memory and throws if an allocation failed (e.g., new).
305 bool llvm::isOpNewLikeFn(const Value *V, const TargetLibraryInfo *TLI,
306                      bool LookThroughBitCast) {
307   return getAllocationData(V, OpNewLike, TLI, LookThroughBitCast).hasValue();
308 }
309 
310 /// extractMallocCall - Returns the corresponding CallInst if the instruction
311 /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
312 /// ignore InvokeInst here.
313 const CallInst *llvm::extractMallocCall(
314     const Value *I,
315     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
316   return isMallocLikeFn(I, GetTLI) ? dyn_cast<CallInst>(I) : nullptr;
317 }
318 
319 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
320                                const TargetLibraryInfo *TLI,
321                                bool LookThroughSExt = false) {
322   if (!CI)
323     return nullptr;
324 
325   // The size of the malloc's result type must be known to determine array size.
326   Type *T = getMallocAllocatedType(CI, TLI);
327   if (!T || !T->isSized())
328     return nullptr;
329 
330   unsigned ElementSize = DL.getTypeAllocSize(T);
331   if (StructType *ST = dyn_cast<StructType>(T))
332     ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
333 
334   // If malloc call's arg can be determined to be a multiple of ElementSize,
335   // return the multiple.  Otherwise, return NULL.
336   Value *MallocArg = CI->getArgOperand(0);
337   Value *Multiple = nullptr;
338   if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt))
339     return Multiple;
340 
341   return nullptr;
342 }
343 
344 /// getMallocType - Returns the PointerType resulting from the malloc call.
345 /// The PointerType depends on the number of bitcast uses of the malloc call:
346 ///   0: PointerType is the calls' return type.
347 ///   1: PointerType is the bitcast's result type.
348 ///  >1: Unique PointerType cannot be determined, return NULL.
349 PointerType *llvm::getMallocType(const CallInst *CI,
350                                  const TargetLibraryInfo *TLI) {
351   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
352 
353   PointerType *MallocType = nullptr;
354   unsigned NumOfBitCastUses = 0;
355 
356   // Determine if CallInst has a bitcast use.
357   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
358        UI != E;)
359     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
360       MallocType = cast<PointerType>(BCI->getDestTy());
361       NumOfBitCastUses++;
362     }
363 
364   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
365   if (NumOfBitCastUses == 1)
366     return MallocType;
367 
368   // Malloc call was not bitcast, so type is the malloc function's return type.
369   if (NumOfBitCastUses == 0)
370     return cast<PointerType>(CI->getType());
371 
372   // Type could not be determined.
373   return nullptr;
374 }
375 
376 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
377 /// The Type depends on the number of bitcast uses of the malloc call:
378 ///   0: PointerType is the malloc calls' return type.
379 ///   1: PointerType is the bitcast's result type.
380 ///  >1: Unique PointerType cannot be determined, return NULL.
381 Type *llvm::getMallocAllocatedType(const CallInst *CI,
382                                    const TargetLibraryInfo *TLI) {
383   PointerType *PT = getMallocType(CI, TLI);
384   return PT ? PT->getElementType() : nullptr;
385 }
386 
387 /// getMallocArraySize - Returns the array size of a malloc call.  If the
388 /// argument passed to malloc is a multiple of the size of the malloced type,
389 /// then return that multiple.  For non-array mallocs, the multiple is
390 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
391 /// determined.
392 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
393                                 const TargetLibraryInfo *TLI,
394                                 bool LookThroughSExt) {
395   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
396   return computeArraySize(CI, DL, TLI, LookThroughSExt);
397 }
398 
399 /// extractCallocCall - Returns the corresponding CallInst if the instruction
400 /// is a calloc call.
401 const CallInst *llvm::extractCallocCall(const Value *I,
402                                         const TargetLibraryInfo *TLI) {
403   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
404 }
405 
406 /// isLibFreeFunction - Returns true if the function is a builtin free()
407 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
408   unsigned ExpectedNumParams;
409   if (TLIFn == LibFunc_free ||
410       TLIFn == LibFunc_ZdlPv || // operator delete(void*)
411       TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
412       TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
413       TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
414       TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
415       TLIFn == LibFunc_msvc_delete_array_ptr64)   // operator delete[](void*)
416     ExpectedNumParams = 1;
417   else if (TLIFn == LibFunc_ZdlPvj ||              // delete(void*, uint)
418            TLIFn == LibFunc_ZdlPvm ||              // delete(void*, ulong)
419            TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
420            TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
421            TLIFn == LibFunc_ZdaPvj ||              // delete[](void*, uint)
422            TLIFn == LibFunc_ZdaPvm ||              // delete[](void*, ulong)
423            TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
424            TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
425            TLIFn == LibFunc_msvc_delete_ptr32_int ||      // delete(void*, uint)
426            TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
427            TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
428            TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
429            TLIFn == LibFunc_msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
430            TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
431            TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
432            TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow)   // delete[](void*, nothrow)
433     ExpectedNumParams = 2;
434   else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
435            TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow)
436     ExpectedNumParams = 3;
437   else
438     return false;
439 
440   // Check free prototype.
441   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
442   // attribute will exist.
443   FunctionType *FTy = F->getFunctionType();
444   if (!FTy->getReturnType()->isVoidTy())
445     return false;
446   if (FTy->getNumParams() != ExpectedNumParams)
447     return false;
448   if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
449     return false;
450 
451   return true;
452 }
453 
454 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
455 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
456   bool IsNoBuiltinCall;
457   const Function *Callee =
458       getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
459   if (Callee == nullptr || IsNoBuiltinCall)
460     return nullptr;
461 
462   StringRef FnName = Callee->getName();
463   LibFunc TLIFn;
464   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
465     return nullptr;
466 
467   return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
468 }
469 
470 
471 //===----------------------------------------------------------------------===//
472 //  Utility functions to compute size of objects.
473 //
474 static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
475   if (Data.second.isNegative() || Data.first.ult(Data.second))
476     return APInt(Data.first.getBitWidth(), 0);
477   return Data.first - Data.second;
478 }
479 
480 /// Compute the size of the object pointed by Ptr. Returns true and the
481 /// object size in Size if successful, and false otherwise.
482 /// If RoundToAlign is true, then Size is rounded up to the alignment of
483 /// allocas, byval arguments, and global variables.
484 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
485                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
486   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
487   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
488   if (!Visitor.bothKnown(Data))
489     return false;
490 
491   Size = getSizeWithOverflow(Data).getZExtValue();
492   return true;
493 }
494 
495 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
496                                  const DataLayout &DL,
497                                  const TargetLibraryInfo *TLI,
498                                  bool MustSucceed) {
499   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
500          "ObjectSize must be a call to llvm.objectsize!");
501 
502   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
503   ObjectSizeOpts EvalOptions;
504   // Unless we have to fold this to something, try to be as accurate as
505   // possible.
506   if (MustSucceed)
507     EvalOptions.EvalMode =
508         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
509   else
510     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
511 
512   EvalOptions.NullIsUnknownSize =
513       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
514 
515   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
516   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
517   if (StaticOnly) {
518     // FIXME: Does it make sense to just return a failure value if the size won't
519     // fit in the output and `!MustSucceed`?
520     uint64_t Size;
521     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
522         isUIntN(ResultType->getBitWidth(), Size))
523       return ConstantInt::get(ResultType, Size);
524   } else {
525     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
526     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
527     SizeOffsetEvalType SizeOffsetPair =
528         Eval.compute(ObjectSize->getArgOperand(0));
529 
530     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
531       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
532       Builder.SetInsertPoint(ObjectSize);
533 
534       // If we've outside the end of the object, then we can always access
535       // exactly 0 bytes.
536       Value *ResultSize =
537           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
538       Value *UseZero =
539           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
540       return Builder.CreateSelect(UseZero, ConstantInt::get(ResultType, 0),
541                                   ResultSize);
542     }
543   }
544 
545   if (!MustSucceed)
546     return nullptr;
547 
548   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
549 }
550 
551 STATISTIC(ObjectVisitorArgument,
552           "Number of arguments with unsolved size and offset");
553 STATISTIC(ObjectVisitorLoad,
554           "Number of load instructions with unsolved size and offset");
555 
556 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
557   if (Options.RoundToAlign && Align)
558     return APInt(IntTyBits, alignTo(Size.getZExtValue(), llvm::Align(Align)));
559   return Size;
560 }
561 
562 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
563                                                  const TargetLibraryInfo *TLI,
564                                                  LLVMContext &Context,
565                                                  ObjectSizeOpts Options)
566     : DL(DL), TLI(TLI), Options(Options) {
567   // Pointer size must be rechecked for each object visited since it could have
568   // a different address space.
569 }
570 
571 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
572   IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
573   Zero = APInt::getNullValue(IntTyBits);
574 
575   V = V->stripPointerCasts();
576   if (Instruction *I = dyn_cast<Instruction>(V)) {
577     // If we have already seen this instruction, bail out. Cycles can happen in
578     // unreachable code after constant propagation.
579     if (!SeenInsts.insert(I).second)
580       return unknown();
581 
582     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
583       return visitGEPOperator(*GEP);
584     return visit(*I);
585   }
586   if (Argument *A = dyn_cast<Argument>(V))
587     return visitArgument(*A);
588   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
589     return visitConstantPointerNull(*P);
590   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
591     return visitGlobalAlias(*GA);
592   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
593     return visitGlobalVariable(*GV);
594   if (UndefValue *UV = dyn_cast<UndefValue>(V))
595     return visitUndefValue(*UV);
596   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
597     if (CE->getOpcode() == Instruction::IntToPtr)
598       return unknown(); // clueless
599     if (CE->getOpcode() == Instruction::GetElementPtr)
600       return visitGEPOperator(cast<GEPOperator>(*CE));
601   }
602 
603   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
604                     << *V << '\n');
605   return unknown();
606 }
607 
608 /// When we're compiling N-bit code, and the user uses parameters that are
609 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
610 /// trouble with APInt size issues. This function handles resizing + overflow
611 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
612 /// I's value.
613 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
614   // More bits than we can handle. Checking the bit width isn't necessary, but
615   // it's faster than checking active bits, and should give `false` in the
616   // vast majority of cases.
617   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
618     return false;
619   if (I.getBitWidth() != IntTyBits)
620     I = I.zextOrTrunc(IntTyBits);
621   return true;
622 }
623 
624 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
625   if (!I.getAllocatedType()->isSized())
626     return unknown();
627 
628   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
629   if (!I.isArrayAllocation())
630     return std::make_pair(align(Size, I.getAlignment()), Zero);
631 
632   Value *ArraySize = I.getArraySize();
633   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
634     APInt NumElems = C->getValue();
635     if (!CheckedZextOrTrunc(NumElems))
636       return unknown();
637 
638     bool Overflow;
639     Size = Size.umul_ov(NumElems, Overflow);
640     return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
641                                                  Zero);
642   }
643   return unknown();
644 }
645 
646 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
647   // No interprocedural analysis is done at the moment.
648   if (!A.hasByValOrInAllocaAttr()) {
649     ++ObjectVisitorArgument;
650     return unknown();
651   }
652   PointerType *PT = cast<PointerType>(A.getType());
653   APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
654   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
655 }
656 
657 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
658   Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
659   if (!FnData)
660     return unknown();
661 
662   // Handle strdup-like functions separately.
663   if (FnData->AllocTy == StrDupLike) {
664     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
665     if (!Size)
666       return unknown();
667 
668     // Strndup limits strlen.
669     if (FnData->FstParam > 0) {
670       ConstantInt *Arg =
671           dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
672       if (!Arg)
673         return unknown();
674 
675       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
676       if (Size.ugt(MaxSize))
677         Size = MaxSize + 1;
678     }
679     return std::make_pair(Size, Zero);
680   }
681 
682   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
683   if (!Arg)
684     return unknown();
685 
686   APInt Size = Arg->getValue();
687   if (!CheckedZextOrTrunc(Size))
688     return unknown();
689 
690   // Size is determined by just 1 parameter.
691   if (FnData->SndParam < 0)
692     return std::make_pair(Size, Zero);
693 
694   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
695   if (!Arg)
696     return unknown();
697 
698   APInt NumElems = Arg->getValue();
699   if (!CheckedZextOrTrunc(NumElems))
700     return unknown();
701 
702   bool Overflow;
703   Size = Size.umul_ov(NumElems, Overflow);
704   return Overflow ? unknown() : std::make_pair(Size, Zero);
705 
706   // TODO: handle more standard functions (+ wchar cousins):
707   // - strdup / strndup
708   // - strcpy / strncpy
709   // - strcat / strncat
710   // - memcpy / memmove
711   // - strcat / strncat
712   // - memset
713 }
714 
715 SizeOffsetType
716 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
717   // If null is unknown, there's nothing we can do. Additionally, non-zero
718   // address spaces can make use of null, so we don't presume to know anything
719   // about that.
720   //
721   // TODO: How should this work with address space casts? We currently just drop
722   // them on the floor, but it's unclear what we should do when a NULL from
723   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
724   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
725     return unknown();
726   return std::make_pair(Zero, Zero);
727 }
728 
729 SizeOffsetType
730 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
731   return unknown();
732 }
733 
734 SizeOffsetType
735 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
736   // Easy cases were already folded by previous passes.
737   return unknown();
738 }
739 
740 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
741   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
742   APInt Offset(IntTyBits, 0);
743   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
744     return unknown();
745 
746   return std::make_pair(PtrData.first, PtrData.second + Offset);
747 }
748 
749 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
750   if (GA.isInterposable())
751     return unknown();
752   return compute(GA.getAliasee());
753 }
754 
755 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
756   if (!GV.hasDefinitiveInitializer())
757     return unknown();
758 
759   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
760   return std::make_pair(align(Size, GV.getAlignment()), Zero);
761 }
762 
763 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
764   // clueless
765   return unknown();
766 }
767 
768 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
769   ++ObjectVisitorLoad;
770   return unknown();
771 }
772 
773 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
774   // too complex to analyze statically.
775   return unknown();
776 }
777 
778 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
779   SizeOffsetType TrueSide  = compute(I.getTrueValue());
780   SizeOffsetType FalseSide = compute(I.getFalseValue());
781   if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
782     if (TrueSide == FalseSide) {
783         return TrueSide;
784     }
785 
786     APInt TrueResult = getSizeWithOverflow(TrueSide);
787     APInt FalseResult = getSizeWithOverflow(FalseSide);
788 
789     if (TrueResult == FalseResult) {
790       return TrueSide;
791     }
792     if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
793       if (TrueResult.slt(FalseResult))
794         return TrueSide;
795       return FalseSide;
796     }
797     if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
798       if (TrueResult.sgt(FalseResult))
799         return TrueSide;
800       return FalseSide;
801     }
802   }
803   return unknown();
804 }
805 
806 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
807   return std::make_pair(Zero, Zero);
808 }
809 
810 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
811   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
812                     << '\n');
813   return unknown();
814 }
815 
816 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
817     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
818     ObjectSizeOpts EvalOpts)
819     : DL(DL), TLI(TLI), Context(Context),
820       Builder(Context, TargetFolder(DL),
821               IRBuilderCallbackInserter(
822                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
823       EvalOpts(EvalOpts) {
824   // IntTy and Zero must be set for each compute() since the address space may
825   // be different for later objects.
826 }
827 
828 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
829   // XXX - Are vectors of pointers possible here?
830   IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
831   Zero = ConstantInt::get(IntTy, 0);
832 
833   SizeOffsetEvalType Result = compute_(V);
834 
835   if (!bothKnown(Result)) {
836     // Erase everything that was computed in this iteration from the cache, so
837     // that no dangling references are left behind. We could be a bit smarter if
838     // we kept a dependency graph. It's probably not worth the complexity.
839     for (const Value *SeenVal : SeenVals) {
840       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
841       // non-computable results can be safely cached
842       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
843         CacheMap.erase(CacheIt);
844     }
845 
846     // Erase any instructions we inserted as part of the traversal.
847     for (Instruction *I : InsertedInstructions) {
848       I->replaceAllUsesWith(UndefValue::get(I->getType()));
849       I->eraseFromParent();
850     }
851   }
852 
853   SeenVals.clear();
854   InsertedInstructions.clear();
855   return Result;
856 }
857 
858 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
859   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
860   SizeOffsetType Const = Visitor.compute(V);
861   if (Visitor.bothKnown(Const))
862     return std::make_pair(ConstantInt::get(Context, Const.first),
863                           ConstantInt::get(Context, Const.second));
864 
865   V = V->stripPointerCasts();
866 
867   // Check cache.
868   CacheMapTy::iterator CacheIt = CacheMap.find(V);
869   if (CacheIt != CacheMap.end())
870     return CacheIt->second;
871 
872   // Always generate code immediately before the instruction being
873   // processed, so that the generated code dominates the same BBs.
874   BuilderTy::InsertPointGuard Guard(Builder);
875   if (Instruction *I = dyn_cast<Instruction>(V))
876     Builder.SetInsertPoint(I);
877 
878   // Now compute the size and offset.
879   SizeOffsetEvalType Result;
880 
881   // Record the pointers that were handled in this run, so that they can be
882   // cleaned later if something fails. We also use this set to break cycles that
883   // can occur in dead code.
884   if (!SeenVals.insert(V).second) {
885     Result = unknown();
886   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
887     Result = visitGEPOperator(*GEP);
888   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
889     Result = visit(*I);
890   } else if (isa<Argument>(V) ||
891              (isa<ConstantExpr>(V) &&
892               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
893              isa<GlobalAlias>(V) ||
894              isa<GlobalVariable>(V)) {
895     // Ignore values where we cannot do more than ObjectSizeVisitor.
896     Result = unknown();
897   } else {
898     LLVM_DEBUG(
899         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
900                << '\n');
901     Result = unknown();
902   }
903 
904   // Don't reuse CacheIt since it may be invalid at this point.
905   CacheMap[V] = Result;
906   return Result;
907 }
908 
909 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
910   if (!I.getAllocatedType()->isSized())
911     return unknown();
912 
913   // must be a VLA
914   assert(I.isArrayAllocation());
915   Value *ArraySize = I.getArraySize();
916   Value *Size = ConstantInt::get(ArraySize->getType(),
917                                  DL.getTypeAllocSize(I.getAllocatedType()));
918   Size = Builder.CreateMul(Size, ArraySize);
919   return std::make_pair(Size, Zero);
920 }
921 
922 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
923   Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI);
924   if (!FnData)
925     return unknown();
926 
927   // Handle strdup-like functions separately.
928   if (FnData->AllocTy == StrDupLike) {
929     // TODO
930     return unknown();
931   }
932 
933   Value *FirstArg = CS.getArgument(FnData->FstParam);
934   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
935   if (FnData->SndParam < 0)
936     return std::make_pair(FirstArg, Zero);
937 
938   Value *SecondArg = CS.getArgument(FnData->SndParam);
939   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
940   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
941   return std::make_pair(Size, Zero);
942 
943   // TODO: handle more standard functions (+ wchar cousins):
944   // - strdup / strndup
945   // - strcpy / strncpy
946   // - strcat / strncat
947   // - memcpy / memmove
948   // - strcat / strncat
949   // - memset
950 }
951 
952 SizeOffsetEvalType
953 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
954   return unknown();
955 }
956 
957 SizeOffsetEvalType
958 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
959   return unknown();
960 }
961 
962 SizeOffsetEvalType
963 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
964   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
965   if (!bothKnown(PtrData))
966     return unknown();
967 
968   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
969   Offset = Builder.CreateAdd(PtrData.second, Offset);
970   return std::make_pair(PtrData.first, Offset);
971 }
972 
973 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
974   // clueless
975   return unknown();
976 }
977 
978 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
979   return unknown();
980 }
981 
982 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
983   // Create 2 PHIs: one for size and another for offset.
984   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
985   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
986 
987   // Insert right away in the cache to handle recursive PHIs.
988   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
989 
990   // Compute offset/size for each PHI incoming pointer.
991   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
992     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
993     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
994 
995     if (!bothKnown(EdgeData)) {
996       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
997       OffsetPHI->eraseFromParent();
998       InsertedInstructions.erase(OffsetPHI);
999       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
1000       SizePHI->eraseFromParent();
1001       InsertedInstructions.erase(SizePHI);
1002       return unknown();
1003     }
1004     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1005     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1006   }
1007 
1008   Value *Size = SizePHI, *Offset = OffsetPHI;
1009   if (Value *Tmp = SizePHI->hasConstantValue()) {
1010     Size = Tmp;
1011     SizePHI->replaceAllUsesWith(Size);
1012     SizePHI->eraseFromParent();
1013     InsertedInstructions.erase(SizePHI);
1014   }
1015   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1016     Offset = Tmp;
1017     OffsetPHI->replaceAllUsesWith(Offset);
1018     OffsetPHI->eraseFromParent();
1019     InsertedInstructions.erase(OffsetPHI);
1020   }
1021   return std::make_pair(Size, Offset);
1022 }
1023 
1024 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
1025   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
1026   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1027 
1028   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1029     return unknown();
1030   if (TrueSide == FalseSide)
1031     return TrueSide;
1032 
1033   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1034                                      FalseSide.first);
1035   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1036                                        FalseSide.second);
1037   return std::make_pair(Size, Offset);
1038 }
1039 
1040 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1041   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1042                     << '\n');
1043   return unknown();
1044 }
1045