LLVM  mainline
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/TargetLibraryInfo.h"
00019 #include "llvm/Analysis/ValueTracking.h"
00020 #include "llvm/IR/DataLayout.h"
00021 #include "llvm/IR/GlobalVariable.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/IR/Intrinsics.h"
00024 #include "llvm/IR/Metadata.h"
00025 #include "llvm/IR/Module.h"
00026 #include "llvm/Support/Debug.h"
00027 #include "llvm/Support/MathExtras.h"
00028 #include "llvm/Support/raw_ostream.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())
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 /// getMallocType - Returns the PointerType resulting from the malloc call.
00236 /// The PointerType depends on the number of bitcast uses of the malloc call:
00237 ///   0: PointerType is the calls' return type.
00238 ///   1: PointerType is the bitcast's result type.
00239 ///  >1: Unique PointerType cannot be determined, return NULL.
00240 PointerType *llvm::getMallocType(const CallInst *CI,
00241                                  const TargetLibraryInfo *TLI) {
00242   assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
00243 
00244   PointerType *MallocType = nullptr;
00245   unsigned NumOfBitCastUses = 0;
00246 
00247   // Determine if CallInst has a bitcast use.
00248   for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end();
00249        UI != E;)
00250     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) {
00251       MallocType = cast<PointerType>(BCI->getDestTy());
00252       NumOfBitCastUses++;
00253     }
00254 
00255   // Malloc call has 1 bitcast use, so type is the bitcast's destination type.
00256   if (NumOfBitCastUses == 1)
00257     return MallocType;
00258 
00259   // Malloc call was not bitcast, so type is the malloc function's return type.
00260   if (NumOfBitCastUses == 0)
00261     return cast<PointerType>(CI->getType());
00262 
00263   // Type could not be determined.
00264   return nullptr;
00265 }
00266 
00267 /// getMallocAllocatedType - Returns the Type allocated by malloc call.
00268 /// The Type depends on the number of bitcast uses of the malloc call:
00269 ///   0: PointerType is the malloc calls' return type.
00270 ///   1: PointerType is the bitcast's result type.
00271 ///  >1: Unique PointerType cannot be determined, return NULL.
00272 Type *llvm::getMallocAllocatedType(const CallInst *CI,
00273                                    const TargetLibraryInfo *TLI) {
00274   PointerType *PT = getMallocType(CI, TLI);
00275   return PT ? PT->getElementType() : nullptr;
00276 }
00277 
00278 /// getMallocArraySize - Returns the array size of a malloc call.  If the
00279 /// argument passed to malloc is a multiple of the size of the malloced type,
00280 /// then return that multiple.  For non-array mallocs, the multiple is
00281 /// constant 1.  Otherwise, return NULL for mallocs whose array size cannot be
00282 /// determined.
00283 Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL,
00284                                 const TargetLibraryInfo *TLI,
00285                                 bool LookThroughSExt) {
00286   assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call");
00287   return computeArraySize(CI, DL, TLI, LookThroughSExt);
00288 }
00289 
00290 
00291 /// extractCallocCall - Returns the corresponding CallInst if the instruction
00292 /// is a calloc call.
00293 const CallInst *llvm::extractCallocCall(const Value *I,
00294                                         const TargetLibraryInfo *TLI) {
00295   return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
00296 }
00297 
00298 
00299 /// isFreeCall - Returns non-null if the value is a call to the builtin free()
00300 const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
00301   const CallInst *CI = dyn_cast<CallInst>(I);
00302   if (!CI || isa<IntrinsicInst>(CI))
00303     return nullptr;
00304   Function *Callee = CI->getCalledFunction();
00305   if (Callee == nullptr)
00306     return nullptr;
00307 
00308   StringRef FnName = Callee->getName();
00309   LibFunc::Func TLIFn;
00310   if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
00311     return nullptr;
00312 
00313   unsigned ExpectedNumParams;
00314   if (TLIFn == LibFunc::free ||
00315       TLIFn == LibFunc::ZdlPv || // operator delete(void*)
00316       TLIFn == LibFunc::ZdaPv)   // operator delete[](void*)
00317     ExpectedNumParams = 1;
00318   else if (TLIFn == LibFunc::ZdlPvj ||              // delete(void*, uint)
00319            TLIFn == LibFunc::ZdlPvm ||              // delete(void*, ulong)
00320            TLIFn == LibFunc::ZdlPvRKSt9nothrow_t || // delete(void*, nothrow)
00321            TLIFn == LibFunc::ZdaPvj ||              // delete[](void*, uint)
00322            TLIFn == LibFunc::ZdaPvm ||              // delete[](void*, ulong)
00323            TLIFn == LibFunc::ZdaPvRKSt9nothrow_t)   // delete[](void*, nothrow)
00324     ExpectedNumParams = 2;
00325   else
00326     return nullptr;
00327 
00328   // Check free prototype.
00329   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
00330   // attribute will exist.
00331   FunctionType *FTy = Callee->getFunctionType();
00332   if (!FTy->getReturnType()->isVoidTy())
00333     return nullptr;
00334   if (FTy->getNumParams() != ExpectedNumParams)
00335     return nullptr;
00336   if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
00337     return nullptr;
00338 
00339   return CI;
00340 }
00341 
00342 
00343 
00344 //===----------------------------------------------------------------------===//
00345 //  Utility functions to compute size of objects.
00346 //
00347 
00348 
00349 /// \brief Compute the size of the object pointed by Ptr. Returns true and the
00350 /// object size in Size if successful, and false otherwise.
00351 /// If RoundToAlign is true, then Size is rounded up to the aligment of allocas,
00352 /// byval arguments, and global variables.
00353 bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL,
00354                          const TargetLibraryInfo *TLI, bool RoundToAlign) {
00355   ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), RoundToAlign);
00356   SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr));
00357   if (!Visitor.bothKnown(Data))
00358     return false;
00359 
00360   APInt ObjSize = Data.first, Offset = Data.second;
00361   // check for overflow
00362   if (Offset.slt(0) || ObjSize.ult(Offset))
00363     Size = 0;
00364   else
00365     Size = (ObjSize - Offset).getZExtValue();
00366   return true;
00367 }
00368 
00369 
00370 STATISTIC(ObjectVisitorArgument,
00371           "Number of arguments with unsolved size and offset");
00372 STATISTIC(ObjectVisitorLoad,
00373           "Number of load instructions with unsolved size and offset");
00374 
00375 
00376 APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) {
00377   if (RoundToAlign && Align)
00378     return APInt(IntTyBits, RoundUpToAlignment(Size.getZExtValue(), Align));
00379   return Size;
00380 }
00381 
00382 ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL,
00383                                                  const TargetLibraryInfo *TLI,
00384                                                  LLVMContext &Context,
00385                                                  bool RoundToAlign)
00386     : DL(DL), TLI(TLI), RoundToAlign(RoundToAlign) {
00387   // Pointer size must be rechecked for each object visited since it could have
00388   // a different address space.
00389 }
00390 
00391 SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) {
00392   IntTyBits = DL.getPointerTypeSizeInBits(V->getType());
00393   Zero = APInt::getNullValue(IntTyBits);
00394 
00395   V = V->stripPointerCasts();
00396   if (Instruction *I = dyn_cast<Instruction>(V)) {
00397     // If we have already seen this instruction, bail out. Cycles can happen in
00398     // unreachable code after constant propagation.
00399     if (!SeenInsts.insert(I).second)
00400       return unknown();
00401 
00402     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
00403       return visitGEPOperator(*GEP);
00404     return visit(*I);
00405   }
00406   if (Argument *A = dyn_cast<Argument>(V))
00407     return visitArgument(*A);
00408   if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V))
00409     return visitConstantPointerNull(*P);
00410   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
00411     return visitGlobalAlias(*GA);
00412   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00413     return visitGlobalVariable(*GV);
00414   if (UndefValue *UV = dyn_cast<UndefValue>(V))
00415     return visitUndefValue(*UV);
00416   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00417     if (CE->getOpcode() == Instruction::IntToPtr)
00418       return unknown(); // clueless
00419     if (CE->getOpcode() == Instruction::GetElementPtr)
00420       return visitGEPOperator(cast<GEPOperator>(*CE));
00421   }
00422 
00423   DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V
00424         << '\n');
00425   return unknown();
00426 }
00427 
00428 SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) {
00429   if (!I.getAllocatedType()->isSized())
00430     return unknown();
00431 
00432   APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType()));
00433   if (!I.isArrayAllocation())
00434     return std::make_pair(align(Size, I.getAlignment()), Zero);
00435 
00436   Value *ArraySize = I.getArraySize();
00437   if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) {
00438     Size *= C->getValue().zextOrSelf(IntTyBits);
00439     return std::make_pair(align(Size, I.getAlignment()), Zero);
00440   }
00441   return unknown();
00442 }
00443 
00444 SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) {
00445   // no interprocedural analysis is done at the moment
00446   if (!A.hasByValOrInAllocaAttr()) {
00447     ++ObjectVisitorArgument;
00448     return unknown();
00449   }
00450   PointerType *PT = cast<PointerType>(A.getType());
00451   APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType()));
00452   return std::make_pair(align(Size, A.getParamAlignment()), Zero);
00453 }
00454 
00455 SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) {
00456   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
00457                                                TLI);
00458   if (!FnData)
00459     return unknown();
00460 
00461   // handle strdup-like functions separately
00462   if (FnData->AllocTy == StrDupLike) {
00463     APInt Size(IntTyBits, GetStringLength(CS.getArgument(0)));
00464     if (!Size)
00465       return unknown();
00466 
00467     // strndup limits strlen
00468     if (FnData->FstParam > 0) {
00469       ConstantInt *Arg= dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
00470       if (!Arg)
00471         return unknown();
00472 
00473       APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits);
00474       if (Size.ugt(MaxSize))
00475         Size = MaxSize + 1;
00476     }
00477     return std::make_pair(Size, Zero);
00478   }
00479 
00480   ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam));
00481   if (!Arg)
00482     return unknown();
00483 
00484   APInt Size = Arg->getValue().zextOrSelf(IntTyBits);
00485   // size determined by just 1 parameter
00486   if (FnData->SndParam < 0)
00487     return std::make_pair(Size, Zero);
00488 
00489   Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam));
00490   if (!Arg)
00491     return unknown();
00492 
00493   Size *= Arg->getValue().zextOrSelf(IntTyBits);
00494   return std::make_pair(Size, Zero);
00495 
00496   // TODO: handle more standard functions (+ wchar cousins):
00497   // - strdup / strndup
00498   // - strcpy / strncpy
00499   // - strcat / strncat
00500   // - memcpy / memmove
00501   // - strcat / strncat
00502   // - memset
00503 }
00504 
00505 SizeOffsetType
00506 ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull&) {
00507   return std::make_pair(Zero, Zero);
00508 }
00509 
00510 SizeOffsetType
00511 ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) {
00512   return unknown();
00513 }
00514 
00515 SizeOffsetType
00516 ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) {
00517   // Easy cases were already folded by previous passes.
00518   return unknown();
00519 }
00520 
00521 SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) {
00522   SizeOffsetType PtrData = compute(GEP.getPointerOperand());
00523   APInt Offset(IntTyBits, 0);
00524   if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset))
00525     return unknown();
00526 
00527   return std::make_pair(PtrData.first, PtrData.second + Offset);
00528 }
00529 
00530 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) {
00531   if (GA.mayBeOverridden())
00532     return unknown();
00533   return compute(GA.getAliasee());
00534 }
00535 
00536 SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){
00537   if (!GV.hasDefinitiveInitializer())
00538     return unknown();
00539 
00540   APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType()));
00541   return std::make_pair(align(Size, GV.getAlignment()), Zero);
00542 }
00543 
00544 SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) {
00545   // clueless
00546   return unknown();
00547 }
00548 
00549 SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) {
00550   ++ObjectVisitorLoad;
00551   return unknown();
00552 }
00553 
00554 SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) {
00555   // too complex to analyze statically.
00556   return unknown();
00557 }
00558 
00559 SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) {
00560   SizeOffsetType TrueSide  = compute(I.getTrueValue());
00561   SizeOffsetType FalseSide = compute(I.getFalseValue());
00562   if (bothKnown(TrueSide) && bothKnown(FalseSide) && TrueSide == FalseSide)
00563     return TrueSide;
00564   return unknown();
00565 }
00566 
00567 SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) {
00568   return std::make_pair(Zero, Zero);
00569 }
00570 
00571 SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) {
00572   DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n');
00573   return unknown();
00574 }
00575 
00576 ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator(
00577     const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context,
00578     bool RoundToAlign)
00579     : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL)),
00580       RoundToAlign(RoundToAlign) {
00581   // IntTy and Zero must be set for each compute() since the address space may
00582   // be different for later objects.
00583 }
00584 
00585 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) {
00586   // XXX - Are vectors of pointers possible here?
00587   IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
00588   Zero = ConstantInt::get(IntTy, 0);
00589 
00590   SizeOffsetEvalType Result = compute_(V);
00591 
00592   if (!bothKnown(Result)) {
00593     // erase everything that was computed in this iteration from the cache, so
00594     // that no dangling references are left behind. We could be a bit smarter if
00595     // we kept a dependency graph. It's probably not worth the complexity.
00596     for (PtrSetTy::iterator I=SeenVals.begin(), E=SeenVals.end(); I != E; ++I) {
00597       CacheMapTy::iterator CacheIt = CacheMap.find(*I);
00598       // non-computable results can be safely cached
00599       if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second))
00600         CacheMap.erase(CacheIt);
00601     }
00602   }
00603 
00604   SeenVals.clear();
00605   return Result;
00606 }
00607 
00608 SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) {
00609   ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, RoundToAlign);
00610   SizeOffsetType Const = Visitor.compute(V);
00611   if (Visitor.bothKnown(Const))
00612     return std::make_pair(ConstantInt::get(Context, Const.first),
00613                           ConstantInt::get(Context, Const.second));
00614 
00615   V = V->stripPointerCasts();
00616 
00617   // check cache
00618   CacheMapTy::iterator CacheIt = CacheMap.find(V);
00619   if (CacheIt != CacheMap.end())
00620     return CacheIt->second;
00621 
00622   // always generate code immediately before the instruction being
00623   // processed, so that the generated code dominates the same BBs
00624   Instruction *PrevInsertPoint = Builder.GetInsertPoint();
00625   if (Instruction *I = dyn_cast<Instruction>(V))
00626     Builder.SetInsertPoint(I);
00627 
00628   // now compute the size and offset
00629   SizeOffsetEvalType Result;
00630 
00631   // Record the pointers that were handled in this run, so that they can be
00632   // cleaned later if something fails. We also use this set to break cycles that
00633   // can occur in dead code.
00634   if (!SeenVals.insert(V).second) {
00635     Result = unknown();
00636   } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00637     Result = visitGEPOperator(*GEP);
00638   } else if (Instruction *I = dyn_cast<Instruction>(V)) {
00639     Result = visit(*I);
00640   } else if (isa<Argument>(V) ||
00641              (isa<ConstantExpr>(V) &&
00642               cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) ||
00643              isa<GlobalAlias>(V) ||
00644              isa<GlobalVariable>(V)) {
00645     // ignore values where we cannot do more than what ObjectSizeVisitor can
00646     Result = unknown();
00647   } else {
00648     DEBUG(dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: "
00649           << *V << '\n');
00650     Result = unknown();
00651   }
00652 
00653   if (PrevInsertPoint)
00654     Builder.SetInsertPoint(PrevInsertPoint);
00655 
00656   // Don't reuse CacheIt since it may be invalid at this point.
00657   CacheMap[V] = Result;
00658   return Result;
00659 }
00660 
00661 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) {
00662   if (!I.getAllocatedType()->isSized())
00663     return unknown();
00664 
00665   // must be a VLA
00666   assert(I.isArrayAllocation());
00667   Value *ArraySize = I.getArraySize();
00668   Value *Size = ConstantInt::get(ArraySize->getType(),
00669                                  DL.getTypeAllocSize(I.getAllocatedType()));
00670   Size = Builder.CreateMul(Size, ArraySize);
00671   return std::make_pair(Size, Zero);
00672 }
00673 
00674 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) {
00675   const AllocFnsTy *FnData = getAllocationData(CS.getInstruction(), AnyAlloc,
00676                                                TLI);
00677   if (!FnData)
00678     return unknown();
00679 
00680   // handle strdup-like functions separately
00681   if (FnData->AllocTy == StrDupLike) {
00682     // TODO
00683     return unknown();
00684   }
00685 
00686   Value *FirstArg = CS.getArgument(FnData->FstParam);
00687   FirstArg = Builder.CreateZExt(FirstArg, IntTy);
00688   if (FnData->SndParam < 0)
00689     return std::make_pair(FirstArg, Zero);
00690 
00691   Value *SecondArg = CS.getArgument(FnData->SndParam);
00692   SecondArg = Builder.CreateZExt(SecondArg, IntTy);
00693   Value *Size = Builder.CreateMul(FirstArg, SecondArg);
00694   return std::make_pair(Size, Zero);
00695 
00696   // TODO: handle more standard functions (+ wchar cousins):
00697   // - strdup / strndup
00698   // - strcpy / strncpy
00699   // - strcat / strncat
00700   // - memcpy / memmove
00701   // - strcat / strncat
00702   // - memset
00703 }
00704 
00705 SizeOffsetEvalType
00706 ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) {
00707   return unknown();
00708 }
00709 
00710 SizeOffsetEvalType
00711 ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) {
00712   return unknown();
00713 }
00714 
00715 SizeOffsetEvalType
00716 ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) {
00717   SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand());
00718   if (!bothKnown(PtrData))
00719     return unknown();
00720 
00721   Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true);
00722   Offset = Builder.CreateAdd(PtrData.second, Offset);
00723   return std::make_pair(PtrData.first, Offset);
00724 }
00725 
00726 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) {
00727   // clueless
00728   return unknown();
00729 }
00730 
00731 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) {
00732   return unknown();
00733 }
00734 
00735 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) {
00736   // create 2 PHIs: one for size and another for offset
00737   PHINode *SizePHI   = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
00738   PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues());
00739 
00740   // insert right away in the cache to handle recursive PHIs
00741   CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI);
00742 
00743   // compute offset/size for each PHI incoming pointer
00744   for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) {
00745     Builder.SetInsertPoint(PHI.getIncomingBlock(i)->getFirstInsertionPt());
00746     SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i));
00747 
00748     if (!bothKnown(EdgeData)) {
00749       OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy));
00750       OffsetPHI->eraseFromParent();
00751       SizePHI->replaceAllUsesWith(UndefValue::get(IntTy));
00752       SizePHI->eraseFromParent();
00753       return unknown();
00754     }
00755     SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i));
00756     OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i));
00757   }
00758 
00759   Value *Size = SizePHI, *Offset = OffsetPHI, *Tmp;
00760   if ((Tmp = SizePHI->hasConstantValue())) {
00761     Size = Tmp;
00762     SizePHI->replaceAllUsesWith(Size);
00763     SizePHI->eraseFromParent();
00764   }
00765   if ((Tmp = OffsetPHI->hasConstantValue())) {
00766     Offset = Tmp;
00767     OffsetPHI->replaceAllUsesWith(Offset);
00768     OffsetPHI->eraseFromParent();
00769   }
00770   return std::make_pair(Size, Offset);
00771 }
00772 
00773 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) {
00774   SizeOffsetEvalType TrueSide  = compute_(I.getTrueValue());
00775   SizeOffsetEvalType FalseSide = compute_(I.getFalseValue());
00776 
00777   if (!bothKnown(TrueSide) || !bothKnown(FalseSide))
00778     return unknown();
00779   if (TrueSide == FalseSide)
00780     return TrueSide;
00781 
00782   Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first,
00783                                      FalseSide.first);
00784   Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second,
00785                                        FalseSide.second);
00786   return std::make_pair(Size, Offset);
00787 }
00788 
00789 SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) {
00790   DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I <<'\n');
00791   return unknown();
00792 }