Home | History | Annotate | Download | only in Core
      1 // BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- C++ -*--//
      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 file defines a set of BugReporter "visitors" which can be used to
     11 //  enhance the diagnostics reported for a bug.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
     15 #include "clang/AST/Expr.h"
     16 #include "clang/AST/ExprObjC.h"
     17 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
     18 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
     19 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
     20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
     21 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
     22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
     23 #include "llvm/ADT/SmallString.h"
     24 #include "llvm/ADT/StringExtras.h"
     25 #include "llvm/Support/raw_ostream.h"
     26 
     27 using namespace clang;
     28 using namespace ento;
     29 
     30 using llvm::FoldingSetNodeID;
     31 
     32 //===----------------------------------------------------------------------===//
     33 // Utility functions.
     34 //===----------------------------------------------------------------------===//
     35 
     36 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
     37   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
     38     return DRE->getDecl()->getType()->isReferenceType();
     39   }
     40   return false;
     41 }
     42 
     43 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
     44   // Pattern match for a few useful cases (do something smarter later):
     45   //   a[0], p->f, *p
     46   const Expr *E = dyn_cast<Expr>(S);
     47   if (!E)
     48     return 0;
     49   E = E->IgnoreParenCasts();
     50 
     51   while (true) {
     52     if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
     53       assert(B->isAssignmentOp());
     54       E = B->getLHS()->IgnoreParenCasts();
     55       continue;
     56     }
     57     else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
     58       if (U->getOpcode() == UO_Deref)
     59         return U->getSubExpr()->IgnoreParenCasts();
     60     }
     61     else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
     62       if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
     63         return ME->getBase()->IgnoreParenCasts();
     64       }
     65     }
     66     else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
     67       return IvarRef->getBase()->IgnoreParenCasts();
     68     }
     69     else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
     70       return AE->getBase();
     71     }
     72     break;
     73   }
     74 
     75   return NULL;
     76 }
     77 
     78 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
     79   const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
     80   if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
     81     return BE->getRHS();
     82   return NULL;
     83 }
     84 
     85 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
     86   const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
     87   if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
     88     return RS->getRetValue();
     89   return NULL;
     90 }
     91 
     92 //===----------------------------------------------------------------------===//
     93 // Definitions for bug reporter visitors.
     94 //===----------------------------------------------------------------------===//
     95 
     96 PathDiagnosticPiece*
     97 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
     98                                const ExplodedNode *EndPathNode,
     99                                BugReport &BR) {
    100   return 0;
    101 }
    102 
    103 PathDiagnosticPiece*
    104 BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
    105                                       const ExplodedNode *EndPathNode,
    106                                       BugReport &BR) {
    107   PathDiagnosticLocation L =
    108     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
    109 
    110   BugReport::ranges_iterator Beg, End;
    111   llvm::tie(Beg, End) = BR.getRanges();
    112 
    113   // Only add the statement itself as a range if we didn't specify any
    114   // special ranges for this report.
    115   PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
    116       BR.getDescription(),
    117       Beg == End);
    118   for (; Beg != End; ++Beg)
    119     P->addRange(*Beg);
    120 
    121   return P;
    122 }
    123 
    124 
    125 namespace {
    126 /// Emits an extra note at the return statement of an interesting stack frame.
    127 ///
    128 /// The returned value is marked as an interesting value, and if it's null,
    129 /// adds a visitor to track where it became null.
    130 ///
    131 /// This visitor is intended to be used when another visitor discovers that an
    132 /// interesting value comes from an inlined function call.
    133 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
    134   const StackFrameContext *StackFrame;
    135   enum {
    136     Initial,
    137     MaybeUnsuppress,
    138     Satisfied
    139   } Mode;
    140   bool InitiallySuppressed;
    141 
    142 public:
    143   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
    144     : StackFrame(Frame), Mode(Initial), InitiallySuppressed(Suppressed) {}
    145 
    146   static void *getTag() {
    147     static int Tag = 0;
    148     return static_cast<void *>(&Tag);
    149   }
    150 
    151   virtual void Profile(llvm::FoldingSetNodeID &ID) const {
    152     ID.AddPointer(ReturnVisitor::getTag());
    153     ID.AddPointer(StackFrame);
    154     ID.AddBoolean(InitiallySuppressed);
    155   }
    156 
    157   /// Adds a ReturnVisitor if the given statement represents a call that was
    158   /// inlined.
    159   ///
    160   /// This will search back through the ExplodedGraph, starting from the given
    161   /// node, looking for when the given statement was processed. If it turns out
    162   /// the statement is a call that was inlined, we add the visitor to the
    163   /// bug report, so it can print a note later.
    164   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
    165                                     BugReport &BR) {
    166     if (!CallEvent::isCallStmt(S))
    167       return;
    168 
    169     // First, find when we processed the statement.
    170     do {
    171       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
    172         if (CEE->getCalleeContext()->getCallSite() == S)
    173           break;
    174       if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
    175         if (SP->getStmt() == S)
    176           break;
    177 
    178       Node = Node->getFirstPred();
    179     } while (Node);
    180 
    181     // Next, step over any post-statement checks.
    182     while (Node && Node->getLocation().getAs<PostStmt>())
    183       Node = Node->getFirstPred();
    184     if (!Node)
    185       return;
    186 
    187     // Finally, see if we inlined the call.
    188     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
    189     if (!CEE)
    190       return;
    191 
    192     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
    193     if (CalleeContext->getCallSite() != S)
    194       return;
    195 
    196     // Check the return value.
    197     ProgramStateRef State = Node->getState();
    198     SVal RetVal = State->getSVal(S, Node->getLocationContext());
    199 
    200     // Handle cases where a reference is returned and then immediately used.
    201     if (cast<Expr>(S)->isGLValue())
    202       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
    203         RetVal = State->getSVal(*LValue);
    204 
    205     // See if the return value is NULL. If so, suppress the report.
    206     SubEngine *Eng = State->getStateManager().getOwningEngine();
    207     assert(Eng && "Cannot file a bug report without an owning engine");
    208     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
    209 
    210     bool InitiallySuppressed = false;
    211     if (Options.shouldSuppressNullReturnPaths())
    212       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
    213         InitiallySuppressed = !State->assume(*RetLoc, true);
    214 
    215     BR.markInteresting(CalleeContext);
    216     BR.addVisitor(new ReturnVisitor(CalleeContext, InitiallySuppressed));
    217   }
    218 
    219   /// Returns true if any counter-suppression heuristics are enabled for
    220   /// ReturnVisitor.
    221   static bool hasCounterSuppression(AnalyzerOptions &Options) {
    222     return Options.shouldAvoidSuppressingNullArgumentPaths();
    223   }
    224 
    225   PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
    226                                         const ExplodedNode *PrevN,
    227                                         BugReporterContext &BRC,
    228                                         BugReport &BR) {
    229     // Only print a message at the interesting return statement.
    230     if (N->getLocationContext() != StackFrame)
    231       return 0;
    232 
    233     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
    234     if (!SP)
    235       return 0;
    236 
    237     const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
    238     if (!Ret)
    239       return 0;
    240 
    241     // Okay, we're at the right return statement, but do we have the return
    242     // value available?
    243     ProgramStateRef State = N->getState();
    244     SVal V = State->getSVal(Ret, StackFrame);
    245     if (V.isUnknownOrUndef())
    246       return 0;
    247 
    248     // Don't print any more notes after this one.
    249     Mode = Satisfied;
    250 
    251     const Expr *RetE = Ret->getRetValue();
    252     assert(RetE && "Tracking a return value for a void function");
    253 
    254     // Handle cases where a reference is returned and then immediately used.
    255     Optional<Loc> LValue;
    256     if (RetE->isGLValue()) {
    257       if ((LValue = V.getAs<Loc>())) {
    258         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
    259         if (RValue.getAs<DefinedSVal>())
    260           V = RValue;
    261       }
    262     }
    263 
    264     // Ignore aggregate rvalues.
    265     if (V.getAs<nonloc::LazyCompoundVal>() ||
    266         V.getAs<nonloc::CompoundVal>())
    267       return 0;
    268 
    269     RetE = RetE->IgnoreParenCasts();
    270 
    271     // If we can't prove the return value is 0, just mark it interesting, and
    272     // make sure to track it into any further inner functions.
    273     if (State->assume(V.castAs<DefinedSVal>(), true)) {
    274       BR.markInteresting(V);
    275       ReturnVisitor::addVisitorIfNecessary(N, RetE, BR);
    276       return 0;
    277     }
    278 
    279     // If we're returning 0, we should track where that 0 came from.
    280     bugreporter::trackNullOrUndefValue(N, RetE, BR);
    281 
    282     // Build an appropriate message based on the return value.
    283     SmallString<64> Msg;
    284     llvm::raw_svector_ostream Out(Msg);
    285 
    286     if (V.getAs<Loc>()) {
    287       // If we have counter-suppression enabled, make sure we keep visiting
    288       // future nodes. We want to emit a path note as well, in case
    289       // the report is resurrected as valid later on.
    290       ExprEngine &Eng = BRC.getBugReporter().getEngine();
    291       AnalyzerOptions &Options = Eng.getAnalysisManager().options;
    292       if (InitiallySuppressed && hasCounterSuppression(Options))
    293         Mode = MaybeUnsuppress;
    294 
    295       if (RetE->getType()->isObjCObjectPointerType())
    296         Out << "Returning nil";
    297       else
    298         Out << "Returning null pointer";
    299     } else {
    300       Out << "Returning zero";
    301     }
    302 
    303     if (LValue) {
    304       if (const MemRegion *MR = LValue->getAsRegion()) {
    305         if (MR->canPrintPretty()) {
    306           Out << " (reference to '";
    307           MR->printPretty(Out);
    308           Out << "')";
    309         }
    310       }
    311     } else {
    312       // FIXME: We should have a more generalized location printing mechanism.
    313       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
    314         if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
    315           Out << " (loaded from '" << *DD << "')";
    316     }
    317 
    318     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
    319     return new PathDiagnosticEventPiece(L, Out.str());
    320   }
    321 
    322   PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
    323                                                 const ExplodedNode *PrevN,
    324                                                 BugReporterContext &BRC,
    325                                                 BugReport &BR) {
    326 #ifndef NDEBUG
    327     ExprEngine &Eng = BRC.getBugReporter().getEngine();
    328     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
    329     assert(hasCounterSuppression(Options));
    330 #endif
    331 
    332     // Are we at the entry node for this call?
    333     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
    334     if (!CE)
    335       return 0;
    336 
    337     if (CE->getCalleeContext() != StackFrame)
    338       return 0;
    339 
    340     Mode = Satisfied;
    341 
    342     // Don't automatically suppress a report if one of the arguments is
    343     // known to be a null pointer. Instead, start tracking /that/ null
    344     // value back to its origin.
    345     ProgramStateManager &StateMgr = BRC.getStateManager();
    346     CallEventManager &CallMgr = StateMgr.getCallEventManager();
    347 
    348     ProgramStateRef State = N->getState();
    349     CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
    350     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
    351       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
    352       if (!ArgV)
    353         continue;
    354 
    355       const Expr *ArgE = Call->getArgExpr(I);
    356       if (!ArgE)
    357         continue;
    358 
    359       // Is it possible for this argument to be non-null?
    360       if (State->assume(*ArgV, true))
    361         continue;
    362 
    363       if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true))
    364         BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
    365 
    366       // If we /can't/ track the null pointer, we should err on the side of
    367       // false negatives, and continue towards marking this report invalid.
    368       // (We will still look at the other arguments, though.)
    369     }
    370 
    371     return 0;
    372   }
    373 
    374   PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
    375                                  const ExplodedNode *PrevN,
    376                                  BugReporterContext &BRC,
    377                                  BugReport &BR) {
    378     switch (Mode) {
    379     case Initial:
    380       return visitNodeInitial(N, PrevN, BRC, BR);
    381     case MaybeUnsuppress:
    382       return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
    383     case Satisfied:
    384       return 0;
    385     }
    386 
    387     llvm_unreachable("Invalid visit mode!");
    388   }
    389 
    390   PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
    391                                   const ExplodedNode *N,
    392                                   BugReport &BR) {
    393     if (InitiallySuppressed)
    394       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
    395     return 0;
    396   }
    397 };
    398 } // end anonymous namespace
    399 
    400 
    401 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
    402   static int tag = 0;
    403   ID.AddPointer(&tag);
    404   ID.AddPointer(R);
    405   ID.Add(V);
    406 }
    407 
    408 PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
    409                                                        const ExplodedNode *Pred,
    410                                                        BugReporterContext &BRC,
    411                                                        BugReport &BR) {
    412 
    413   if (Satisfied)
    414     return NULL;
    415 
    416   const ExplodedNode *StoreSite = 0;
    417   const Expr *InitE = 0;
    418   bool IsParam = false;
    419 
    420   // First see if we reached the declaration of the region.
    421   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
    422     if (Optional<PostStmt> P = Pred->getLocationAs<PostStmt>()) {
    423       if (const DeclStmt *DS = P->getStmtAs<DeclStmt>()) {
    424         if (DS->getSingleDecl() == VR->getDecl()) {
    425           StoreSite = Pred;
    426           InitE = VR->getDecl()->getInit();
    427         }
    428       }
    429     }
    430   }
    431 
    432   // Otherwise, see if this is the store site:
    433   // (1) Succ has this binding and Pred does not, i.e. this is
    434   //     where the binding first occurred.
    435   // (2) Succ has this binding and is a PostStore node for this region, i.e.
    436   //     the same binding was re-assigned here.
    437   if (!StoreSite) {
    438     if (Succ->getState()->getSVal(R) != V)
    439       return NULL;
    440 
    441     if (Pred->getState()->getSVal(R) == V) {
    442       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
    443       if (!PS || PS->getLocationValue() != R)
    444         return NULL;
    445     }
    446 
    447     StoreSite = Succ;
    448 
    449     // If this is an assignment expression, we can track the value
    450     // being assigned.
    451     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
    452       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
    453         if (BO->isAssignmentOp())
    454           InitE = BO->getRHS();
    455 
    456     // If this is a call entry, the variable should be a parameter.
    457     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
    458     // 'this' should never be NULL, but this visitor isn't just for NULL and
    459     // UndefinedVal.)
    460     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
    461       if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
    462         const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
    463 
    464         ProgramStateManager &StateMgr = BRC.getStateManager();
    465         CallEventManager &CallMgr = StateMgr.getCallEventManager();
    466 
    467         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
    468                                                 Succ->getState());
    469         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
    470         IsParam = true;
    471       }
    472     }
    473 
    474     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
    475     // is wrapped inside of it.
    476     if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
    477       InitE = TmpR->getExpr();
    478   }
    479 
    480   if (!StoreSite)
    481     return NULL;
    482   Satisfied = true;
    483 
    484   // If we have an expression that provided the value, try to track where it
    485   // came from.
    486   if (InitE) {
    487     if (V.isUndef() || V.getAs<loc::ConcreteInt>()) {
    488       if (!IsParam)
    489         InitE = InitE->IgnoreParenCasts();
    490       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam);
    491     } else {
    492       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
    493                                            BR);
    494     }
    495   }
    496 
    497   if (!R->canPrintPretty())
    498     return 0;
    499 
    500   // Okay, we've found the binding. Emit an appropriate message.
    501   SmallString<256> sbuf;
    502   llvm::raw_svector_ostream os(sbuf);
    503 
    504   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
    505     const Stmt *S = PS->getStmt();
    506     const char *action = 0;
    507     const DeclStmt *DS = dyn_cast<DeclStmt>(S);
    508     const VarRegion *VR = dyn_cast<VarRegion>(R);
    509 
    510     if (DS) {
    511       action = "initialized to ";
    512     } else if (isa<BlockExpr>(S)) {
    513       action = "captured by block as ";
    514       if (VR) {
    515         // See if we can get the BlockVarRegion.
    516         ProgramStateRef State = StoreSite->getState();
    517         SVal V = State->getSVal(S, PS->getLocationContext());
    518         if (const BlockDataRegion *BDR =
    519               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
    520           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
    521             if (Optional<KnownSVal> KV =
    522                 State->getSVal(OriginalR).getAs<KnownSVal>())
    523               BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR));
    524           }
    525         }
    526       }
    527     }
    528 
    529     if (action) {
    530       if (!R)
    531         return 0;
    532 
    533       os << '\'';
    534       R->printPretty(os);
    535       os << "' ";
    536 
    537       if (V.getAs<loc::ConcreteInt>()) {
    538         bool b = false;
    539         if (R->isBoundable()) {
    540           if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
    541             if (TR->getValueType()->isObjCObjectPointerType()) {
    542               os << action << "nil";
    543               b = true;
    544             }
    545           }
    546         }
    547 
    548         if (!b)
    549           os << action << "a null pointer value";
    550       } else if (Optional<nonloc::ConcreteInt> CVal =
    551                      V.getAs<nonloc::ConcreteInt>()) {
    552         os << action << CVal->getValue();
    553       }
    554       else if (DS) {
    555         if (V.isUndef()) {
    556           if (isa<VarRegion>(R)) {
    557             const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
    558             if (VD->getInit())
    559               os << "initialized to a garbage value";
    560             else
    561               os << "declared without an initial value";
    562           }
    563         }
    564         else {
    565           os << "initialized here";
    566         }
    567       }
    568     }
    569   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
    570     if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
    571       const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
    572 
    573       os << "Passing ";
    574 
    575       if (V.getAs<loc::ConcreteInt>()) {
    576         if (Param->getType()->isObjCObjectPointerType())
    577           os << "nil object reference";
    578         else
    579           os << "null pointer value";
    580       } else if (V.isUndef()) {
    581         os << "uninitialized value";
    582       } else if (Optional<nonloc::ConcreteInt> CI =
    583                      V.getAs<nonloc::ConcreteInt>()) {
    584         os << "the value " << CI->getValue();
    585       } else {
    586         os << "value";
    587       }
    588 
    589       // Printed parameter indexes are 1-based, not 0-based.
    590       unsigned Idx = Param->getFunctionScopeIndex() + 1;
    591       os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter '";
    592 
    593       R->printPretty(os);
    594       os << '\'';
    595     }
    596   }
    597 
    598   if (os.str().empty()) {
    599     if (V.getAs<loc::ConcreteInt>()) {
    600       bool b = false;
    601       if (R->isBoundable()) {
    602         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
    603           if (TR->getValueType()->isObjCObjectPointerType()) {
    604             os << "nil object reference stored to ";
    605             b = true;
    606           }
    607         }
    608       }
    609 
    610       if (!b)
    611         os << "Null pointer value stored to ";
    612     }
    613     else if (V.isUndef()) {
    614       os << "Uninitialized value stored to ";
    615     } else if (Optional<nonloc::ConcreteInt> CV =
    616                    V.getAs<nonloc::ConcreteInt>()) {
    617       os << "The value " << CV->getValue() << " is assigned to ";
    618     }
    619     else
    620       os << "Value assigned to ";
    621 
    622     os << '\'';
    623     R->printPretty(os);
    624     os << '\'';
    625   }
    626 
    627   // Construct a new PathDiagnosticPiece.
    628   ProgramPoint P = StoreSite->getLocation();
    629   PathDiagnosticLocation L;
    630   if (P.getAs<CallEnter>() && InitE)
    631     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
    632                                P.getLocationContext());
    633   else
    634     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
    635   if (!L.isValid())
    636     return NULL;
    637   return new PathDiagnosticEventPiece(L, os.str());
    638 }
    639 
    640 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
    641   static int tag = 0;
    642   ID.AddPointer(&tag);
    643   ID.AddBoolean(Assumption);
    644   ID.Add(Constraint);
    645 }
    646 
    647 /// Return the tag associated with this visitor.  This tag will be used
    648 /// to make all PathDiagnosticPieces created by this visitor.
    649 const char *TrackConstraintBRVisitor::getTag() {
    650   return "TrackConstraintBRVisitor";
    651 }
    652 
    653 PathDiagnosticPiece *
    654 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
    655                                     const ExplodedNode *PrevN,
    656                                     BugReporterContext &BRC,
    657                                     BugReport &BR) {
    658   if (isSatisfied)
    659     return NULL;
    660 
    661   // Check if in the previous state it was feasible for this constraint
    662   // to *not* be true.
    663   if (PrevN->getState()->assume(Constraint, !Assumption)) {
    664 
    665     isSatisfied = true;
    666 
    667     // As a sanity check, make sure that the negation of the constraint
    668     // was infeasible in the current state.  If it is feasible, we somehow
    669     // missed the transition point.
    670     if (N->getState()->assume(Constraint, !Assumption))
    671       return NULL;
    672 
    673     // We found the transition point for the constraint.  We now need to
    674     // pretty-print the constraint. (work-in-progress)
    675     std::string sbuf;
    676     llvm::raw_string_ostream os(sbuf);
    677 
    678     if (Constraint.getAs<Loc>()) {
    679       os << "Assuming pointer value is ";
    680       os << (Assumption ? "non-null" : "null");
    681     }
    682 
    683     if (os.str().empty())
    684       return NULL;
    685 
    686     // Construct a new PathDiagnosticPiece.
    687     ProgramPoint P = N->getLocation();
    688     PathDiagnosticLocation L =
    689       PathDiagnosticLocation::create(P, BRC.getSourceManager());
    690     if (!L.isValid())
    691       return NULL;
    692 
    693     PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
    694     X->setTag(getTag());
    695     return X;
    696   }
    697 
    698   return NULL;
    699 }
    700 
    701 SuppressInlineDefensiveChecksVisitor::
    702 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
    703   : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
    704 
    705     // Check if the visitor is disabled.
    706     SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
    707     assert(Eng && "Cannot file a bug report without an owning engine");
    708     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
    709     if (!Options.shouldSuppressInlinedDefensiveChecks())
    710       IsSatisfied = true;
    711 
    712     assert(N->getState()->isNull(V).isConstrainedTrue() &&
    713            "The visitor only tracks the cases where V is constrained to 0");
    714 }
    715 
    716 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
    717   static int id = 0;
    718   ID.AddPointer(&id);
    719   ID.Add(V);
    720 }
    721 
    722 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
    723   return "IDCVisitor";
    724 }
    725 
    726 PathDiagnosticPiece *
    727 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
    728                                                 const ExplodedNode *Pred,
    729                                                 BugReporterContext &BRC,
    730                                                 BugReport &BR) {
    731   if (IsSatisfied)
    732     return 0;
    733 
    734   // Start tracking after we see the first state in which the value is null.
    735   if (!IsTrackingTurnedOn)
    736     if (Succ->getState()->isNull(V).isConstrainedTrue())
    737       IsTrackingTurnedOn = true;
    738   if (!IsTrackingTurnedOn)
    739     return 0;
    740 
    741   // Check if in the previous state it was feasible for this value
    742   // to *not* be null.
    743   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
    744     IsSatisfied = true;
    745 
    746     assert(Succ->getState()->isNull(V).isConstrainedTrue());
    747 
    748     // Check if this is inlined defensive checks.
    749     const LocationContext *CurLC =Succ->getLocationContext();
    750     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
    751     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
    752       BR.markInvalid("Suppress IDC", CurLC);
    753   }
    754   return 0;
    755 }
    756 
    757 static const MemRegion *getLocationRegionIfReference(const Expr *E,
    758                                                      const ExplodedNode *N) {
    759   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
    760     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
    761       if (!VD->getType()->isReferenceType())
    762         return 0;
    763       ProgramStateManager &StateMgr = N->getState()->getStateManager();
    764       MemRegionManager &MRMgr = StateMgr.getRegionManager();
    765       return MRMgr.getVarRegion(VD, N->getLocationContext());
    766     }
    767   }
    768 
    769   // FIXME: This does not handle other kinds of null references,
    770   // for example, references from FieldRegions:
    771   //   struct Wrapper { int &ref; };
    772   //   Wrapper w = { *(int *)0 };
    773   //   w.ref = 1;
    774 
    775   return 0;
    776 }
    777 
    778 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
    779                                         const Stmt *S,
    780                                         BugReport &report, bool IsArg) {
    781   if (!S || !N)
    782     return false;
    783 
    784   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S))
    785     S = EWC->getSubExpr();
    786   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S))
    787     S = OVE->getSourceExpr();
    788 
    789   // Peel off the ternary operator.
    790   if (const Expr *Ex = dyn_cast<Expr>(S)) {
    791     Ex = Ex->IgnoreParenCasts();
    792     if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
    793       ProgramStateRef State = N->getState();
    794       SVal CondVal = State->getSVal(CO->getCond(), N->getLocationContext());
    795       if (State->isNull(CondVal).isConstrainedTrue()) {
    796         S = CO->getTrueExpr();
    797       } else {
    798         assert(State->isNull(CondVal).isConstrainedFalse());
    799         S =  CO->getFalseExpr();
    800       }
    801     }
    802   }
    803 
    804   const Expr *Inner = 0;
    805   if (const Expr *Ex = dyn_cast<Expr>(S)) {
    806     Ex = Ex->IgnoreParenCasts();
    807     if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
    808       Inner = Ex;
    809   }
    810 
    811   if (IsArg) {
    812     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
    813   } else {
    814     // Walk through nodes until we get one that matches the statement exactly.
    815     // Alternately, if we hit a known lvalue for the statement, we know we've
    816     // gone too far (though we can likely track the lvalue better anyway).
    817     do {
    818       const ProgramPoint &pp = N->getLocation();
    819       if (Optional<PostStmt> ps = pp.getAs<PostStmt>()) {
    820         if (ps->getStmt() == S || ps->getStmt() == Inner)
    821           break;
    822       } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
    823         if (CEE->getCalleeContext()->getCallSite() == S ||
    824             CEE->getCalleeContext()->getCallSite() == Inner)
    825           break;
    826       }
    827       N = N->getFirstPred();
    828     } while (N);
    829 
    830     if (!N)
    831       return false;
    832   }
    833 
    834   ProgramStateRef state = N->getState();
    835 
    836   // See if the expression we're interested refers to a variable.
    837   // If so, we can track both its contents and constraints on its value.
    838   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
    839     const MemRegion *R = 0;
    840 
    841     // Find the ExplodedNode where the lvalue (the value of 'Ex')
    842     // was computed.  We need this for getting the location value.
    843     const ExplodedNode *LVNode = N;
    844     while (LVNode) {
    845       if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
    846         if (P->getStmt() == Inner)
    847           break;
    848       }
    849       LVNode = LVNode->getFirstPred();
    850     }
    851     assert(LVNode && "Unable to find the lvalue node.");
    852     ProgramStateRef LVState = LVNode->getState();
    853     SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
    854 
    855     if (LVState->isNull(LVal).isConstrainedTrue()) {
    856       // In case of C++ references, we want to differentiate between a null
    857       // reference and reference to null pointer.
    858       // If the LVal is null, check if we are dealing with null reference.
    859       // For those, we want to track the location of the reference.
    860       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
    861         R = RR;
    862     } else {
    863       R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
    864 
    865       // If this is a C++ reference to a null pointer, we are tracking the
    866       // pointer. In additon, we should find the store at which the reference
    867       // got initialized.
    868       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
    869         if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
    870           report.addVisitor(new FindLastStoreBRVisitor(*KV, RR));
    871       }
    872     }
    873 
    874     if (R) {
    875       // Mark both the variable region and its contents as interesting.
    876       SVal V = state->getRawSVal(loc::MemRegionVal(R));
    877 
    878       // If the value matches the default for the variable region, that
    879       // might mean that it's been cleared out of the state. Fall back to
    880       // the full argument expression (with casts and such intact).
    881       if (IsArg) {
    882         bool UseArgValue = V.isUnknownOrUndef() || V.isZeroConstant();
    883         if (!UseArgValue) {
    884           const SymbolRegionValue *SRV =
    885             dyn_cast_or_null<SymbolRegionValue>(V.getAsLocSymbol());
    886           if (SRV)
    887             UseArgValue = (SRV->getRegion() == R);
    888         }
    889         if (UseArgValue)
    890           V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
    891       }
    892 
    893       report.markInteresting(R);
    894       report.markInteresting(V);
    895       report.addVisitor(new UndefOrNullArgVisitor(R));
    896 
    897       if (isa<SymbolicRegion>(R)) {
    898         TrackConstraintBRVisitor *VI =
    899           new TrackConstraintBRVisitor(loc::MemRegionVal(R), false);
    900         report.addVisitor(VI);
    901       }
    902 
    903       // If the contents are symbolic, find out when they became null.
    904       if (V.getAsLocSymbol()) {
    905         BugReporterVisitor *ConstraintTracker =
    906           new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
    907         report.addVisitor(ConstraintTracker);
    908 
    909         // Add visitor, which will suppress inline defensive checks.
    910         if (N->getState()->isNull(V).isConstrainedTrue()) {
    911           BugReporterVisitor *IDCSuppressor =
    912             new SuppressInlineDefensiveChecksVisitor(V.castAs<DefinedSVal>(),
    913                                                      N);
    914           report.addVisitor(IDCSuppressor);
    915         }
    916       }
    917 
    918       if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
    919         report.addVisitor(new FindLastStoreBRVisitor(*KV, R));
    920       return true;
    921     }
    922   }
    923 
    924   // If the expression is not an "lvalue expression", we can still
    925   // track the constraints on its contents.
    926   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
    927 
    928   // If the value came from an inlined function call, we should at least make
    929   // sure that function isn't pruned in our output.
    930   if (const Expr *E = dyn_cast<Expr>(S))
    931     S = E->IgnoreParenCasts();
    932   ReturnVisitor::addVisitorIfNecessary(N, S, report);
    933 
    934   // Uncomment this to find cases where we aren't properly getting the
    935   // base value that was dereferenced.
    936   // assert(!V.isUnknownOrUndef());
    937   // Is it a symbolic value?
    938   if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
    939     // At this point we are dealing with the region's LValue.
    940     // However, if the rvalue is a symbolic region, we should track it as well.
    941     SVal RVal = state->getSVal(L->getRegion());
    942     const MemRegion *RegionRVal = RVal.getAsRegion();
    943     report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
    944 
    945     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
    946       report.markInteresting(RegionRVal);
    947       report.addVisitor(new TrackConstraintBRVisitor(
    948         loc::MemRegionVal(RegionRVal), false));
    949     }
    950   }
    951 
    952   return true;
    953 }
    954 
    955 BugReporterVisitor *
    956 FindLastStoreBRVisitor::createVisitorObject(const ExplodedNode *N,
    957                                             const MemRegion *R) {
    958   assert(R && "The memory region is null.");
    959 
    960   ProgramStateRef state = N->getState();
    961   if (Optional<KnownSVal> KV = state->getSVal(R).getAs<KnownSVal>())
    962     return new FindLastStoreBRVisitor(*KV, R);
    963   return 0;
    964 }
    965 
    966 PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
    967                                                      const ExplodedNode *PrevN,
    968                                                      BugReporterContext &BRC,
    969                                                      BugReport &BR) {
    970   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
    971   if (!P)
    972     return 0;
    973   const ObjCMessageExpr *ME = P->getStmtAs<ObjCMessageExpr>();
    974   if (!ME)
    975     return 0;
    976   const Expr *Receiver = ME->getInstanceReceiver();
    977   if (!Receiver)
    978     return 0;
    979   ProgramStateRef state = N->getState();
    980   const SVal &V = state->getSVal(Receiver, N->getLocationContext());
    981   Optional<DefinedOrUnknownSVal> DV = V.getAs<DefinedOrUnknownSVal>();
    982   if (!DV)
    983     return 0;
    984   state = state->assume(*DV, true);
    985   if (state)
    986     return 0;
    987 
    988   // The receiver was nil, and hence the method was skipped.
    989   // Register a BugReporterVisitor to issue a message telling us how
    990   // the receiver was null.
    991   bugreporter::trackNullOrUndefValue(N, Receiver, BR);
    992   // Issue a message saying that the method was skipped.
    993   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
    994                                      N->getLocationContext());
    995   return new PathDiagnosticEventPiece(L, "No method is called "
    996       "because the receiver is nil");
    997 }
    998 
    999 // Registers every VarDecl inside a Stmt with a last store visitor.
   1000 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
   1001                                                        const Stmt *S) {
   1002   const ExplodedNode *N = BR.getErrorNode();
   1003   std::deque<const Stmt *> WorkList;
   1004   WorkList.push_back(S);
   1005 
   1006   while (!WorkList.empty()) {
   1007     const Stmt *Head = WorkList.front();
   1008     WorkList.pop_front();
   1009 
   1010     ProgramStateRef state = N->getState();
   1011     ProgramStateManager &StateMgr = state->getStateManager();
   1012 
   1013     if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
   1014       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
   1015         const VarRegion *R =
   1016         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
   1017 
   1018         // What did we load?
   1019         SVal V = state->getSVal(S, N->getLocationContext());
   1020 
   1021         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
   1022           // Register a new visitor with the BugReport.
   1023           BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R));
   1024         }
   1025       }
   1026     }
   1027 
   1028     for (Stmt::const_child_iterator I = Head->child_begin();
   1029         I != Head->child_end(); ++I)
   1030       WorkList.push_back(*I);
   1031   }
   1032 }
   1033 
   1034 //===----------------------------------------------------------------------===//
   1035 // Visitor that tries to report interesting diagnostics from conditions.
   1036 //===----------------------------------------------------------------------===//
   1037 
   1038 /// Return the tag associated with this visitor.  This tag will be used
   1039 /// to make all PathDiagnosticPieces created by this visitor.
   1040 const char *ConditionBRVisitor::getTag() {
   1041   return "ConditionBRVisitor";
   1042 }
   1043 
   1044 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
   1045                                                    const ExplodedNode *Prev,
   1046                                                    BugReporterContext &BRC,
   1047                                                    BugReport &BR) {
   1048   PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
   1049   if (piece) {
   1050     piece->setTag(getTag());
   1051     if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
   1052       ev->setPrunable(true, /* override */ false);
   1053   }
   1054   return piece;
   1055 }
   1056 
   1057 PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
   1058                                                        const ExplodedNode *Prev,
   1059                                                        BugReporterContext &BRC,
   1060                                                        BugReport &BR) {
   1061 
   1062   ProgramPoint progPoint = N->getLocation();
   1063   ProgramStateRef CurrentState = N->getState();
   1064   ProgramStateRef PrevState = Prev->getState();
   1065 
   1066   // Compare the GDMs of the state, because that is where constraints
   1067   // are managed.  Note that ensure that we only look at nodes that
   1068   // were generated by the analyzer engine proper, not checkers.
   1069   if (CurrentState->getGDM().getRoot() ==
   1070       PrevState->getGDM().getRoot())
   1071     return 0;
   1072 
   1073   // If an assumption was made on a branch, it should be caught
   1074   // here by looking at the state transition.
   1075   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
   1076     const CFGBlock *srcBlk = BE->getSrc();
   1077     if (const Stmt *term = srcBlk->getTerminator())
   1078       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
   1079     return 0;
   1080   }
   1081 
   1082   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
   1083     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
   1084     // violation.
   1085     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
   1086       cast<GRBugReporter>(BRC.getBugReporter()).
   1087         getEngine().geteagerlyAssumeBinOpBifurcationTags();
   1088 
   1089     const ProgramPointTag *tag = PS->getTag();
   1090     if (tag == tags.first)
   1091       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
   1092                            BRC, BR, N);
   1093     if (tag == tags.second)
   1094       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
   1095                            BRC, BR, N);
   1096 
   1097     return 0;
   1098   }
   1099 
   1100   return 0;
   1101 }
   1102 
   1103 PathDiagnosticPiece *
   1104 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
   1105                                     const ExplodedNode *N,
   1106                                     const CFGBlock *srcBlk,
   1107                                     const CFGBlock *dstBlk,
   1108                                     BugReport &R,
   1109                                     BugReporterContext &BRC) {
   1110   const Expr *Cond = 0;
   1111 
   1112   switch (Term->getStmtClass()) {
   1113   default:
   1114     return 0;
   1115   case Stmt::IfStmtClass:
   1116     Cond = cast<IfStmt>(Term)->getCond();
   1117     break;
   1118   case Stmt::ConditionalOperatorClass:
   1119     Cond = cast<ConditionalOperator>(Term)->getCond();
   1120     break;
   1121   }
   1122 
   1123   assert(Cond);
   1124   assert(srcBlk->succ_size() == 2);
   1125   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
   1126   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
   1127 }
   1128 
   1129 PathDiagnosticPiece *
   1130 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
   1131                                   bool tookTrue,
   1132                                   BugReporterContext &BRC,
   1133                                   BugReport &R,
   1134                                   const ExplodedNode *N) {
   1135 
   1136   const Expr *Ex = Cond;
   1137 
   1138   while (true) {
   1139     Ex = Ex->IgnoreParenCasts();
   1140     switch (Ex->getStmtClass()) {
   1141       default:
   1142         return 0;
   1143       case Stmt::BinaryOperatorClass:
   1144         return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
   1145                              R, N);
   1146       case Stmt::DeclRefExprClass:
   1147         return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
   1148                              R, N);
   1149       case Stmt::UnaryOperatorClass: {
   1150         const UnaryOperator *UO = cast<UnaryOperator>(Ex);
   1151         if (UO->getOpcode() == UO_LNot) {
   1152           tookTrue = !tookTrue;
   1153           Ex = UO->getSubExpr();
   1154           continue;
   1155         }
   1156         return 0;
   1157       }
   1158     }
   1159   }
   1160 }
   1161 
   1162 bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
   1163                                       BugReporterContext &BRC,
   1164                                       BugReport &report,
   1165                                       const ExplodedNode *N,
   1166                                       Optional<bool> &prunable) {
   1167   const Expr *OriginalExpr = Ex;
   1168   Ex = Ex->IgnoreParenCasts();
   1169 
   1170   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
   1171     const bool quotes = isa<VarDecl>(DR->getDecl());
   1172     if (quotes) {
   1173       Out << '\'';
   1174       const LocationContext *LCtx = N->getLocationContext();
   1175       const ProgramState *state = N->getState().getPtr();
   1176       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
   1177                                                 LCtx).getAsRegion()) {
   1178         if (report.isInteresting(R))
   1179           prunable = false;
   1180         else {
   1181           const ProgramState *state = N->getState().getPtr();
   1182           SVal V = state->getSVal(R);
   1183           if (report.isInteresting(V))
   1184             prunable = false;
   1185         }
   1186       }
   1187     }
   1188     Out << DR->getDecl()->getDeclName().getAsString();
   1189     if (quotes)
   1190       Out << '\'';
   1191     return quotes;
   1192   }
   1193 
   1194   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
   1195     QualType OriginalTy = OriginalExpr->getType();
   1196     if (OriginalTy->isPointerType()) {
   1197       if (IL->getValue() == 0) {
   1198         Out << "null";
   1199         return false;
   1200       }
   1201     }
   1202     else if (OriginalTy->isObjCObjectPointerType()) {
   1203       if (IL->getValue() == 0) {
   1204         Out << "nil";
   1205         return false;
   1206       }
   1207     }
   1208 
   1209     Out << IL->getValue();
   1210     return false;
   1211   }
   1212 
   1213   return false;
   1214 }
   1215 
   1216 PathDiagnosticPiece *
   1217 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
   1218                                   const BinaryOperator *BExpr,
   1219                                   const bool tookTrue,
   1220                                   BugReporterContext &BRC,
   1221                                   BugReport &R,
   1222                                   const ExplodedNode *N) {
   1223 
   1224   bool shouldInvert = false;
   1225   Optional<bool> shouldPrune;
   1226 
   1227   SmallString<128> LhsString, RhsString;
   1228   {
   1229     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
   1230     const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
   1231                                        shouldPrune);
   1232     const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
   1233                                        shouldPrune);
   1234 
   1235     shouldInvert = !isVarLHS && isVarRHS;
   1236   }
   1237 
   1238   BinaryOperator::Opcode Op = BExpr->getOpcode();
   1239 
   1240   if (BinaryOperator::isAssignmentOp(Op)) {
   1241     // For assignment operators, all that we care about is that the LHS
   1242     // evaluates to "true" or "false".
   1243     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
   1244                                   BRC, R, N);
   1245   }
   1246 
   1247   // For non-assignment operations, we require that we can understand
   1248   // both the LHS and RHS.
   1249   if (LhsString.empty() || RhsString.empty())
   1250     return 0;
   1251 
   1252   // Should we invert the strings if the LHS is not a variable name?
   1253   SmallString<256> buf;
   1254   llvm::raw_svector_ostream Out(buf);
   1255   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
   1256 
   1257   // Do we need to invert the opcode?
   1258   if (shouldInvert)
   1259     switch (Op) {
   1260       default: break;
   1261       case BO_LT: Op = BO_GT; break;
   1262       case BO_GT: Op = BO_LT; break;
   1263       case BO_LE: Op = BO_GE; break;
   1264       case BO_GE: Op = BO_LE; break;
   1265     }
   1266 
   1267   if (!tookTrue)
   1268     switch (Op) {
   1269       case BO_EQ: Op = BO_NE; break;
   1270       case BO_NE: Op = BO_EQ; break;
   1271       case BO_LT: Op = BO_GE; break;
   1272       case BO_GT: Op = BO_LE; break;
   1273       case BO_LE: Op = BO_GT; break;
   1274       case BO_GE: Op = BO_LT; break;
   1275       default:
   1276         return 0;
   1277     }
   1278 
   1279   switch (Op) {
   1280     case BO_EQ:
   1281       Out << "equal to ";
   1282       break;
   1283     case BO_NE:
   1284       Out << "not equal to ";
   1285       break;
   1286     default:
   1287       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
   1288       break;
   1289   }
   1290 
   1291   Out << (shouldInvert ? LhsString : RhsString);
   1292   const LocationContext *LCtx = N->getLocationContext();
   1293   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
   1294   PathDiagnosticEventPiece *event =
   1295     new PathDiagnosticEventPiece(Loc, Out.str());
   1296   if (shouldPrune.hasValue())
   1297     event->setPrunable(shouldPrune.getValue());
   1298   return event;
   1299 }
   1300 
   1301 PathDiagnosticPiece *
   1302 ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
   1303                                            const Expr *CondVarExpr,
   1304                                            const bool tookTrue,
   1305                                            BugReporterContext &BRC,
   1306                                            BugReport &report,
   1307                                            const ExplodedNode *N) {
   1308   // FIXME: If there's already a constraint tracker for this variable,
   1309   // we shouldn't emit anything here (c.f. the double note in
   1310   // test/Analysis/inlining/path-notes.c)
   1311   SmallString<256> buf;
   1312   llvm::raw_svector_ostream Out(buf);
   1313   Out << "Assuming " << LhsString << " is ";
   1314 
   1315   QualType Ty = CondVarExpr->getType();
   1316 
   1317   if (Ty->isPointerType())
   1318     Out << (tookTrue ? "not null" : "null");
   1319   else if (Ty->isObjCObjectPointerType())
   1320     Out << (tookTrue ? "not nil" : "nil");
   1321   else if (Ty->isBooleanType())
   1322     Out << (tookTrue ? "true" : "false");
   1323   else if (Ty->isIntegerType())
   1324     Out << (tookTrue ? "non-zero" : "zero");
   1325   else
   1326     return 0;
   1327 
   1328   const LocationContext *LCtx = N->getLocationContext();
   1329   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
   1330   PathDiagnosticEventPiece *event =
   1331     new PathDiagnosticEventPiece(Loc, Out.str());
   1332 
   1333   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
   1334     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
   1335       const ProgramState *state = N->getState().getPtr();
   1336       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
   1337         if (report.isInteresting(R))
   1338           event->setPrunable(false);
   1339       }
   1340     }
   1341   }
   1342 
   1343   return event;
   1344 }
   1345 
   1346 PathDiagnosticPiece *
   1347 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
   1348                                   const DeclRefExpr *DR,
   1349                                   const bool tookTrue,
   1350                                   BugReporterContext &BRC,
   1351                                   BugReport &report,
   1352                                   const ExplodedNode *N) {
   1353 
   1354   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
   1355   if (!VD)
   1356     return 0;
   1357 
   1358   SmallString<256> Buf;
   1359   llvm::raw_svector_ostream Out(Buf);
   1360 
   1361   Out << "Assuming '";
   1362   VD->getDeclName().printName(Out);
   1363   Out << "' is ";
   1364 
   1365   QualType VDTy = VD->getType();
   1366 
   1367   if (VDTy->isPointerType())
   1368     Out << (tookTrue ? "non-null" : "null");
   1369   else if (VDTy->isObjCObjectPointerType())
   1370     Out << (tookTrue ? "non-nil" : "nil");
   1371   else if (VDTy->isScalarType())
   1372     Out << (tookTrue ? "not equal to 0" : "0");
   1373   else
   1374     return 0;
   1375 
   1376   const LocationContext *LCtx = N->getLocationContext();
   1377   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
   1378   PathDiagnosticEventPiece *event =
   1379     new PathDiagnosticEventPiece(Loc, Out.str());
   1380 
   1381   const ProgramState *state = N->getState().getPtr();
   1382   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
   1383     if (report.isInteresting(R))
   1384       event->setPrunable(false);
   1385     else {
   1386       SVal V = state->getSVal(R);
   1387       if (report.isInteresting(V))
   1388         event->setPrunable(false);
   1389     }
   1390   }
   1391   return event;
   1392 }
   1393 
   1394 PathDiagnosticPiece *
   1395 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
   1396                                                     const ExplodedNode *N,
   1397                                                     BugReport &BR) {
   1398   const Stmt *S = BR.getStmt();
   1399   if (!S)
   1400     return 0;
   1401 
   1402   // Here we suppress false positives coming from system macros. This list is
   1403   // based on known issues.
   1404 
   1405   // Skip reports within the sys/queue.h macros as we do not have the ability to
   1406   // reason about data structure shapes.
   1407   SourceManager &SM = BRC.getSourceManager();
   1408   SourceLocation Loc = S->getLocStart();
   1409   while (Loc.isMacroID()) {
   1410     if (SM.isInSystemMacro(Loc) &&
   1411        (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
   1412       BR.markInvalid(getTag(), 0);
   1413       return 0;
   1414     }
   1415     Loc = SM.getSpellingLoc(Loc);
   1416   }
   1417 
   1418   return 0;
   1419 }
   1420 
   1421 PathDiagnosticPiece *
   1422 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
   1423                                   const ExplodedNode *PrevN,
   1424                                   BugReporterContext &BRC,
   1425                                   BugReport &BR) {
   1426 
   1427   ProgramStateRef State = N->getState();
   1428   ProgramPoint ProgLoc = N->getLocation();
   1429 
   1430   // We are only interested in visiting CallEnter nodes.
   1431   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
   1432   if (!CEnter)
   1433     return 0;
   1434 
   1435   // Check if one of the arguments is the region the visitor is tracking.
   1436   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
   1437   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
   1438   unsigned Idx = 0;
   1439   for (CallEvent::param_iterator I = Call->param_begin(),
   1440                                  E = Call->param_end(); I != E; ++I, ++Idx) {
   1441     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
   1442 
   1443     // Are we tracking the argument or its subregion?
   1444     if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
   1445       continue;
   1446 
   1447     // Check the function parameter type.
   1448     const ParmVarDecl *ParamDecl = *I;
   1449     assert(ParamDecl && "Formal parameter has no decl?");
   1450     QualType T = ParamDecl->getType();
   1451 
   1452     if (!(T->isAnyPointerType() || T->isReferenceType())) {
   1453       // Function can only change the value passed in by address.
   1454       continue;
   1455     }
   1456 
   1457     // If it is a const pointer value, the function does not intend to
   1458     // change the value.
   1459     if (T->getPointeeType().isConstQualified())
   1460       continue;
   1461 
   1462     // Mark the call site (LocationContext) as interesting if the value of the
   1463     // argument is undefined or '0'/'NULL'.
   1464     SVal BoundVal = State->getSVal(R);
   1465     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
   1466       BR.markInteresting(CEnter->getCalleeContext());
   1467       return 0;
   1468     }
   1469   }
   1470   return 0;
   1471 }
   1472