LCOV - code coverage report
Current view: top level - lib/Analysis - Lint.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 239 290 82.4 %
Date: 2017-09-14 15:23:50 Functions: 41 46 89.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This pass statically checks for common and easily-identified constructs
      11             : // which produce undefined or likely unintended behavior in LLVM IR.
      12             : //
      13             : // It is not a guarantee of correctness, in two ways. First, it isn't
      14             : // comprehensive. There are checks which could be done statically which are
      15             : // not yet implemented. Some of these are indicated by TODO comments, but
      16             : // those aren't comprehensive either. Second, many conditions cannot be
      17             : // checked statically. This pass does no dynamic instrumentation, so it
      18             : // can't check for all possible problems.
      19             : //
      20             : // Another limitation is that it assumes all code will be executed. A store
      21             : // through a null pointer in a basic block which is never reached is harmless,
      22             : // but this pass will warn about it anyway. This is the main reason why most
      23             : // of these checks live here instead of in the Verifier pass.
      24             : //
      25             : // Optimization passes may make conditions that this pass checks for more or
      26             : // less obvious. If an optimization pass appears to be introducing a warning,
      27             : // it may be that the optimization pass is merely exposing an existing
      28             : // condition in the code.
      29             : //
      30             : // This code may be run before instcombine. In many cases, instcombine checks
      31             : // for the same kinds of things and turns instructions with undefined behavior
      32             : // into unreachable (or equivalent). Because of this, this pass makes some
      33             : // effort to look through bitcasts and so on.
      34             : //
      35             : //===----------------------------------------------------------------------===//
      36             : 
      37             : #include "llvm/Analysis/Lint.h"
      38             : #include "llvm/ADT/APInt.h"
      39             : #include "llvm/ADT/ArrayRef.h"
      40             : #include "llvm/ADT/SmallPtrSet.h"
      41             : #include "llvm/ADT/Twine.h"
      42             : #include "llvm/Analysis/AliasAnalysis.h"
      43             : #include "llvm/Analysis/AssumptionCache.h"
      44             : #include "llvm/Analysis/ConstantFolding.h"
      45             : #include "llvm/Analysis/InstructionSimplify.h"
      46             : #include "llvm/Analysis/Loads.h"
      47             : #include "llvm/Analysis/MemoryLocation.h"
      48             : #include "llvm/Analysis/Passes.h"
      49             : #include "llvm/Analysis/TargetLibraryInfo.h"
      50             : #include "llvm/Analysis/ValueTracking.h"
      51             : #include "llvm/IR/Argument.h"
      52             : #include "llvm/IR/BasicBlock.h"
      53             : #include "llvm/IR/CallSite.h"
      54             : #include "llvm/IR/Constant.h"
      55             : #include "llvm/IR/Constants.h"
      56             : #include "llvm/IR/DataLayout.h"
      57             : #include "llvm/IR/DerivedTypes.h"
      58             : #include "llvm/IR/Dominators.h"
      59             : #include "llvm/IR/Function.h"
      60             : #include "llvm/IR/GlobalVariable.h"
      61             : #include "llvm/IR/InstVisitor.h"
      62             : #include "llvm/IR/InstrTypes.h"
      63             : #include "llvm/IR/Instruction.h"
      64             : #include "llvm/IR/Instructions.h"
      65             : #include "llvm/IR/IntrinsicInst.h"
      66             : #include "llvm/IR/LegacyPassManager.h"
      67             : #include "llvm/IR/Module.h"
      68             : #include "llvm/IR/Type.h"
      69             : #include "llvm/IR/Value.h"
      70             : #include "llvm/Pass.h"
      71             : #include "llvm/Support/Casting.h"
      72             : #include "llvm/Support/Debug.h"
      73             : #include "llvm/Support/KnownBits.h"
      74             : #include "llvm/Support/MathExtras.h"
      75             : #include "llvm/Support/raw_ostream.h"
      76             : #include <cassert>
      77             : #include <cstdint>
      78             : #include <iterator>
      79             : #include <string>
      80             : 
      81             : using namespace llvm;
      82             : 
      83             : namespace {
      84             :   namespace MemRef {
      85             :     static const unsigned Read     = 1;
      86             :     static const unsigned Write    = 2;
      87             :     static const unsigned Callee   = 4;
      88             :     static const unsigned Branchee = 8;
      89             :   } // end namespace MemRef
      90             : 
      91          20 :   class Lint : public FunctionPass, public InstVisitor<Lint> {
      92             :     friend class InstVisitor<Lint>;
      93             : 
      94             :     void visitFunction(Function &F);
      95             : 
      96             :     void visitCallSite(CallSite CS);
      97             :     void visitMemoryReference(Instruction &I, Value *Ptr,
      98             :                               uint64_t Size, unsigned Align,
      99             :                               Type *Ty, unsigned Flags);
     100             :     void visitEHBeginCatch(IntrinsicInst *II);
     101             :     void visitEHEndCatch(IntrinsicInst *II);
     102             : 
     103             :     void visitCallInst(CallInst &I);
     104             :     void visitInvokeInst(InvokeInst &I);
     105             :     void visitReturnInst(ReturnInst &I);
     106             :     void visitLoadInst(LoadInst &I);
     107             :     void visitStoreInst(StoreInst &I);
     108             :     void visitXor(BinaryOperator &I);
     109             :     void visitSub(BinaryOperator &I);
     110             :     void visitLShr(BinaryOperator &I);
     111             :     void visitAShr(BinaryOperator &I);
     112             :     void visitShl(BinaryOperator &I);
     113             :     void visitSDiv(BinaryOperator &I);
     114             :     void visitUDiv(BinaryOperator &I);
     115             :     void visitSRem(BinaryOperator &I);
     116             :     void visitURem(BinaryOperator &I);
     117             :     void visitAllocaInst(AllocaInst &I);
     118             :     void visitVAArgInst(VAArgInst &I);
     119             :     void visitIndirectBrInst(IndirectBrInst &I);
     120             :     void visitExtractElementInst(ExtractElementInst &I);
     121             :     void visitInsertElementInst(InsertElementInst &I);
     122             :     void visitUnreachableInst(UnreachableInst &I);
     123             : 
     124             :     Value *findValue(Value *V, bool OffsetOk) const;
     125             :     Value *findValueImpl(Value *V, bool OffsetOk,
     126             :                          SmallPtrSetImpl<Value *> &Visited) const;
     127             : 
     128             :   public:
     129             :     Module *Mod;
     130             :     const DataLayout *DL;
     131             :     AliasAnalysis *AA;
     132             :     AssumptionCache *AC;
     133             :     DominatorTree *DT;
     134             :     TargetLibraryInfo *TLI;
     135             : 
     136             :     std::string Messages;
     137             :     raw_string_ostream MessagesStr;
     138             : 
     139             :     static char ID; // Pass identification, replacement for typeid
     140          20 :     Lint() : FunctionPass(ID), MessagesStr(Messages) {
     141           5 :       initializeLintPass(*PassRegistry::getPassRegistry());
     142           5 :     }
     143             : 
     144             :     bool runOnFunction(Function &F) override;
     145             : 
     146           5 :     void getAnalysisUsage(AnalysisUsage &AU) const override {
     147          10 :       AU.setPreservesAll();
     148           5 :       AU.addRequired<AAResultsWrapperPass>();
     149           5 :       AU.addRequired<AssumptionCacheTracker>();
     150           5 :       AU.addRequired<TargetLibraryInfoWrapperPass>();
     151           5 :       AU.addRequired<DominatorTreeWrapperPass>();
     152           5 :     }
     153           0 :     void print(raw_ostream &O, const Module *M) const override {}
     154             : 
     155          56 :     void WriteValues(ArrayRef<const Value *> Vs) {
     156         168 :       for (const Value *V : Vs) {
     157          56 :         if (!V)
     158           0 :           continue;
     159         112 :         if (isa<Instruction>(V)) {
     160         110 :           MessagesStr << *V << '\n';
     161             :         } else {
     162           1 :           V->printAsOperand(MessagesStr, true, Mod);
     163           1 :           MessagesStr << '\n';
     164             :         }
     165             :       }
     166          56 :     }
     167             : 
     168             :     /// \brief A check failed, so printout out the condition and the message.
     169             :     ///
     170             :     /// This provides a nice place to put a breakpoint if you want to see why
     171             :     /// something is not correct.
     172         168 :     void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
     173             : 
     174             :     /// \brief A check failed (with values to print).
     175             :     ///
     176             :     /// This calls the Message-only version so that the above is easier to set
     177             :     /// a breakpoint on.
     178             :     template <typename T1, typename... Ts>
     179          56 :     void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
     180          56 :       CheckFailed(Message);
     181         112 :       WriteValues({V1, Vs...});
     182          56 :     }
     183             :   };
     184             : } // end anonymous namespace
     185             : 
     186             : char Lint::ID = 0;
     187        9158 : INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
     188             :                       false, true)
     189        9158 : INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
     190        9158 : INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
     191        9158 : INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
     192        9158 : INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
     193       45805 : INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
     194             :                     false, true)
     195             : 
     196             : // Assert - We know that cond should be true, if not print an error message.
     197             : #define Assert(C, ...) \
     198             :     do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
     199             : 
     200             : // Lint::run - This is the main Analysis entry point for a
     201             : // function.
     202             : //
     203          29 : bool Lint::runOnFunction(Function &F) {
     204          29 :   Mod = F.getParent();
     205          29 :   DL = &F.getParent()->getDataLayout();
     206          58 :   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
     207          29 :   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
     208          58 :   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
     209          58 :   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
     210          29 :   visit(F);
     211          87 :   dbgs() << MessagesStr.str();
     212          58 :   Messages.clear();
     213          29 :   return false;
     214             : }
     215             : 
     216          29 : void Lint::visitFunction(Function &F) {
     217             :   // This isn't undefined behavior, it's just a little unusual, and it's a
     218             :   // fairly common mistake to neglect to name a function.
     219          60 :   Assert(F.hasName() || F.hasLocalLinkage(),
     220             :          "Unusual: Unnamed function with non-local linkage", &F);
     221             : 
     222             :   // TODO: Check for irreducible control flow.
     223             : }
     224             : 
     225          32 : void Lint::visitCallSite(CallSite CS) {
     226          32 :   Instruction &I = *CS.getInstruction();
     227          32 :   Value *Callee = CS.getCalledValue();
     228             : 
     229          32 :   visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
     230             :                        MemRef::Callee);
     231             : 
     232          32 :   if (Function *F = dyn_cast<Function>(findValue(Callee,
     233          31 :                                                  /*OffsetOk=*/false))) {
     234          63 :     Assert(CS.getCallingConv() == F->getCallingConv(),
     235             :            "Undefined behavior: Caller and callee calling convention differ",
     236             :            &I);
     237             : 
     238          30 :     FunctionType *FT = F->getFunctionType();
     239          30 :     unsigned NumActualArgs = CS.arg_size();
     240             : 
     241          62 :     Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
     242             :                           : FT->getNumParams() == NumActualArgs,
     243             :            "Undefined behavior: Call argument count mismatches callee "
     244             :            "argument count",
     245             :            &I);
     246             : 
     247          29 :     Assert(FT->getReturnType() == I.getType(),
     248             :            "Undefined behavior: Call return type mismatches "
     249             :            "callee return type",
     250             :            &I);
     251             : 
     252             :     // Check argument types (in case the callee was casted) and attributes.
     253             :     // TODO: Verify that caller and callee attributes are compatible.
     254          54 :     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
     255          27 :     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
     256          71 :     for (; AI != AE; ++AI) {
     257          24 :       Value *Actual = *AI;
     258          24 :       if (PI != PE) {
     259          20 :         Argument *Formal = &*PI++;
     260          21 :         Assert(Formal->getType() == Actual->getType(),
     261             :                "Undefined behavior: Call argument type mismatches "
     262             :                "callee parameter type",
     263             :                &I);
     264             : 
     265             :         // Check that noalias arguments don't alias other arguments. This is
     266             :         // not fully precise because we don't know the sizes of the dereferenced
     267             :         // memory regions.
     268          20 :         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
     269           3 :           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
     270           3 :             if (AI != BI && (*BI)->getType()->isPointerTy()) {
     271           2 :               AliasResult Result = AA->alias(*AI, *BI);
     272           2 :               Assert(Result != MustAlias && Result != PartialAlias,
     273             :                      "Unusual: noalias argument aliases another argument", &I);
     274             :             }
     275             : 
     276             :         // Check that an sret argument points to valid memory.
     277          19 :         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
     278             :           Type *Ty =
     279           2 :             cast<PointerType>(Formal->getType())->getElementType();
     280           2 :           visitMemoryReference(I, Actual, DL->getTypeStoreSize(Ty),
     281           1 :                                DL->getABITypeAlignment(Ty), Ty,
     282             :                                MemRef::Read | MemRef::Write);
     283             :         }
     284             :       }
     285             :     }
     286             :   }
     287             : 
     288          86 :   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
     289           1 :     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
     290           1 :          AI != AE; ++AI) {
     291           1 :       Value *Obj = findValue(*AI, /*OffsetOk=*/true);
     292           3 :       Assert(!isa<AllocaInst>(Obj),
     293             :              "Undefined behavior: Call with \"tail\" keyword references "
     294             :              "alloca",
     295             :              &I);
     296             :     }
     297             : 
     298             : 
     299          13 :   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
     300          13 :     switch (II->getIntrinsicID()) {
     301             :     default: break;
     302             : 
     303             :     // TODO: Check more intrinsics
     304             : 
     305           1 :     case Intrinsic::memcpy: {
     306           1 :       MemCpyInst *MCI = cast<MemCpyInst>(&I);
     307             :       // TODO: If the size is known, use it.
     308           3 :       visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
     309             :                            MCI->getAlignment(), nullptr, MemRef::Write);
     310           3 :       visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
     311             :                            MCI->getAlignment(), nullptr, MemRef::Read);
     312             : 
     313             :       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
     314             :       // isn't expressive enough for what we really want to do. Known partial
     315             :       // overlap is not distinguished from the case where nothing is known.
     316           1 :       uint64_t Size = 0;
     317             :       if (const ConstantInt *Len =
     318           2 :               dyn_cast<ConstantInt>(findValue(MCI->getLength(),
     319           1 :                                               /*OffsetOk=*/false)))
     320           2 :         if (Len->getValue().isIntN(32))
     321           1 :           Size = Len->getValue().getZExtValue();
     322           4 :       Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
     323             :                  MustAlias,
     324             :              "Undefined behavior: memcpy source and destination overlap", &I);
     325             :       break;
     326             :     }
     327           0 :     case Intrinsic::memmove: {
     328           0 :       MemMoveInst *MMI = cast<MemMoveInst>(&I);
     329             :       // TODO: If the size is known, use it.
     330           0 :       visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
     331             :                            MMI->getAlignment(), nullptr, MemRef::Write);
     332           0 :       visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
     333             :                            MMI->getAlignment(), nullptr, MemRef::Read);
     334           0 :       break;
     335             :     }
     336           0 :     case Intrinsic::memset: {
     337           0 :       MemSetInst *MSI = cast<MemSetInst>(&I);
     338             :       // TODO: If the size is known, use it.
     339           0 :       visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
     340             :                            MSI->getAlignment(), nullptr, MemRef::Write);
     341           0 :       break;
     342             :     }
     343             : 
     344           1 :     case Intrinsic::vastart:
     345           3 :       Assert(I.getParent()->getParent()->isVarArg(),
     346             :              "Undefined behavior: va_start called in a non-varargs function",
     347             :              &I);
     348             : 
     349           0 :       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
     350             :                            nullptr, MemRef::Read | MemRef::Write);
     351           0 :       break;
     352           0 :     case Intrinsic::vacopy:
     353           0 :       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
     354             :                            nullptr, MemRef::Write);
     355           0 :       visitMemoryReference(I, CS.getArgument(1), MemoryLocation::UnknownSize, 0,
     356             :                            nullptr, MemRef::Read);
     357           0 :       break;
     358           0 :     case Intrinsic::vaend:
     359           0 :       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
     360             :                            nullptr, MemRef::Read | MemRef::Write);
     361           0 :       break;
     362             : 
     363           1 :     case Intrinsic::stackrestore:
     364             :       // Stackrestore doesn't read or write memory, but it sets the
     365             :       // stack pointer, which the compiler may read from or write to
     366             :       // at any time, so check it for both readability and writeability.
     367           1 :       visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
     368             :                            nullptr, MemRef::Read | MemRef::Write);
     369           1 :       break;
     370             :     }
     371             : }
     372             : 
     373             : void Lint::visitCallInst(CallInst &I) {
     374          26 :   return visitCallSite(&I);
     375             : }
     376             : 
     377             : void Lint::visitInvokeInst(InvokeInst &I) {
     378           6 :   return visitCallSite(&I);
     379             : }
     380             : 
     381          26 : void Lint::visitReturnInst(ReturnInst &I) {
     382          26 :   Function *F = I.getParent()->getParent();
     383          27 :   Assert(!F->doesNotReturn(),
     384             :          "Unusual: Return statement in function with noreturn attribute", &I);
     385             : 
     386          18 :   if (Value *V = I.getReturnValue()) {
     387          18 :     Value *Obj = findValue(V, /*OffsetOk=*/true);
     388          22 :     Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
     389             :   }
     390             : }
     391             : 
     392             : // TODO: Check that the reference is in bounds.
     393             : // TODO: Check readnone/readonly function attributes.
     394          56 : void Lint::visitMemoryReference(Instruction &I,
     395             :                                 Value *Ptr, uint64_t Size, unsigned Align,
     396             :                                 Type *Ty, unsigned Flags) {
     397             :   // If no memory is being referenced, it doesn't matter if the pointer
     398             :   // is valid.
     399          56 :   if (Size == 0)
     400          21 :     return;
     401             : 
     402          56 :   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
     403         117 :   Assert(!isa<ConstantPointerNull>(UnderlyingObject),
     404             :          "Undefined behavior: Null pointer dereference", &I);
     405         105 :   Assert(!isa<UndefValue>(UnderlyingObject),
     406             :          "Undefined behavior: Undef pointer dereference", &I);
     407         101 :   Assert(!isa<ConstantInt>(UnderlyingObject) ||
     408             :              !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
     409             :          "Unusual: All-ones pointer dereference", &I);
     410          98 :   Assert(!isa<ConstantInt>(UnderlyingObject) ||
     411             :              !cast<ConstantInt>(UnderlyingObject)->isOne(),
     412             :          "Unusual: Address one pointer dereference", &I);
     413             : 
     414          46 :   if (Flags & MemRef::Write) {
     415          13 :     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
     416           5 :       Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
     417             :              &I);
     418          24 :     Assert(!isa<Function>(UnderlyingObject) &&
     419             :                !isa<BlockAddress>(UnderlyingObject),
     420             :            "Undefined behavior: Write to text section", &I);
     421             :   }
     422          43 :   if (Flags & MemRef::Read) {
     423           6 :     Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
     424             :            &I);
     425           7 :     Assert(!isa<BlockAddress>(UnderlyingObject),
     426             :            "Undefined behavior: Load from block address", &I);
     427             :   }
     428          42 :   if (Flags & MemRef::Callee) {
     429          65 :     Assert(!isa<BlockAddress>(UnderlyingObject),
     430             :            "Undefined behavior: Call to block address", &I);
     431             :   }
     432          41 :   if (Flags & MemRef::Branchee) {
     433           4 :     Assert(!isa<Constant>(UnderlyingObject) ||
     434             :                isa<BlockAddress>(UnderlyingObject),
     435             :            "Undefined behavior: Branch to non-blockaddress", &I);
     436             :   }
     437             : 
     438             :   // Check for buffer overflows and misalignment.
     439             :   // Only handles memory references that read/write something simple like an
     440             :   // alloca instruction or a global variable.
     441          40 :   int64_t Offset = 0;
     442          40 :   if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
     443             :     // OK, so the access is to a constant offset from Ptr.  Check that Ptr is
     444             :     // something we can handle and if so extract the size of this base object
     445             :     // along with its alignment.
     446          40 :     uint64_t BaseSize = MemoryLocation::UnknownSize;
     447          40 :     unsigned BaseAlign = 0;
     448             : 
     449           7 :     if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
     450           7 :       Type *ATy = AI->getAllocatedType();
     451           7 :       if (!AI->isArrayAllocation() && ATy->isSized())
     452           7 :         BaseSize = DL->getTypeAllocSize(ATy);
     453           7 :       BaseAlign = AI->getAlignment();
     454           7 :       if (BaseAlign == 0 && ATy->isSized())
     455           5 :         BaseAlign = DL->getABITypeAlignment(ATy);
     456           2 :     } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
     457             :       // If the global may be defined differently in another compilation unit
     458             :       // then don't warn about funky memory accesses.
     459           2 :       if (GV->hasDefinitiveInitializer()) {
     460           1 :         Type *GTy = GV->getValueType();
     461           1 :         if (GTy->isSized())
     462           1 :           BaseSize = DL->getTypeAllocSize(GTy);
     463           2 :         BaseAlign = GV->getAlignment();
     464           1 :         if (BaseAlign == 0 && GTy->isSized())
     465           1 :           BaseAlign = DL->getABITypeAlignment(GTy);
     466             :       }
     467             :     }
     468             : 
     469             :     // Accesses from before the start or after the end of the object are not
     470             :     // defined.
     471          43 :     Assert(Size == MemoryLocation::UnknownSize ||
     472             :                BaseSize == MemoryLocation::UnknownSize ||
     473             :                (Offset >= 0 && Offset + Size <= BaseSize),
     474             :            "Undefined behavior: Buffer overflow", &I);
     475             : 
     476             :     // Accesses that say that the memory is more aligned than it is are not
     477             :     // defined.
     478          37 :     if (Align == 0 && Ty && Ty->isSized())
     479           3 :       Align = DL->getABITypeAlignment(Ty);
     480          44 :     Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
     481             :            "Undefined behavior: Memory reference address is misaligned", &I);
     482             :   }
     483             : }
     484             : 
     485           5 : void Lint::visitLoadInst(LoadInst &I) {
     486          25 :   visitMemoryReference(I, I.getPointerOperand(),
     487           5 :                        DL->getTypeStoreSize(I.getType()), I.getAlignment(),
     488             :                        I.getType(), MemRef::Read);
     489           5 : }
     490             : 
     491          13 : void Lint::visitStoreInst(StoreInst &I) {
     492          65 :   visitMemoryReference(I, I.getPointerOperand(),
     493          13 :                        DL->getTypeStoreSize(I.getOperand(0)->getType()),
     494             :                        I.getAlignment(),
     495             :                        I.getOperand(0)->getType(), MemRef::Write);
     496          13 : }
     497             : 
     498           1 : void Lint::visitXor(BinaryOperator &I) {
     499           5 :   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
     500             :          "Undefined result: xor(undef, undef)", &I);
     501             : }
     502             : 
     503           1 : void Lint::visitSub(BinaryOperator &I) {
     504           5 :   Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
     505             :          "Undefined result: sub(undef, undef)", &I);
     506             : }
     507             : 
     508           1 : void Lint::visitLShr(BinaryOperator &I) {
     509           1 :   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
     510           1 :                                                         /*OffsetOk=*/false)))
     511           4 :     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
     512             :            "Undefined result: Shift count out of range", &I);
     513             : }
     514             : 
     515           1 : void Lint::visitAShr(BinaryOperator &I) {
     516             :   if (ConstantInt *CI =
     517           2 :           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
     518           4 :     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
     519             :            "Undefined result: Shift count out of range", &I);
     520             : }
     521             : 
     522           1 : void Lint::visitShl(BinaryOperator &I) {
     523             :   if (ConstantInt *CI =
     524           2 :           dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
     525           4 :     Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
     526             :            "Undefined result: Shift count out of range", &I);
     527             : }
     528             : 
     529          16 : static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
     530             :                    AssumptionCache *AC) {
     531             :   // Assume undef could be zero.
     532          32 :   if (isa<UndefValue>(V))
     533             :     return true;
     534             : 
     535          24 :   VectorType *VecTy = dyn_cast<VectorType>(V->getType());
     536             :   if (!VecTy) {
     537          18 :     KnownBits Known = computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT);
     538           6 :     return Known.isZero();
     539             :   }
     540             : 
     541             :   // Per-component check doesn't work with zeroinitializer
     542          18 :   Constant *C = dyn_cast<Constant>(V);
     543             :   if (!C)
     544             :     return false;
     545             : 
     546           9 :   if (C->isZeroValue())
     547             :     return true;
     548             : 
     549             :   // For a vector, KnownZero will only be true if all values are zero, so check
     550             :   // this per component
     551          18 :   for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
     552          14 :     Constant *Elem = C->getAggregateElement(I);
     553          28 :     if (isa<UndefValue>(Elem))
     554           4 :       return true;
     555             : 
     556          22 :     KnownBits Known = computeKnownBits(Elem, DL);
     557          12 :     if (Known.isZero())
     558           2 :       return true;
     559             :   }
     560             : 
     561             :   return false;
     562             : }
     563             : 
     564          10 : void Lint::visitSDiv(BinaryOperator &I) {
     565          39 :   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
     566             :          "Undefined behavior: Division by zero", &I);
     567             : }
     568             : 
     569           2 : void Lint::visitUDiv(BinaryOperator &I) {
     570           7 :   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
     571             :          "Undefined behavior: Division by zero", &I);
     572             : }
     573             : 
     574           2 : void Lint::visitSRem(BinaryOperator &I) {
     575           7 :   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
     576             :          "Undefined behavior: Division by zero", &I);
     577             : }
     578             : 
     579           2 : void Lint::visitURem(BinaryOperator &I) {
     580           7 :   Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
     581             :          "Undefined behavior: Division by zero", &I);
     582             : }
     583             : 
     584           7 : void Lint::visitAllocaInst(AllocaInst &I) {
     585          14 :   if (isa<ConstantInt>(I.getArraySize()))
     586             :     // This isn't undefined behavior, it's just an obvious pessimization.
     587          13 :     Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
     588             :            "Pessimization: Static alloca outside of entry block", &I);
     589             : 
     590             :   // TODO: Check for an unusual size (MSB set?)
     591             : }
     592             : 
     593           0 : void Lint::visitVAArgInst(VAArgInst &I) {
     594           0 :   visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
     595             :                        nullptr, MemRef::Read | MemRef::Write);
     596           0 : }
     597             : 
     598           2 : void Lint::visitIndirectBrInst(IndirectBrInst &I) {
     599           2 :   visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
     600             :                        nullptr, MemRef::Branchee);
     601             : 
     602           3 :   Assert(I.getNumDestinations() != 0,
     603             :          "Undefined behavior: indirectbr with no destinations", &I);
     604             : }
     605             : 
     606           1 : void Lint::visitExtractElementInst(ExtractElementInst &I) {
     607           1 :   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
     608           1 :                                                         /*OffsetOk=*/false)))
     609           3 :     Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
     610             :            "Undefined result: extractelement index out of range", &I);
     611             : }
     612             : 
     613           1 : void Lint::visitInsertElementInst(InsertElementInst &I) {
     614           1 :   if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
     615           1 :                                                         /*OffsetOk=*/false)))
     616           3 :     Assert(CI->getValue().ult(I.getType()->getNumElements()),
     617             :            "Undefined result: insertelement index out of range", &I);
     618             : }
     619             : 
     620           3 : void Lint::visitUnreachableInst(UnreachableInst &I) {
     621             :   // This isn't undefined behavior, it's merely suspicious.
     622          10 :   Assert(&I == &I.getParent()->front() ||
     623             :              std::prev(I.getIterator())->mayHaveSideEffects(),
     624             :          "Unusual: unreachable immediately preceded by instruction without "
     625             :          "side effects",
     626             :          &I);
     627             : }
     628             : 
     629             : /// findValue - Look through bitcasts and simple memory reference patterns
     630             : /// to identify an equivalent, but more informative, value.  If OffsetOk
     631             : /// is true, look through getelementptrs with non-zero offsets too.
     632             : ///
     633             : /// Most analysis passes don't require this logic, because instcombine
     634             : /// will simplify most of these kinds of things away. But it's a goal of
     635             : /// this Lint pass to be useful even on non-optimized IR.
     636         113 : Value *Lint::findValue(Value *V, bool OffsetOk) const {
     637         226 :   SmallPtrSet<Value *, 4> Visited;
     638         226 :   return findValueImpl(V, OffsetOk, Visited);
     639             : }
     640             : 
     641             : /// findValueImpl - Implementation helper for findValue.
     642         127 : Value *Lint::findValueImpl(Value *V, bool OffsetOk,
     643             :                            SmallPtrSetImpl<Value *> &Visited) const {
     644             :   // Detect self-referential values.
     645         127 :   if (!Visited.insert(V).second)
     646           1 :     return UndefValue::get(V->getType());
     647             : 
     648             :   // TODO: Look through sext or zext cast, when the result is known to
     649             :   // be interpreted as signed or unsigned, respectively.
     650             :   // TODO: Look through eliminable cast pairs.
     651             :   // TODO: Look through calls with unique return values.
     652             :   // TODO: Look through vector insert/extract/shuffle.
     653         164 :   V = OffsetOk ? GetUnderlyingObject(V, *DL) : V->stripPointerCasts();
     654           1 :   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
     655           2 :     BasicBlock::iterator BBI = L->getIterator();
     656           1 :     BasicBlock *BB = L->getParent();
     657           0 :     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
     658             :     for (;;) {
     659           2 :       if (!VisitedBlocks.insert(BB).second)
     660             :         break;
     661           2 :       if (Value *U =
     662           4 :           FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA))
     663           2 :         return findValueImpl(U, OffsetOk, Visited);
     664           2 :       if (BBI != BB->begin()) break;
     665           1 :       BB = BB->getUniquePredecessor();
     666           1 :       if (!BB) break;
     667           1 :       BBI = BB->end();
     668           1 :     }
     669           1 :   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
     670           1 :     if (Value *W = PN->hasConstantValue())
     671           1 :       if (W != V)
     672           1 :         return findValueImpl(W, OffsetOk, Visited);
     673           7 :   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
     674           7 :     if (CI->isNoopCast(*DL))
     675           6 :       return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
     676           0 :   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
     677           0 :     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
     678           0 :                                      Ex->getIndices()))
     679           0 :       if (W != V)
     680           0 :         return findValueImpl(W, OffsetOk, Visited);
     681           2 :   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
     682             :     // Same as above, but for ConstantExpr instead of Instruction.
     683           4 :     if (Instruction::isCast(CE->getOpcode())) {
     684           6 :       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
     685           2 :                                CE->getOperand(0)->getType(), CE->getType(),
     686           2 :                                DL->getIntPtrType(V->getType())))
     687           4 :         return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
     688           0 :     } else if (CE->getOpcode() == Instruction::ExtractValue) {
     689           0 :       ArrayRef<unsigned> Indices = CE->getIndices();
     690           0 :       if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
     691           0 :         if (W != V)
     692           0 :           return findValueImpl(W, OffsetOk, Visited);
     693             :     }
     694             :   }
     695             : 
     696             :   // As a last resort, try SimplifyInstruction or constant folding.
     697          27 :   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
     698          54 :     if (Value *W = SimplifyInstruction(Inst, {*DL, TLI, DT, AC}))
     699           7 :       return findValueImpl(W, OffsetOk, Visited);
     700          92 :   } else if (auto *C = dyn_cast<Constant>(V)) {
     701          92 :     if (Value *W = ConstantFoldConstant(C, *DL, TLI))
     702           0 :       if (W && W != V)
     703           0 :         return findValueImpl(W, OffsetOk, Visited);
     704             :   }
     705             : 
     706             :   return V;
     707             : }
     708             : 
     709             : //===----------------------------------------------------------------------===//
     710             : //  Implement the public interfaces to this file...
     711             : //===----------------------------------------------------------------------===//
     712             : 
     713           0 : FunctionPass *llvm::createLintPass() {
     714           0 :   return new Lint();
     715             : }
     716             : 
     717             : /// lintFunction - Check a function for errors, printing messages on stderr.
     718             : ///
     719           0 : void llvm::lintFunction(const Function &f) {
     720           0 :   Function &F = const_cast<Function&>(f);
     721             :   assert(!F.isDeclaration() && "Cannot lint external functions");
     722             : 
     723           0 :   legacy::FunctionPassManager FPM(F.getParent());
     724           0 :   Lint *V = new Lint();
     725           0 :   FPM.add(V);
     726           0 :   FPM.run(F);
     727           0 : }
     728             : 
     729             : /// lintModule - Check a module for errors, printing messages on stderr.
     730             : ///
     731           0 : void llvm::lintModule(const Module &M) {
     732           0 :   legacy::PassManager PM;
     733           0 :   Lint *V = new Lint();
     734           0 :   PM.add(V);
     735           0 :   PM.run(const_cast<Module&>(M));
     736           0 : }

Generated by: LCOV version 1.13