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