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 (const User *U : CI->users())
382     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
383       MallocType = cast<PointerType>(BCI->getDestTy());
384       NumOfBitCastUses++;
385     }
386 
387   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
388   if (NumOfBitCastUses == 1)
389     return MallocType;
390 
391   // Malloc call was not bitcast, so type is the malloc function's return type.
392   if (NumOfBitCastUses == 0)
393     return cast<PointerType>(CI->getType());
394 
395   // Type could not be determined.
396   return nullptr;
397 }
398 
399 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
400 /// The Type depends on the number of bitcast uses of the malloc call:
401 ///   0: PointerType is the malloc calls' return type.
402 ///   1: PointerType is the bitcast's result type.
403 ///  >1: Unique PointerType cannot be determined, return NULL.
404 Type *llvm::getMallocAllocatedType(const CallInst *CI,
405                                    const TargetLibraryInfo *TLI) {
406   PointerType *PT = getMallocType(CI, TLI);
407   return PT ? PT->getElementType() : nullptr;
408 }
409 
410 /// getMallocArraySize - Returns the array size of a malloc call.  If the
411 /// argument passed to malloc is a multiple of the size of the malloced type,
412 /// then return that multiple.  For non-array mallocs, the multiple is
413 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
414 /// determined.
415 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
416                                 const TargetLibraryInfo *TLI,
417                                 bool LookThroughSExt) {
418   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
419   return computeArraySize(CI, DL, TLI, LookThroughSExt);
420 }
421 
422 /// extractCallocCall - Returns the corresponding CallInst if the instruction
423 /// is a calloc call.
424 const CallInst *llvm::extractCallocCall(const Value *I,
425                                         const TargetLibraryInfo *TLI) {
426   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
427 }
428 
429 /// isLibFreeFunction - Returns true if the function is a builtin free()
430 bool llvm::isLibFreeFunction(const Function *F, const LibFunc TLIFn) {
431   unsigned ExpectedNumParams;
432   if (TLIFn == LibFunc_free ||
433       TLIFn == LibFunc_ZdlPv || // operator delete(void*)
434       TLIFn == LibFunc_ZdaPv || // operator delete[](void*)
435       TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*)
436       TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*)
437       TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*)
438       TLIFn == LibFunc_msvc_delete_array_ptr64)   // operator delete[](void*)
439     ExpectedNumParams = 1;
440   else if (TLIFn == LibFunc_ZdlPvj ||              // delete(void*, uint)
441            TLIFn == LibFunc_ZdlPvm ||              // delete(void*, ulong)
442            TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
443            TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t)
444            TLIFn == LibFunc_ZdaPvj ||              // delete[](void*, uint)
445            TLIFn == LibFunc_ZdaPvm ||              // delete[](void*, ulong)
446            TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow)
447            TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t)
448            TLIFn == LibFunc_msvc_delete_ptr32_int ||      // delete(void*, uint)
449            TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong)
450            TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow)
451            TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow)
452            TLIFn == LibFunc_msvc_delete_array_ptr32_int ||      // delete[](void*, uint)
453            TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong)
454            TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow)
455            TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow)   // delete[](void*, nothrow)
456     ExpectedNumParams = 2;
457   else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow)
458            TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t || // delete[](void*, align_val_t, nothrow)
459            TLIFn == LibFunc_ZdlPvjSt11align_val_t || // delete(void*, unsigned long, align_val_t)
460            TLIFn == LibFunc_ZdlPvmSt11align_val_t || // delete(void*, unsigned long, align_val_t)
461            TLIFn == LibFunc_ZdaPvjSt11align_val_t || // delete[](void*, unsigned int, align_val_t)
462            TLIFn == LibFunc_ZdaPvmSt11align_val_t) // delete[](void*, unsigned long, align_val_t)
463     ExpectedNumParams = 3;
464   else
465     return false;
466 
467   // Check free prototype.
468   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
469   // attribute will exist.
470   FunctionType *FTy = F->getFunctionType();
471   if (!FTy->getReturnType()->isVoidTy())
472     return false;
473   if (FTy->getNumParams() != ExpectedNumParams)
474     return false;
475   if (FTy->getParamType(0) != Type::getInt8PtrTy(F->getContext()))
476     return false;
477 
478   return true;
479 }
480 
481 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
482 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
483   bool IsNoBuiltinCall;
484   const Function *Callee =
485       getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall);
486   if (Callee == nullptr || IsNoBuiltinCall)
487     return nullptr;
488 
489   StringRef FnName = Callee->getName();
490   LibFunc TLIFn;
491   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
492     return nullptr;
493 
494   return isLibFreeFunction(Callee, TLIFn) ? dyn_cast<CallInst>(I) : nullptr;
495 }
496 
497 
498 //===----------------------------------------------------------------------===//
499 //  Utility functions to compute size of objects.
500 //
501 static APInt getSizeWithOverflow(const SizeOffsetType &Data) {
502   if (Data.second.isNegative() || Data.first.ult(Data.second))
503     return APInt(Data.first.getBitWidth(), 0);
504   return Data.first - Data.second;
505 }
506 
507 /// Compute the size of the object pointed by Ptr. Returns true and the
508 /// object size in Size if successful, and false otherwise.
509 /// If RoundToAlign is true, then Size is rounded up to the alignment of
510 /// allocas, byval arguments, and global variables.
511 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
512                          const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) {
513   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts);
514   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
515   if (!Visitor.bothKnown(Data))
516     return false;
517 
518   Size = getSizeWithOverflow(Data).getZExtValue();
519   return true;
520 }
521 
522 Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize,
523                                  const DataLayout &DL,
524                                  const TargetLibraryInfo *TLI,
525                                  bool MustSucceed) {
526   assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize &&
527          "ObjectSize must be a call to llvm.objectsize!");
528 
529   bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero();
530   ObjectSizeOpts EvalOptions;
531   // Unless we have to fold this to something, try to be as accurate as
532   // possible.
533   if (MustSucceed)
534     EvalOptions.EvalMode =
535         MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min;
536   else
537     EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact;
538 
539   EvalOptions.NullIsUnknownSize =
540       cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne();
541 
542   auto *ResultType = cast<IntegerType>(ObjectSize->getType());
543   bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero();
544   if (StaticOnly) {
545     // FIXME: Does it make sense to just return a failure value if the size won't
546     // fit in the output and `!MustSucceed`?
547     uint64_t Size;
548     if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) &&
549         isUIntN(ResultType->getBitWidth(), Size))
550       return ConstantInt::get(ResultType, Size);
551   } else {
552     LLVMContext &Ctx = ObjectSize->getFunction()->getContext();
553     ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions);
554     SizeOffsetEvalType SizeOffsetPair =
555         Eval.compute(ObjectSize->getArgOperand(0));
556 
557     if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) {
558       IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL));
559       Builder.SetInsertPoint(ObjectSize);
560 
561       // If we've outside the end of the object, then we can always access
562       // exactly 0 bytes.
563       Value *ResultSize =
564           Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second);
565       Value *UseZero =
566           Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second);
567       ResultSize = Builder.CreateZExtOrTrunc(ResultSize, ResultType);
568       Value *Ret = Builder.CreateSelect(
569           UseZero, ConstantInt::get(ResultType, 0), ResultSize);
570 
571       // The non-constant size expression cannot evaluate to -1.
572       if (!isa<Constant>(SizeOffsetPair.first) ||
573           !isa<Constant>(SizeOffsetPair.second))
574         Builder.CreateAssumption(
575             Builder.CreateICmpNE(Ret, ConstantInt::get(ResultType, -1)));
576 
577       return Ret;
578     }
579   }
580 
581   if (!MustSucceed)
582     return nullptr;
583 
584   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
585 }
586 
587 STATISTIC(ObjectVisitorArgument,
588           "Number of arguments with unsolved size and offset");
589 STATISTIC(ObjectVisitorLoad,
590           "Number of load instructions with unsolved size and offset");
591 
592 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Alignment) {
593   if (Options.RoundToAlign && Alignment)
594     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align(Alignment)));
595   return Size;
596 }
597 
598 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
599                                                  const TargetLibraryInfo *TLI,
600                                                  LLVMContext &Context,
601                                                  ObjectSizeOpts Options)
602     : DL(DL), TLI(TLI), Options(Options) {
603   // Pointer size must be rechecked for each object visited since it could have
604   // a different address space.
605 }
606 
607 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
608   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
609   Zero = APInt::getNullValue(IntTyBits);
610 
611   V = V->stripPointerCasts();
612   if (Instruction *I = dyn_cast<Instruction>(V)) {
613     // If we have already seen this instruction, bail out. Cycles can happen in
614     // unreachable code after constant propagation.
615     if (!SeenInsts.insert(I).second)
616       return unknown();
617 
618     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
619       return visitGEPOperator(*GEP);
620     return visit(*I);
621   }
622   if (Argument *A = dyn_cast<Argument>(V))
623     return visitArgument(*A);
624   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
625     return visitConstantPointerNull(*P);
626   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
627     return visitGlobalAlias(*GA);
628   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
629     return visitGlobalVariable(*GV);
630   if (UndefValue *UV = dyn_cast<UndefValue>(V))
631     return visitUndefValue(*UV);
632   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
633     if (CE->getOpcode() == Instruction::IntToPtr)
634       return unknown(); // clueless
635     if (CE->getOpcode() == Instruction::GetElementPtr)
636       return visitGEPOperator(cast<GEPOperator>(*CE));
637   }
638 
639   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
640                     << *V << '\n');
641   return unknown();
642 }
643 
644 /// When we're compiling N-bit code, and the user uses parameters that are
645 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
646 /// trouble with APInt size issues. This function handles resizing + overflow
647 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
648 /// I's value.
649 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
650   // More bits than we can handle. Checking the bit width isn't necessary, but
651   // it's faster than checking active bits, and should give `false` in the
652   // vast majority of cases.
653   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
654     return false;
655   if (I.getBitWidth() != IntTyBits)
656     I = I.zextOrTrunc(IntTyBits);
657   return true;
658 }
659 
660 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
661   if (!I.getAllocatedType()->isSized())
662     return unknown();
663 
664   if (isa<ScalableVectorType>(I.getAllocatedType()))
665     return unknown();
666 
667   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
668   if (!I.isArrayAllocation())
669     return std::make_pair(align(Size, I.getAlignment()), Zero);
670 
671   Value *ArraySize = I.getArraySize();
672   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
673     APInt NumElems = C->getValue();
674     if (!CheckedZextOrTrunc(NumElems))
675       return unknown();
676 
677     bool Overflow;
678     Size = Size.umul_ov(NumElems, Overflow);
679     return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
680                                                  Zero);
681   }
682   return unknown();
683 }
684 
685 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
686   Type *MemoryTy = A.getPointeeInMemoryValueType();
687   // No interprocedural analysis is done at the moment.
688   if (!MemoryTy|| !MemoryTy->isSized()) {
689     ++ObjectVisitorArgument;
690     return unknown();
691   }
692 
693   APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
694   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
695 }
696 
697 SizeOffsetType ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
698   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
699   if (!FnData)
700     return unknown();
701 
702   // Handle strdup-like functions separately.
703   if (FnData->AllocTy == StrDupLike) {
704     APInt Size(IntTyBits, GetStringLength(CB.getArgOperand(0)));
705     if (!Size)
706       return unknown();
707 
708     // Strndup limits strlen.
709     if (FnData->FstParam > 0) {
710       ConstantInt *Arg =
711           dyn_cast<ConstantInt>(CB.getArgOperand(FnData->FstParam));
712       if (!Arg)
713         return unknown();
714 
715       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
716       if (Size.ugt(MaxSize))
717         Size = MaxSize + 1;
718     }
719     return std::make_pair(Size, Zero);
720   }
721 
722   ConstantInt *Arg = dyn_cast<ConstantInt>(CB.getArgOperand(FnData->FstParam));
723   if (!Arg)
724     return unknown();
725 
726   APInt Size = Arg->getValue();
727   if (!CheckedZextOrTrunc(Size))
728     return unknown();
729 
730   // Size is determined by just 1 parameter.
731   if (FnData->SndParam < 0)
732     return std::make_pair(Size, Zero);
733 
734   Arg = dyn_cast<ConstantInt>(CB.getArgOperand(FnData->SndParam));
735   if (!Arg)
736     return unknown();
737 
738   APInt NumElems = Arg->getValue();
739   if (!CheckedZextOrTrunc(NumElems))
740     return unknown();
741 
742   bool Overflow;
743   Size = Size.umul_ov(NumElems, Overflow);
744   return Overflow ? unknown() : std::make_pair(Size, Zero);
745 
746   // TODO: handle more standard functions (+ wchar cousins):
747   // - strdup / strndup
748   // - strcpy / strncpy
749   // - strcat / strncat
750   // - memcpy / memmove
751   // - strcat / strncat
752   // - memset
753 }
754 
755 SizeOffsetType
756 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
757   // If null is unknown, there's nothing we can do. Additionally, non-zero
758   // address spaces can make use of null, so we don't presume to know anything
759   // about that.
760   //
761   // TODO: How should this work with address space casts? We currently just drop
762   // them on the floor, but it's unclear what we should do when a NULL from
763   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
764   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
765     return unknown();
766   return std::make_pair(Zero, Zero);
767 }
768 
769 SizeOffsetType
770 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
771   return unknown();
772 }
773 
774 SizeOffsetType
775 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
776   // Easy cases were already folded by previous passes.
777   return unknown();
778 }
779 
780 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
781   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
782   APInt Offset(DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()), 0);
783   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
784     return unknown();
785 
786   return std::make_pair(PtrData.first, PtrData.second + Offset);
787 }
788 
789 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
790   if (GA.isInterposable())
791     return unknown();
792   return compute(GA.getAliasee());
793 }
794 
795 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
796   if (!GV.hasDefinitiveInitializer())
797     return unknown();
798 
799   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
800   return std::make_pair(align(Size, GV.getAlignment()), Zero);
801 }
802 
803 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
804   // clueless
805   return unknown();
806 }
807 
808 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
809   ++ObjectVisitorLoad;
810   return unknown();
811 }
812 
813 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
814   // too complex to analyze statically.
815   return unknown();
816 }
817 
818 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
819   SizeOffsetType TrueSide  = compute(I.getTrueValue());
820   SizeOffsetType FalseSide = compute(I.getFalseValue());
821   if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
822     if (TrueSide == FalseSide) {
823         return TrueSide;
824     }
825 
826     APInt TrueResult = getSizeWithOverflow(TrueSide);
827     APInt FalseResult = getSizeWithOverflow(FalseSide);
828 
829     if (TrueResult == FalseResult) {
830       return TrueSide;
831     }
832     if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
833       if (TrueResult.slt(FalseResult))
834         return TrueSide;
835       return FalseSide;
836     }
837     if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
838       if (TrueResult.sgt(FalseResult))
839         return TrueSide;
840       return FalseSide;
841     }
842   }
843   return unknown();
844 }
845 
846 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
847   return std::make_pair(Zero, Zero);
848 }
849 
850 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
851   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
852                     << '\n');
853   return unknown();
854 }
855 
856 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
857     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
858     ObjectSizeOpts EvalOpts)
859     : DL(DL), TLI(TLI), Context(Context),
860       Builder(Context, TargetFolder(DL),
861               IRBuilderCallbackInserter(
862                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
863       EvalOpts(EvalOpts) {
864   // IntTy and Zero must be set for each compute() since the address space may
865   // be different for later objects.
866 }
867 
868 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
869   // XXX - Are vectors of pointers possible here?
870   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
871   Zero = ConstantInt::get(IntTy, 0);
872 
873   SizeOffsetEvalType Result = compute_(V);
874 
875   if (!bothKnown(Result)) {
876     // Erase everything that was computed in this iteration from the cache, so
877     // that no dangling references are left behind. We could be a bit smarter if
878     // we kept a dependency graph. It's probably not worth the complexity.
879     for (const Value *SeenVal : SeenVals) {
880       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
881       // non-computable results can be safely cached
882       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
883         CacheMap.erase(CacheIt);
884     }
885 
886     // Erase any instructions we inserted as part of the traversal.
887     for (Instruction *I : InsertedInstructions) {
888       I->replaceAllUsesWith(UndefValue::get(I->getType()));
889       I->eraseFromParent();
890     }
891   }
892 
893   SeenVals.clear();
894   InsertedInstructions.clear();
895   return Result;
896 }
897 
898 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
899   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
900   SizeOffsetType Const = Visitor.compute(V);
901   if (Visitor.bothKnown(Const))
902     return std::make_pair(ConstantInt::get(Context, Const.first),
903                           ConstantInt::get(Context, Const.second));
904 
905   V = V->stripPointerCasts();
906 
907   // Check cache.
908   CacheMapTy::iterator CacheIt = CacheMap.find(V);
909   if (CacheIt != CacheMap.end())
910     return CacheIt->second;
911 
912   // Always generate code immediately before the instruction being
913   // processed, so that the generated code dominates the same BBs.
914   BuilderTy::InsertPointGuard Guard(Builder);
915   if (Instruction *I = dyn_cast<Instruction>(V))
916     Builder.SetInsertPoint(I);
917 
918   // Now compute the size and offset.
919   SizeOffsetEvalType Result;
920 
921   // Record the pointers that were handled in this run, so that they can be
922   // cleaned later if something fails. We also use this set to break cycles that
923   // can occur in dead code.
924   if (!SeenVals.insert(V).second) {
925     Result = unknown();
926   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
927     Result = visitGEPOperator(*GEP);
928   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
929     Result = visit(*I);
930   } else if (isa<Argument>(V) ||
931              (isa<ConstantExpr>(V) &&
932               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
933              isa<GlobalAlias>(V) ||
934              isa<GlobalVariable>(V)) {
935     // Ignore values where we cannot do more than ObjectSizeVisitor.
936     Result = unknown();
937   } else {
938     LLVM_DEBUG(
939         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
940                << '\n');
941     Result = unknown();
942   }
943 
944   // Don't reuse CacheIt since it may be invalid at this point.
945   CacheMap[V] = Result;
946   return Result;
947 }
948 
949 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
950   if (!I.getAllocatedType()->isSized())
951     return unknown();
952 
953   // must be a VLA
954   assert(I.isArrayAllocation());
955   Value *ArraySize = I.getArraySize();
956   Value *Size = ConstantInt::get(ArraySize->getType(),
957                                  DL.getTypeAllocSize(I.getAllocatedType()));
958   Size = Builder.CreateMul(Size, ArraySize);
959   return std::make_pair(Size, Zero);
960 }
961 
962 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallBase(CallBase &CB) {
963   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
964   if (!FnData)
965     return unknown();
966 
967   // Handle strdup-like functions separately.
968   if (FnData->AllocTy == StrDupLike) {
969     // TODO
970     return unknown();
971   }
972 
973   Value *FirstArg = CB.getArgOperand(FnData->FstParam);
974   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
975   if (FnData->SndParam < 0)
976     return std::make_pair(FirstArg, Zero);
977 
978   Value *SecondArg = CB.getArgOperand(FnData->SndParam);
979   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
980   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
981   return std::make_pair(Size, Zero);
982 
983   // TODO: handle more standard functions (+ wchar cousins):
984   // - strdup / strndup
985   // - strcpy / strncpy
986   // - strcat / strncat
987   // - memcpy / memmove
988   // - strcat / strncat
989   // - memset
990 }
991 
992 SizeOffsetEvalType
993 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
994   return unknown();
995 }
996 
997 SizeOffsetEvalType
998 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
999   return unknown();
1000 }
1001 
1002 SizeOffsetEvalType
1003 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
1004   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
1005   if (!bothKnown(PtrData))
1006     return unknown();
1007 
1008   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
1009   Offset = Builder.CreateAdd(PtrData.second, Offset);
1010   return std::make_pair(PtrData.first, Offset);
1011 }
1012 
1013 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
1014   // clueless
1015   return unknown();
1016 }
1017 
1018 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
1019   return unknown();
1020 }
1021 
1022 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
1023   // Create 2 PHIs: one for size and another for offset.
1024   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1025   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1026 
1027   // Insert right away in the cache to handle recursive PHIs.
1028   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
1029 
1030   // Compute offset/size for each PHI incoming pointer.
1031   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1032     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
1033     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
1034 
1035     if (!bothKnown(EdgeData)) {
1036       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
1037       OffsetPHI->eraseFromParent();
1038       InsertedInstructions.erase(OffsetPHI);
1039       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
1040       SizePHI->eraseFromParent();
1041       InsertedInstructions.erase(SizePHI);
1042       return unknown();
1043     }
1044     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1045     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1046   }
1047 
1048   Value *Size = SizePHI, *Offset = OffsetPHI;
1049   if (Value *Tmp = SizePHI->hasConstantValue()) {
1050     Size = Tmp;
1051     SizePHI->replaceAllUsesWith(Size);
1052     SizePHI->eraseFromParent();
1053     InsertedInstructions.erase(SizePHI);
1054   }
1055   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1056     Offset = Tmp;
1057     OffsetPHI->replaceAllUsesWith(Offset);
1058     OffsetPHI->eraseFromParent();
1059     InsertedInstructions.erase(OffsetPHI);
1060   }
1061   return std::make_pair(Size, Offset);
1062 }
1063 
1064 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
1065   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
1066   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1067 
1068   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1069     return unknown();
1070   if (TrueSide == FalseSide)
1071     return TrueSide;
1072 
1073   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1074                                      FalseSide.first);
1075   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1076                                        FalseSide.second);
1077   return std::make_pair(Size, Offset);
1078 }
1079 
1080 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1081   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1082                     << '\n');
1083   return unknown();
1084 }
1085