LLVM  mainline
Lint.cpp
Go to the documentation of this file.
00001 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
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 pass statically checks for common and easily-identified constructs
00011 // which produce undefined or likely unintended behavior in LLVM IR.
00012 //
00013 // It is not a guarantee of correctness, in two ways. First, it isn't
00014 // comprehensive. There are checks which could be done statically which are
00015 // not yet implemented. Some of these are indicated by TODO comments, but
00016 // those aren't comprehensive either. Second, many conditions cannot be
00017 // checked statically. This pass does no dynamic instrumentation, so it
00018 // can't check for all possible problems.
00019 //
00020 // Another limitation is that it assumes all code will be executed. A store
00021 // through a null pointer in a basic block which is never reached is harmless,
00022 // but this pass will warn about it anyway. This is the main reason why most
00023 // of these checks live here instead of in the Verifier pass.
00024 //
00025 // Optimization passes may make conditions that this pass checks for more or
00026 // less obvious. If an optimization pass appears to be introducing a warning,
00027 // it may be that the optimization pass is merely exposing an existing
00028 // condition in the code.
00029 //
00030 // This code may be run before instcombine. In many cases, instcombine checks
00031 // for the same kinds of things and turns instructions with undefined behavior
00032 // into unreachable (or equivalent). Because of this, this pass makes some
00033 // effort to look through bitcasts and so on.
00034 //
00035 //===----------------------------------------------------------------------===//
00036 
00037 #include "llvm/Analysis/Lint.h"
00038 #include "llvm/ADT/STLExtras.h"
00039 #include "llvm/ADT/SmallSet.h"
00040 #include "llvm/Analysis/AliasAnalysis.h"
00041 #include "llvm/Analysis/AssumptionCache.h"
00042 #include "llvm/Analysis/ConstantFolding.h"
00043 #include "llvm/Analysis/InstructionSimplify.h"
00044 #include "llvm/Analysis/Loads.h"
00045 #include "llvm/Analysis/Passes.h"
00046 #include "llvm/Analysis/TargetLibraryInfo.h"
00047 #include "llvm/Analysis/ValueTracking.h"
00048 #include "llvm/IR/CallSite.h"
00049 #include "llvm/IR/DataLayout.h"
00050 #include "llvm/IR/Dominators.h"
00051 #include "llvm/IR/Function.h"
00052 #include "llvm/IR/InstVisitor.h"
00053 #include "llvm/IR/IntrinsicInst.h"
00054 #include "llvm/IR/LegacyPassManager.h"
00055 #include "llvm/Pass.h"
00056 #include "llvm/Support/Debug.h"
00057 #include "llvm/Support/raw_ostream.h"
00058 using namespace llvm;
00059 
00060 namespace {
00061   namespace MemRef {
00062     static const unsigned Read     = 1;
00063     static const unsigned Write    = 2;
00064     static const unsigned Callee   = 4;
00065     static const unsigned Branchee = 8;
00066   }
00067 
00068   class Lint : public FunctionPass, public InstVisitor<Lint> {
00069     friend class InstVisitor<Lint>;
00070 
00071     void visitFunction(Function &F);
00072 
00073     void visitCallSite(CallSite CS);
00074     void visitMemoryReference(Instruction &I, Value *Ptr,
00075                               uint64_t Size, unsigned Align,
00076                               Type *Ty, unsigned Flags);
00077     void visitEHBeginCatch(IntrinsicInst *II);
00078     void visitEHEndCatch(IntrinsicInst *II);
00079 
00080     void visitCallInst(CallInst &I);
00081     void visitInvokeInst(InvokeInst &I);
00082     void visitReturnInst(ReturnInst &I);
00083     void visitLoadInst(LoadInst &I);
00084     void visitStoreInst(StoreInst &I);
00085     void visitXor(BinaryOperator &I);
00086     void visitSub(BinaryOperator &I);
00087     void visitLShr(BinaryOperator &I);
00088     void visitAShr(BinaryOperator &I);
00089     void visitShl(BinaryOperator &I);
00090     void visitSDiv(BinaryOperator &I);
00091     void visitUDiv(BinaryOperator &I);
00092     void visitSRem(BinaryOperator &I);
00093     void visitURem(BinaryOperator &I);
00094     void visitAllocaInst(AllocaInst &I);
00095     void visitVAArgInst(VAArgInst &I);
00096     void visitIndirectBrInst(IndirectBrInst &I);
00097     void visitExtractElementInst(ExtractElementInst &I);
00098     void visitInsertElementInst(InsertElementInst &I);
00099     void visitUnreachableInst(UnreachableInst &I);
00100 
00101     Value *findValue(Value *V, const DataLayout &DL, bool OffsetOk) const;
00102     Value *findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
00103                          SmallPtrSetImpl<Value *> &Visited) const;
00104 
00105   public:
00106     Module *Mod;
00107     AliasAnalysis *AA;
00108     AssumptionCache *AC;
00109     DominatorTree *DT;
00110     TargetLibraryInfo *TLI;
00111 
00112     std::string Messages;
00113     raw_string_ostream MessagesStr;
00114 
00115     static char ID; // Pass identification, replacement for typeid
00116     Lint() : FunctionPass(ID), MessagesStr(Messages) {
00117       initializeLintPass(*PassRegistry::getPassRegistry());
00118     }
00119 
00120     bool runOnFunction(Function &F) override;
00121 
00122     void getAnalysisUsage(AnalysisUsage &AU) const override {
00123       AU.setPreservesAll();
00124       AU.addRequired<AliasAnalysis>();
00125       AU.addRequired<AssumptionCacheTracker>();
00126       AU.addRequired<TargetLibraryInfoWrapperPass>();
00127       AU.addRequired<DominatorTreeWrapperPass>();
00128     }
00129     void print(raw_ostream &O, const Module *M) const override {}
00130 
00131     void WriteValues(ArrayRef<const Value *> Vs) {
00132       for (const Value *V : Vs) {
00133         if (!V)
00134           continue;
00135         if (isa<Instruction>(V)) {
00136           MessagesStr << *V << '\n';
00137         } else {
00138           V->printAsOperand(MessagesStr, true, Mod);
00139           MessagesStr << '\n';
00140         }
00141       }
00142     }
00143 
00144     /// \brief A check failed, so printout out the condition and the message.
00145     ///
00146     /// This provides a nice place to put a breakpoint if you want to see why
00147     /// something is not correct.
00148     void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
00149 
00150     /// \brief A check failed (with values to print).
00151     ///
00152     /// This calls the Message-only version so that the above is easier to set
00153     /// a breakpoint on.
00154     template <typename T1, typename... Ts>
00155     void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
00156       CheckFailed(Message);
00157       WriteValues({V1, Vs...});
00158     }
00159   };
00160 }
00161 
00162 char Lint::ID = 0;
00163 INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
00164                       false, true)
00165 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00166 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00167 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00168 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00169 INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
00170                     false, true)
00171 
00172 // Assert - We know that cond should be true, if not print an error message.
00173 #define Assert(C, ...) \
00174     do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
00175 
00176 // Lint::run - This is the main Analysis entry point for a
00177 // function.
00178 //
00179 bool Lint::runOnFunction(Function &F) {
00180   Mod = F.getParent();
00181   AA = &getAnalysis<AliasAnalysis>();
00182   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00183   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00184   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
00185   visit(F);
00186   dbgs() << MessagesStr.str();
00187   Messages.clear();
00188   return false;
00189 }
00190 
00191 void Lint::visitFunction(Function &F) {
00192   // This isn't undefined behavior, it's just a little unusual, and it's a
00193   // fairly common mistake to neglect to name a function.
00194   Assert(F.hasName() || F.hasLocalLinkage(),
00195          "Unusual: Unnamed function with non-local linkage", &F);
00196 
00197   // TODO: Check for irreducible control flow.
00198 }
00199 
00200 void Lint::visitCallSite(CallSite CS) {
00201   Instruction &I = *CS.getInstruction();
00202   Value *Callee = CS.getCalledValue();
00203   const DataLayout &DL = CS->getModule()->getDataLayout();
00204 
00205   visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
00206                        MemRef::Callee);
00207 
00208   if (Function *F = dyn_cast<Function>(findValue(Callee, DL,
00209                                                  /*OffsetOk=*/false))) {
00210     Assert(CS.getCallingConv() == F->getCallingConv(),
00211            "Undefined behavior: Caller and callee calling convention differ",
00212            &I);
00213 
00214     FunctionType *FT = F->getFunctionType();
00215     unsigned NumActualArgs = CS.arg_size();
00216 
00217     Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
00218                           : FT->getNumParams() == NumActualArgs,
00219            "Undefined behavior: Call argument count mismatches callee "
00220            "argument count",
00221            &I);
00222 
00223     Assert(FT->getReturnType() == I.getType(),
00224            "Undefined behavior: Call return type mismatches "
00225            "callee return type",
00226            &I);
00227 
00228     // Check argument types (in case the callee was casted) and attributes.
00229     // TODO: Verify that caller and callee attributes are compatible.
00230     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
00231     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
00232     for (; AI != AE; ++AI) {
00233       Value *Actual = *AI;
00234       if (PI != PE) {
00235         Argument *Formal = PI++;
00236         Assert(Formal->getType() == Actual->getType(),
00237                "Undefined behavior: Call argument type mismatches "
00238                "callee parameter type",
00239                &I);
00240 
00241         // Check that noalias arguments don't alias other arguments. This is
00242         // not fully precise because we don't know the sizes of the dereferenced
00243         // memory regions.
00244         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
00245           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
00246             if (AI != BI && (*BI)->getType()->isPointerTy()) {
00247               AliasResult Result = AA->alias(*AI, *BI);
00248               Assert(Result != MustAlias && Result != PartialAlias,
00249                      "Unusual: noalias argument aliases another argument", &I);
00250             }
00251 
00252         // Check that an sret argument points to valid memory.
00253         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
00254           Type *Ty =
00255             cast<PointerType>(Formal->getType())->getElementType();
00256           visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
00257                                DL.getABITypeAlignment(Ty), Ty,
00258                                MemRef::Read | MemRef::Write);
00259         }
00260       }
00261     }
00262   }
00263 
00264   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
00265     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
00266          AI != AE; ++AI) {
00267       Value *Obj = findValue(*AI, DL, /*OffsetOk=*/true);
00268       Assert(!isa<AllocaInst>(Obj),
00269              "Undefined behavior: Call with \"tail\" keyword references "
00270              "alloca",
00271              &I);
00272     }
00273 
00274 
00275   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
00276     switch (II->getIntrinsicID()) {
00277     default: break;
00278 
00279     // TODO: Check more intrinsics
00280 
00281     case Intrinsic::memcpy: {
00282       MemCpyInst *MCI = cast<MemCpyInst>(&I);
00283       // TODO: If the size is known, use it.
00284       visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
00285                            MCI->getAlignment(), nullptr, MemRef::Write);
00286       visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
00287                            MCI->getAlignment(), nullptr, MemRef::Read);
00288 
00289       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
00290       // isn't expressive enough for what we really want to do. Known partial
00291       // overlap is not distinguished from the case where nothing is known.
00292       uint64_t Size = 0;
00293       if (const ConstantInt *Len =
00294               dyn_cast<ConstantInt>(findValue(MCI->getLength(), DL,
00295                                               /*OffsetOk=*/false)))
00296         if (Len->getValue().isIntN(32))
00297           Size = Len->getValue().getZExtValue();
00298       Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
00299                  MustAlias,
00300              "Undefined behavior: memcpy source and destination overlap", &I);
00301       break;
00302     }
00303     case Intrinsic::memmove: {
00304       MemMoveInst *MMI = cast<MemMoveInst>(&I);
00305       // TODO: If the size is known, use it.
00306       visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
00307                            MMI->getAlignment(), nullptr, MemRef::Write);
00308       visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
00309                            MMI->getAlignment(), nullptr, MemRef::Read);
00310       break;
00311     }
00312     case Intrinsic::memset: {
00313       MemSetInst *MSI = cast<MemSetInst>(&I);
00314       // TODO: If the size is known, use it.
00315       visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
00316                            MSI->getAlignment(), nullptr, MemRef::Write);
00317       break;
00318     }
00319 
00320     case Intrinsic::vastart:
00321       Assert(I.getParent()->getParent()->isVarArg(),
00322              "Undefined behavior: va_start called in a non-varargs function",
00323              &I);
00324 
00325       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00326                            nullptr, MemRef::Read | MemRef::Write);
00327       break;
00328     case Intrinsic::vacopy:
00329       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00330                            nullptr, MemRef::Write);
00331       visitMemoryReference(I, CS.getArgument(1), MemoryLocation::UnknownSize, 0,
00332                            nullptr, MemRef::Read);
00333       break;
00334     case Intrinsic::vaend:
00335       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00336                            nullptr, MemRef::Read | MemRef::Write);
00337       break;
00338 
00339     case Intrinsic::stackrestore:
00340       // Stackrestore doesn't read or write memory, but it sets the
00341       // stack pointer, which the compiler may read from or write to
00342       // at any time, so check it for both readability and writeability.
00343       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
00344                            nullptr, MemRef::Read | MemRef::Write);
00345       break;
00346 
00347     case Intrinsic::eh_begincatch:
00348       visitEHBeginCatch(II);
00349       break;
00350     case Intrinsic::eh_endcatch:
00351       visitEHEndCatch(II);
00352       break;
00353     }
00354 }
00355 
00356 void Lint::visitCallInst(CallInst &I) {
00357   return visitCallSite(&I);
00358 }
00359 
00360 void Lint::visitInvokeInst(InvokeInst &I) {
00361   return visitCallSite(&I);
00362 }
00363 
00364 void Lint::visitReturnInst(ReturnInst &I) {
00365   Function *F = I.getParent()->getParent();
00366   Assert(!F->doesNotReturn(),
00367          "Unusual: Return statement in function with noreturn attribute", &I);
00368 
00369   if (Value *V = I.getReturnValue()) {
00370     Value *Obj =
00371         findValue(V, F->getParent()->getDataLayout(), /*OffsetOk=*/true);
00372     Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
00373   }
00374 }
00375 
00376 // TODO: Check that the reference is in bounds.
00377 // TODO: Check readnone/readonly function attributes.
00378 void Lint::visitMemoryReference(Instruction &I,
00379                                 Value *Ptr, uint64_t Size, unsigned Align,
00380                                 Type *Ty, unsigned Flags) {
00381   // If no memory is being referenced, it doesn't matter if the pointer
00382   // is valid.
00383   if (Size == 0)
00384     return;
00385 
00386   Value *UnderlyingObject =
00387       findValue(Ptr, I.getModule()->getDataLayout(), /*OffsetOk=*/true);
00388   Assert(!isa<ConstantPointerNull>(UnderlyingObject),
00389          "Undefined behavior: Null pointer dereference", &I);
00390   Assert(!isa<UndefValue>(UnderlyingObject),
00391          "Undefined behavior: Undef pointer dereference", &I);
00392   Assert(!isa<ConstantInt>(UnderlyingObject) ||
00393              !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
00394          "Unusual: All-ones pointer dereference", &I);
00395   Assert(!isa<ConstantInt>(UnderlyingObject) ||
00396              !cast<ConstantInt>(UnderlyingObject)->isOne(),
00397          "Unusual: Address one pointer dereference", &I);
00398 
00399   if (Flags & MemRef::Write) {
00400     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
00401       Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
00402              &I);
00403     Assert(!isa<Function>(UnderlyingObject) &&
00404                !isa<BlockAddress>(UnderlyingObject),
00405            "Undefined behavior: Write to text section", &I);
00406   }
00407   if (Flags & MemRef::Read) {
00408     Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
00409            &I);
00410     Assert(!isa<BlockAddress>(UnderlyingObject),
00411            "Undefined behavior: Load from block address", &I);
00412   }
00413   if (Flags & MemRef::Callee) {
00414     Assert(!isa<BlockAddress>(UnderlyingObject),
00415            "Undefined behavior: Call to block address", &I);
00416   }
00417   if (Flags & MemRef::Branchee) {
00418     Assert(!isa<Constant>(UnderlyingObject) ||
00419                isa<BlockAddress>(UnderlyingObject),
00420            "Undefined behavior: Branch to non-blockaddress", &I);
00421   }
00422 
00423   // Check for buffer overflows and misalignment.
00424   // Only handles memory references that read/write something simple like an
00425   // alloca instruction or a global variable.
00426   auto &DL = I.getModule()->getDataLayout();
00427   int64_t Offset = 0;
00428   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL)) {
00429     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
00430     // something we can handle and if so extract the size of this base object
00431     // along with its alignment.
00432     uint64_t BaseSize = MemoryLocation::UnknownSize;
00433     unsigned BaseAlign = 0;
00434 
00435     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
00436       Type *ATy = AI->getAllocatedType();
00437       if (!AI->isArrayAllocation() && ATy->isSized())
00438         BaseSize = DL.getTypeAllocSize(ATy);
00439       BaseAlign = AI->getAlignment();
00440       if (BaseAlign == 0 && ATy->isSized())
00441         BaseAlign = DL.getABITypeAlignment(ATy);
00442     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
00443       // If the global may be defined differently in another compilation unit
00444       // then don't warn about funky memory accesses.
00445       if (GV->hasDefinitiveInitializer()) {
00446         Type *GTy = GV->getType()->getElementType();
00447         if (GTy->isSized())
00448           BaseSize = DL.getTypeAllocSize(GTy);
00449         BaseAlign = GV->getAlignment();
00450         if (BaseAlign == 0 && GTy->isSized())
00451           BaseAlign = DL.getABITypeAlignment(GTy);
00452       }
00453     }
00454 
00455     // Accesses from before the start or after the end of the object are not
00456     // defined.
00457     Assert(Size == MemoryLocation::UnknownSize ||
00458                BaseSize == MemoryLocation::UnknownSize ||
00459                (Offset >= 0 && Offset + Size <= BaseSize),
00460            "Undefined behavior: Buffer overflow", &I);
00461 
00462     // Accesses that say that the memory is more aligned than it is are not
00463     // defined.
00464     if (Align == 0 && Ty && Ty->isSized())
00465       Align = DL.getABITypeAlignment(Ty);
00466     Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
00467            "Undefined behavior: Memory reference address is misaligned", &I);
00468   }
00469 }
00470 
00471 void Lint::visitLoadInst(LoadInst &I) {
00472   visitMemoryReference(I, I.getPointerOperand(),
00473                        AA->getTypeStoreSize(I.getType()), I.getAlignment(),
00474                        I.getType(), MemRef::Read);
00475 }
00476 
00477 void Lint::visitStoreInst(StoreInst &I) {
00478   visitMemoryReference(I, I.getPointerOperand(),
00479                        AA->getTypeStoreSize(I.getOperand(0)->getType()),
00480                        I.getAlignment(),
00481                        I.getOperand(0)->getType(), MemRef::Write);
00482 }
00483 
00484 void Lint::visitXor(BinaryOperator &I) {
00485   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
00486          "Undefined result: xor(undef, undef)", &I);
00487 }
00488 
00489 void Lint::visitSub(BinaryOperator &I) {
00490   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
00491          "Undefined result: sub(undef, undef)", &I);
00492 }
00493 
00494 void Lint::visitLShr(BinaryOperator &I) {
00495   if (ConstantInt *CI = dyn_cast<ConstantInt>(
00496           findValue(I.getOperand(1), I.getModule()->getDataLayout(),
00497                     /*OffsetOk=*/false)))
00498     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00499            "Undefined result: Shift count out of range", &I);
00500 }
00501 
00502 void Lint::visitAShr(BinaryOperator &I) {
00503   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
00504           I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
00505     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00506            "Undefined result: Shift count out of range", &I);
00507 }
00508 
00509 void Lint::visitShl(BinaryOperator &I) {
00510   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(
00511           I.getOperand(1), I.getModule()->getDataLayout(), /*OffsetOk=*/false)))
00512     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
00513            "Undefined result: Shift count out of range", &I);
00514 }
00515 
00516 static bool
00517 allPredsCameFromLandingPad(BasicBlock *BB,
00518                            SmallSet<BasicBlock *, 4> &VisitedBlocks) {
00519   VisitedBlocks.insert(BB);
00520   if (BB->isLandingPad())
00521     return true;
00522   // If we find a block with no predecessors, the search failed.
00523   if (pred_empty(BB))
00524     return false;
00525   for (BasicBlock *Pred : predecessors(BB)) {
00526     if (VisitedBlocks.count(Pred))
00527       continue;
00528     if (!allPredsCameFromLandingPad(Pred, VisitedBlocks))
00529       return false;
00530   }
00531   return true;
00532 }
00533 
00534 static bool
00535 allSuccessorsReachEndCatch(BasicBlock *BB, BasicBlock::iterator InstBegin,
00536                            IntrinsicInst **SecondBeginCatch,
00537                            SmallSet<BasicBlock *, 4> &VisitedBlocks) {
00538   VisitedBlocks.insert(BB);
00539   for (BasicBlock::iterator I = InstBegin, E = BB->end(); I != E; ++I) {
00540     IntrinsicInst *IC = dyn_cast<IntrinsicInst>(I);
00541     if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch)
00542       return true;
00543     // If we find another begincatch while looking for an endcatch,
00544     // that's also an error.
00545     if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch) {
00546       *SecondBeginCatch = IC;
00547       return false;
00548     }
00549   }
00550 
00551   // If we reach a block with no successors while searching, the
00552   // search has failed.
00553   if (succ_empty(BB))
00554     return false;
00555   // Otherwise, search all of the successors.
00556   for (BasicBlock *Succ : successors(BB)) {
00557     if (VisitedBlocks.count(Succ))
00558       continue;
00559     if (!allSuccessorsReachEndCatch(Succ, Succ->begin(), SecondBeginCatch,
00560                                     VisitedBlocks))
00561       return false;
00562   }
00563   return true;
00564 }
00565 
00566 void Lint::visitEHBeginCatch(IntrinsicInst *II) {
00567   // The checks in this function make a potentially dubious assumption about
00568   // the CFG, namely that any block involved in a catch is only used for the
00569   // catch.  This will very likely be true of IR generated by a front end,
00570   // but it may cease to be true, for example, if the IR is run through a
00571   // pass which combines similar blocks.
00572   //
00573   // In general, if we encounter a block the isn't dominated by the catch
00574   // block while we are searching the catch block's successors for a call
00575   // to end catch intrinsic, then it is possible that it will be legal for
00576   // a path through this block to never reach a call to llvm.eh.endcatch.
00577   // An analogous statement could be made about our search for a landing
00578   // pad among the catch block's predecessors.
00579   //
00580   // What is actually required is that no path is possible at runtime that
00581   // reaches a call to llvm.eh.begincatch without having previously visited
00582   // a landingpad instruction and that no path is possible at runtime that
00583   // calls llvm.eh.begincatch and does not subsequently call llvm.eh.endcatch
00584   // (mentally adjusting for the fact that in reality these calls will be
00585   // removed before code generation).
00586   //
00587   // Because this is a lint check, we take a pessimistic approach and warn if
00588   // the control flow is potentially incorrect.
00589 
00590   SmallSet<BasicBlock *, 4> VisitedBlocks;
00591   BasicBlock *CatchBB = II->getParent();
00592 
00593   // The begin catch must occur in a landing pad block or all paths
00594   // to it must have come from a landing pad.
00595   Assert(allPredsCameFromLandingPad(CatchBB, VisitedBlocks),
00596          "llvm.eh.begincatch may be reachable without passing a landingpad",
00597          II);
00598 
00599   // Reset the visited block list.
00600   VisitedBlocks.clear();
00601 
00602   IntrinsicInst *SecondBeginCatch = nullptr;
00603 
00604   // This has to be called before it is asserted.  Otherwise, the first assert
00605   // below can never be hit.
00606   bool EndCatchFound = allSuccessorsReachEndCatch(
00607       CatchBB, std::next(static_cast<BasicBlock::iterator>(II)),
00608       &SecondBeginCatch, VisitedBlocks);
00609   Assert(
00610       SecondBeginCatch == nullptr,
00611       "llvm.eh.begincatch may be called a second time before llvm.eh.endcatch",
00612       II, SecondBeginCatch);
00613   Assert(EndCatchFound,
00614          "Some paths from llvm.eh.begincatch may not reach llvm.eh.endcatch",
00615          II);
00616 }
00617 
00618 static bool allPredCameFromBeginCatch(
00619     BasicBlock *BB, BasicBlock::reverse_iterator InstRbegin,
00620     IntrinsicInst **SecondEndCatch, SmallSet<BasicBlock *, 4> &VisitedBlocks) {
00621   VisitedBlocks.insert(BB);
00622   // Look for a begincatch in this block.
00623   for (BasicBlock::reverse_iterator RI = InstRbegin, RE = BB->rend(); RI != RE;
00624        ++RI) {
00625     IntrinsicInst *IC = dyn_cast<IntrinsicInst>(&*RI);
00626     if (IC && IC->getIntrinsicID() == Intrinsic::eh_begincatch)
00627       return true;
00628     // If we find another end catch before we find a begin catch, that's
00629     // an error.
00630     if (IC && IC->getIntrinsicID() == Intrinsic::eh_endcatch) {
00631       *SecondEndCatch = IC;
00632       return false;
00633     }
00634     // If we encounter a landingpad instruction, the search failed.
00635     if (isa<LandingPadInst>(*RI))
00636       return false;
00637   }
00638   // If while searching we find a block with no predeccesors,
00639   // the search failed.
00640   if (pred_empty(BB))
00641     return false;
00642   // Search any predecessors we haven't seen before.
00643   for (BasicBlock *Pred : predecessors(BB)) {
00644     if (VisitedBlocks.count(Pred))
00645       continue;
00646     if (!allPredCameFromBeginCatch(Pred, Pred->rbegin(), SecondEndCatch,
00647                                    VisitedBlocks))
00648       return false;
00649   }
00650   return true;
00651 }
00652 
00653 void Lint::visitEHEndCatch(IntrinsicInst *II) {
00654   // The check in this function makes a potentially dubious assumption about
00655   // the CFG, namely that any block involved in a catch is only used for the
00656   // catch.  This will very likely be true of IR generated by a front end,
00657   // but it may cease to be true, for example, if the IR is run through a
00658   // pass which combines similar blocks.
00659   //
00660   // In general, if we encounter a block the isn't post-dominated by the
00661   // end catch block while we are searching the end catch block's predecessors
00662   // for a call to the begin catch intrinsic, then it is possible that it will
00663   // be legal for a path to reach the end catch block without ever having
00664   // called llvm.eh.begincatch.
00665   //
00666   // What is actually required is that no path is possible at runtime that
00667   // reaches a call to llvm.eh.endcatch without having previously visited
00668   // a call to llvm.eh.begincatch (mentally adjusting for the fact that in
00669   // reality these calls will be removed before code generation).
00670   //
00671   // Because this is a lint check, we take a pessimistic approach and warn if
00672   // the control flow is potentially incorrect.
00673 
00674   BasicBlock *EndCatchBB = II->getParent();
00675 
00676   // Alls paths to the end catch call must pass through a begin catch call.
00677 
00678   // If llvm.eh.begincatch wasn't called in the current block, we'll use this
00679   // lambda to recursively look for it in predecessors.
00680   SmallSet<BasicBlock *, 4> VisitedBlocks;
00681   IntrinsicInst *SecondEndCatch = nullptr;
00682 
00683   // This has to be called before it is asserted.  Otherwise, the first assert
00684   // below can never be hit.
00685   bool BeginCatchFound =
00686       allPredCameFromBeginCatch(EndCatchBB, BasicBlock::reverse_iterator(II),
00687                                 &SecondEndCatch, VisitedBlocks);
00688   Assert(
00689       SecondEndCatch == nullptr,
00690       "llvm.eh.endcatch may be called a second time after llvm.eh.begincatch",
00691       II, SecondEndCatch);
00692   Assert(BeginCatchFound,
00693          "llvm.eh.endcatch may be reachable without passing llvm.eh.begincatch",
00694          II);
00695 }
00696 
00697 static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
00698                    AssumptionCache *AC) {
00699   // Assume undef could be zero.
00700   if (isa<UndefValue>(V))
00701     return true;
00702 
00703   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
00704   if (!VecTy) {
00705     unsigned BitWidth = V->getType()->getIntegerBitWidth();
00706     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00707     computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
00708                      dyn_cast<Instruction>(V), DT);
00709     return KnownZero.isAllOnesValue();
00710   }
00711 
00712   // Per-component check doesn't work with zeroinitializer
00713   Constant *C = dyn_cast<Constant>(V);
00714   if (!C)
00715     return false;
00716 
00717   if (C->isZeroValue())
00718     return true;
00719 
00720   // For a vector, KnownZero will only be true if all values are zero, so check
00721   // this per component
00722   unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
00723   for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
00724     Constant *Elem = C->getAggregateElement(I);
00725     if (isa<UndefValue>(Elem))
00726       return true;
00727 
00728     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
00729     computeKnownBits(Elem, KnownZero, KnownOne, DL);
00730     if (KnownZero.isAllOnesValue())
00731       return true;
00732   }
00733 
00734   return false;
00735 }
00736 
00737 void Lint::visitSDiv(BinaryOperator &I) {
00738   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00739          "Undefined behavior: Division by zero", &I);
00740 }
00741 
00742 void Lint::visitUDiv(BinaryOperator &I) {
00743   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00744          "Undefined behavior: Division by zero", &I);
00745 }
00746 
00747 void Lint::visitSRem(BinaryOperator &I) {
00748   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00749          "Undefined behavior: Division by zero", &I);
00750 }
00751 
00752 void Lint::visitURem(BinaryOperator &I) {
00753   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
00754          "Undefined behavior: Division by zero", &I);
00755 }
00756 
00757 void Lint::visitAllocaInst(AllocaInst &I) {
00758   if (isa<ConstantInt>(I.getArraySize()))
00759     // This isn't undefined behavior, it's just an obvious pessimization.
00760     Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
00761            "Pessimization: Static alloca outside of entry block", &I);
00762 
00763   // TODO: Check for an unusual size (MSB set?)
00764 }
00765 
00766 void Lint::visitVAArgInst(VAArgInst &I) {
00767   visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
00768                        nullptr, MemRef::Read | MemRef::Write);
00769 }
00770 
00771 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
00772   visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
00773                        nullptr, MemRef::Branchee);
00774 
00775   Assert(I.getNumDestinations() != 0,
00776          "Undefined behavior: indirectbr with no destinations", &I);
00777 }
00778 
00779 void Lint::visitExtractElementInst(ExtractElementInst &I) {
00780   if (ConstantInt *CI = dyn_cast<ConstantInt>(
00781           findValue(I.getIndexOperand(), I.getModule()->getDataLayout(),
00782                     /*OffsetOk=*/false)))
00783     Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
00784            "Undefined result: extractelement index out of range", &I);
00785 }
00786 
00787 void Lint::visitInsertElementInst(InsertElementInst &I) {
00788   if (ConstantInt *CI = dyn_cast<ConstantInt>(
00789           findValue(I.getOperand(2), I.getModule()->getDataLayout(),
00790                     /*OffsetOk=*/false)))
00791     Assert(CI->getValue().ult(I.getType()->getNumElements()),
00792            "Undefined result: insertelement index out of range", &I);
00793 }
00794 
00795 void Lint::visitUnreachableInst(UnreachableInst &I) {
00796   // This isn't undefined behavior, it's merely suspicious.
00797   Assert(&I == I.getParent()->begin() ||
00798              std::prev(BasicBlock::iterator(&I))->mayHaveSideEffects(),
00799          "Unusual: unreachable immediately preceded by instruction without "
00800          "side effects",
00801          &I);
00802 }
00803 
00804 /// findValue - Look through bitcasts and simple memory reference patterns
00805 /// to identify an equivalent, but more informative, value.  If OffsetOk
00806 /// is true, look through getelementptrs with non-zero offsets too.
00807 ///
00808 /// Most analysis passes don't require this logic, because instcombine
00809 /// will simplify most of these kinds of things away. But it's a goal of
00810 /// this Lint pass to be useful even on non-optimized IR.
00811 Value *Lint::findValue(Value *V, const DataLayout &DL, bool OffsetOk) const {
00812   SmallPtrSet<Value *, 4> Visited;
00813   return findValueImpl(V, DL, OffsetOk, Visited);
00814 }
00815 
00816 /// findValueImpl - Implementation helper for findValue.
00817 Value *Lint::findValueImpl(Value *V, const DataLayout &DL, bool OffsetOk,
00818                            SmallPtrSetImpl<Value *> &Visited) const {
00819   // Detect self-referential values.
00820   if (!Visited.insert(V).second)
00821     return UndefValue::get(V->getType());
00822 
00823   // TODO: Look through sext or zext cast, when the result is known to
00824   // be interpreted as signed or unsigned, respectively.
00825   // TODO: Look through eliminable cast pairs.
00826   // TODO: Look through calls with unique return values.
00827   // TODO: Look through vector insert/extract/shuffle.
00828   V = OffsetOk ? GetUnderlyingObject(V, DL) : V->stripPointerCasts();
00829   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
00830     BasicBlock::iterator BBI = L;
00831     BasicBlock *BB = L->getParent();
00832     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
00833     for (;;) {
00834       if (!VisitedBlocks.insert(BB).second)
00835         break;
00836       if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
00837                                               BB, BBI, 6, AA))
00838         return findValueImpl(U, DL, OffsetOk, Visited);
00839       if (BBI != BB->begin()) break;
00840       BB = BB->getUniquePredecessor();
00841       if (!BB) break;
00842       BBI = BB->end();
00843     }
00844   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
00845     if (Value *W = PN->hasConstantValue())
00846       if (W != V)
00847         return findValueImpl(W, DL, OffsetOk, Visited);
00848   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
00849     if (CI->isNoopCast(DL))
00850       return findValueImpl(CI->getOperand(0), DL, OffsetOk, Visited);
00851   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
00852     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
00853                                      Ex->getIndices()))
00854       if (W != V)
00855         return findValueImpl(W, DL, OffsetOk, Visited);
00856   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00857     // Same as above, but for ConstantExpr instead of Instruction.
00858     if (Instruction::isCast(CE->getOpcode())) {
00859       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
00860                                CE->getOperand(0)->getType(), CE->getType(),
00861                                DL.getIntPtrType(V->getType())))
00862         return findValueImpl(CE->getOperand(0), DL, OffsetOk, Visited);
00863     } else if (CE->getOpcode() == Instruction::ExtractValue) {
00864       ArrayRef<unsigned> Indices = CE->getIndices();
00865       if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
00866         if (W != V)
00867           return findValueImpl(W, DL, OffsetOk, Visited);
00868     }
00869   }
00870 
00871   // As a last resort, try SimplifyInstruction or constant folding.
00872   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
00873     if (Value *W = SimplifyInstruction(Inst, DL, TLI, DT, AC))
00874       return findValueImpl(W, DL, OffsetOk, Visited);
00875   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00876     if (Value *W = ConstantFoldConstantExpression(CE, DL, TLI))
00877       if (W != V)
00878         return findValueImpl(W, DL, OffsetOk, Visited);
00879   }
00880 
00881   return V;
00882 }
00883 
00884 //===----------------------------------------------------------------------===//
00885 //  Implement the public interfaces to this file...
00886 //===----------------------------------------------------------------------===//
00887 
00888 FunctionPass *llvm::createLintPass() {
00889   return new Lint();
00890 }
00891 
00892 /// lintFunction - Check a function for errors, printing messages on stderr.
00893 ///
00894 void llvm::lintFunction(const Function &f) {
00895   Function &F = const_cast<Function&>(f);
00896   assert(!F.isDeclaration() && "Cannot lint external functions");
00897 
00898   legacy::FunctionPassManager FPM(F.getParent());
00899   Lint *V = new Lint();
00900   FPM.add(V);
00901   FPM.run(F);
00902 }
00903 
00904 /// lintModule - Check a module for errors, printing messages on stderr.
00905 ///
00906 void llvm::lintModule(const Module &M) {
00907   legacy::PassManager PM;
00908   Lint *V = new Lint();
00909   PM.add(V);
00910   PM.run(const_cast<Module&>(M));
00911 }