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