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       Value *Ret = Builder.CreateSelect(
570           UseZero, ConstantInt::get(ResultType, 0), ResultSize);
571 
572       // The non-constant size expression cannot evaluate to -1.
573       if (!isa<Constant>(SizeOffsetPair.first) ||
574           !isa<Constant>(SizeOffsetPair.second))
575         Builder.CreateAssumption(
576             Builder.CreateICmpNE(Ret, ConstantInt::get(ResultType, -1)));
577 
578       return Ret;
579     }
580   }
581 
582   if (!MustSucceed)
583     return nullptr;
584 
585   return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
586 }
587 
588 STATISTIC(ObjectVisitorArgument,
589           "Number of arguments with unsolved size and offset");
590 STATISTIC(ObjectVisitorLoad,
591           "Number of load instructions with unsolved size and offset");
592 
593 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Alignment) {
594   if (Options.RoundToAlign && Alignment)
595     return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align(Alignment)));
596   return Size;
597 }
598 
599 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
600                                                  const TargetLibraryInfo *TLI,
601                                                  LLVMContext &Context,
602                                                  ObjectSizeOpts Options)
603     : DL(DL), TLI(TLI), Options(Options) {
604   // Pointer size must be rechecked for each object visited since it could have
605   // a different address space.
606 }
607 
608 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
609   IntTyBits = DL.getIndexTypeSizeInBits(V->getType());
610   Zero = APInt::getNullValue(IntTyBits);
611 
612   V = V->stripPointerCasts();
613   if (Instruction *I = dyn_cast<Instruction>(V)) {
614     // If we have already seen this instruction, bail out. Cycles can happen in
615     // unreachable code after constant propagation.
616     if (!SeenInsts.insert(I).second)
617       return unknown();
618 
619     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
620       return visitGEPOperator(*GEP);
621     return visit(*I);
622   }
623   if (Argument *A = dyn_cast<Argument>(V))
624     return visitArgument(*A);
625   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
626     return visitConstantPointerNull(*P);
627   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
628     return visitGlobalAlias(*GA);
629   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
630     return visitGlobalVariable(*GV);
631   if (UndefValue *UV = dyn_cast<UndefValue>(V))
632     return visitUndefValue(*UV);
633   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
634     if (CE->getOpcode() == Instruction::IntToPtr)
635       return unknown(); // clueless
636     if (CE->getOpcode() == Instruction::GetElementPtr)
637       return visitGEPOperator(cast<GEPOperator>(*CE));
638   }
639 
640   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: "
641                     << *V << '\n');
642   return unknown();
643 }
644 
645 /// When we're compiling N-bit code, and the user uses parameters that are
646 /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into
647 /// trouble with APInt size issues. This function handles resizing + overflow
648 /// checks for us. Check and zext or trunc \p I depending on IntTyBits and
649 /// I's value.
650 bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) {
651   // More bits than we can handle. Checking the bit width isn't necessary, but
652   // it's faster than checking active bits, and should give `false` in the
653   // vast majority of cases.
654   if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits)
655     return false;
656   if (I.getBitWidth() != IntTyBits)
657     I = I.zextOrTrunc(IntTyBits);
658   return true;
659 }
660 
661 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
662   if (!I.getAllocatedType()->isSized())
663     return unknown();
664 
665   if (isa<ScalableVectorType>(I.getAllocatedType()))
666     return unknown();
667 
668   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
669   if (!I.isArrayAllocation())
670     return std::make_pair(align(Size, I.getAlignment()), Zero);
671 
672   Value *ArraySize = I.getArraySize();
673   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
674     APInt NumElems = C->getValue();
675     if (!CheckedZextOrTrunc(NumElems))
676       return unknown();
677 
678     bool Overflow;
679     Size = Size.umul_ov(NumElems, Overflow);
680     return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()),
681                                                  Zero);
682   }
683   return unknown();
684 }
685 
686 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
687   Type *MemoryTy = A.getPointeeInMemoryValueType();
688   // No interprocedural analysis is done at the moment.
689   if (!MemoryTy|| !MemoryTy->isSized()) {
690     ++ObjectVisitorArgument;
691     return unknown();
692   }
693 
694   APInt Size(IntTyBits, DL.getTypeAllocSize(MemoryTy));
695   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
696 }
697 
698 SizeOffsetType ObjectSizeOffsetVisitor::visitCallBase(CallBase &CB) {
699   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
700   if (!FnData)
701     return unknown();
702 
703   // Handle strdup-like functions separately.
704   if (FnData->AllocTy == StrDupLike) {
705     APInt Size(IntTyBits, GetStringLength(CB.getArgOperand(0)));
706     if (!Size)
707       return unknown();
708 
709     // Strndup limits strlen.
710     if (FnData->FstParam > 0) {
711       ConstantInt *Arg =
712           dyn_cast<ConstantInt>(CB.getArgOperand(FnData->FstParam));
713       if (!Arg)
714         return unknown();
715 
716       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
717       if (Size.ugt(MaxSize))
718         Size = MaxSize + 1;
719     }
720     return std::make_pair(Size, Zero);
721   }
722 
723   ConstantInt *Arg = dyn_cast<ConstantInt>(CB.getArgOperand(FnData->FstParam));
724   if (!Arg)
725     return unknown();
726 
727   APInt Size = Arg->getValue();
728   if (!CheckedZextOrTrunc(Size))
729     return unknown();
730 
731   // Size is determined by just 1 parameter.
732   if (FnData->SndParam < 0)
733     return std::make_pair(Size, Zero);
734 
735   Arg = dyn_cast<ConstantInt>(CB.getArgOperand(FnData->SndParam));
736   if (!Arg)
737     return unknown();
738 
739   APInt NumElems = Arg->getValue();
740   if (!CheckedZextOrTrunc(NumElems))
741     return unknown();
742 
743   bool Overflow;
744   Size = Size.umul_ov(NumElems, Overflow);
745   return Overflow ? unknown() : std::make_pair(Size, Zero);
746 
747   // TODO: handle more standard functions (+ wchar cousins):
748   // - strdup / strndup
749   // - strcpy / strncpy
750   // - strcat / strncat
751   // - memcpy / memmove
752   // - strcat / strncat
753   // - memset
754 }
755 
756 SizeOffsetType
757 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) {
758   // If null is unknown, there's nothing we can do. Additionally, non-zero
759   // address spaces can make use of null, so we don't presume to know anything
760   // about that.
761   //
762   // TODO: How should this work with address space casts? We currently just drop
763   // them on the floor, but it's unclear what we should do when a NULL from
764   // addrspace(1) gets casted to addrspace(0) (or vice-versa).
765   if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace())
766     return unknown();
767   return std::make_pair(Zero, Zero);
768 }
769 
770 SizeOffsetType
771 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
772   return unknown();
773 }
774 
775 SizeOffsetType
776 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
777   // Easy cases were already folded by previous passes.
778   return unknown();
779 }
780 
781 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
782   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
783   APInt Offset(DL.getIndexTypeSizeInBits(GEP.getPointerOperand()->getType()), 0);
784   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
785     return unknown();
786 
787   return std::make_pair(PtrData.first, PtrData.second + Offset);
788 }
789 
790 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
791   if (GA.isInterposable())
792     return unknown();
793   return compute(GA.getAliasee());
794 }
795 
796 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
797   if (!GV.hasDefinitiveInitializer())
798     return unknown();
799 
800   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getValueType()));
801   return std::make_pair(align(Size, GV.getAlignment()), Zero);
802 }
803 
804 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
805   // clueless
806   return unknown();
807 }
808 
809 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
810   ++ObjectVisitorLoad;
811   return unknown();
812 }
813 
814 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
815   // too complex to analyze statically.
816   return unknown();
817 }
818 
819 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
820   SizeOffsetType TrueSide  = compute(I.getTrueValue());
821   SizeOffsetType FalseSide = compute(I.getFalseValue());
822   if (bothKnown(TrueSide) && bothKnown(FalseSide)) {
823     if (TrueSide == FalseSide) {
824         return TrueSide;
825     }
826 
827     APInt TrueResult = getSizeWithOverflow(TrueSide);
828     APInt FalseResult = getSizeWithOverflow(FalseSide);
829 
830     if (TrueResult == FalseResult) {
831       return TrueSide;
832     }
833     if (Options.EvalMode == ObjectSizeOpts::Mode::Min) {
834       if (TrueResult.slt(FalseResult))
835         return TrueSide;
836       return FalseSide;
837     }
838     if (Options.EvalMode == ObjectSizeOpts::Mode::Max) {
839       if (TrueResult.sgt(FalseResult))
840         return TrueSide;
841       return FalseSide;
842     }
843   }
844   return unknown();
845 }
846 
847 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
848   return std::make_pair(Zero, Zero);
849 }
850 
851 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
852   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I
853                     << '\n');
854   return unknown();
855 }
856 
857 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
858     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
859     ObjectSizeOpts EvalOpts)
860     : DL(DL), TLI(TLI), Context(Context),
861       Builder(Context, TargetFolder(DL),
862               IRBuilderCallbackInserter(
863                   [&](Instruction *I) { InsertedInstructions.insert(I); })),
864       EvalOpts(EvalOpts) {
865   // IntTy and Zero must be set for each compute() since the address space may
866   // be different for later objects.
867 }
868 
869 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
870   // XXX - Are vectors of pointers possible here?
871   IntTy = cast<IntegerType>(DL.getIndexType(V->getType()));
872   Zero = ConstantInt::get(IntTy, 0);
873 
874   SizeOffsetEvalType Result = compute_(V);
875 
876   if (!bothKnown(Result)) {
877     // Erase everything that was computed in this iteration from the cache, so
878     // that no dangling references are left behind. We could be a bit smarter if
879     // we kept a dependency graph. It's probably not worth the complexity.
880     for (const Value *SeenVal : SeenVals) {
881       CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal);
882       // non-computable results can be safely cached
883       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
884         CacheMap.erase(CacheIt);
885     }
886 
887     // Erase any instructions we inserted as part of the traversal.
888     for (Instruction *I : InsertedInstructions) {
889       I->replaceAllUsesWith(UndefValue::get(I->getType()));
890       I->eraseFromParent();
891     }
892   }
893 
894   SeenVals.clear();
895   InsertedInstructions.clear();
896   return Result;
897 }
898 
899 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
900   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts);
901   SizeOffsetType Const = Visitor.compute(V);
902   if (Visitor.bothKnown(Const))
903     return std::make_pair(ConstantInt::get(Context, Const.first),
904                           ConstantInt::get(Context, Const.second));
905 
906   V = V->stripPointerCasts();
907 
908   // Check cache.
909   CacheMapTy::iterator CacheIt = CacheMap.find(V);
910   if (CacheIt != CacheMap.end())
911     return CacheIt->second;
912 
913   // Always generate code immediately before the instruction being
914   // processed, so that the generated code dominates the same BBs.
915   BuilderTy::InsertPointGuard Guard(Builder);
916   if (Instruction *I = dyn_cast<Instruction>(V))
917     Builder.SetInsertPoint(I);
918 
919   // Now compute the size and offset.
920   SizeOffsetEvalType Result;
921 
922   // Record the pointers that were handled in this run, so that they can be
923   // cleaned later if something fails. We also use this set to break cycles that
924   // can occur in dead code.
925   if (!SeenVals.insert(V).second) {
926     Result = unknown();
927   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
928     Result = visitGEPOperator(*GEP);
929   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
930     Result = visit(*I);
931   } else if (isa<Argument>(V) ||
932              (isa<ConstantExpr>(V) &&
933               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
934              isa<GlobalAlias>(V) ||
935              isa<GlobalVariable>(V)) {
936     // Ignore values where we cannot do more than ObjectSizeVisitor.
937     Result = unknown();
938   } else {
939     LLVM_DEBUG(
940         dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V
941                << '\n');
942     Result = unknown();
943   }
944 
945   // Don't reuse CacheIt since it may be invalid at this point.
946   CacheMap[V] = Result;
947   return Result;
948 }
949 
950 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
951   if (!I.getAllocatedType()->isSized())
952     return unknown();
953 
954   // must be a VLA
955   assert(I.isArrayAllocation());
956   Value *ArraySize = I.getArraySize();
957   Value *Size = ConstantInt::get(ArraySize->getType(),
958                                  DL.getTypeAllocSize(I.getAllocatedType()));
959   Size = Builder.CreateMul(Size, ArraySize);
960   return std::make_pair(Size, Zero);
961 }
962 
963 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallBase(CallBase &CB) {
964   Optional<AllocFnsTy> FnData = getAllocationSize(&CB, TLI);
965   if (!FnData)
966     return unknown();
967 
968   // Handle strdup-like functions separately.
969   if (FnData->AllocTy == StrDupLike) {
970     // TODO
971     return unknown();
972   }
973 
974   Value *FirstArg = CB.getArgOperand(FnData->FstParam);
975   FirstArg = Builder.CreateZExtOrTrunc(FirstArg, IntTy);
976   if (FnData->SndParam < 0)
977     return std::make_pair(FirstArg, Zero);
978 
979   Value *SecondArg = CB.getArgOperand(FnData->SndParam);
980   SecondArg = Builder.CreateZExtOrTrunc(SecondArg, IntTy);
981   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
982   return std::make_pair(Size, Zero);
983 
984   // TODO: handle more standard functions (+ wchar cousins):
985   // - strdup / strndup
986   // - strcpy / strncpy
987   // - strcat / strncat
988   // - memcpy / memmove
989   // - strcat / strncat
990   // - memset
991 }
992 
993 SizeOffsetEvalType
994 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
995   return unknown();
996 }
997 
998 SizeOffsetEvalType
999 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
1000   return unknown();
1001 }
1002 
1003 SizeOffsetEvalType
1004 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
1005   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
1006   if (!bothKnown(PtrData))
1007     return unknown();
1008 
1009   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
1010   Offset = Builder.CreateAdd(PtrData.second, Offset);
1011   return std::make_pair(PtrData.first, Offset);
1012 }
1013 
1014 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
1015   // clueless
1016   return unknown();
1017 }
1018 
1019 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
1020   return unknown();
1021 }
1022 
1023 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
1024   // Create 2 PHIs: one for size and another for offset.
1025   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1026   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
1027 
1028   // Insert right away in the cache to handle recursive PHIs.
1029   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
1030 
1031   // Compute offset/size for each PHI incoming pointer.
1032   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
1033     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
1034     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
1035 
1036     if (!bothKnown(EdgeData)) {
1037       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
1038       OffsetPHI->eraseFromParent();
1039       InsertedInstructions.erase(OffsetPHI);
1040       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
1041       SizePHI->eraseFromParent();
1042       InsertedInstructions.erase(SizePHI);
1043       return unknown();
1044     }
1045     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
1046     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
1047   }
1048 
1049   Value *Size = SizePHI, *Offset = OffsetPHI;
1050   if (Value *Tmp = SizePHI->hasConstantValue()) {
1051     Size = Tmp;
1052     SizePHI->replaceAllUsesWith(Size);
1053     SizePHI->eraseFromParent();
1054     InsertedInstructions.erase(SizePHI);
1055   }
1056   if (Value *Tmp = OffsetPHI->hasConstantValue()) {
1057     Offset = Tmp;
1058     OffsetPHI->replaceAllUsesWith(Offset);
1059     OffsetPHI->eraseFromParent();
1060     InsertedInstructions.erase(OffsetPHI);
1061   }
1062   return std::make_pair(Size, Offset);
1063 }
1064 
1065 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
1066   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
1067   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
1068 
1069   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
1070     return unknown();
1071   if (TrueSide == FalseSide)
1072     return TrueSide;
1073 
1074   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
1075                                      FalseSide.first);
1076   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
1077                                        FalseSide.second);
1078   return std::make_pair(Size, Offset);
1079 }
1080 
1081 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
1082   LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I
1083                     << '\n');
1084   return unknown();
1085 }
1086