LLVM API Documentation

MemoryBuiltins.cpp
Go to the documentation of this file.
00001 //===------ MemoryBuiltins.cpp - Identify calls to memory builtins --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions identifies calls to builtin functions that allocate
00011 // or free memory.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/MemoryBuiltins.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/Analysis/ValueTracking.h"
00019 #include "llvm/IR/DataLayout.h"
00020 #include "llvm/IR/GlobalVariable.h"
00021 #include "llvm/IR/Instructions.h"
00022 #include "llvm/IR/Intrinsics.h"
00023 #include "llvm/IR/Metadata.h"
00024 #include "llvm/IR/Module.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/Support/MathExtras.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include "llvm/Target/TargetLibraryInfo.h"
00029 #include "llvm/Transforms/Utils/Local.h"
00030 using namespace llvm;
00031 
00032 #define DEBUG_TYPE "memory-builtins"
00033 
00034 enum AllocType {
00035   OpNewLike          = 1<<0, // allocates; never returns null
00036   MallocLike         = 1<<1 | OpNewLike, // allocates; may return null
00037   CallocLike         = 1<<2, // allocates + bzero
00038   ReallocLike        = 1<<3, // reallocates
00039   StrDupLike         = 1<<4,
00040   AllocLike          = MallocLike | CallocLike | StrDupLike,
00041   AnyAlloc           = AllocLike | ReallocLike
00042 };
00043 
00044 struct AllocFnsTy {
00045   LibFunc::Func Func;
00046   AllocType AllocTy;
00047   unsigned char NumParams;
00048   // First and Second size parameters (or -1 if unused)
00049   signed char FstParam, SndParam;
00050 };
00051 
00052 // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to
00053 // know which functions are nounwind, noalias, nocapture parameters, etc.
00054 static const AllocFnsTy AllocationFnData[] = {
00055   {LibFunc::malloc,              MallocLike,  1, 0,  -1},
00056   {LibFunc::valloc,              MallocLike,  1, 0,  -1},
00057   {LibFunc::Znwj,                OpNewLike,   1, 0,  -1}, // new(unsigned int)
00058   {LibFunc::ZnwjRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned int, nothrow)
00059   {LibFunc::Znwm,                OpNewLike,   1, 0,  -1}, // new(unsigned long)
00060   {LibFunc::ZnwmRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new(unsigned long, nothrow)
00061   {LibFunc::Znaj,                OpNewLike,   1, 0,  -1}, // new[](unsigned int)
00062   {LibFunc::ZnajRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned int, nothrow)
00063   {LibFunc::Znam,                OpNewLike,   1, 0,  -1}, // new[](unsigned long)
00064   {LibFunc::ZnamRKSt9nothrow_t,  MallocLike,  2, 0,  -1}, // new[](unsigned long, nothrow)
00065   {LibFunc::calloc,              CallocLike,  2, 0,   1},
00066   {LibFunc::realloc,             ReallocLike, 2, 1,  -1},
00067   {LibFunc::reallocf,            ReallocLike, 2, 1,  -1},
00068   {LibFunc::strdup,              StrDupLike,  1, -1, -1},
00069   {LibFunc::strndup,             StrDupLike,  2, 1,  -1}
00070   // TODO: Handle "int posix_memalign(void **, size_t, size_t)"
00071 };
00072 
00073 
00074 static Function *getCalledFunction(const Value *V, bool LookThroughBitCast) {
00075   if (LookThroughBitCast)
00076     V = V->stripPointerCasts();
00077 
00078   CallSite CS(const_cast<Value*>(V));
00079   if (!CS.getInstruction())
00080     return nullptr;
00081 
00082   if (CS.isNoBuiltin())
00083     return nullptr;
00084 
00085   Function *Callee = CS.getCalledFunction();
00086   if (!Callee || !Callee->isDeclaration())
00087     return nullptr;
00088   return Callee;
00089 }
00090 
00091 /// \brief Returns the allocation data for the given value if it is a call to a
00092 /// known allocation function, and NULL otherwise.
00093 static const AllocFnsTy *getAllocationData(const Value *V, AllocType AllocTy,
00094                                            const TargetLibraryInfo *TLI,
00095                                            bool LookThroughBitCast = false) {
00096   // Skip intrinsics
00097   if (isa<IntrinsicInst>(V))
00098     return nullptr;
00099 
00100   Function *Callee = getCalledFunction(V, LookThroughBitCast);
00101   if (!Callee)
00102     return nullptr;
00103 
00104   // Make sure that the function is available.
00105   StringRef FnName = Callee->getName();
00106   LibFunc::Func TLIFn;
00107   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
00108     return nullptr;
00109 
00110   unsigned i = 0;
00111   bool found = false;
00112   for ( ; i < array_lengthof(AllocationFnData); ++i) {
00113     if (AllocationFnData[i].Func == TLIFn) {
00114       found = true;
00115       break;
00116     }
00117   }
00118   if (!found)
00119     return nullptr;
00120 
00121   const AllocFnsTy *FnData = &AllocationFnData[i];
00122   if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
00123     return nullptr;
00124 
00125   // Check function prototype.
00126   int FstParam = FnData->FstParam;
00127   int SndParam = FnData->SndParam;
00128   FunctionType *FTy = Callee->getFunctionType();
00129 
00130   if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) &&
00131       FTy->getNumParams() == FnData->NumParams &&
00132       (FstParam < 0 ||
00133        (FTy->getParamType(FstParam)->isIntegerTy(32) ||
00134         FTy->getParamType(FstParam)->isIntegerTy(64))) &&
00135       (SndParam < 0 ||
00136        FTy->getParamType(SndParam)->isIntegerTy(32) ||
00137        FTy->getParamType(SndParam)->isIntegerTy(64)))
00138     return FnData;
00139   return nullptr;
00140 }
00141 
00142 static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
00143   ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V);
00144   return CS && CS.hasFnAttr(Attribute::NoAlias);
00145 }
00146 
00147 
00148 /// \brief Tests if a value is a call or invoke to a library function that
00149 /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup
00150 /// like).
00151 bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI,
00152                           bool LookThroughBitCast) {
00153   return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast);
00154 }
00155 
00156 /// \brief Tests if a value is a call or invoke to a function that returns a
00157 /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions).
00158 bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI,
00159                        bool LookThroughBitCast) {
00160   // it's safe to consider realloc as noalias since accessing the original
00161   // pointer is undefined behavior
00162   return isAllocationFn(V, TLI, LookThroughBitCast) ||
00163          hasNoAliasAttr(V, LookThroughBitCast);
00164 }
00165 
00166 /// \brief Tests if a value is a call or invoke to a library function that
00167 /// allocates uninitialized memory (such as malloc).
00168 bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00169                           bool LookThroughBitCast) {
00170   return getAllocationData(V, MallocLike, TLI, LookThroughBitCast);
00171 }
00172 
00173 /// \brief Tests if a value is a call or invoke to a library function that
00174 /// allocates zero-filled memory (such as calloc).
00175 bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00176                           bool LookThroughBitCast) {
00177   return getAllocationData(V, CallocLike, TLI, LookThroughBitCast);
00178 }
00179 
00180 /// \brief Tests if a value is a call or invoke to a library function that
00181 /// allocates memory (either malloc, calloc, or strdup like).
00182 bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00183                          bool LookThroughBitCast) {
00184   return getAllocationData(V, AllocLike, TLI, LookThroughBitCast);
00185 }
00186 
00187 /// \brief Tests if a value is a call or invoke to a library function that
00188 /// reallocates memory (such as realloc).
00189 bool llvm::isReallocLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00190                            bool LookThroughBitCast) {
00191   return getAllocationData(V, ReallocLike, TLI, LookThroughBitCast);
00192 }
00193 
00194 /// \brief Tests if a value is a call or invoke to a library function that
00195 /// allocates memory and never returns null (such as operator new).
00196 bool llvm::isOperatorNewLikeFn(const Value *V, const TargetLibraryInfo *TLI,
00197                                bool LookThroughBitCast) {
00198   return getAllocationData(V, OpNewLike, TLI, LookThroughBitCast);
00199 }
00200 
00201 /// extractMallocCall - Returns the corresponding CallInst if the instruction
00202 /// is a malloc call.  Since CallInst::CreateMalloc() only creates calls, we
00203 /// ignore InvokeInst here.
00204 const CallInst *llvm::extractMallocCall(const Value *I,
00205                                         const TargetLibraryInfo *TLI) {
00206   return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
00207 }
00208 
00209 static Value *computeArraySize(const CallInst *CI, const DataLayout *DL,
00210                                const TargetLibraryInfo *TLI,
00211                                bool LookThroughSExt = false) {
00212   if (!CI)
00213     return nullptr;
00214 
00215   // The size of the malloc's result type must be known to determine array size.
00216   Type *T = getMallocAllocatedType(CI, TLI);
00217   if (!T || !T->isSized() || !DL)
00218     return nullptr;
00219 
00220   unsigned ElementSize = DL->getTypeAllocSize(T);
00221   if (StructType *ST = dyn_cast<StructType>(T))
00222     ElementSize = DL->getStructLayout(ST)->getSizeInBytes();
00223 
00224   // If malloc call's arg can be determined to be a multiple of ElementSize,
00225   // return the multiple.  Otherwise, return NULL.
00226   Value *MallocArg = CI->getArgOperand(0);
00227   Value *Multiple = nullptr;
00228   if (ComputeMultiple(MallocArg, ElementSize, Multiple,
00229                       LookThroughSExt))
00230     return Multiple;
00231 
00232   return nullptr;
00233 }
00234 
00235 /// isArrayMalloc - Returns the corresponding CallInst if the instruction
00236 /// is a call to malloc whose array size can be determined and the array size
00237 /// is not constant 1.  Otherwise, return NULL.
00238 const CallInst *llvm::isArrayMalloc(const Value *I,
00239                                     const DataLayout *DL,
00240                                     const TargetLibraryInfo *TLI) {
00241   const CallInst *CI = extractMallocCall(I, TLI);
00242   Value *ArraySize = computeArraySize(CI, DL, TLI);
00243 
00244   if (ConstantInt *ConstSize = dyn_cast_or_null<ConstantInt>(ArraySize))
00245     if (ConstSize->isOne())
00246       return CI;
00247 
00248   // CI is a non-array malloc or we can't figure out that it is an array malloc.
00249   return nullptr;
00250 }
00251 
00252 /// getMallocType - Returns the PointerType resulting from the malloc call.
00253 /// The PointerType depends on the number of bitcast uses of the malloc call:
00254 ///   0: PointerType is the calls' return type.
00255 ///   1: PointerType is the bitcast's result type.
00256 ///  >1: Unique PointerType cannot be determined, return NULL.
00257 PointerType *llvm::getMallocType(const CallInst *CI,
00258                                  const TargetLibraryInfo *TLI) {
00259   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
00260 
00261   PointerType *MallocType = nullptr;
00262   unsigned NumOfBitCastUses = 0;
00263 
00264   // Determine if CallInst has a bitcast use.
00265   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
00266        UI != E;)
00267     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
00268       MallocType = cast<PointerType>(BCI->getDestTy());
00269       NumOfBitCastUses++;
00270     }
00271 
00272   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
00273   if (NumOfBitCastUses == 1)
00274     return MallocType;
00275 
00276   // Malloc call was not bitcast, so type is the malloc function's return type.
00277   if (NumOfBitCastUses == 0)
00278     return cast<PointerType>(CI->getType());
00279 
00280   // Type could not be determined.
00281   return nullptr;
00282 }
00283 
00284 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
00285 /// The Type depends on the number of bitcast uses of the malloc call:
00286 ///   0: PointerType is the malloc calls' return type.
00287 ///   1: PointerType is the bitcast's result type.
00288 ///  >1: Unique PointerType cannot be determined, return NULL.
00289 Type *llvm::getMallocAllocatedType(const CallInst *CI,
00290                                    const TargetLibraryInfo *TLI) {
00291   PointerType *PT = getMallocType(CI, TLI);
00292   return PT ? PT->getElementType() : nullptr;
00293 }
00294 
00295 /// getMallocArraySize - Returns the array size of a malloc call.  If the
00296 /// argument passed to malloc is a multiple of the size of the malloced type,
00297 /// then return that multiple.  For non-array mallocs, the multiple is
00298 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
00299 /// determined.
00300 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout *DL,
00301                                 const TargetLibraryInfo *TLI,
00302                                 bool LookThroughSExt) {
00303   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
00304   return computeArraySize(CI, DL, TLI, LookThroughSExt);
00305 }
00306 
00307 
00308 /// extractCallocCall - Returns the corresponding CallInst if the instruction
00309 /// is a calloc call.
00310 const CallInst *llvm::extractCallocCall(const Value *I,
00311                                         const TargetLibraryInfo *TLI) {
00312   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
00313 }
00314 
00315 
00316 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
00317 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
00318   const CallInst *CI = dyn_cast<CallInst>(I);
00319   if (!CI || isa<IntrinsicInst>(CI))
00320     return nullptr;
00321   Function *Callee = CI->getCalledFunction();
00322   if (Callee == nullptr || !Callee->isDeclaration())
00323     return nullptr;
00324 
00325   StringRef FnName = Callee->getName();
00326   LibFunc::Func TLIFn;
00327   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
00328     return nullptr;
00329 
00330   unsigned ExpectedNumParams;
00331   if (TLIFn == LibFunc::free ||
00332       TLIFn == LibFunc::ZdlPv || // operator delete(void*)
00333       TLIFn == LibFunc::ZdaPv)   // operator delete[](void*)
00334     ExpectedNumParams = 1;
00335   else if (TLIFn == LibFunc::ZdlPvj ||              // delete(void*, uint)
00336            TLIFn == LibFunc::ZdlPvm ||              // delete(void*, ulong)
00337            TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
00338            TLIFn == LibFunc::ZdaPvj ||              // delete[](void*, uint)
00339            TLIFn == LibFunc::ZdaPvm ||              // delete[](void*, ulong)
00340            TLIFn == LibFunc::ZdaPvRKSt9nothrow_t)   // delete[](void*, nothrow)
00341     ExpectedNumParams = 2;
00342   else
00343     return nullptr;
00344 
00345   // Check free prototype.
00346   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
00347   // attribute will exist.
00348   FunctionType *FTy = Callee->getFunctionType();
00349   if (!FTy->getReturnType()->isVoidTy())
00350     return nullptr;
00351   if (FTy->getNumParams() != ExpectedNumParams)
00352     return nullptr;
00353   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
00354     return nullptr;
00355 
00356   return CI;
00357 }
00358 
00359 
00360 
00361 //===----------------------------------------------------------------------===//
00362 //  Utility functions to compute size of objects.
00363 //
00364 
00365 
00366 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
00367 /// object size in Size if successful, and false otherwise.
00368 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
00369 /// byval arguments, and global variables.
00370 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout *DL,
00371                          const TargetLibraryInfo *TLI, bool RoundToAlign) {
00372   if (!DL)
00373     return false;
00374 
00375   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), RoundToAlign);
00376   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
00377   if (!Visitor.bothKnown(Data))
00378     return false;
00379 
00380   APInt ObjSize = Data.first, Offset = Data.second;
00381   // check for overflow
00382   if (Offset.slt(0) || ObjSize.ult(Offset))
00383     Size = 0;
00384   else
00385     Size = (ObjSize - Offset).getZExtValue();
00386   return true;
00387 }
00388 
00389 
00390 STATISTIC(ObjectVisitorArgument,
00391           "Number of arguments with unsolved size and offset");
00392 STATISTIC(ObjectVisitorLoad,
00393           "Number of load instructions with unsolved size and offset");
00394 
00395 
00396 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
00397   if (RoundToAlign && Align)
00398     return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
00399   return Size;
00400 }
00401 
00402 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout *DL,
00403                                                  const TargetLibraryInfo *TLI,
00404                                                  LLVMContext &Context,
00405                                                  bool RoundToAlign)
00406 : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign) {
00407   // Pointer size must be rechecked for each object visited since it could have
00408   // a different address space.
00409 }
00410 
00411 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
00412   IntTyBits = DL->getPointerTypeSizeInBits(V->getType());
00413   Zero = APInt::getNullValue(IntTyBits);
00414 
00415   V = V->stripPointerCasts();
00416   if (Instruction *I = dyn_cast<Instruction>(V)) {
00417     // If we have already seen this instruction, bail out. Cycles can happen in
00418     // unreachable code after constant propagation.
00419     if (!SeenInsts.insert(I).second)
00420       return unknown();
00421 
00422     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
00423       return visitGEPOperator(*GEP);
00424     return visit(*I);
00425   }
00426   if (Argument *A = dyn_cast<Argument>(V))
00427     return visitArgument(*A);
00428   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
00429     return visitConstantPointerNull(*P);
00430   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00431     return visitGlobalAlias(*GA);
00432   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00433     return visitGlobalVariable(*GV);
00434   if (UndefValue *UV = dyn_cast<UndefValue>(V))
00435     return visitUndefValue(*UV);
00436   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00437     if (CE->getOpcode() == Instruction::IntToPtr)
00438       return unknown(); // clueless
00439     if (CE->getOpcode() == Instruction::GetElementPtr)
00440       return visitGEPOperator(cast<GEPOperator>(*CE));
00441   }
00442 
00443   DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
00444         << '\n');
00445   return unknown();
00446 }
00447 
00448 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
00449   if (!I.getAllocatedType()->isSized())
00450     return unknown();
00451 
00452   APInt Size(IntTyBits, DL->getTypeAllocSize(I.getAllocatedType()));
00453   if (!I.isArrayAllocation())
00454     return std::make_pair(align(Size, I.getAlignment()), Zero);
00455 
00456   Value *ArraySize = I.getArraySize();
00457   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
00458     Size *= C->getValue().zextOrSelf(IntTyBits);
00459     return std::make_pair(align(Size, I.getAlignment()), Zero);
00460   }
00461   return unknown();
00462 }
00463 
00464 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
00465   // no interprocedural analysis is done at the moment
00466   if (!A.hasByValOrInAllocaAttr()) {
00467     ++ObjectVisitorArgument;
00468     return unknown();
00469   }
00470   PointerType *PT = cast<PointerType>(A.getType());
00471   APInt Size(IntTyBits, DL->getTypeAllocSize(PT->getElementType()));
00472   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
00473 }
00474 
00475 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
00476   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
00477                                                TLI);
00478   if (!FnData)
00479     return unknown();
00480 
00481   // handle strdup-like functions separately
00482   if (FnData->AllocTy == StrDupLike) {
00483     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
00484     if (!Size)
00485       return unknown();
00486 
00487     // strndup limits strlen
00488     if (FnData->FstParam > 0) {
00489       ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
00490       if (!Arg)
00491         return unknown();
00492 
00493       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
00494       if (Size.ugt(MaxSize))
00495         Size = MaxSize + 1;
00496     }
00497     return std::make_pair(Size, Zero);
00498   }
00499 
00500   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
00501   if (!Arg)
00502     return unknown();
00503 
00504   APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
00505   // size determined by just 1 parameter
00506   if (FnData->SndParam < 0)
00507     return std::make_pair(Size, Zero);
00508 
00509   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
00510   if (!Arg)
00511     return unknown();
00512 
00513   Size *= Arg->getValue().zextOrSelf(IntTyBits);
00514   return std::make_pair(Size, Zero);
00515 
00516   // TODO: handle more standard functions (+ wchar cousins):
00517   // - strdup / strndup
00518   // - strcpy / strncpy
00519   // - strcat / strncat
00520   // - memcpy / memmove
00521   // - strcat / strncat
00522   // - memset
00523 }
00524 
00525 SizeOffsetType
00526 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
00527   return std::make_pair(Zero, Zero);
00528 }
00529 
00530 SizeOffsetType
00531 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
00532   return unknown();
00533 }
00534 
00535 SizeOffsetType
00536 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
00537   // Easy cases were already folded by previous passes.
00538   return unknown();
00539 }
00540 
00541 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
00542   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
00543   APInt Offset(IntTyBits, 0);
00544   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(*DL, Offset))
00545     return unknown();
00546 
00547   return std::make_pair(PtrData.first, PtrData.second + Offset);
00548 }
00549 
00550 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
00551   if (GA.mayBeOverridden())
00552     return unknown();
00553   return compute(GA.getAliasee());
00554 }
00555 
00556 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
00557   if (!GV.hasDefinitiveInitializer())
00558     return unknown();
00559 
00560   APInt Size(IntTyBits, DL->getTypeAllocSize(GV.getType()->getElementType()));
00561   return std::make_pair(align(Size, GV.getAlignment()), Zero);
00562 }
00563 
00564 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
00565   // clueless
00566   return unknown();
00567 }
00568 
00569 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
00570   ++ObjectVisitorLoad;
00571   return unknown();
00572 }
00573 
00574 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
00575   // too complex to analyze statically.
00576   return unknown();
00577 }
00578 
00579 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
00580   SizeOffsetType TrueSide  = compute(I.getTrueValue());
00581   SizeOffsetType FalseSide = compute(I.getFalseValue());
00582   if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
00583     return TrueSide;
00584   return unknown();
00585 }
00586 
00587 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
00588   return std::make_pair(Zero, Zero);
00589 }
00590 
00591 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
00592   DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
00593   return unknown();
00594 }
00595 
00596 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(const DataLayout *DL,
00597                                                      const TargetLibraryInfo *TLI,
00598                                                      LLVMContext &Context,
00599                                                      bool RoundToAlign)
00600 : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
00601   RoundToAlign(RoundToAlign) {
00602   // IntTy and Zero must be set for each compute() since the address space may
00603   // be different for later objects.
00604 }
00605 
00606 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
00607   // XXX - Are vectors of pointers possible here?
00608   IntTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
00609   Zero = ConstantInt::get(IntTy, 0);
00610 
00611   SizeOffsetEvalType Result = compute_(V);
00612 
00613   if (!bothKnown(Result)) {
00614     // erase everything that was computed in this iteration from the cache, so
00615     // that no dangling references are left behind. We could be a bit smarter if
00616     // we kept a dependency graph. It's probably not worth the complexity.
00617     for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
00618       CacheMapTy::iterator CacheIt = CacheMap.find(*I);
00619       // non-computable results can be safely cached
00620       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
00621         CacheMap.erase(CacheIt);
00622     }
00623   }
00624 
00625   SeenVals.clear();
00626   return Result;
00627 }
00628 
00629 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
00630   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
00631   SizeOffsetType Const = Visitor.compute(V);
00632   if (Visitor.bothKnown(Const))
00633     return std::make_pair(ConstantInt::get(Context, Const.first),
00634                           ConstantInt::get(Context, Const.second));
00635 
00636   V = V->stripPointerCasts();
00637 
00638   // check cache
00639   CacheMapTy::iterator CacheIt = CacheMap.find(V);
00640   if (CacheIt != CacheMap.end())
00641     return CacheIt->second;
00642 
00643   // always generate code immediately before the instruction being
00644   // processed, so that the generated code dominates the same BBs
00645   Instruction *PrevInsertPoint = Builder.GetInsertPoint();
00646   if (Instruction *I = dyn_cast<Instruction>(V))
00647     Builder.SetInsertPoint(I);
00648 
00649   // now compute the size and offset
00650   SizeOffsetEvalType Result;
00651 
00652   // Record the pointers that were handled in this run, so that they can be
00653   // cleaned later if something fails. We also use this set to break cycles that
00654   // can occur in dead code.
00655   if (!SeenVals.insert(V).second) {
00656     Result = unknown();
00657   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00658     Result = visitGEPOperator(*GEP);
00659   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
00660     Result = visit(*I);
00661   } else if (isa<Argument>(V) ||
00662              (isa<ConstantExpr>(V) &&
00663               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
00664              isa<GlobalAlias>(V) ||
00665              isa<GlobalVariable>(V)) {
00666     // ignore values where we cannot do more than what ObjectSizeVisitor can
00667     Result = unknown();
00668   } else {
00669     DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
00670           << *V << '\n');
00671     Result = unknown();
00672   }
00673 
00674   if (PrevInsertPoint)
00675     Builder.SetInsertPoint(PrevInsertPoint);
00676 
00677   // Don't reuse CacheIt since it may be invalid at this point.
00678   CacheMap[V] = Result;
00679   return Result;
00680 }
00681 
00682 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
00683   if (!I.getAllocatedType()->isSized())
00684     return unknown();
00685 
00686   // must be a VLA
00687   assert(I.isArrayAllocation());
00688   Value *ArraySize = I.getArraySize();
00689   Value *Size = ConstantInt::get(ArraySize->getType(),
00690                                  DL->getTypeAllocSize(I.getAllocatedType()));
00691   Size = Builder.CreateMul(Size, ArraySize);
00692   return std::make_pair(Size, Zero);
00693 }
00694 
00695 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
00696   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
00697                                                TLI);
00698   if (!FnData)
00699     return unknown();
00700 
00701   // handle strdup-like functions separately
00702   if (FnData->AllocTy == StrDupLike) {
00703     // TODO
00704     return unknown();
00705   }
00706 
00707   Value *FirstArg = CS.getArgument(FnData->FstParam);
00708   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
00709   if (FnData->SndParam < 0)
00710     return std::make_pair(FirstArg, Zero);
00711 
00712   Value *SecondArg = CS.getArgument(FnData->SndParam);
00713   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
00714   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
00715   return std::make_pair(Size, Zero);
00716 
00717   // TODO: handle more standard functions (+ wchar cousins):
00718   // - strdup / strndup
00719   // - strcpy / strncpy
00720   // - strcat / strncat
00721   // - memcpy / memmove
00722   // - strcat / strncat
00723   // - memset
00724 }
00725 
00726 SizeOffsetEvalType
00727 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
00728   return unknown();
00729 }
00730 
00731 SizeOffsetEvalType
00732 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
00733   return unknown();
00734 }
00735 
00736 SizeOffsetEvalType
00737 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
00738   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
00739   if (!bothKnown(PtrData))
00740     return unknown();
00741 
00742   Value *Offset = EmitGEPOffset(&Builder, *DL, &GEP, /*NoAssumptions=*/true);
00743   Offset = Builder.CreateAdd(PtrData.second, Offset);
00744   return std::make_pair(PtrData.first, Offset);
00745 }
00746 
00747 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
00748   // clueless
00749   return unknown();
00750 }
00751 
00752 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
00753   return unknown();
00754 }
00755 
00756 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
00757   // create 2 PHIs: one for size and another for offset
00758   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
00759   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
00760 
00761   // insert right away in the cache to handle recursive PHIs
00762   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
00763 
00764   // compute offset/size for each PHI incoming pointer
00765   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
00766     Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
00767     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
00768 
00769     if (!bothKnown(EdgeData)) {
00770       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
00771       OffsetPHI->eraseFromParent();
00772       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
00773       SizePHI->eraseFromParent();
00774       return unknown();
00775     }
00776     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
00777     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
00778   }
00779 
00780   Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
00781   if ((Tmp = SizePHI->hasConstantValue())) {
00782     Size = Tmp;
00783     SizePHI->replaceAllUsesWith(Size);
00784     SizePHI->eraseFromParent();
00785   }
00786   if ((Tmp = OffsetPHI->hasConstantValue())) {
00787     Offset = Tmp;
00788     OffsetPHI->replaceAllUsesWith(Offset);
00789     OffsetPHI->eraseFromParent();
00790   }
00791   return std::make_pair(Size, Offset);
00792 }
00793 
00794 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
00795   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
00796   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
00797 
00798   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
00799     return unknown();
00800   if (TrueSide == FalseSide)
00801     return TrueSide;
00802 
00803   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
00804                                      FalseSide.first);
00805   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
00806                                        FalseSide.second);
00807   return std::make_pair(Size, Offset);
00808 }
00809 
00810 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
00811   DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
00812   return unknown();
00813 }