[ValueTracking] De-pessimize isImpliedCondition around unsigned compares
[oota-llvm.git] / lib / Analysis / MemoryBuiltins.cpp
1 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions identifies calls to builtin functions that allocate
11 // or free memory.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/MemoryBuiltins.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 using namespace llvm;
31
32 #define DEBUG_TYPE "memory-builtins"
33
34 enum AllocType {
35   OpNewLike          = 1<<0, // allocates; never returns null
36   MallocLike         = 1<<1 | OpNewLike, // allocates; may return null
37   CallocLike         = 1<<2, // allocates + bzero
38   ReallocLike        = 1<<3, // reallocates
39   StrDupLike         = 1<<4,
40   AllocLike          = MallocLike | CallocLike | StrDupLike,
41   AnyAlloc           = AllocLike | ReallocLike
42 };
43
44 struct AllocFnsTy {
45   LibFunc::Func Func;
46   AllocType AllocTy;
47   unsigned char NumParams;
48   // First and Second size parameters (or -1 if unused)
49   signed char FstParam, SndParam;
50 };
51
52 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
53 // know which functions are nounwind, noalias, nocapture parameters, etc.
54 static const AllocFnsTy AllocationFnData[] = {
55   {LibFunc::malloc,              MallocLike,  1, 0,  -1},
56   {LibFunc::valloc,              MallocLike,  1, 0,  -1},
57   {LibFunc::Znwj,                OpNewLike,   1, 0,  -1}, // new(unsigned int)
58   {LibFunc::ZnwjRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
59   {LibFunc::Znwm,                OpNewLike,   1, 0,  -1}, // new(unsigned long)
60   {LibFunc::ZnwmRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned long, nothrow)
61   {LibFunc::Znaj,                OpNewLike,   1, 0,  -1}, // new[](unsigned int)
62   {LibFunc::ZnajRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
63   {LibFunc::Znam,                OpNewLike,   1, 0,  -1}, // new[](unsigned long)
64   {LibFunc::ZnamRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned long, nothrow)
65   {LibFunc::calloc,              CallocLike,  2, 0,   1},
66   {LibFunc::realloc,             ReallocLike, 2, 1,  -1},
67   {LibFunc::reallocf,            ReallocLike, 2, 1,  -1},
68   {LibFunc::strdup,              StrDupLike,  1, -1, -1},
69   {LibFunc::strndup,             StrDupLike,  2, 1,  -1}
70   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
71 };
72
73
74 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
75   if (LookThroughBitCast)
76     V = V->stripPointerCasts();
77
78   CallSite CS(const_cast<Value*>(V));
79   if (!CS.getInstruction())
80     return nullptr;
81
82   if (CS.isNoBuiltin())
83     return nullptr;
84
85   Function *Callee = CS.getCalledFunction();
86   if (!Callee || !Callee->isDeclaration())
87     return nullptr;
88   return Callee;
89 }
90
91 /// \brief Returns the allocation data for the given value if it is a call to a
92 /// known allocation function, and NULL otherwise.
93 static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
94                                            const TargetLibraryInfo *TLI,
95                                            bool LookThroughBitCast = false) {
96   // Skip intrinsics
97   if (isa<IntrinsicInst>(V))
98     return nullptr;
99
100   Function *Callee = getCalledFunction(V, LookThroughBitCast);
101   if (!Callee)
102     return nullptr;
103
104   // Make sure that the function is available.
105   StringRef FnName = Callee->getName();
106   LibFunc::Func TLIFn;
107   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
108     return nullptr;
109
110   const AllocFnsTy *FnData =
111       std::find_if(std::begin(AllocationFnData), std::end(AllocationFnData),
112                    [TLIFn](const AllocFnsTy &Fn) { return Fn.Func == TLIFn; });
113
114   if (FnData == std::end(AllocationFnData))
115     return nullptr;
116
117   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
118     return nullptr;
119
120   // Check function prototype.
121   int FstParam = FnData->FstParam;
122   int SndParam = FnData->SndParam;
123   FunctionType *FTy = Callee->getFunctionType();
124
125   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
126       FTy->getNumParams() == FnData->NumParams &&
127       (FstParam < 0 ||
128        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
129         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
130       (SndParam < 0 ||
131        FTy->getParamType(SndParam)->isIntegerTy(32) ||
132        FTy->getParamType(SndParam)->isIntegerTy(64)))
133     return FnData;
134   return nullptr;
135 }
136
137 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
138   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
139   return CS && CS.hasFnAttr(Attribute::NoAlias);
140 }
141
142
143 /// \brief Tests if a value is a call or invoke to a library function that
144 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
145 /// like).
146 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
147                           bool LookThroughBitCast) {
148   return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
149 }
150
151 /// \brief Tests if a value is a call or invoke to a function that returns a
152 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
153 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
154                        bool LookThroughBitCast) {
155   // it's safe to consider realloc as noalias since accessing the original
156   // pointer is undefined behavior
157   return isAllocationFn(V, TLI, LookThroughBitCast) ||
158          hasNoAliasAttr(V, LookThroughBitCast);
159 }
160
161 /// \brief Tests if a value is a call or invoke to a library function that
162 /// allocates uninitialized memory (such as malloc).
163 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
164                           bool LookThroughBitCast) {
165   return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
166 }
167
168 /// \brief Tests if a value is a call or invoke to a library function that
169 /// allocates zero-filled memory (such as calloc).
170 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
171                           bool LookThroughBitCast) {
172   return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
173 }
174
175 /// \brief Tests if a value is a call or invoke to a library function that
176 /// allocates memory (either malloc, calloc, or strdup like).
177 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
178                          bool LookThroughBitCast) {
179   return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
180 }
181
182 /// \brief Tests if a value is a call or invoke to a library function that
183 /// reallocates memory (such as realloc).
184 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
185                            bool LookThroughBitCast) {
186   return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast);
187 }
188
189 /// \brief Tests if a value is a call or invoke to a library function that
190 /// allocates memory and never returns null (such as operator new).
191 bool llvm::isOperatorNewLikeFn(const Value *V, const TargetLibraryInfo *TLI,
192                                bool LookThroughBitCast) {
193   return getAllocationData(V, OpNewLike, TLI, LookThroughBitCast);
194 }
195
196 /// extractMallocCall - Returns the corresponding CallInst if the instruction
197 /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
198 /// ignore InvokeInst here.
199 const CallInst *llvm::extractMallocCall(const Value *I,
200                                         const TargetLibraryInfo *TLI) {
201   return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
202 }
203
204 static Value *computeArraySize(const CallInst *CI, const DataLayout &DL,
205                                const TargetLibraryInfo *TLI,
206                                bool LookThroughSExt = false) {
207   if (!CI)
208     return nullptr;
209
210   // The size of the malloc's result type must be known to determine array size.
211   Type *T = getMallocAllocatedType(CI, TLI);
212   if (!T || !T->isSized())
213     return nullptr;
214
215   unsigned ElementSize = DL.getTypeAllocSize(T);
216   if (StructType *ST = dyn_cast<StructType>(T))
217     ElementSize = DL.getStructLayout(ST)->getSizeInBytes();
218
219   // If malloc call's arg can be determined to be a multiple of ElementSize,
220   // return the multiple.  Otherwise, return NULL.
221   Value *MallocArg = CI->getArgOperand(0);
222   Value *Multiple = nullptr;
223   if (ComputeMultiple(MallocArg, ElementSize, Multiple,
224                       LookThroughSExt))
225     return Multiple;
226
227   return nullptr;
228 }
229
230 /// getMallocType - Returns the PointerType resulting from the malloc call.
231 /// The PointerType depends on the number of bitcast uses of the malloc call:
232 ///   0: PointerType is the calls' return type.
233 ///   1: PointerType is the bitcast's result type.
234 ///  >1: Unique PointerType cannot be determined, return NULL.
235 PointerType *llvm::getMallocType(const CallInst *CI,
236                                  const TargetLibraryInfo *TLI) {
237   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
238
239   PointerType *MallocType = nullptr;
240   unsigned NumOfBitCastUses = 0;
241
242   // Determine if CallInst has a bitcast use.
243   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
244        UI != E;)
245     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
246       MallocType = cast<PointerType>(BCI->getDestTy());
247       NumOfBitCastUses++;
248     }
249
250   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
251   if (NumOfBitCastUses == 1)
252     return MallocType;
253
254   // Malloc call was not bitcast, so type is the malloc function's return type.
255   if (NumOfBitCastUses == 0)
256     return cast<PointerType>(CI->getType());
257
258   // Type could not be determined.
259   return nullptr;
260 }
261
262 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
263 /// The Type depends on the number of bitcast uses of the malloc call:
264 ///   0: PointerType is the malloc calls' return type.
265 ///   1: PointerType is the bitcast's result type.
266 ///  >1: Unique PointerType cannot be determined, return NULL.
267 Type *llvm::getMallocAllocatedType(const CallInst *CI,
268                                    const TargetLibraryInfo *TLI) {
269   PointerType *PT = getMallocType(CI, TLI);
270   return PT ? PT->getElementType() : nullptr;
271 }
272
273 /// getMallocArraySize - Returns the array size of a malloc call.  If the
274 /// argument passed to malloc is a multiple of the size of the malloced type,
275 /// then return that multiple.  For non-array mallocs, the multiple is
276 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
277 /// determined.
278 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
279                                 const TargetLibraryInfo *TLI,
280                                 bool LookThroughSExt) {
281   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
282   return computeArraySize(CI, DL, TLI, LookThroughSExt);
283 }
284
285
286 /// extractCallocCall - Returns the corresponding CallInst if the instruction
287 /// is a calloc call.
288 const CallInst *llvm::extractCallocCall(const Value *I,
289                                         const TargetLibraryInfo *TLI) {
290   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
291 }
292
293
294 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
295 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
296   const CallInst *CI = dyn_cast<CallInst>(I);
297   if (!CI || isa<IntrinsicInst>(CI))
298     return nullptr;
299   Function *Callee = CI->getCalledFunction();
300   if (Callee == nullptr)
301     return nullptr;
302
303   StringRef FnName = Callee->getName();
304   LibFunc::Func TLIFn;
305   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
306     return nullptr;
307
308   unsigned ExpectedNumParams;
309   if (TLIFn == LibFunc::free ||
310       TLIFn == LibFunc::ZdlPv || // operator delete(void*)
311       TLIFn == LibFunc::ZdaPv)   // operator delete[](void*)
312     ExpectedNumParams = 1;
313   else if (TLIFn == LibFunc::ZdlPvj ||              // delete(void*, uint)
314            TLIFn == LibFunc::ZdlPvm ||              // delete(void*, ulong)
315            TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
316            TLIFn == LibFunc::ZdaPvj ||              // delete[](void*, uint)
317            TLIFn == LibFunc::ZdaPvm ||              // delete[](void*, ulong)
318            TLIFn == LibFunc::ZdaPvRKSt9nothrow_t)   // delete[](void*, nothrow)
319     ExpectedNumParams = 2;
320   else
321     return nullptr;
322
323   // Check free prototype.
324   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
325   // attribute will exist.
326   FunctionType *FTy = Callee->getFunctionType();
327   if (!FTy->getReturnType()->isVoidTy())
328     return nullptr;
329   if (FTy->getNumParams() != ExpectedNumParams)
330     return nullptr;
331   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
332     return nullptr;
333
334   return CI;
335 }
336
337
338
339 //===----------------------------------------------------------------------===//
340 //  Utility functions to compute size of objects.
341 //
342
343
344 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
345 /// object size in Size if successful, and false otherwise.
346 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
347 /// byval arguments, and global variables.
348 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
349                          const TargetLibraryInfo *TLI, bool RoundToAlign) {
350   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), RoundToAlign);
351   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
352   if (!Visitor.bothKnown(Data))
353     return false;
354
355   APInt ObjSize = Data.first, Offset = Data.second;
356   // check for overflow
357   if (Offset.slt(0) || ObjSize.ult(Offset))
358     Size = 0;
359   else
360     Size = (ObjSize - Offset).getZExtValue();
361   return true;
362 }
363
364
365 STATISTIC(ObjectVisitorArgument,
366           "Number of arguments with unsolved size and offset");
367 STATISTIC(ObjectVisitorLoad,
368           "Number of load instructions with unsolved size and offset");
369
370
371 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
372   if (RoundToAlign && Align)
373     return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
374   return Size;
375 }
376
377 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
378                                                  const TargetLibraryInfo *TLI,
379                                                  LLVMContext &Context,
380                                                  bool RoundToAlign)
381     : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign) {
382   // Pointer size must be rechecked for each object visited since it could have
383   // a different address space.
384 }
385
386 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
387   IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
388   Zero = APInt::getNullValue(IntTyBits);
389
390   V = V->stripPointerCasts();
391   if (Instruction *I = dyn_cast<Instruction>(V)) {
392     // If we have already seen this instruction, bail out. Cycles can happen in
393     // unreachable code after constant propagation.
394     if (!SeenInsts.insert(I).second)
395       return unknown();
396
397     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
398       return visitGEPOperator(*GEP);
399     return visit(*I);
400   }
401   if (Argument *A = dyn_cast<Argument>(V))
402     return visitArgument(*A);
403   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
404     return visitConstantPointerNull(*P);
405   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
406     return visitGlobalAlias(*GA);
407   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
408     return visitGlobalVariable(*GV);
409   if (UndefValue *UV = dyn_cast<UndefValue>(V))
410     return visitUndefValue(*UV);
411   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
412     if (CE->getOpcode() == Instruction::IntToPtr)
413       return unknown(); // clueless
414     if (CE->getOpcode() == Instruction::GetElementPtr)
415       return visitGEPOperator(cast<GEPOperator>(*CE));
416   }
417
418   DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
419         << '\n');
420   return unknown();
421 }
422
423 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
424   if (!I.getAllocatedType()->isSized())
425     return unknown();
426
427   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
428   if (!I.isArrayAllocation())
429     return std::make_pair(align(Size, I.getAlignment()), Zero);
430
431   Value *ArraySize = I.getArraySize();
432   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
433     Size *= C->getValue().zextOrSelf(IntTyBits);
434     return std::make_pair(align(Size, I.getAlignment()), Zero);
435   }
436   return unknown();
437 }
438
439 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
440   // no interprocedural analysis is done at the moment
441   if (!A.hasByValOrInAllocaAttr()) {
442     ++ObjectVisitorArgument;
443     return unknown();
444   }
445   PointerType *PT = cast<PointerType>(A.getType());
446   APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
447   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
448 }
449
450 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
451   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
452                                                TLI);
453   if (!FnData)
454     return unknown();
455
456   // handle strdup-like functions separately
457   if (FnData->AllocTy == StrDupLike) {
458     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
459     if (!Size)
460       return unknown();
461
462     // strndup limits strlen
463     if (FnData->FstParam > 0) {
464       ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
465       if (!Arg)
466         return unknown();
467
468       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
469       if (Size.ugt(MaxSize))
470         Size = MaxSize + 1;
471     }
472     return std::make_pair(Size, Zero);
473   }
474
475   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
476   if (!Arg)
477     return unknown();
478
479   APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
480   // size determined by just 1 parameter
481   if (FnData->SndParam < 0)
482     return std::make_pair(Size, Zero);
483
484   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
485   if (!Arg)
486     return unknown();
487
488   Size *= Arg->getValue().zextOrSelf(IntTyBits);
489   return std::make_pair(Size, Zero);
490
491   // TODO: handle more standard functions (+ wchar cousins):
492   // - strdup / strndup
493   // - strcpy / strncpy
494   // - strcat / strncat
495   // - memcpy / memmove
496   // - strcat / strncat
497   // - memset
498 }
499
500 SizeOffsetType
501 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
502   return std::make_pair(Zero, Zero);
503 }
504
505 SizeOffsetType
506 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
507   return unknown();
508 }
509
510 SizeOffsetType
511 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
512   // Easy cases were already folded by previous passes.
513   return unknown();
514 }
515
516 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
517   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
518   APInt Offset(IntTyBits, 0);
519   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
520     return unknown();
521
522   return std::make_pair(PtrData.first, PtrData.second + Offset);
523 }
524
525 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
526   if (GA.mayBeOverridden())
527     return unknown();
528   return compute(GA.getAliasee());
529 }
530
531 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
532   if (!GV.hasDefinitiveInitializer())
533     return unknown();
534
535   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
536   return std::make_pair(align(Size, GV.getAlignment()), Zero);
537 }
538
539 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
540   // clueless
541   return unknown();
542 }
543
544 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
545   ++ObjectVisitorLoad;
546   return unknown();
547 }
548
549 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
550   // too complex to analyze statically.
551   return unknown();
552 }
553
554 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
555   SizeOffsetType TrueSide  = compute(I.getTrueValue());
556   SizeOffsetType FalseSide = compute(I.getFalseValue());
557   if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
558     return TrueSide;
559   return unknown();
560 }
561
562 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
563   return std::make_pair(Zero, Zero);
564 }
565
566 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
567   DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
568   return unknown();
569 }
570
571 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
572     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
573     bool RoundToAlign)
574     : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
575       RoundToAlign(RoundToAlign) {
576   // IntTy and Zero must be set for each compute() since the address space may
577   // be different for later objects.
578 }
579
580 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
581   // XXX - Are vectors of pointers possible here?
582   IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
583   Zero = ConstantInt::get(IntTy, 0);
584
585   SizeOffsetEvalType Result = compute_(V);
586
587   if (!bothKnown(Result)) {
588     // erase everything that was computed in this iteration from the cache, so
589     // that no dangling references are left behind. We could be a bit smarter if
590     // we kept a dependency graph. It's probably not worth the complexity.
591     for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
592       CacheMapTy::iterator CacheIt = CacheMap.find(*I);
593       // non-computable results can be safely cached
594       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
595         CacheMap.erase(CacheIt);
596     }
597   }
598
599   SeenVals.clear();
600   return Result;
601 }
602
603 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
604   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
605   SizeOffsetType Const = Visitor.compute(V);
606   if (Visitor.bothKnown(Const))
607     return std::make_pair(ConstantInt::get(Context, Const.first),
608                           ConstantInt::get(Context, Const.second));
609
610   V = V->stripPointerCasts();
611
612   // check cache
613   CacheMapTy::iterator CacheIt = CacheMap.find(V);
614   if (CacheIt != CacheMap.end())
615     return CacheIt->second;
616
617   // always generate code immediately before the instruction being
618   // processed, so that the generated code dominates the same BBs
619   BuilderTy::InsertPointGuard Guard(Builder);
620   if (Instruction *I = dyn_cast<Instruction>(V))
621     Builder.SetInsertPoint(I);
622
623   // now compute the size and offset
624   SizeOffsetEvalType Result;
625
626   // Record the pointers that were handled in this run, so that they can be
627   // cleaned later if something fails. We also use this set to break cycles that
628   // can occur in dead code.
629   if (!SeenVals.insert(V).second) {
630     Result = unknown();
631   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
632     Result = visitGEPOperator(*GEP);
633   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
634     Result = visit(*I);
635   } else if (isa<Argument>(V) ||
636              (isa<ConstantExpr>(V) &&
637               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
638              isa<GlobalAlias>(V) ||
639              isa<GlobalVariable>(V)) {
640     // ignore values where we cannot do more than what ObjectSizeVisitor can
641     Result = unknown();
642   } else {
643     DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
644           << *V << '\n');
645     Result = unknown();
646   }
647
648   // Don't reuse CacheIt since it may be invalid at this point.
649   CacheMap[V] = Result;
650   return Result;
651 }
652
653 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
654   if (!I.getAllocatedType()->isSized())
655     return unknown();
656
657   // must be a VLA
658   assert(I.isArrayAllocation());
659   Value *ArraySize = I.getArraySize();
660   Value *Size = ConstantInt::get(ArraySize->getType(),
661                                  DL.getTypeAllocSize(I.getAllocatedType()));
662   Size = Builder.CreateMul(Size, ArraySize);
663   return std::make_pair(Size, Zero);
664 }
665
666 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
667   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
668                                                TLI);
669   if (!FnData)
670     return unknown();
671
672   // handle strdup-like functions separately
673   if (FnData->AllocTy == StrDupLike) {
674     // TODO
675     return unknown();
676   }
677
678   Value *FirstArg = CS.getArgument(FnData->FstParam);
679   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
680   if (FnData->SndParam < 0)
681     return std::make_pair(FirstArg, Zero);
682
683   Value *SecondArg = CS.getArgument(FnData->SndParam);
684   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
685   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
686   return std::make_pair(Size, Zero);
687
688   // TODO: handle more standard functions (+ wchar cousins):
689   // - strdup / strndup
690   // - strcpy / strncpy
691   // - strcat / strncat
692   // - memcpy / memmove
693   // - strcat / strncat
694   // - memset
695 }
696
697 SizeOffsetEvalType
698 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
699   return unknown();
700 }
701
702 SizeOffsetEvalType
703 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
704   return unknown();
705 }
706
707 SizeOffsetEvalType
708 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
709   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
710   if (!bothKnown(PtrData))
711     return unknown();
712
713   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
714   Offset = Builder.CreateAdd(PtrData.second, Offset);
715   return std::make_pair(PtrData.first, Offset);
716 }
717
718 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
719   // clueless
720   return unknown();
721 }
722
723 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
724   return unknown();
725 }
726
727 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
728   // create 2 PHIs: one for size and another for offset
729   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
730   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
731
732   // insert right away in the cache to handle recursive PHIs
733   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
734
735   // compute offset/size for each PHI incoming pointer
736   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
737     Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt());
738     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
739
740     if (!bothKnown(EdgeData)) {
741       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
742       OffsetPHI->eraseFromParent();
743       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
744       SizePHI->eraseFromParent();
745       return unknown();
746     }
747     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
748     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
749   }
750
751   Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
752   if ((Tmp = SizePHI->hasConstantValue())) {
753     Size = Tmp;
754     SizePHI->replaceAllUsesWith(Size);
755     SizePHI->eraseFromParent();
756   }
757   if ((Tmp = OffsetPHI->hasConstantValue())) {
758     Offset = Tmp;
759     OffsetPHI->replaceAllUsesWith(Offset);
760     OffsetPHI->eraseFromParent();
761   }
762   return std::make_pair(Size, Offset);
763 }
764
765 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
766   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
767   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
768
769   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
770     return unknown();
771   if (TrueSide == FalseSide)
772     return TrueSide;
773
774   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
775                                      FalseSide.first);
776   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
777                                        FalseSide.second);
778   return std::make_pair(Size, Offset);
779 }
780
781 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
782   DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
783   return unknown();
784 }