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/BugReporterVisitors.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/Analysis/CFGStmtMap.h"
18 #include "clang/Lex/Lexer.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
28 
29 using namespace clang;
30 using namespace ento;
31 
32 using llvm::FoldingSetNodeID;
33 
34 //===----------------------------------------------------------------------===//
35 // Utility functions.
36 //===----------------------------------------------------------------------===//
37 
38 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
39   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
40     return DRE->getDecl()->getType()->isReferenceType();
41   }
42   return false;
43 }
44 
45 /// Given that expression S represents a pointer that would be dereferenced,
46 /// try to find a sub-expression from which the pointer came from.
47 /// This is used for tracking down origins of a null or undefined value:
48 /// "this is null because that is null because that is null" etc.
49 /// We wipe away field and element offsets because they merely add offsets.
50 /// We also wipe away all casts except lvalue-to-rvalue casts, because the
51 /// latter represent an actual pointer dereference; however, we remove
52 /// the final lvalue-to-rvalue cast before returning from this function
53 /// because it demonstrates more clearly from where the pointer rvalue was
54 /// loaded. Examples:
55 ///   x->y.z      ==>  x (lvalue)
56 ///   foo()->y.z  ==>  foo() (rvalue)
57 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
58   const Expr *E = dyn_cast<Expr>(S);
59   if (!E)
60     return nullptr;
61 
62   while (true) {
63     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
64       if (CE->getCastKind() == CK_LValueToRValue) {
65         // This cast represents the load we're looking for.
66         break;
67       }
68       E = CE->getSubExpr();
69     } else if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
70       // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
71       if (B->getType()->isPointerType()) {
72         if (B->getLHS()->getType()->isPointerType()) {
73           E = B->getLHS();
74         } else if (B->getRHS()->getType()->isPointerType()) {
75           E = B->getRHS();
76         } else {
77           break;
78         }
79       } else {
80         // Probably more arithmetic can be pattern-matched here,
81         // but for now give up.
82         break;
83       }
84     } else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
85       if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
86           (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
87         // Operators '*' and '&' don't actually mean anything.
88         // We look at casts instead.
89         E = U->getSubExpr();
90       } else {
91         // Probably more arithmetic can be pattern-matched here,
92         // but for now give up.
93         break;
94       }
95     }
96     // Pattern match for a few useful cases: a[0], p->f, *p etc.
97     else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
98       E = ME->getBase();
99     } else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
100       E = IvarRef->getBase();
101     } else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
102       E = AE->getBase();
103     } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
104       E = PE->getSubExpr();
105     } else {
106       // Other arbitrary stuff.
107       break;
108     }
109   }
110 
111   // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
112   // deeper into the sub-expression. This way we return the lvalue from which
113   // our pointer rvalue was loaded.
114   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
115     if (CE->getCastKind() == CK_LValueToRValue)
116       E = CE->getSubExpr();
117 
118   return E;
119 }
120 
121 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
122   const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
123   if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
124     return BE->getRHS();
125   return nullptr;
126 }
127 
128 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
129   const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
130   if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
131     return RS->getRetValue();
132   return nullptr;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 // Definitions for bug reporter visitors.
137 //===----------------------------------------------------------------------===//
138 
139 std::unique_ptr<PathDiagnosticPiece>
140 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
141                                const ExplodedNode *EndPathNode, BugReport &BR) {
142   return nullptr;
143 }
144 
145 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
146     BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
147   PathDiagnosticLocation L =
148     PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
149 
150   const auto &Ranges = BR.getRanges();
151 
152   // Only add the statement itself as a range if we didn't specify any
153   // special ranges for this report.
154   auto P = llvm::make_unique<PathDiagnosticEventPiece>(
155       L, BR.getDescription(), Ranges.begin() == Ranges.end());
156   for (SourceRange Range : Ranges)
157     P->addRange(Range);
158 
159   return std::move(P);
160 }
161 
162 /// \return name of the macro inside the location \p Loc.
163 static StringRef getMacroName(SourceLocation Loc,
164     BugReporterContext &BRC) {
165   return Lexer::getImmediateMacroName(
166       Loc,
167       BRC.getSourceManager(),
168       BRC.getASTContext().getLangOpts());
169 }
170 
171 /// \return Whether given spelling location corresponds to an expansion
172 /// of a function-like macro.
173 static bool isFunctionMacroExpansion(SourceLocation Loc,
174                                 const SourceManager &SM) {
175   if (!Loc.isMacroID())
176     return false;
177   while (SM.isMacroArgExpansion(Loc))
178     Loc = SM.getImmediateExpansionRange(Loc).first;
179   std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
180   SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
181   const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
182   return EInfo.isFunctionMacroExpansion();
183 }
184 
185 namespace {
186 
187 class MacroNullReturnSuppressionVisitor final
188     : public BugReporterVisitorImpl<MacroNullReturnSuppressionVisitor> {
189 
190   const SubRegion *RegionOfInterest;
191 
192 public:
193   MacroNullReturnSuppressionVisitor(const SubRegion *R) : RegionOfInterest(R) {}
194 
195   static void *getTag() {
196     static int Tag = 0;
197     return static_cast<void *>(&Tag);
198   }
199 
200   void Profile(llvm::FoldingSetNodeID &ID) const override {
201     ID.AddPointer(getTag());
202   }
203 
204   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
205                                                  const ExplodedNode *PrevN,
206                                                  BugReporterContext &BRC,
207                                                  BugReport &BR) override {
208     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
209     if (!BugPoint)
210       return nullptr;
211 
212     const SourceManager &SMgr = BRC.getSourceManager();
213     if (auto Loc = matchAssignment(N, BRC)) {
214       if (isFunctionMacroExpansion(*Loc, SMgr)) {
215         std::string MacroName = getMacroName(*Loc, BRC);
216         SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
217         if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
218           BR.markInvalid(getTag(), MacroName.c_str());
219       }
220     }
221     return nullptr;
222   }
223 
224   static void addMacroVisitorIfNecessary(
225         const ExplodedNode *N, const MemRegion *R,
226         bool EnableNullFPSuppression, BugReport &BR,
227         const SVal V) {
228     AnalyzerOptions &Options = N->getState()->getStateManager()
229         .getOwningEngine()->getAnalysisManager().options;
230     if (EnableNullFPSuppression && Options.shouldSuppressNullReturnPaths()
231           && V.getAs<Loc>())
232       BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
233               R->getAs<SubRegion>()));
234   }
235 
236 private:
237   /// \return Source location of right hand side of an assignment
238   /// into \c RegionOfInterest, empty optional if none found.
239   Optional<SourceLocation> matchAssignment(const ExplodedNode *N,
240                                            BugReporterContext &BRC) {
241     const Stmt *S = PathDiagnosticLocation::getStmt(N);
242     ProgramStateRef State = N->getState();
243     auto *LCtx = N->getLocationContext();
244     if (!S)
245       return None;
246 
247     if (auto *DS = dyn_cast<DeclStmt>(S)) {
248       if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
249         if (const Expr *RHS = VD->getInit())
250           if (RegionOfInterest->isSubRegionOf(
251                   State->getLValue(VD, LCtx).getAsRegion()))
252             return RHS->getLocStart();
253     } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
254       const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
255       const Expr *RHS = BO->getRHS();
256       if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
257         return RHS->getLocStart();
258       }
259     }
260     return None;
261   }
262 };
263 
264 /// Emits an extra note at the return statement of an interesting stack frame.
265 ///
266 /// The returned value is marked as an interesting value, and if it's null,
267 /// adds a visitor to track where it became null.
268 ///
269 /// This visitor is intended to be used when another visitor discovers that an
270 /// interesting value comes from an inlined function call.
271 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
272   const StackFrameContext *StackFrame;
273   enum {
274     Initial,
275     MaybeUnsuppress,
276     Satisfied
277   } Mode;
278 
279   bool EnableNullFPSuppression;
280 
281 public:
282   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
283     : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
284 
285   static void *getTag() {
286     static int Tag = 0;
287     return static_cast<void *>(&Tag);
288   }
289 
290   void Profile(llvm::FoldingSetNodeID &ID) const override {
291     ID.AddPointer(ReturnVisitor::getTag());
292     ID.AddPointer(StackFrame);
293     ID.AddBoolean(EnableNullFPSuppression);
294   }
295 
296   /// Adds a ReturnVisitor if the given statement represents a call that was
297   /// inlined.
298   ///
299   /// This will search back through the ExplodedGraph, starting from the given
300   /// node, looking for when the given statement was processed. If it turns out
301   /// the statement is a call that was inlined, we add the visitor to the
302   /// bug report, so it can print a note later.
303   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
304                                     BugReport &BR,
305                                     bool InEnableNullFPSuppression) {
306     if (!CallEvent::isCallStmt(S))
307       return;
308 
309     // First, find when we processed the statement.
310     do {
311       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
312         if (CEE->getCalleeContext()->getCallSite() == S)
313           break;
314       if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
315         if (SP->getStmt() == S)
316           break;
317 
318       Node = Node->getFirstPred();
319     } while (Node);
320 
321     // Next, step over any post-statement checks.
322     while (Node && Node->getLocation().getAs<PostStmt>())
323       Node = Node->getFirstPred();
324     if (!Node)
325       return;
326 
327     // Finally, see if we inlined the call.
328     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
329     if (!CEE)
330       return;
331 
332     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
333     if (CalleeContext->getCallSite() != S)
334       return;
335 
336     // Check the return value.
337     ProgramStateRef State = Node->getState();
338     SVal RetVal = Node->getSVal(S);
339 
340     // Handle cases where a reference is returned and then immediately used.
341     if (cast<Expr>(S)->isGLValue())
342       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
343         RetVal = State->getSVal(*LValue);
344 
345     // See if the return value is NULL. If so, suppress the report.
346     SubEngine *Eng = State->getStateManager().getOwningEngine();
347     assert(Eng && "Cannot file a bug report without an owning engine");
348     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
349 
350     bool EnableNullFPSuppression = false;
351     if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
352       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
353         EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
354 
355     BR.markInteresting(CalleeContext);
356     BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
357                                                    EnableNullFPSuppression));
358   }
359 
360   /// Returns true if any counter-suppression heuristics are enabled for
361   /// ReturnVisitor.
362   static bool hasCounterSuppression(AnalyzerOptions &Options) {
363     return Options.shouldAvoidSuppressingNullArgumentPaths();
364   }
365 
366   std::shared_ptr<PathDiagnosticPiece>
367   visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
368                    BugReporterContext &BRC, BugReport &BR) {
369     // Only print a message at the interesting return statement.
370     if (N->getLocationContext() != StackFrame)
371       return nullptr;
372 
373     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
374     if (!SP)
375       return nullptr;
376 
377     const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
378     if (!Ret)
379       return nullptr;
380 
381     // Okay, we're at the right return statement, but do we have the return
382     // value available?
383     ProgramStateRef State = N->getState();
384     SVal V = State->getSVal(Ret, StackFrame);
385     if (V.isUnknownOrUndef())
386       return nullptr;
387 
388     // Don't print any more notes after this one.
389     Mode = Satisfied;
390 
391     const Expr *RetE = Ret->getRetValue();
392     assert(RetE && "Tracking a return value for a void function");
393 
394     // Handle cases where a reference is returned and then immediately used.
395     Optional<Loc> LValue;
396     if (RetE->isGLValue()) {
397       if ((LValue = V.getAs<Loc>())) {
398         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
399         if (RValue.getAs<DefinedSVal>())
400           V = RValue;
401       }
402     }
403 
404     // Ignore aggregate rvalues.
405     if (V.getAs<nonloc::LazyCompoundVal>() ||
406         V.getAs<nonloc::CompoundVal>())
407       return nullptr;
408 
409     RetE = RetE->IgnoreParenCasts();
410 
411     // If we can't prove the return value is 0, just mark it interesting, and
412     // make sure to track it into any further inner functions.
413     if (!State->isNull(V).isConstrainedTrue()) {
414       BR.markInteresting(V);
415       ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
416                                            EnableNullFPSuppression);
417       return nullptr;
418     }
419 
420     // If we're returning 0, we should track where that 0 came from.
421     bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
422                                        EnableNullFPSuppression);
423 
424     // Build an appropriate message based on the return value.
425     SmallString<64> Msg;
426     llvm::raw_svector_ostream Out(Msg);
427 
428     if (V.getAs<Loc>()) {
429       // If we have counter-suppression enabled, make sure we keep visiting
430       // future nodes. We want to emit a path note as well, in case
431       // the report is resurrected as valid later on.
432       ExprEngine &Eng = BRC.getBugReporter().getEngine();
433       AnalyzerOptions &Options = Eng.getAnalysisManager().options;
434       if (EnableNullFPSuppression && hasCounterSuppression(Options))
435         Mode = MaybeUnsuppress;
436 
437       if (RetE->getType()->isObjCObjectPointerType())
438         Out << "Returning nil";
439       else
440         Out << "Returning null pointer";
441     } else {
442       Out << "Returning zero";
443     }
444 
445     if (LValue) {
446       if (const MemRegion *MR = LValue->getAsRegion()) {
447         if (MR->canPrintPretty()) {
448           Out << " (reference to ";
449           MR->printPretty(Out);
450           Out << ")";
451         }
452       }
453     } else {
454       // FIXME: We should have a more generalized location printing mechanism.
455       if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
456         if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
457           Out << " (loaded from '" << *DD << "')";
458     }
459 
460     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
461     if (!L.isValid() || !L.asLocation().isValid())
462       return nullptr;
463 
464     return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
465   }
466 
467   std::shared_ptr<PathDiagnosticPiece>
468   visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
469                            BugReporterContext &BRC, BugReport &BR) {
470 #ifndef NDEBUG
471     ExprEngine &Eng = BRC.getBugReporter().getEngine();
472     AnalyzerOptions &Options = Eng.getAnalysisManager().options;
473     assert(hasCounterSuppression(Options));
474 #endif
475 
476     // Are we at the entry node for this call?
477     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
478     if (!CE)
479       return nullptr;
480 
481     if (CE->getCalleeContext() != StackFrame)
482       return nullptr;
483 
484     Mode = Satisfied;
485 
486     // Don't automatically suppress a report if one of the arguments is
487     // known to be a null pointer. Instead, start tracking /that/ null
488     // value back to its origin.
489     ProgramStateManager &StateMgr = BRC.getStateManager();
490     CallEventManager &CallMgr = StateMgr.getCallEventManager();
491 
492     ProgramStateRef State = N->getState();
493     CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
494     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
495       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
496       if (!ArgV)
497         continue;
498 
499       const Expr *ArgE = Call->getArgExpr(I);
500       if (!ArgE)
501         continue;
502 
503       // Is it possible for this argument to be non-null?
504       if (!State->isNull(*ArgV).isConstrainedTrue())
505         continue;
506 
507       if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
508                                              EnableNullFPSuppression))
509         BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
510 
511       // If we /can't/ track the null pointer, we should err on the side of
512       // false negatives, and continue towards marking this report invalid.
513       // (We will still look at the other arguments, though.)
514     }
515 
516     return nullptr;
517   }
518 
519   std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
520                                                  const ExplodedNode *PrevN,
521                                                  BugReporterContext &BRC,
522                                                  BugReport &BR) override {
523     switch (Mode) {
524     case Initial:
525       return visitNodeInitial(N, PrevN, BRC, BR);
526     case MaybeUnsuppress:
527       return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
528     case Satisfied:
529       return nullptr;
530     }
531 
532     llvm_unreachable("Invalid visit mode!");
533   }
534 
535   std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
536                                                   const ExplodedNode *N,
537                                                   BugReport &BR) override {
538     if (EnableNullFPSuppression)
539       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
540     return nullptr;
541   }
542 };
543 } // end anonymous namespace
544 
545 
546 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
547   static int tag = 0;
548   ID.AddPointer(&tag);
549   ID.AddPointer(R);
550   ID.Add(V);
551   ID.AddBoolean(EnableNullFPSuppression);
552 }
553 
554 /// Returns true if \p N represents the DeclStmt declaring and initializing
555 /// \p VR.
556 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
557   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
558   if (!P)
559     return false;
560 
561   const DeclStmt *DS = P->getStmtAs<DeclStmt>();
562   if (!DS)
563     return false;
564 
565   if (DS->getSingleDecl() != VR->getDecl())
566     return false;
567 
568   const MemSpaceRegion *VarSpace = VR->getMemorySpace();
569   const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
570   if (!FrameSpace) {
571     // If we ever directly evaluate global DeclStmts, this assertion will be
572     // invalid, but this still seems preferable to silently accepting an
573     // initialization that may be for a path-sensitive variable.
574     assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
575     return true;
576   }
577 
578   assert(VR->getDecl()->hasLocalStorage());
579   const LocationContext *LCtx = N->getLocationContext();
580   return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
581 }
582 
583 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
584 void showBRDiagnostics(const char *action,
585     llvm::raw_svector_ostream& os,
586     const MemRegion *R,
587     SVal V,
588     const DeclStmt *DS) {
589   if (R->canPrintPretty()) {
590     R->printPretty(os);
591     os << " ";
592   }
593 
594   if (V.getAs<loc::ConcreteInt>()) {
595     bool b = false;
596     if (R->isBoundable()) {
597       if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
598         if (TR->getValueType()->isObjCObjectPointerType()) {
599           os << action << "nil";
600           b = true;
601         }
602       }
603     }
604     if (!b)
605       os << action << "a null pointer value";
606 
607   } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
608     os << action << CVal->getValue();
609   } else if (DS) {
610     if (V.isUndef()) {
611       if (isa<VarRegion>(R)) {
612         const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
613         if (VD->getInit()) {
614           os << (R->canPrintPretty() ? "initialized" : "Initializing")
615             << " to a garbage value";
616         } else {
617           os << (R->canPrintPretty() ? "declared" : "Declaring")
618             << " without an initial value";
619         }
620       }
621     } else {
622       os << (R->canPrintPretty() ? "initialized" : "Initialized")
623         << " here";
624     }
625   }
626 }
627 
628 /// Display diagnostics for passing bad region as a parameter.
629 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
630     const VarRegion *VR,
631     SVal V) {
632   const auto *Param = cast<ParmVarDecl>(VR->getDecl());
633 
634   os << "Passing ";
635 
636   if (V.getAs<loc::ConcreteInt>()) {
637     if (Param->getType()->isObjCObjectPointerType())
638       os << "nil object reference";
639     else
640       os << "null pointer value";
641   } else if (V.isUndef()) {
642     os << "uninitialized value";
643   } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
644     os << "the value " << CI->getValue();
645   } else {
646     os << "value";
647   }
648 
649   // Printed parameter indexes are 1-based, not 0-based.
650   unsigned Idx = Param->getFunctionScopeIndex() + 1;
651   os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
652   if (VR->canPrintPretty()) {
653     os << " ";
654     VR->printPretty(os);
655   }
656 }
657 
658 /// Show default diagnostics for storing bad region.
659 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
660     const MemRegion *R,
661     SVal V) {
662   if (V.getAs<loc::ConcreteInt>()) {
663     bool b = false;
664     if (R->isBoundable()) {
665       if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
666         if (TR->getValueType()->isObjCObjectPointerType()) {
667           os << "nil object reference stored";
668           b = true;
669         }
670       }
671     }
672     if (!b) {
673       if (R->canPrintPretty())
674         os << "Null pointer value stored";
675       else
676         os << "Storing null pointer value";
677     }
678 
679   } else if (V.isUndef()) {
680     if (R->canPrintPretty())
681       os << "Uninitialized value stored";
682     else
683       os << "Storing uninitialized value";
684 
685   } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
686     if (R->canPrintPretty())
687       os << "The value " << CV->getValue() << " is assigned";
688     else
689       os << "Assigning " << CV->getValue();
690 
691   } else {
692     if (R->canPrintPretty())
693       os << "Value assigned";
694     else
695       os << "Assigning value";
696   }
697 
698   if (R->canPrintPretty()) {
699     os << " to ";
700     R->printPretty(os);
701   }
702 }
703 
704 std::shared_ptr<PathDiagnosticPiece>
705 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
706                                   const ExplodedNode *Pred,
707                                   BugReporterContext &BRC, BugReport &BR) {
708 
709   if (Satisfied)
710     return nullptr;
711 
712   const ExplodedNode *StoreSite = nullptr;
713   const Expr *InitE = nullptr;
714   bool IsParam = false;
715 
716   // First see if we reached the declaration of the region.
717   if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
718     if (isInitializationOfVar(Pred, VR)) {
719       StoreSite = Pred;
720       InitE = VR->getDecl()->getInit();
721     }
722   }
723 
724   // If this is a post initializer expression, initializing the region, we
725   // should track the initializer expression.
726   if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
727     const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
728     if (FieldReg && FieldReg == R) {
729       StoreSite = Pred;
730       InitE = PIP->getInitializer()->getInit();
731     }
732   }
733 
734   // Otherwise, see if this is the store site:
735   // (1) Succ has this binding and Pred does not, i.e. this is
736   //     where the binding first occurred.
737   // (2) Succ has this binding and is a PostStore node for this region, i.e.
738   //     the same binding was re-assigned here.
739   if (!StoreSite) {
740     if (Succ->getState()->getSVal(R) != V)
741       return nullptr;
742 
743     if (Pred->getState()->getSVal(R) == V) {
744       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
745       if (!PS || PS->getLocationValue() != R)
746         return nullptr;
747     }
748 
749     StoreSite = Succ;
750 
751     // If this is an assignment expression, we can track the value
752     // being assigned.
753     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
754       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
755         if (BO->isAssignmentOp())
756           InitE = BO->getRHS();
757 
758     // If this is a call entry, the variable should be a parameter.
759     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
760     // 'this' should never be NULL, but this visitor isn't just for NULL and
761     // UndefinedVal.)
762     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
763       if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
764         const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
765 
766         ProgramStateManager &StateMgr = BRC.getStateManager();
767         CallEventManager &CallMgr = StateMgr.getCallEventManager();
768 
769         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
770                                                 Succ->getState());
771         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
772         IsParam = true;
773       }
774     }
775 
776     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
777     // is wrapped inside of it.
778     if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
779       InitE = TmpR->getExpr();
780   }
781 
782   if (!StoreSite)
783     return nullptr;
784   Satisfied = true;
785 
786   // If we have an expression that provided the value, try to track where it
787   // came from.
788   if (InitE) {
789     if (V.isUndef() ||
790         V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
791       if (!IsParam)
792         InitE = InitE->IgnoreParenCasts();
793       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
794                                          EnableNullFPSuppression);
795     } else {
796       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
797                                            BR, EnableNullFPSuppression);
798     }
799   }
800 
801   // Okay, we've found the binding. Emit an appropriate message.
802   SmallString<256> sbuf;
803   llvm::raw_svector_ostream os(sbuf);
804 
805   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
806     const Stmt *S = PS->getStmt();
807     const char *action = nullptr;
808     const DeclStmt *DS = dyn_cast<DeclStmt>(S);
809     const VarRegion *VR = dyn_cast<VarRegion>(R);
810 
811     if (DS) {
812       action = R->canPrintPretty() ? "initialized to " :
813                                      "Initializing to ";
814     } else if (isa<BlockExpr>(S)) {
815       action = R->canPrintPretty() ? "captured by block as " :
816                                      "Captured by block as ";
817       if (VR) {
818         // See if we can get the BlockVarRegion.
819         ProgramStateRef State = StoreSite->getState();
820         SVal V = StoreSite->getSVal(S);
821         if (const BlockDataRegion *BDR =
822               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
823           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
824             if (Optional<KnownSVal> KV =
825                 State->getSVal(OriginalR).getAs<KnownSVal>())
826               BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
827                   *KV, OriginalR, EnableNullFPSuppression));
828           }
829         }
830       }
831     }
832     if (action)
833       showBRDiagnostics(action, os, R, V, DS);
834 
835   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
836     if (const VarRegion *VR = dyn_cast<VarRegion>(R))
837       showBRParamDiagnostics(os, VR, V);
838   }
839 
840   if (os.str().empty())
841     showBRDefaultDiagnostics(os, R, V);
842 
843   // Construct a new PathDiagnosticPiece.
844   ProgramPoint P = StoreSite->getLocation();
845   PathDiagnosticLocation L;
846   if (P.getAs<CallEnter>() && InitE)
847     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
848                                P.getLocationContext());
849 
850   if (!L.isValid() || !L.asLocation().isValid())
851     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
852 
853   if (!L.isValid() || !L.asLocation().isValid())
854     return nullptr;
855 
856   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
857 }
858 
859 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
860   static int tag = 0;
861   ID.AddPointer(&tag);
862   ID.AddBoolean(Assumption);
863   ID.Add(Constraint);
864 }
865 
866 /// Return the tag associated with this visitor.  This tag will be used
867 /// to make all PathDiagnosticPieces created by this visitor.
868 const char *TrackConstraintBRVisitor::getTag() {
869   return "TrackConstraintBRVisitor";
870 }
871 
872 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
873   if (IsZeroCheck)
874     return N->getState()->isNull(Constraint).isUnderconstrained();
875   return (bool)N->getState()->assume(Constraint, !Assumption);
876 }
877 
878 std::shared_ptr<PathDiagnosticPiece>
879 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
880                                     const ExplodedNode *PrevN,
881                                     BugReporterContext &BRC, BugReport &BR) {
882   if (IsSatisfied)
883     return nullptr;
884 
885   // Start tracking after we see the first state in which the value is
886   // constrained.
887   if (!IsTrackingTurnedOn)
888     if (!isUnderconstrained(N))
889       IsTrackingTurnedOn = true;
890   if (!IsTrackingTurnedOn)
891     return nullptr;
892 
893   // Check if in the previous state it was feasible for this constraint
894   // to *not* be true.
895   if (isUnderconstrained(PrevN)) {
896 
897     IsSatisfied = true;
898 
899     // As a sanity check, make sure that the negation of the constraint
900     // was infeasible in the current state.  If it is feasible, we somehow
901     // missed the transition point.
902     assert(!isUnderconstrained(N));
903 
904     // We found the transition point for the constraint.  We now need to
905     // pretty-print the constraint. (work-in-progress)
906     SmallString<64> sbuf;
907     llvm::raw_svector_ostream os(sbuf);
908 
909     if (Constraint.getAs<Loc>()) {
910       os << "Assuming pointer value is ";
911       os << (Assumption ? "non-null" : "null");
912     }
913 
914     if (os.str().empty())
915       return nullptr;
916 
917     // Construct a new PathDiagnosticPiece.
918     ProgramPoint P = N->getLocation();
919     PathDiagnosticLocation L =
920       PathDiagnosticLocation::create(P, BRC.getSourceManager());
921     if (!L.isValid())
922       return nullptr;
923 
924     auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
925     X->setTag(getTag());
926     return std::move(X);
927   }
928 
929   return nullptr;
930 }
931 
932 SuppressInlineDefensiveChecksVisitor::
933 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
934   : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
935 
936     // Check if the visitor is disabled.
937     SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
938     assert(Eng && "Cannot file a bug report without an owning engine");
939     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
940     if (!Options.shouldSuppressInlinedDefensiveChecks())
941       IsSatisfied = true;
942 
943     assert(N->getState()->isNull(V).isConstrainedTrue() &&
944            "The visitor only tracks the cases where V is constrained to 0");
945 }
946 
947 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
948   static int id = 0;
949   ID.AddPointer(&id);
950   ID.Add(V);
951 }
952 
953 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
954   return "IDCVisitor";
955 }
956 
957 std::shared_ptr<PathDiagnosticPiece>
958 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
959                                                 const ExplodedNode *Pred,
960                                                 BugReporterContext &BRC,
961                                                 BugReport &BR) {
962   if (IsSatisfied)
963     return nullptr;
964 
965   // Start tracking after we see the first state in which the value is null.
966   if (!IsTrackingTurnedOn)
967     if (Succ->getState()->isNull(V).isConstrainedTrue())
968       IsTrackingTurnedOn = true;
969   if (!IsTrackingTurnedOn)
970     return nullptr;
971 
972   // Check if in the previous state it was feasible for this value
973   // to *not* be null.
974   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
975     IsSatisfied = true;
976 
977     assert(Succ->getState()->isNull(V).isConstrainedTrue());
978 
979     // Check if this is inlined defensive checks.
980     const LocationContext *CurLC =Succ->getLocationContext();
981     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
982     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
983       BR.markInvalid("Suppress IDC", CurLC);
984       return nullptr;
985     }
986 
987     // Treat defensive checks in function-like macros as if they were an inlined
988     // defensive check. If the bug location is not in a macro and the
989     // terminator for the current location is in a macro then suppress the
990     // warning.
991     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
992 
993     if (!BugPoint)
994       return nullptr;
995 
996 
997     ProgramPoint CurPoint = Succ->getLocation();
998     const Stmt *CurTerminatorStmt = nullptr;
999     if (auto BE = CurPoint.getAs<BlockEdge>()) {
1000       CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1001     } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1002       const Stmt *CurStmt = SP->getStmt();
1003       if (!CurStmt->getLocStart().isMacroID())
1004         return nullptr;
1005 
1006       CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1007       CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
1008     } else {
1009       return nullptr;
1010     }
1011 
1012     if (!CurTerminatorStmt)
1013       return nullptr;
1014 
1015     SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
1016     if (TerminatorLoc.isMacroID()) {
1017       SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
1018 
1019       // Suppress reports unless we are in that same macro.
1020       if (!BugLoc.isMacroID() ||
1021           getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1022         BR.markInvalid("Suppress Macro IDC", CurLC);
1023       }
1024       return nullptr;
1025     }
1026   }
1027   return nullptr;
1028 }
1029 
1030 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1031                                                      const ExplodedNode *N) {
1032   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
1033     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1034       if (!VD->getType()->isReferenceType())
1035         return nullptr;
1036       ProgramStateManager &StateMgr = N->getState()->getStateManager();
1037       MemRegionManager &MRMgr = StateMgr.getRegionManager();
1038       return MRMgr.getVarRegion(VD, N->getLocationContext());
1039     }
1040   }
1041 
1042   // FIXME: This does not handle other kinds of null references,
1043   // for example, references from FieldRegions:
1044   //   struct Wrapper { int &ref; };
1045   //   Wrapper w = { *(int *)0 };
1046   //   w.ref = 1;
1047 
1048   return nullptr;
1049 }
1050 
1051 static const Expr *peelOffOuterExpr(const Expr *Ex,
1052                                     const ExplodedNode *N) {
1053   Ex = Ex->IgnoreParenCasts();
1054   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
1055     return peelOffOuterExpr(EWC->getSubExpr(), N);
1056   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1057     return peelOffOuterExpr(OVE->getSourceExpr(), N);
1058   if (auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1059     auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1060     if (PropRef && PropRef->isMessagingGetter()) {
1061       const Expr *GetterMessageSend =
1062           POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1063       assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1064       return peelOffOuterExpr(GetterMessageSend, N);
1065     }
1066   }
1067 
1068   // Peel off the ternary operator.
1069   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
1070     // Find a node where the branching occurred and find out which branch
1071     // we took (true/false) by looking at the ExplodedGraph.
1072     const ExplodedNode *NI = N;
1073     do {
1074       ProgramPoint ProgPoint = NI->getLocation();
1075       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1076         const CFGBlock *srcBlk = BE->getSrc();
1077         if (const Stmt *term = srcBlk->getTerminator()) {
1078           if (term == CO) {
1079             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1080             if (TookTrueBranch)
1081               return peelOffOuterExpr(CO->getTrueExpr(), N);
1082             else
1083               return peelOffOuterExpr(CO->getFalseExpr(), N);
1084           }
1085         }
1086       }
1087       NI = NI->getFirstPred();
1088     } while (NI);
1089   }
1090   return Ex;
1091 }
1092 
1093 /// Walk through nodes until we get one that matches the statement exactly.
1094 /// Alternately, if we hit a known lvalue for the statement, we know we've
1095 /// gone too far (though we can likely track the lvalue better anyway).
1096 static const ExplodedNode* findNodeForStatement(const ExplodedNode *N,
1097                                                 const Stmt *S,
1098                                                 const Expr *Inner) {
1099   do {
1100     const ProgramPoint &pp = N->getLocation();
1101     if (auto ps = pp.getAs<StmtPoint>()) {
1102       if (ps->getStmt() == S || ps->getStmt() == Inner)
1103         break;
1104     } else if (auto CEE = pp.getAs<CallExitEnd>()) {
1105       if (CEE->getCalleeContext()->getCallSite() == S ||
1106           CEE->getCalleeContext()->getCallSite() == Inner)
1107         break;
1108     }
1109     N = N->getFirstPred();
1110   } while (N);
1111   return N;
1112 }
1113 
1114 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1115 /// was computed.
1116 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1117     const Expr *Inner) {
1118   while (N) {
1119     if (auto P = N->getLocation().getAs<PostStmt>()) {
1120       if (P->getStmt() == Inner)
1121         break;
1122     }
1123     N = N->getFirstPred();
1124   }
1125   assert(N && "Unable to find the lvalue node.");
1126   return N;
1127 
1128 }
1129 
1130 /// Performing operator `&' on an lvalue expression is essentially a no-op.
1131 /// Then, if we are taking addresses of fields or elements, these are also
1132 /// unlikely to matter.
1133 static const Expr* peelOfOuterAddrOf(const Expr* Ex) {
1134   Ex = Ex->IgnoreParenCasts();
1135 
1136   // FIXME: There's a hack in our Store implementation that always computes
1137   // field offsets around null pointers as if they are always equal to 0.
1138   // The idea here is to report accesses to fields as null dereferences
1139   // even though the pointer value that's being dereferenced is actually
1140   // the offset of the field rather than exactly 0.
1141   // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1142   // This code interacts heavily with this hack; otherwise the value
1143   // would not be null at all for most fields, so we'd be unable to track it.
1144   if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
1145     if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
1146       if (const Expr *DerefEx = bugreporter::getDerefExpr(Op->getSubExpr()))
1147         return DerefEx;
1148   return Ex;
1149 
1150 }
1151 
1152 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
1153                                         const Stmt *S,
1154                                         BugReport &report, bool IsArg,
1155                                         bool EnableNullFPSuppression) {
1156   if (!S || !N)
1157     return false;
1158 
1159   if (const auto *Ex = dyn_cast<Expr>(S))
1160     S = peelOffOuterExpr(Ex, N);
1161 
1162   const Expr *Inner = nullptr;
1163   if (const auto *Ex = dyn_cast<Expr>(S)) {
1164     Ex = peelOfOuterAddrOf(Ex);
1165     Ex = Ex->IgnoreParenCasts();
1166 
1167     if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex)
1168           || CallEvent::isCallStmt(Ex)))
1169       Inner = Ex;
1170   }
1171 
1172   if (IsArg && !Inner) {
1173     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
1174   } else {
1175     N = findNodeForStatement(N, S, Inner);
1176     if (!N)
1177       return false;
1178   }
1179 
1180   ProgramStateRef state = N->getState();
1181 
1182   // The message send could be nil due to the receiver being nil.
1183   // At this point in the path, the receiver should be live since we are at the
1184   // message send expr. If it is nil, start tracking it.
1185   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
1186     trackNullOrUndefValue(N, Receiver, report, /* IsArg=*/ false,
1187         EnableNullFPSuppression);
1188 
1189   // See if the expression we're interested refers to a variable.
1190   // If so, we can track both its contents and constraints on its value.
1191   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1192     const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
1193     ProgramStateRef LVState = LVNode->getState();
1194     SVal LVal = LVNode->getSVal(Inner);
1195 
1196     const MemRegion *RR = getLocationRegionIfReference(Inner, N);
1197     bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1198 
1199     // If this is a C++ reference to a null pointer, we are tracking the
1200     // pointer. In addition, we should find the store at which the reference
1201     // got initialized.
1202     if (RR && !LVIsNull) {
1203       if (auto KV = LVal.getAs<KnownSVal>())
1204         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1205               *KV, RR, EnableNullFPSuppression));
1206     }
1207 
1208     // In case of C++ references, we want to differentiate between a null
1209     // reference and reference to null pointer.
1210     // If the LVal is null, check if we are dealing with null reference.
1211     // For those, we want to track the location of the reference.
1212     const MemRegion *R = (RR && LVIsNull) ? RR :
1213         LVNode->getSVal(Inner).getAsRegion();
1214 
1215     if (R) {
1216       // Mark both the variable region and its contents as interesting.
1217       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1218 
1219       MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1220           N, R, EnableNullFPSuppression, report, V);
1221 
1222       report.markInteresting(R);
1223       report.markInteresting(V);
1224       report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1225 
1226       // If the contents are symbolic, find out when they became null.
1227       if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1228         report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1229               V.castAs<DefinedSVal>(), false));
1230 
1231       // Add visitor, which will suppress inline defensive checks.
1232       if (auto DV = V.getAs<DefinedSVal>()) {
1233         if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1234             EnableNullFPSuppression) {
1235           report.addVisitor(
1236               llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1237                 LVNode));
1238         }
1239       }
1240 
1241       if (auto KV = V.getAs<KnownSVal>())
1242         report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1243               *KV, R, EnableNullFPSuppression));
1244       return true;
1245     }
1246   }
1247 
1248   // If the expression is not an "lvalue expression", we can still
1249   // track the constraints on its contents.
1250   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1251 
1252   // If the value came from an inlined function call, we should at least make
1253   // sure that function isn't pruned in our output.
1254   if (const auto *E = dyn_cast<Expr>(S))
1255     S = E->IgnoreParenCasts();
1256 
1257   ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1258 
1259   // Uncomment this to find cases where we aren't properly getting the
1260   // base value that was dereferenced.
1261   // assert(!V.isUnknownOrUndef());
1262   // Is it a symbolic value?
1263   if (auto L = V.getAs<loc::MemRegionVal>()) {
1264     report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1265 
1266     // At this point we are dealing with the region's LValue.
1267     // However, if the rvalue is a symbolic region, we should track it as well.
1268     // Try to use the correct type when looking up the value.
1269     SVal RVal;
1270     if (const auto *E = dyn_cast<Expr>(S))
1271       RVal = state->getRawSVal(L.getValue(), E->getType());
1272     else
1273       RVal = state->getSVal(L->getRegion());
1274 
1275     if (auto KV = RVal.getAs<KnownSVal>())
1276       report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1277             *KV, L->getRegion(), EnableNullFPSuppression));
1278 
1279     const MemRegion *RegionRVal = RVal.getAsRegion();
1280     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1281       report.markInteresting(RegionRVal);
1282       report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1283             loc::MemRegionVal(RegionRVal), false));
1284     }
1285   }
1286   return true;
1287 }
1288 
1289 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1290                                                  const ExplodedNode *N) {
1291   const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1292   if (!ME)
1293     return nullptr;
1294   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1295     ProgramStateRef state = N->getState();
1296     SVal V = N->getSVal(Receiver);
1297     if (state->isNull(V).isConstrainedTrue())
1298       return Receiver;
1299   }
1300   return nullptr;
1301 }
1302 
1303 std::shared_ptr<PathDiagnosticPiece>
1304 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1305                                 const ExplodedNode *PrevN,
1306                                 BugReporterContext &BRC, BugReport &BR) {
1307   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1308   if (!P)
1309     return nullptr;
1310 
1311   const Stmt *S = P->getStmt();
1312   const Expr *Receiver = getNilReceiver(S, N);
1313   if (!Receiver)
1314     return nullptr;
1315 
1316   llvm::SmallString<256> Buf;
1317   llvm::raw_svector_ostream OS(Buf);
1318 
1319   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1320     OS << "'";
1321     ME->getSelector().print(OS);
1322     OS << "' not called";
1323   }
1324   else {
1325     OS << "No method is called";
1326   }
1327   OS << " because the receiver is nil";
1328 
1329   // The receiver was nil, and hence the method was skipped.
1330   // Register a BugReporterVisitor to issue a message telling us how
1331   // the receiver was null.
1332   bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1333                                      /*EnableNullFPSuppression*/ false);
1334   // Issue a message saying that the method was skipped.
1335   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1336                                      N->getLocationContext());
1337   return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1338 }
1339 
1340 // Registers every VarDecl inside a Stmt with a last store visitor.
1341 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1342                                                 const Stmt *S,
1343                                                 bool EnableNullFPSuppression) {
1344   const ExplodedNode *N = BR.getErrorNode();
1345   std::deque<const Stmt *> WorkList;
1346   WorkList.push_back(S);
1347 
1348   while (!WorkList.empty()) {
1349     const Stmt *Head = WorkList.front();
1350     WorkList.pop_front();
1351 
1352     ProgramStateManager &StateMgr = N->getState()->getStateManager();
1353 
1354     if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1355       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1356         const VarRegion *R =
1357         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1358 
1359         // What did we load?
1360         SVal V = N->getSVal(S);
1361 
1362         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1363           // Register a new visitor with the BugReport.
1364           BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1365               V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1366         }
1367       }
1368     }
1369 
1370     for (const Stmt *SubStmt : Head->children())
1371       WorkList.push_back(SubStmt);
1372   }
1373 }
1374 
1375 //===----------------------------------------------------------------------===//
1376 // Visitor that tries to report interesting diagnostics from conditions.
1377 //===----------------------------------------------------------------------===//
1378 
1379 /// Return the tag associated with this visitor.  This tag will be used
1380 /// to make all PathDiagnosticPieces created by this visitor.
1381 const char *ConditionBRVisitor::getTag() {
1382   return "ConditionBRVisitor";
1383 }
1384 
1385 std::shared_ptr<PathDiagnosticPiece>
1386 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1387                               BugReporterContext &BRC, BugReport &BR) {
1388   auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1389   if (piece) {
1390     piece->setTag(getTag());
1391     if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1392       ev->setPrunable(true, /* override */ false);
1393   }
1394   return piece;
1395 }
1396 
1397 std::shared_ptr<PathDiagnosticPiece>
1398 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1399                                   const ExplodedNode *Prev,
1400                                   BugReporterContext &BRC, BugReport &BR) {
1401 
1402   ProgramPoint progPoint = N->getLocation();
1403   ProgramStateRef CurrentState = N->getState();
1404   ProgramStateRef PrevState = Prev->getState();
1405 
1406   // Compare the GDMs of the state, because that is where constraints
1407   // are managed.  Note that ensure that we only look at nodes that
1408   // were generated by the analyzer engine proper, not checkers.
1409   if (CurrentState->getGDM().getRoot() ==
1410       PrevState->getGDM().getRoot())
1411     return nullptr;
1412 
1413   // If an assumption was made on a branch, it should be caught
1414   // here by looking at the state transition.
1415   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1416     const CFGBlock *srcBlk = BE->getSrc();
1417     if (const Stmt *term = srcBlk->getTerminator())
1418       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1419     return nullptr;
1420   }
1421 
1422   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1423     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1424     // violation.
1425     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1426       cast<GRBugReporter>(BRC.getBugReporter()).
1427         getEngine().geteagerlyAssumeBinOpBifurcationTags();
1428 
1429     const ProgramPointTag *tag = PS->getTag();
1430     if (tag == tags.first)
1431       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1432                            BRC, BR, N);
1433     if (tag == tags.second)
1434       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1435                            BRC, BR, N);
1436 
1437     return nullptr;
1438   }
1439 
1440   return nullptr;
1441 }
1442 
1443 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1444     const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1445     const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1446   const Expr *Cond = nullptr;
1447 
1448   // In the code below, Term is a CFG terminator and Cond is a branch condition
1449   // expression upon which the decision is made on this terminator.
1450   //
1451   // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1452   // and "x == 0" is the respective condition.
1453   //
1454   // Another example: in "if (x && y)", we've got two terminators and two
1455   // conditions due to short-circuit nature of operator "&&":
1456   // 1. The "if (x && y)" statement is a terminator,
1457   //    and "y" is the respective condition.
1458   // 2. Also "x && ..." is another terminator,
1459   //    and "x" is its condition.
1460 
1461   switch (Term->getStmtClass()) {
1462   // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1463   // more tricky because there are more than two branches to account for.
1464   default:
1465     return nullptr;
1466   case Stmt::IfStmtClass:
1467     Cond = cast<IfStmt>(Term)->getCond();
1468     break;
1469   case Stmt::ConditionalOperatorClass:
1470     Cond = cast<ConditionalOperator>(Term)->getCond();
1471     break;
1472   case Stmt::BinaryOperatorClass:
1473     // When we encounter a logical operator (&& or ||) as a CFG terminator,
1474     // then the condition is actually its LHS; otherwise, we'd encounter
1475     // the parent, such as if-statement, as a terminator.
1476     const auto *BO = cast<BinaryOperator>(Term);
1477     assert(BO->isLogicalOp() &&
1478            "CFG terminator is not a short-circuit operator!");
1479     Cond = BO->getLHS();
1480     break;
1481   }
1482 
1483   // However, when we encounter a logical operator as a branch condition,
1484   // then the condition is actually its RHS, because LHS would be
1485   // the condition for the logical operator terminator.
1486   while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1487     if (!InnerBO->isLogicalOp())
1488       break;
1489     Cond = InnerBO->getRHS()->IgnoreParens();
1490   }
1491 
1492   assert(Cond);
1493   assert(srcBlk->succ_size() == 2);
1494   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1495   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1496 }
1497 
1498 std::shared_ptr<PathDiagnosticPiece>
1499 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1500                                   BugReporterContext &BRC, BugReport &R,
1501                                   const ExplodedNode *N) {
1502   // These will be modified in code below, but we need to preserve the original
1503   //  values in case we want to throw the generic message.
1504   const Expr *CondTmp = Cond;
1505   bool tookTrueTmp = tookTrue;
1506 
1507   while (true) {
1508     CondTmp = CondTmp->IgnoreParenCasts();
1509     switch (CondTmp->getStmtClass()) {
1510       default:
1511         break;
1512       case Stmt::BinaryOperatorClass:
1513         if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1514                                    tookTrueTmp, BRC, R, N))
1515           return P;
1516         break;
1517       case Stmt::DeclRefExprClass:
1518         if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1519                                    tookTrueTmp, BRC, R, N))
1520           return P;
1521         break;
1522       case Stmt::UnaryOperatorClass: {
1523         const UnaryOperator *UO = cast<UnaryOperator>(CondTmp);
1524         if (UO->getOpcode() == UO_LNot) {
1525           tookTrueTmp = !tookTrueTmp;
1526           CondTmp = UO->getSubExpr();
1527           continue;
1528         }
1529         break;
1530       }
1531     }
1532     break;
1533   }
1534 
1535   // Condition too complex to explain? Just say something so that the user
1536   // knew we've made some path decision at this point.
1537   const LocationContext *LCtx = N->getLocationContext();
1538   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1539   if (!Loc.isValid() || !Loc.asLocation().isValid())
1540     return nullptr;
1541 
1542   return std::make_shared<PathDiagnosticEventPiece>(
1543       Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1544 }
1545 
1546 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1547                                       const Expr *ParentEx,
1548                                       raw_ostream &Out,
1549                                       BugReporterContext &BRC,
1550                                       BugReport &report,
1551                                       const ExplodedNode *N,
1552                                       Optional<bool> &prunable) {
1553   const Expr *OriginalExpr = Ex;
1554   Ex = Ex->IgnoreParenCasts();
1555 
1556   // Use heuristics to determine if Ex is a macro expending to a literal and
1557   // if so, use the macro's name.
1558   SourceLocation LocStart = Ex->getLocStart();
1559   SourceLocation LocEnd = Ex->getLocEnd();
1560   if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1561       (isa<GNUNullExpr>(Ex) ||
1562        isa<ObjCBoolLiteralExpr>(Ex) ||
1563        isa<CXXBoolLiteralExpr>(Ex) ||
1564        isa<IntegerLiteral>(Ex) ||
1565        isa<FloatingLiteral>(Ex))) {
1566 
1567     StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1568       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1569     StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1570       BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1571     bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1572 
1573     bool partOfParentMacro = false;
1574     if (ParentEx->getLocStart().isMacroID()) {
1575       StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1576         ParentEx->getLocStart(), BRC.getSourceManager(),
1577         BRC.getASTContext().getLangOpts());
1578       partOfParentMacro = PName.equals(StartName);
1579     }
1580 
1581     if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1582       // Get the location of the macro name as written by the caller.
1583       SourceLocation Loc = LocStart;
1584       while (LocStart.isMacroID()) {
1585         Loc = LocStart;
1586         LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1587       }
1588       StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1589         Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1590 
1591       // Return the macro name.
1592       Out << MacroName;
1593       return false;
1594     }
1595   }
1596 
1597   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1598     const bool quotes = isa<VarDecl>(DR->getDecl());
1599     if (quotes) {
1600       Out << '\'';
1601       const LocationContext *LCtx = N->getLocationContext();
1602       const ProgramState *state = N->getState().get();
1603       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1604                                                 LCtx).getAsRegion()) {
1605         if (report.isInteresting(R))
1606           prunable = false;
1607         else {
1608           const ProgramState *state = N->getState().get();
1609           SVal V = state->getSVal(R);
1610           if (report.isInteresting(V))
1611             prunable = false;
1612         }
1613       }
1614     }
1615     Out << DR->getDecl()->getDeclName().getAsString();
1616     if (quotes)
1617       Out << '\'';
1618     return quotes;
1619   }
1620 
1621   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1622     QualType OriginalTy = OriginalExpr->getType();
1623     if (OriginalTy->isPointerType()) {
1624       if (IL->getValue() == 0) {
1625         Out << "null";
1626         return false;
1627       }
1628     }
1629     else if (OriginalTy->isObjCObjectPointerType()) {
1630       if (IL->getValue() == 0) {
1631         Out << "nil";
1632         return false;
1633       }
1634     }
1635 
1636     Out << IL->getValue();
1637     return false;
1638   }
1639 
1640   return false;
1641 }
1642 
1643 std::shared_ptr<PathDiagnosticPiece>
1644 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
1645                                   const bool tookTrue, BugReporterContext &BRC,
1646                                   BugReport &R, const ExplodedNode *N) {
1647 
1648   bool shouldInvert = false;
1649   Optional<bool> shouldPrune;
1650 
1651   SmallString<128> LhsString, RhsString;
1652   {
1653     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1654     const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
1655                                        BRC, R, N, shouldPrune);
1656     const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
1657                                        BRC, R, N, shouldPrune);
1658 
1659     shouldInvert = !isVarLHS && isVarRHS;
1660   }
1661 
1662   BinaryOperator::Opcode Op = BExpr->getOpcode();
1663 
1664   if (BinaryOperator::isAssignmentOp(Op)) {
1665     // For assignment operators, all that we care about is that the LHS
1666     // evaluates to "true" or "false".
1667     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1668                                   BRC, R, N);
1669   }
1670 
1671   // For non-assignment operations, we require that we can understand
1672   // both the LHS and RHS.
1673   if (LhsString.empty() || RhsString.empty() ||
1674       !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
1675     return nullptr;
1676 
1677   // Should we invert the strings if the LHS is not a variable name?
1678   SmallString<256> buf;
1679   llvm::raw_svector_ostream Out(buf);
1680   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1681 
1682   // Do we need to invert the opcode?
1683   if (shouldInvert)
1684     switch (Op) {
1685       default: break;
1686       case BO_LT: Op = BO_GT; break;
1687       case BO_GT: Op = BO_LT; break;
1688       case BO_LE: Op = BO_GE; break;
1689       case BO_GE: Op = BO_LE; break;
1690     }
1691 
1692   if (!tookTrue)
1693     switch (Op) {
1694       case BO_EQ: Op = BO_NE; break;
1695       case BO_NE: Op = BO_EQ; break;
1696       case BO_LT: Op = BO_GE; break;
1697       case BO_GT: Op = BO_LE; break;
1698       case BO_LE: Op = BO_GT; break;
1699       case BO_GE: Op = BO_LT; break;
1700       default:
1701         return nullptr;
1702     }
1703 
1704   switch (Op) {
1705     case BO_EQ:
1706       Out << "equal to ";
1707       break;
1708     case BO_NE:
1709       Out << "not equal to ";
1710       break;
1711     default:
1712       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1713       break;
1714   }
1715 
1716   Out << (shouldInvert ? LhsString : RhsString);
1717   const LocationContext *LCtx = N->getLocationContext();
1718   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1719   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1720   if (shouldPrune.hasValue())
1721     event->setPrunable(shouldPrune.getValue());
1722   return event;
1723 }
1724 
1725 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
1726     StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
1727     BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
1728   // FIXME: If there's already a constraint tracker for this variable,
1729   // we shouldn't emit anything here (c.f. the double note in
1730   // test/Analysis/inlining/path-notes.c)
1731   SmallString<256> buf;
1732   llvm::raw_svector_ostream Out(buf);
1733   Out << "Assuming " << LhsString << " is ";
1734 
1735   QualType Ty = CondVarExpr->getType();
1736 
1737   if (Ty->isPointerType())
1738     Out << (tookTrue ? "not null" : "null");
1739   else if (Ty->isObjCObjectPointerType())
1740     Out << (tookTrue ? "not nil" : "nil");
1741   else if (Ty->isBooleanType())
1742     Out << (tookTrue ? "true" : "false");
1743   else if (Ty->isIntegralOrEnumerationType())
1744     Out << (tookTrue ? "non-zero" : "zero");
1745   else
1746     return nullptr;
1747 
1748   const LocationContext *LCtx = N->getLocationContext();
1749   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1750   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1751 
1752   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1753     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1754       const ProgramState *state = N->getState().get();
1755       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1756         if (report.isInteresting(R))
1757           event->setPrunable(false);
1758       }
1759     }
1760   }
1761 
1762   return event;
1763 }
1764 
1765 std::shared_ptr<PathDiagnosticPiece>
1766 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
1767                                   const bool tookTrue, BugReporterContext &BRC,
1768                                   BugReport &report, const ExplodedNode *N) {
1769 
1770   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1771   if (!VD)
1772     return nullptr;
1773 
1774   SmallString<256> Buf;
1775   llvm::raw_svector_ostream Out(Buf);
1776 
1777   Out << "Assuming '" << VD->getDeclName() << "' is ";
1778 
1779   QualType VDTy = VD->getType();
1780 
1781   if (VDTy->isPointerType())
1782     Out << (tookTrue ? "non-null" : "null");
1783   else if (VDTy->isObjCObjectPointerType())
1784     Out << (tookTrue ? "non-nil" : "nil");
1785   else if (VDTy->isScalarType())
1786     Out << (tookTrue ? "not equal to 0" : "0");
1787   else
1788     return nullptr;
1789 
1790   const LocationContext *LCtx = N->getLocationContext();
1791   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1792   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1793 
1794   const ProgramState *state = N->getState().get();
1795   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1796     if (report.isInteresting(R))
1797       event->setPrunable(false);
1798     else {
1799       SVal V = state->getSVal(R);
1800       if (report.isInteresting(V))
1801         event->setPrunable(false);
1802     }
1803   }
1804   return std::move(event);
1805 }
1806 
1807 const char *const ConditionBRVisitor::GenericTrueMessage =
1808     "Assuming the condition is true";
1809 const char *const ConditionBRVisitor::GenericFalseMessage =
1810     "Assuming the condition is false";
1811 
1812 bool ConditionBRVisitor::isPieceMessageGeneric(
1813     const PathDiagnosticPiece *Piece) {
1814   return Piece->getString() == GenericTrueMessage ||
1815          Piece->getString() == GenericFalseMessage;
1816 }
1817 
1818 std::unique_ptr<PathDiagnosticPiece>
1819 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1820                                                     const ExplodedNode *N,
1821                                                     BugReport &BR) {
1822   // Here we suppress false positives coming from system headers. This list is
1823   // based on known issues.
1824   ExprEngine &Eng = BRC.getBugReporter().getEngine();
1825   AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1826   const Decl *D = N->getLocationContext()->getDecl();
1827 
1828   if (AnalysisDeclContext::isInStdNamespace(D)) {
1829     // Skip reports within the 'std' namespace. Although these can sometimes be
1830     // the user's fault, we currently don't report them very well, and
1831     // Note that this will not help for any other data structure libraries, like
1832     // TR1, Boost, or llvm/ADT.
1833     if (Options.shouldSuppressFromCXXStandardLibrary()) {
1834       BR.markInvalid(getTag(), nullptr);
1835       return nullptr;
1836 
1837     } else {
1838       // If the complete 'std' suppression is not enabled, suppress reports
1839       // from the 'std' namespace that are known to produce false positives.
1840 
1841       // The analyzer issues a false use-after-free when std::list::pop_front
1842       // or std::list::pop_back are called multiple times because we cannot
1843       // reason about the internal invariants of the data structure.
1844       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1845         const CXXRecordDecl *CD = MD->getParent();
1846         if (CD->getName() == "list") {
1847           BR.markInvalid(getTag(), nullptr);
1848           return nullptr;
1849         }
1850       }
1851 
1852       // The analyzer issues a false positive when the constructor of
1853       // std::__independent_bits_engine from algorithms is used.
1854       if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) {
1855         const CXXRecordDecl *CD = MD->getParent();
1856         if (CD->getName() == "__independent_bits_engine") {
1857           BR.markInvalid(getTag(), nullptr);
1858           return nullptr;
1859         }
1860       }
1861 
1862       for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
1863            LCtx = LCtx->getParent()) {
1864         const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1865         if (!MD)
1866           continue;
1867 
1868         const CXXRecordDecl *CD = MD->getParent();
1869         // The analyzer issues a false positive on
1870         //   std::basic_string<uint8_t> v; v.push_back(1);
1871         // and
1872         //   std::u16string s; s += u'a';
1873         // because we cannot reason about the internal invariants of the
1874         // data structure.
1875         if (CD->getName() == "basic_string") {
1876           BR.markInvalid(getTag(), nullptr);
1877           return nullptr;
1878         }
1879 
1880         // The analyzer issues a false positive on
1881         //    std::shared_ptr<int> p(new int(1)); p = nullptr;
1882         // because it does not reason properly about temporary destructors.
1883         if (CD->getName() == "shared_ptr") {
1884           BR.markInvalid(getTag(), nullptr);
1885           return nullptr;
1886         }
1887       }
1888     }
1889   }
1890 
1891   // Skip reports within the sys/queue.h macros as we do not have the ability to
1892   // reason about data structure shapes.
1893   SourceManager &SM = BRC.getSourceManager();
1894   FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1895   while (Loc.isMacroID()) {
1896     Loc = Loc.getSpellingLoc();
1897     if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1898       BR.markInvalid(getTag(), nullptr);
1899       return nullptr;
1900     }
1901   }
1902 
1903   return nullptr;
1904 }
1905 
1906 std::shared_ptr<PathDiagnosticPiece>
1907 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1908                                  const ExplodedNode *PrevN,
1909                                  BugReporterContext &BRC, BugReport &BR) {
1910 
1911   ProgramStateRef State = N->getState();
1912   ProgramPoint ProgLoc = N->getLocation();
1913 
1914   // We are only interested in visiting CallEnter nodes.
1915   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1916   if (!CEnter)
1917     return nullptr;
1918 
1919   // Check if one of the arguments is the region the visitor is tracking.
1920   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1921   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1922   unsigned Idx = 0;
1923   ArrayRef<ParmVarDecl*> parms = Call->parameters();
1924 
1925   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1926                               I != E; ++I, ++Idx) {
1927     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1928 
1929     // Are we tracking the argument or its subregion?
1930     if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
1931       continue;
1932 
1933     // Check the function parameter type.
1934     const ParmVarDecl *ParamDecl = *I;
1935     assert(ParamDecl && "Formal parameter has no decl?");
1936     QualType T = ParamDecl->getType();
1937 
1938     if (!(T->isAnyPointerType() || T->isReferenceType())) {
1939       // Function can only change the value passed in by address.
1940       continue;
1941     }
1942 
1943     // If it is a const pointer value, the function does not intend to
1944     // change the value.
1945     if (T->getPointeeType().isConstQualified())
1946       continue;
1947 
1948     // Mark the call site (LocationContext) as interesting if the value of the
1949     // argument is undefined or '0'/'NULL'.
1950     SVal BoundVal = State->getSVal(R);
1951     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1952       BR.markInteresting(CEnter->getCalleeContext());
1953       return nullptr;
1954     }
1955   }
1956   return nullptr;
1957 }
1958 
1959 std::shared_ptr<PathDiagnosticPiece>
1960 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
1961                                       const ExplodedNode *Pred,
1962                                       BugReporterContext &BRC, BugReport &BR) {
1963   if (Satisfied)
1964     return nullptr;
1965 
1966   auto Edge = Succ->getLocation().getAs<BlockEdge>();
1967   if (!Edge.hasValue())
1968     return nullptr;
1969 
1970   auto Tag = Edge->getTag();
1971   if (!Tag)
1972     return nullptr;
1973 
1974   if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
1975     return nullptr;
1976 
1977   Satisfied = true;
1978 
1979   const auto *Met =
1980       dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
1981   assert(Met && "Not a C++ method.");
1982   assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
1983          "Not a copy/move assignment operator.");
1984 
1985   const auto *LCtx = Edge->getLocationContext();
1986 
1987   const auto &State = Succ->getState();
1988   auto &SVB = State->getStateManager().getSValBuilder();
1989 
1990   const auto Param =
1991       State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
1992   const auto This =
1993       State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
1994 
1995   auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
1996 
1997   if (!L.isValid() || !L.asLocation().isValid())
1998     return nullptr;
1999 
2000   SmallString<256> Buf;
2001   llvm::raw_svector_ostream Out(Buf);
2002 
2003   Out << "Assuming " << Met->getParamDecl(0)->getName() <<
2004     ((Param == This) ? " == " : " != ") << "*this";
2005 
2006   auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
2007   Piece->addRange(Met->getSourceRange());
2008 
2009   return std::move(Piece);
2010 }
2011