1 //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines a set of BugReporter "visitors" which can be used to
10 //  enhance the diagnostics reported for a bug.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclBase.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/Type.h"
24 #include "clang/ASTMatchers/ASTMatchFinder.h"
25 #include "clang/Analysis/Analyses/Dominators.h"
26 #include "clang/Analysis/AnalysisDeclContext.h"
27 #include "clang/Analysis/CFG.h"
28 #include "clang/Analysis/CFGStmtMap.h"
29 #include "clang/Analysis/PathDiagnostic.h"
30 #include "clang/Analysis/ProgramPoint.h"
31 #include "clang/Basic/IdentifierTable.h"
32 #include "clang/Basic/LLVM.h"
33 #include "clang/Basic/SourceLocation.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Lex/Lexer.h"
36 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
37 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
38 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
39 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
40 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/None.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/STLExtras.h"
53 #include "llvm/ADT/SmallPtrSet.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <cassert>
62 #include <deque>
63 #include <memory>
64 #include <string>
65 #include <utility>
66 
67 using namespace clang;
68 using namespace ento;
69 
70 //===----------------------------------------------------------------------===//
71 // Utility functions.
72 //===----------------------------------------------------------------------===//
73 
74 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
75   if (B->isAdditiveOp() && B->getType()->isPointerType()) {
76     if (B->getLHS()->getType()->isPointerType()) {
77       return B->getLHS();
78     } else if (B->getRHS()->getType()->isPointerType()) {
79       return B->getRHS();
80     }
81   }
82   return nullptr;
83 }
84 
85 /// Given that expression S represents a pointer that would be dereferenced,
86 /// try to find a sub-expression from which the pointer came from.
87 /// This is used for tracking down origins of a null or undefined value:
88 /// "this is null because that is null because that is null" etc.
89 /// We wipe away field and element offsets because they merely add offsets.
90 /// We also wipe away all casts except lvalue-to-rvalue casts, because the
91 /// latter represent an actual pointer dereference; however, we remove
92 /// the final lvalue-to-rvalue cast before returning from this function
93 /// because it demonstrates more clearly from where the pointer rvalue was
94 /// loaded. Examples:
95 ///   x->y.z      ==>  x (lvalue)
96 ///   foo()->y.z  ==>  foo() (rvalue)
97 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
98   const auto *E = dyn_cast<Expr>(S);
99   if (!E)
100     return nullptr;
101 
102   while (true) {
103     if (const auto *CE = dyn_cast<CastExpr>(E)) {
104       if (CE->getCastKind() == CK_LValueToRValue) {
105         // This cast represents the load we're looking for.
106         break;
107       }
108       E = CE->getSubExpr();
109     } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
110       // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
111       if (const Expr *Inner = peelOffPointerArithmetic(B)) {
112         E = Inner;
113       } else {
114         // Probably more arithmetic can be pattern-matched here,
115         // but for now give up.
116         break;
117       }
118     } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
119       if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
120           (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
121         // Operators '*' and '&' don't actually mean anything.
122         // We look at casts instead.
123         E = U->getSubExpr();
124       } else {
125         // Probably more arithmetic can be pattern-matched here,
126         // but for now give up.
127         break;
128       }
129     }
130     // Pattern match for a few useful cases: a[0], p->f, *p etc.
131     else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
132       E = ME->getBase();
133     } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
134       E = IvarRef->getBase();
135     } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
136       E = AE->getBase();
137     } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
138       E = PE->getSubExpr();
139     } else if (const auto *FE = dyn_cast<FullExpr>(E)) {
140       E = FE->getSubExpr();
141     } else {
142       // Other arbitrary stuff.
143       break;
144     }
145   }
146 
147   // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
148   // deeper into the sub-expression. This way we return the lvalue from which
149   // our pointer rvalue was loaded.
150   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
151     if (CE->getCastKind() == CK_LValueToRValue)
152       E = CE->getSubExpr();
153 
154   return E;
155 }
156 
157 /// Comparing internal representations of symbolic values (via
158 /// SVal::operator==()) is a valid way to check if the value was updated,
159 /// unless it's a LazyCompoundVal that may have a different internal
160 /// representation every time it is loaded from the state. In this function we
161 /// do an approximate comparison for lazy compound values, checking that they
162 /// are the immediate snapshots of the tracked region's bindings within the
163 /// node's respective states but not really checking that these snapshots
164 /// actually contain the same set of bindings.
165 static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
166                              const ExplodedNode *RightNode, SVal RightVal) {
167   if (LeftVal == RightVal)
168     return true;
169 
170   const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
171   if (!LLCV)
172     return false;
173 
174   const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
175   if (!RLCV)
176     return false;
177 
178   return LLCV->getRegion() == RLCV->getRegion() &&
179     LLCV->getStore() == LeftNode->getState()->getStore() &&
180     RLCV->getStore() == RightNode->getState()->getStore();
181 }
182 
183 static Optional<SVal> getSValForVar(const Expr *CondVarExpr,
184                                     const ExplodedNode *N) {
185   ProgramStateRef State = N->getState();
186   const LocationContext *LCtx = N->getLocationContext();
187 
188   assert(CondVarExpr);
189   CondVarExpr = CondVarExpr->IgnoreImpCasts();
190 
191   // The declaration of the value may rely on a pointer so take its l-value.
192   // FIXME: As seen in VisitCommonDeclRefExpr, sometimes DeclRefExpr may
193   // evaluate to a FieldRegion when it refers to a declaration of a lambda
194   // capture variable. We most likely need to duplicate that logic here.
195   if (const auto *DRE = dyn_cast<DeclRefExpr>(CondVarExpr))
196     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
197       return State->getSVal(State->getLValue(VD, LCtx));
198 
199   if (const auto *ME = dyn_cast<MemberExpr>(CondVarExpr))
200     if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
201       if (auto FieldL = State->getSVal(ME, LCtx).getAs<Loc>())
202         return State->getRawSVal(*FieldL, FD->getType());
203 
204   return None;
205 }
206 
207 static Optional<const llvm::APSInt *>
208 getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) {
209 
210   if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
211     if (auto CI = V->getAs<nonloc::ConcreteInt>())
212       return &CI->getValue();
213   return None;
214 }
215 
216 static bool isVarAnInterestingCondition(const Expr *CondVarExpr,
217                                         const ExplodedNode *N,
218                                         const PathSensitiveBugReport *B) {
219   // Even if this condition is marked as interesting, it isn't *that*
220   // interesting if it didn't happen in a nested stackframe, the user could just
221   // follow the arrows.
222   if (!B->getErrorNode()->getStackFrame()->isParentOf(N->getStackFrame()))
223     return false;
224 
225   if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
226     if (Optional<bugreporter::TrackingKind> K = B->getInterestingnessKind(*V))
227       return *K == bugreporter::TrackingKind::Condition;
228 
229   return false;
230 }
231 
232 static bool isInterestingExpr(const Expr *E, const ExplodedNode *N,
233                               const PathSensitiveBugReport *B) {
234   if (Optional<SVal> V = getSValForVar(E, N))
235     return B->getInterestingnessKind(*V).hasValue();
236   return false;
237 }
238 
239 /// \return name of the macro inside the location \p Loc.
240 static StringRef getMacroName(SourceLocation Loc,
241     BugReporterContext &BRC) {
242   return Lexer::getImmediateMacroName(
243       Loc,
244       BRC.getSourceManager(),
245       BRC.getASTContext().getLangOpts());
246 }
247 
248 /// \return Whether given spelling location corresponds to an expansion
249 /// of a function-like macro.
250 static bool isFunctionMacroExpansion(SourceLocation Loc,
251                                 const SourceManager &SM) {
252   if (!Loc.isMacroID())
253     return false;
254   while (SM.isMacroArgExpansion(Loc))
255     Loc = SM.getImmediateExpansionRange(Loc).getBegin();
256   std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
257   SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
258   const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
259   return EInfo.isFunctionMacroExpansion();
260 }
261 
262 /// \return Whether \c RegionOfInterest was modified at \p N,
263 /// where \p ValueAfter is \c RegionOfInterest's value at the end of the
264 /// stack frame.
265 static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest,
266                                           const ExplodedNode *N,
267                                           SVal ValueAfter) {
268   ProgramStateRef State = N->getState();
269   ProgramStateManager &Mgr = N->getState()->getStateManager();
270 
271   if (!N->getLocationAs<PostStore>() && !N->getLocationAs<PostInitializer>() &&
272       !N->getLocationAs<PostStmt>())
273     return false;
274 
275   // Writing into region of interest.
276   if (auto PS = N->getLocationAs<PostStmt>())
277     if (auto *BO = PS->getStmtAs<BinaryOperator>())
278       if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
279                                       N->getSVal(BO->getLHS()).getAsRegion()))
280         return true;
281 
282   // SVal after the state is possibly different.
283   SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
284   if (!Mgr.getSValBuilder()
285            .areEqual(State, ValueAtN, ValueAfter)
286            .isConstrainedTrue() &&
287       (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
288     return true;
289 
290   return false;
291 }
292 
293 //===----------------------------------------------------------------------===//
294 // Implementation of BugReporterVisitor.
295 //===----------------------------------------------------------------------===//
296 
297 PathDiagnosticPieceRef BugReporterVisitor::getEndPath(BugReporterContext &,
298                                                       const ExplodedNode *,
299                                                       PathSensitiveBugReport &) {
300   return nullptr;
301 }
302 
303 void BugReporterVisitor::finalizeVisitor(BugReporterContext &,
304                                          const ExplodedNode *,
305                                          PathSensitiveBugReport &) {}
306 
307 PathDiagnosticPieceRef
308 BugReporterVisitor::getDefaultEndPath(const BugReporterContext &BRC,
309                                       const ExplodedNode *EndPathNode,
310                                       const PathSensitiveBugReport &BR) {
311   PathDiagnosticLocation L = BR.getLocation();
312   const auto &Ranges = BR.getRanges();
313 
314   // Only add the statement itself as a range if we didn't specify any
315   // special ranges for this report.
316   auto P = std::make_shared<PathDiagnosticEventPiece>(
317       L, BR.getDescription(), Ranges.begin() == Ranges.end());
318   for (SourceRange Range : Ranges)
319     P->addRange(Range);
320 
321   return P;
322 }
323 
324 //===----------------------------------------------------------------------===//
325 // Implementation of NoStoreFuncVisitor.
326 //===----------------------------------------------------------------------===//
327 
328 namespace {
329 
330 /// Put a diagnostic on return statement of all inlined functions
331 /// for which  the region of interest \p RegionOfInterest was passed into,
332 /// but not written inside, and it has caused an undefined read or a null
333 /// pointer dereference outside.
334 class NoStoreFuncVisitor final : public BugReporterVisitor {
335   const SubRegion *RegionOfInterest;
336   MemRegionManager &MmrMgr;
337   const SourceManager &SM;
338   const PrintingPolicy &PP;
339   bugreporter::TrackingKind TKind;
340 
341   /// Recursion limit for dereferencing fields when looking for the
342   /// region of interest.
343   /// The limit of two indicates that we will dereference fields only once.
344   static const unsigned DEREFERENCE_LIMIT = 2;
345 
346   /// Frames writing into \c RegionOfInterest.
347   /// This visitor generates a note only if a function does not write into
348   /// a region of interest. This information is not immediately available
349   /// by looking at the node associated with the exit from the function
350   /// (usually the return statement). To avoid recomputing the same information
351   /// many times (going up the path for each node and checking whether the
352   /// region was written into) we instead lazily compute the
353   /// stack frames along the path which write into the region of interest.
354   llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
355   llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
356 
357   using RegionVector = SmallVector<const MemRegion *, 5>;
358 
359 public:
360   NoStoreFuncVisitor(const SubRegion *R, bugreporter::TrackingKind TKind)
361       : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()),
362         SM(MmrMgr.getContext().getSourceManager()),
363         PP(MmrMgr.getContext().getPrintingPolicy()), TKind(TKind) {}
364 
365   void Profile(llvm::FoldingSetNodeID &ID) const override {
366     static int Tag = 0;
367     ID.AddPointer(&Tag);
368     ID.AddPointer(RegionOfInterest);
369   }
370 
371   void *getTag() const {
372     static int Tag = 0;
373     return static_cast<void *>(&Tag);
374   }
375 
376   PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
377                                    BugReporterContext &BR,
378                                    PathSensitiveBugReport &R) override;
379 
380 private:
381   /// Attempts to find the region of interest in a given record decl,
382   /// by either following the base classes or fields.
383   /// Dereferences fields up to a given recursion limit.
384   /// Note that \p Vec is passed by value, leading to quadratic copying cost,
385   /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
386   /// \return A chain fields leading to the region of interest or None.
387   const Optional<RegionVector>
388   findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
389                                const MemRegion *R, const RegionVector &Vec = {},
390                                int depth = 0);
391 
392   /// Check and lazily calculate whether the region of interest is
393   /// modified in the stack frame to which \p N belongs.
394   /// The calculation is cached in FramesModifyingRegion.
395   bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
396     const LocationContext *Ctx = N->getLocationContext();
397     const StackFrameContext *SCtx = Ctx->getStackFrame();
398     if (!FramesModifyingCalculated.count(SCtx))
399       findModifyingFrames(N);
400     return FramesModifyingRegion.count(SCtx);
401   }
402 
403   /// Write to \c FramesModifyingRegion all stack frames along
404   /// the path in the current stack frame which modify \c RegionOfInterest.
405   void findModifyingFrames(const ExplodedNode *N);
406 
407   /// Consume the information on the no-store stack frame in order to
408   /// either emit a note or suppress the report enirely.
409   /// \return Diagnostics piece for region not modified in the current function,
410   /// if it decides to emit one.
411   PathDiagnosticPieceRef
412   maybeEmitNote(PathSensitiveBugReport &R, const CallEvent &Call,
413                 const ExplodedNode *N, const RegionVector &FieldChain,
414                 const MemRegion *MatchedRegion, StringRef FirstElement,
415                 bool FirstIsReferenceType, unsigned IndirectionLevel);
416 
417   /// Pretty-print region \p MatchedRegion to \p os.
418   /// \return Whether printing succeeded.
419   bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
420                              const MemRegion *MatchedRegion,
421                              const RegionVector &FieldChain,
422                              int IndirectionLevel,
423                              llvm::raw_svector_ostream &os);
424 
425   /// Print first item in the chain, return new separator.
426   static StringRef prettyPrintFirstElement(StringRef FirstElement,
427                                            bool MoreItemsExpected,
428                                            int IndirectionLevel,
429                                            llvm::raw_svector_ostream &os);
430 };
431 
432 } // end of anonymous namespace
433 
434 /// \return Whether the method declaration \p Parent
435 /// syntactically has a binary operation writing into the ivar \p Ivar.
436 static bool potentiallyWritesIntoIvar(const Decl *Parent,
437                                       const ObjCIvarDecl *Ivar) {
438   using namespace ast_matchers;
439   const char *IvarBind = "Ivar";
440   if (!Parent || !Parent->hasBody())
441     return false;
442   StatementMatcher WriteIntoIvarM = binaryOperator(
443       hasOperatorName("="),
444       hasLHS(ignoringParenImpCasts(
445           objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
446   StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
447   auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
448   for (BoundNodes &Match : Matches) {
449     auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
450     if (IvarRef->isFreeIvar())
451       return true;
452 
453     const Expr *Base = IvarRef->getBase();
454     if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
455       Base = ICE->getSubExpr();
456 
457     if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
458       if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
459         if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
460           return true;
461 
462     return false;
463   }
464   return false;
465 }
466 
467 /// Get parameters associated with runtime definition in order
468 /// to get the correct parameter name.
469 static ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
470   // Use runtime definition, if available.
471   RuntimeDefinition RD = Call->getRuntimeDefinition();
472   if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
473     return FD->parameters();
474   if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
475     return MD->parameters();
476 
477   return Call->parameters();
478 }
479 
480 /// \return whether \p Ty points to a const type, or is a const reference.
481 static bool isPointerToConst(QualType Ty) {
482   return !Ty->getPointeeType().isNull() &&
483          Ty->getPointeeType().getCanonicalType().isConstQualified();
484 }
485 
486 /// Attempts to find the region of interest in a given CXX decl,
487 /// by either following the base classes or fields.
488 /// Dereferences fields up to a given recursion limit.
489 /// Note that \p Vec is passed by value, leading to quadratic copying cost,
490 /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
491 /// \return A chain fields leading to the region of interest or None.
492 const Optional<NoStoreFuncVisitor::RegionVector>
493 NoStoreFuncVisitor::findRegionOfInterestInRecord(
494     const RecordDecl *RD, ProgramStateRef State, const MemRegion *R,
495     const NoStoreFuncVisitor::RegionVector &Vec /* = {} */,
496     int depth /* = 0 */) {
497 
498   if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
499     return None;
500 
501   if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
502     if (!RDX->hasDefinition())
503       return None;
504 
505   // Recursively examine the base classes.
506   // Note that following base classes does not increase the recursion depth.
507   if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
508     for (const auto II : RDX->bases())
509       if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
510         if (Optional<RegionVector> Out =
511                 findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
512           return Out;
513 
514   for (const FieldDecl *I : RD->fields()) {
515     QualType FT = I->getType();
516     const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
517     const SVal V = State->getSVal(FR);
518     const MemRegion *VR = V.getAsRegion();
519 
520     RegionVector VecF = Vec;
521     VecF.push_back(FR);
522 
523     if (RegionOfInterest == VR)
524       return VecF;
525 
526     if (const RecordDecl *RRD = FT->getAsRecordDecl())
527       if (auto Out =
528               findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
529         return Out;
530 
531     QualType PT = FT->getPointeeType();
532     if (PT.isNull() || PT->isVoidType() || !VR)
533       continue;
534 
535     if (const RecordDecl *RRD = PT->getAsRecordDecl())
536       if (Optional<RegionVector> Out =
537               findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
538         return Out;
539   }
540 
541   return None;
542 }
543 
544 PathDiagnosticPieceRef
545 NoStoreFuncVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BR,
546                               PathSensitiveBugReport &R) {
547 
548   const LocationContext *Ctx = N->getLocationContext();
549   const StackFrameContext *SCtx = Ctx->getStackFrame();
550   ProgramStateRef State = N->getState();
551   auto CallExitLoc = N->getLocationAs<CallExitBegin>();
552 
553   // No diagnostic if region was modified inside the frame.
554   if (!CallExitLoc || isRegionOfInterestModifiedInFrame(N))
555     return nullptr;
556 
557   CallEventRef<> Call =
558       BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
559 
560   // Region of interest corresponds to an IVar, exiting a method
561   // which could have written into that IVar, but did not.
562   if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
563     if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
564       const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
565       if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
566           potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
567                                     IvarR->getDecl()))
568         return maybeEmitNote(R, *Call, N, {}, SelfRegion, "self",
569                              /*FirstIsReferenceType=*/false, 1);
570     }
571   }
572 
573   if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
574     const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
575     if (RegionOfInterest->isSubRegionOf(ThisR) &&
576         !CCall->getDecl()->isImplicit())
577       return maybeEmitNote(R, *Call, N, {}, ThisR, "this",
578                            /*FirstIsReferenceType=*/false, 1);
579 
580     // Do not generate diagnostics for not modified parameters in
581     // constructors.
582     return nullptr;
583   }
584 
585   ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
586   for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
587     const ParmVarDecl *PVD = parameters[I];
588     SVal V = Call->getArgSVal(I);
589     bool ParamIsReferenceType = PVD->getType()->isReferenceType();
590     std::string ParamName = PVD->getNameAsString();
591 
592     int IndirectionLevel = 1;
593     QualType T = PVD->getType();
594     while (const MemRegion *MR = V.getAsRegion()) {
595       if (RegionOfInterest->isSubRegionOf(MR) && !isPointerToConst(T))
596         return maybeEmitNote(R, *Call, N, {}, MR, ParamName,
597                              ParamIsReferenceType, IndirectionLevel);
598 
599       QualType PT = T->getPointeeType();
600       if (PT.isNull() || PT->isVoidType())
601         break;
602 
603       if (const RecordDecl *RD = PT->getAsRecordDecl())
604         if (Optional<RegionVector> P =
605                 findRegionOfInterestInRecord(RD, State, MR))
606           return maybeEmitNote(R, *Call, N, *P, RegionOfInterest, ParamName,
607                                ParamIsReferenceType, IndirectionLevel);
608 
609       V = State->getSVal(MR, PT);
610       T = PT;
611       IndirectionLevel++;
612     }
613   }
614 
615   return nullptr;
616 }
617 
618 void NoStoreFuncVisitor::findModifyingFrames(const ExplodedNode *N) {
619   assert(N->getLocationAs<CallExitBegin>());
620   ProgramStateRef LastReturnState = N->getState();
621   SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
622   const LocationContext *Ctx = N->getLocationContext();
623   const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
624 
625   do {
626     ProgramStateRef State = N->getState();
627     auto CallExitLoc = N->getLocationAs<CallExitBegin>();
628     if (CallExitLoc) {
629       LastReturnState = State;
630       ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
631     }
632 
633     FramesModifyingCalculated.insert(N->getLocationContext()->getStackFrame());
634 
635     if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
636       const StackFrameContext *SCtx = N->getStackFrame();
637       while (!SCtx->inTopFrame()) {
638         auto p = FramesModifyingRegion.insert(SCtx);
639         if (!p.second)
640           break; // Frame and all its parents already inserted.
641         SCtx = SCtx->getParent()->getStackFrame();
642       }
643     }
644 
645     // Stop calculation at the call to the current function.
646     if (auto CE = N->getLocationAs<CallEnter>())
647       if (CE->getCalleeContext() == OriginalSCtx)
648         break;
649 
650     N = N->getFirstPred();
651   } while (N);
652 }
653 
654 static llvm::StringLiteral WillBeUsedForACondition =
655     ", which participates in a condition later";
656 
657 PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNote(
658     PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N,
659     const RegionVector &FieldChain, const MemRegion *MatchedRegion,
660     StringRef FirstElement, bool FirstIsReferenceType,
661     unsigned IndirectionLevel) {
662   // Optimistically suppress uninitialized value bugs that result
663   // from system headers having a chance to initialize the value
664   // but failing to do so. It's too unlikely a system header's fault.
665   // It's much more likely a situation in which the function has a failure
666   // mode that the user decided not to check. If we want to hunt such
667   // omitted checks, we should provide an explicit function-specific note
668   // describing the precondition under which the function isn't supposed to
669   // initialize its out-parameter, and additionally check that such
670   // precondition can actually be fulfilled on the current path.
671   if (Call.isInSystemHeader()) {
672     // We make an exception for system header functions that have no branches.
673     // Such functions unconditionally fail to initialize the variable.
674     // If they call other functions that have more paths within them,
675     // this suppression would still apply when we visit these inner functions.
676     // One common example of a standard function that doesn't ever initialize
677     // its out parameter is operator placement new; it's up to the follow-up
678     // constructor (if any) to initialize the memory.
679     if (!N->getStackFrame()->getCFG()->isLinear())
680       R.markInvalid(getTag(), nullptr);
681     return nullptr;
682   }
683 
684   PathDiagnosticLocation L =
685       PathDiagnosticLocation::create(N->getLocation(), SM);
686 
687   // For now this shouldn't trigger, but once it does (as we add more
688   // functions to the body farm), we'll need to decide if these reports
689   // are worth suppressing as well.
690   if (!L.hasValidLocation())
691     return nullptr;
692 
693   SmallString<256> sbuf;
694   llvm::raw_svector_ostream os(sbuf);
695   os << "Returning without writing to '";
696 
697   // Do not generate the note if failed to pretty-print.
698   if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType, MatchedRegion,
699                              FieldChain, IndirectionLevel, os))
700     return nullptr;
701 
702   os << "'";
703   if (TKind == bugreporter::TrackingKind::Condition)
704     os << WillBeUsedForACondition;
705   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
706 }
707 
708 bool NoStoreFuncVisitor::prettyPrintRegionName(StringRef FirstElement,
709                                                bool FirstIsReferenceType,
710                                                const MemRegion *MatchedRegion,
711                                                const RegionVector &FieldChain,
712                                                int IndirectionLevel,
713                                                llvm::raw_svector_ostream &os) {
714 
715   if (FirstIsReferenceType)
716     IndirectionLevel--;
717 
718   RegionVector RegionSequence;
719 
720   // Add the regions in the reverse order, then reverse the resulting array.
721   assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
722   const MemRegion *R = RegionOfInterest;
723   while (R != MatchedRegion) {
724     RegionSequence.push_back(R);
725     R = cast<SubRegion>(R)->getSuperRegion();
726   }
727   std::reverse(RegionSequence.begin(), RegionSequence.end());
728   RegionSequence.append(FieldChain.begin(), FieldChain.end());
729 
730   StringRef Sep;
731   for (const MemRegion *R : RegionSequence) {
732 
733     // Just keep going up to the base region.
734     // Element regions may appear due to casts.
735     if (isa<CXXBaseObjectRegion>(R) || isa<CXXTempObjectRegion>(R))
736       continue;
737 
738     if (Sep.empty())
739       Sep = prettyPrintFirstElement(FirstElement,
740                                     /*MoreItemsExpected=*/true,
741                                     IndirectionLevel, os);
742 
743     os << Sep;
744 
745     // Can only reasonably pretty-print DeclRegions.
746     if (!isa<DeclRegion>(R))
747       return false;
748 
749     const auto *DR = cast<DeclRegion>(R);
750     Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
751     DR->getDecl()->getDeclName().print(os, PP);
752   }
753 
754   if (Sep.empty())
755     prettyPrintFirstElement(FirstElement,
756                             /*MoreItemsExpected=*/false, IndirectionLevel, os);
757   return true;
758 }
759 
760 StringRef NoStoreFuncVisitor::prettyPrintFirstElement(
761     StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel,
762     llvm::raw_svector_ostream &os) {
763   StringRef Out = ".";
764 
765   if (IndirectionLevel > 0 && MoreItemsExpected) {
766     IndirectionLevel--;
767     Out = "->";
768   }
769 
770   if (IndirectionLevel > 0 && MoreItemsExpected)
771     os << "(";
772 
773   for (int i = 0; i < IndirectionLevel; i++)
774     os << "*";
775   os << FirstElement;
776 
777   if (IndirectionLevel > 0 && MoreItemsExpected)
778     os << ")";
779 
780   return Out;
781 }
782 
783 //===----------------------------------------------------------------------===//
784 // Implementation of MacroNullReturnSuppressionVisitor.
785 //===----------------------------------------------------------------------===//
786 
787 namespace {
788 
789 /// Suppress null-pointer-dereference bugs where dereferenced null was returned
790 /// the macro.
791 class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
792   const SubRegion *RegionOfInterest;
793   const SVal ValueAtDereference;
794 
795   // Do not invalidate the reports where the value was modified
796   // after it got assigned to from the macro.
797   bool WasModified = false;
798 
799 public:
800   MacroNullReturnSuppressionVisitor(const SubRegion *R, const SVal V)
801       : RegionOfInterest(R), ValueAtDereference(V) {}
802 
803   PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
804                                    BugReporterContext &BRC,
805                                    PathSensitiveBugReport &BR) override {
806     if (WasModified)
807       return nullptr;
808 
809     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
810     if (!BugPoint)
811       return nullptr;
812 
813     const SourceManager &SMgr = BRC.getSourceManager();
814     if (auto Loc = matchAssignment(N)) {
815       if (isFunctionMacroExpansion(*Loc, SMgr)) {
816         std::string MacroName = getMacroName(*Loc, BRC);
817         SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
818         if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
819           BR.markInvalid(getTag(), MacroName.c_str());
820       }
821     }
822 
823     if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
824       WasModified = true;
825 
826     return nullptr;
827   }
828 
829   static void addMacroVisitorIfNecessary(
830         const ExplodedNode *N, const MemRegion *R,
831         bool EnableNullFPSuppression, PathSensitiveBugReport &BR,
832         const SVal V) {
833     AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
834     if (EnableNullFPSuppression &&
835         Options.ShouldSuppressNullReturnPaths && V.getAs<Loc>())
836       BR.addVisitor(std::make_unique<MacroNullReturnSuppressionVisitor>(
837               R->getAs<SubRegion>(), V));
838   }
839 
840   void* getTag() const {
841     static int Tag = 0;
842     return static_cast<void *>(&Tag);
843   }
844 
845   void Profile(llvm::FoldingSetNodeID &ID) const override {
846     ID.AddPointer(getTag());
847   }
848 
849 private:
850   /// \return Source location of right hand side of an assignment
851   /// into \c RegionOfInterest, empty optional if none found.
852   Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
853     const Stmt *S = N->getStmtForDiagnostics();
854     ProgramStateRef State = N->getState();
855     auto *LCtx = N->getLocationContext();
856     if (!S)
857       return None;
858 
859     if (const auto *DS = dyn_cast<DeclStmt>(S)) {
860       if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
861         if (const Expr *RHS = VD->getInit())
862           if (RegionOfInterest->isSubRegionOf(
863                   State->getLValue(VD, LCtx).getAsRegion()))
864             return RHS->getBeginLoc();
865     } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
866       const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
867       const Expr *RHS = BO->getRHS();
868       if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
869         return RHS->getBeginLoc();
870       }
871     }
872     return None;
873   }
874 };
875 
876 } // end of anonymous namespace
877 
878 namespace {
879 
880 /// Emits an extra note at the return statement of an interesting stack frame.
881 ///
882 /// The returned value is marked as an interesting value, and if it's null,
883 /// adds a visitor to track where it became null.
884 ///
885 /// This visitor is intended to be used when another visitor discovers that an
886 /// interesting value comes from an inlined function call.
887 class ReturnVisitor : public BugReporterVisitor {
888   const StackFrameContext *CalleeSFC;
889   enum {
890     Initial,
891     MaybeUnsuppress,
892     Satisfied
893   } Mode = Initial;
894 
895   bool EnableNullFPSuppression;
896   bool ShouldInvalidate = true;
897   AnalyzerOptions& Options;
898   bugreporter::TrackingKind TKind;
899 
900 public:
901   ReturnVisitor(const StackFrameContext *Frame, bool Suppressed,
902                 AnalyzerOptions &Options, bugreporter::TrackingKind TKind)
903       : CalleeSFC(Frame), EnableNullFPSuppression(Suppressed),
904         Options(Options), TKind(TKind) {}
905 
906   static void *getTag() {
907     static int Tag = 0;
908     return static_cast<void *>(&Tag);
909   }
910 
911   void Profile(llvm::FoldingSetNodeID &ID) const override {
912     ID.AddPointer(ReturnVisitor::getTag());
913     ID.AddPointer(CalleeSFC);
914     ID.AddBoolean(EnableNullFPSuppression);
915   }
916 
917   /// Adds a ReturnVisitor if the given statement represents a call that was
918   /// inlined.
919   ///
920   /// This will search back through the ExplodedGraph, starting from the given
921   /// node, looking for when the given statement was processed. If it turns out
922   /// the statement is a call that was inlined, we add the visitor to the
923   /// bug report, so it can print a note later.
924   static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
925                                     PathSensitiveBugReport &BR,
926                                     bool InEnableNullFPSuppression,
927                                     bugreporter::TrackingKind TKind) {
928     if (!CallEvent::isCallStmt(S))
929       return;
930 
931     // First, find when we processed the statement.
932     // If we work with a 'CXXNewExpr' that is going to be purged away before
933     // its call take place. We would catch that purge in the last condition
934     // as a 'StmtPoint' so we have to bypass it.
935     const bool BypassCXXNewExprEval = isa<CXXNewExpr>(S);
936 
937     // This is moving forward when we enter into another context.
938     const StackFrameContext *CurrentSFC = Node->getStackFrame();
939 
940     do {
941       // If that is satisfied we found our statement as an inlined call.
942       if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
943         if (CEE->getCalleeContext()->getCallSite() == S)
944           break;
945 
946       // Try to move forward to the end of the call-chain.
947       Node = Node->getFirstPred();
948       if (!Node)
949         break;
950 
951       const StackFrameContext *PredSFC = Node->getStackFrame();
952 
953       // If that is satisfied we found our statement.
954       // FIXME: This code currently bypasses the call site for the
955       //        conservatively evaluated allocator.
956       if (!BypassCXXNewExprEval)
957         if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
958           // See if we do not enter into another context.
959           if (SP->getStmt() == S && CurrentSFC == PredSFC)
960             break;
961 
962       CurrentSFC = PredSFC;
963     } while (Node->getStackFrame() == CurrentSFC);
964 
965     // Next, step over any post-statement checks.
966     while (Node && Node->getLocation().getAs<PostStmt>())
967       Node = Node->getFirstPred();
968     if (!Node)
969       return;
970 
971     // Finally, see if we inlined the call.
972     Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
973     if (!CEE)
974       return;
975 
976     const StackFrameContext *CalleeContext = CEE->getCalleeContext();
977     if (CalleeContext->getCallSite() != S)
978       return;
979 
980     // Check the return value.
981     ProgramStateRef State = Node->getState();
982     SVal RetVal = Node->getSVal(S);
983 
984     // Handle cases where a reference is returned and then immediately used.
985     if (cast<Expr>(S)->isGLValue())
986       if (Optional<Loc> LValue = RetVal.getAs<Loc>())
987         RetVal = State->getSVal(*LValue);
988 
989     // See if the return value is NULL. If so, suppress the report.
990     AnalyzerOptions &Options = State->getAnalysisManager().options;
991 
992     bool EnableNullFPSuppression = false;
993     if (InEnableNullFPSuppression &&
994         Options.ShouldSuppressNullReturnPaths)
995       if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
996         EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
997 
998     BR.addVisitor(std::make_unique<ReturnVisitor>(CalleeContext,
999                                                    EnableNullFPSuppression,
1000                                                    Options, TKind));
1001   }
1002 
1003   PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N,
1004                                           BugReporterContext &BRC,
1005                                           PathSensitiveBugReport &BR) {
1006     // Only print a message at the interesting return statement.
1007     if (N->getLocationContext() != CalleeSFC)
1008       return nullptr;
1009 
1010     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
1011     if (!SP)
1012       return nullptr;
1013 
1014     const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
1015     if (!Ret)
1016       return nullptr;
1017 
1018     // Okay, we're at the right return statement, but do we have the return
1019     // value available?
1020     ProgramStateRef State = N->getState();
1021     SVal V = State->getSVal(Ret, CalleeSFC);
1022     if (V.isUnknownOrUndef())
1023       return nullptr;
1024 
1025     // Don't print any more notes after this one.
1026     Mode = Satisfied;
1027 
1028     const Expr *RetE = Ret->getRetValue();
1029     assert(RetE && "Tracking a return value for a void function");
1030 
1031     // Handle cases where a reference is returned and then immediately used.
1032     Optional<Loc> LValue;
1033     if (RetE->isGLValue()) {
1034       if ((LValue = V.getAs<Loc>())) {
1035         SVal RValue = State->getRawSVal(*LValue, RetE->getType());
1036         if (RValue.getAs<DefinedSVal>())
1037           V = RValue;
1038       }
1039     }
1040 
1041     // Ignore aggregate rvalues.
1042     if (V.getAs<nonloc::LazyCompoundVal>() ||
1043         V.getAs<nonloc::CompoundVal>())
1044       return nullptr;
1045 
1046     RetE = RetE->IgnoreParenCasts();
1047 
1048     // Let's track the return value.
1049     bugreporter::trackExpressionValue(
1050         N, RetE, BR, TKind, EnableNullFPSuppression);
1051 
1052     // Build an appropriate message based on the return value.
1053     SmallString<64> Msg;
1054     llvm::raw_svector_ostream Out(Msg);
1055 
1056     bool WouldEventBeMeaningless = false;
1057 
1058     if (State->isNull(V).isConstrainedTrue()) {
1059       if (V.getAs<Loc>()) {
1060 
1061         // If we have counter-suppression enabled, make sure we keep visiting
1062         // future nodes. We want to emit a path note as well, in case
1063         // the report is resurrected as valid later on.
1064         if (EnableNullFPSuppression &&
1065             Options.ShouldAvoidSuppressingNullArgumentPaths)
1066           Mode = MaybeUnsuppress;
1067 
1068         if (RetE->getType()->isObjCObjectPointerType()) {
1069           Out << "Returning nil";
1070         } else {
1071           Out << "Returning null pointer";
1072         }
1073       } else {
1074         Out << "Returning zero";
1075       }
1076 
1077     } else {
1078       if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1079         Out << "Returning the value " << CI->getValue();
1080       } else {
1081         // There is nothing interesting about returning a value, when it is
1082         // plain value without any constraints, and the function is guaranteed
1083         // to return that every time. We could use CFG::isLinear() here, but
1084         // constexpr branches are obvious to the compiler, not necesserily to
1085         // the programmer.
1086         if (N->getCFG().size() == 3)
1087           WouldEventBeMeaningless = true;
1088 
1089         if (V.getAs<Loc>())
1090           Out << "Returning pointer";
1091         else
1092           Out << "Returning value";
1093       }
1094     }
1095 
1096     if (LValue) {
1097       if (const MemRegion *MR = LValue->getAsRegion()) {
1098         if (MR->canPrintPretty()) {
1099           Out << " (reference to ";
1100           MR->printPretty(Out);
1101           Out << ")";
1102         }
1103       }
1104     } else {
1105       // FIXME: We should have a more generalized location printing mechanism.
1106       if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
1107         if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
1108           Out << " (loaded from '" << *DD << "')";
1109     }
1110 
1111     PathDiagnosticLocation L(Ret, BRC.getSourceManager(), CalleeSFC);
1112     if (!L.isValid() || !L.asLocation().isValid())
1113       return nullptr;
1114 
1115     if (TKind == bugreporter::TrackingKind::Condition)
1116       Out << WillBeUsedForACondition;
1117 
1118     auto EventPiece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1119 
1120     // If we determined that the note is meaningless, make it prunable, and
1121     // don't mark the stackframe interesting.
1122     if (WouldEventBeMeaningless)
1123       EventPiece->setPrunable(true);
1124     else
1125       BR.markInteresting(CalleeSFC);
1126 
1127     return EventPiece;
1128   }
1129 
1130   PathDiagnosticPieceRef visitNodeMaybeUnsuppress(const ExplodedNode *N,
1131                                                   BugReporterContext &BRC,
1132                                                   PathSensitiveBugReport &BR) {
1133     assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
1134 
1135     // Are we at the entry node for this call?
1136     Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
1137     if (!CE)
1138       return nullptr;
1139 
1140     if (CE->getCalleeContext() != CalleeSFC)
1141       return nullptr;
1142 
1143     Mode = Satisfied;
1144 
1145     // Don't automatically suppress a report if one of the arguments is
1146     // known to be a null pointer. Instead, start tracking /that/ null
1147     // value back to its origin.
1148     ProgramStateManager &StateMgr = BRC.getStateManager();
1149     CallEventManager &CallMgr = StateMgr.getCallEventManager();
1150 
1151     ProgramStateRef State = N->getState();
1152     CallEventRef<> Call = CallMgr.getCaller(CalleeSFC, State);
1153     for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
1154       Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
1155       if (!ArgV)
1156         continue;
1157 
1158       const Expr *ArgE = Call->getArgExpr(I);
1159       if (!ArgE)
1160         continue;
1161 
1162       // Is it possible for this argument to be non-null?
1163       if (!State->isNull(*ArgV).isConstrainedTrue())
1164         continue;
1165 
1166       if (trackExpressionValue(N, ArgE, BR, TKind, EnableNullFPSuppression))
1167         ShouldInvalidate = false;
1168 
1169       // If we /can't/ track the null pointer, we should err on the side of
1170       // false negatives, and continue towards marking this report invalid.
1171       // (We will still look at the other arguments, though.)
1172     }
1173 
1174     return nullptr;
1175   }
1176 
1177   PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1178                                    BugReporterContext &BRC,
1179                                    PathSensitiveBugReport &BR) override {
1180     switch (Mode) {
1181     case Initial:
1182       return visitNodeInitial(N, BRC, BR);
1183     case MaybeUnsuppress:
1184       return visitNodeMaybeUnsuppress(N, BRC, BR);
1185     case Satisfied:
1186       return nullptr;
1187     }
1188 
1189     llvm_unreachable("Invalid visit mode!");
1190   }
1191 
1192   void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
1193                        PathSensitiveBugReport &BR) override {
1194     if (EnableNullFPSuppression && ShouldInvalidate)
1195       BR.markInvalid(ReturnVisitor::getTag(), CalleeSFC);
1196   }
1197 };
1198 
1199 } // end of anonymous namespace
1200 
1201 //===----------------------------------------------------------------------===//
1202 // Implementation of FindLastStoreBRVisitor.
1203 //===----------------------------------------------------------------------===//
1204 
1205 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1206   static int tag = 0;
1207   ID.AddPointer(&tag);
1208   ID.AddPointer(R);
1209   ID.Add(V);
1210   ID.AddInteger(static_cast<int>(TKind));
1211   ID.AddBoolean(EnableNullFPSuppression);
1212 }
1213 
1214 /// Returns true if \p N represents the DeclStmt declaring and initializing
1215 /// \p VR.
1216 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
1217   Optional<PostStmt> P = N->getLocationAs<PostStmt>();
1218   if (!P)
1219     return false;
1220 
1221   const DeclStmt *DS = P->getStmtAs<DeclStmt>();
1222   if (!DS)
1223     return false;
1224 
1225   if (DS->getSingleDecl() != VR->getDecl())
1226     return false;
1227 
1228   const MemSpaceRegion *VarSpace = VR->getMemorySpace();
1229   const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
1230   if (!FrameSpace) {
1231     // If we ever directly evaluate global DeclStmts, this assertion will be
1232     // invalid, but this still seems preferable to silently accepting an
1233     // initialization that may be for a path-sensitive variable.
1234     assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
1235     return true;
1236   }
1237 
1238   assert(VR->getDecl()->hasLocalStorage());
1239   const LocationContext *LCtx = N->getLocationContext();
1240   return FrameSpace->getStackFrame() == LCtx->getStackFrame();
1241 }
1242 
1243 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
1244 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
1245                               const MemRegion *R, SVal V, const DeclStmt *DS) {
1246   if (R->canPrintPretty()) {
1247     R->printPretty(os);
1248     os << " ";
1249   }
1250 
1251   if (V.getAs<loc::ConcreteInt>()) {
1252     bool b = false;
1253     if (R->isBoundable()) {
1254       if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1255         if (TR->getValueType()->isObjCObjectPointerType()) {
1256           os << action << "nil";
1257           b = true;
1258         }
1259       }
1260     }
1261     if (!b)
1262       os << action << "a null pointer value";
1263 
1264   } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
1265     os << action << CVal->getValue();
1266   } else if (DS) {
1267     if (V.isUndef()) {
1268       if (isa<VarRegion>(R)) {
1269         const auto *VD = cast<VarDecl>(DS->getSingleDecl());
1270         if (VD->getInit()) {
1271           os << (R->canPrintPretty() ? "initialized" : "Initializing")
1272             << " to a garbage value";
1273         } else {
1274           os << (R->canPrintPretty() ? "declared" : "Declaring")
1275             << " without an initial value";
1276         }
1277       }
1278     } else {
1279       os << (R->canPrintPretty() ? "initialized" : "Initialized")
1280         << " here";
1281     }
1282   }
1283 }
1284 
1285 /// Display diagnostics for passing bad region as a parameter.
1286 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
1287     const VarRegion *VR,
1288     SVal V) {
1289   const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1290 
1291   os << "Passing ";
1292 
1293   if (V.getAs<loc::ConcreteInt>()) {
1294     if (Param->getType()->isObjCObjectPointerType())
1295       os << "nil object reference";
1296     else
1297       os << "null pointer value";
1298   } else if (V.isUndef()) {
1299     os << "uninitialized value";
1300   } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1301     os << "the value " << CI->getValue();
1302   } else {
1303     os << "value";
1304   }
1305 
1306   // Printed parameter indexes are 1-based, not 0-based.
1307   unsigned Idx = Param->getFunctionScopeIndex() + 1;
1308   os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1309   if (VR->canPrintPretty()) {
1310     os << " ";
1311     VR->printPretty(os);
1312   }
1313 }
1314 
1315 /// Show default diagnostics for storing bad region.
1316 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &os,
1317                                      const MemRegion *R, SVal V) {
1318   if (V.getAs<loc::ConcreteInt>()) {
1319     bool b = false;
1320     if (R->isBoundable()) {
1321       if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1322         if (TR->getValueType()->isObjCObjectPointerType()) {
1323           os << "nil object reference stored";
1324           b = true;
1325         }
1326       }
1327     }
1328     if (!b) {
1329       if (R->canPrintPretty())
1330         os << "Null pointer value stored";
1331       else
1332         os << "Storing null pointer value";
1333     }
1334 
1335   } else if (V.isUndef()) {
1336     if (R->canPrintPretty())
1337       os << "Uninitialized value stored";
1338     else
1339       os << "Storing uninitialized value";
1340 
1341   } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1342     if (R->canPrintPretty())
1343       os << "The value " << CV->getValue() << " is assigned";
1344     else
1345       os << "Assigning " << CV->getValue();
1346 
1347   } else {
1348     if (R->canPrintPretty())
1349       os << "Value assigned";
1350     else
1351       os << "Assigning value";
1352   }
1353 
1354   if (R->canPrintPretty()) {
1355     os << " to ";
1356     R->printPretty(os);
1357   }
1358 }
1359 
1360 PathDiagnosticPieceRef
1361 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1362                                   BugReporterContext &BRC,
1363                                   PathSensitiveBugReport &BR) {
1364   if (Satisfied)
1365     return nullptr;
1366 
1367   const ExplodedNode *StoreSite = nullptr;
1368   const ExplodedNode *Pred = Succ->getFirstPred();
1369   const Expr *InitE = nullptr;
1370   bool IsParam = false;
1371 
1372   // First see if we reached the declaration of the region.
1373   if (const auto *VR = dyn_cast<VarRegion>(R)) {
1374     if (isInitializationOfVar(Pred, VR)) {
1375       StoreSite = Pred;
1376       InitE = VR->getDecl()->getInit();
1377     }
1378   }
1379 
1380   // If this is a post initializer expression, initializing the region, we
1381   // should track the initializer expression.
1382   if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1383     const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1384     if (FieldReg == R) {
1385       StoreSite = Pred;
1386       InitE = PIP->getInitializer()->getInit();
1387     }
1388   }
1389 
1390   // Otherwise, see if this is the store site:
1391   // (1) Succ has this binding and Pred does not, i.e. this is
1392   //     where the binding first occurred.
1393   // (2) Succ has this binding and is a PostStore node for this region, i.e.
1394   //     the same binding was re-assigned here.
1395   if (!StoreSite) {
1396     if (Succ->getState()->getSVal(R) != V)
1397       return nullptr;
1398 
1399     if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
1400       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1401       if (!PS || PS->getLocationValue() != R)
1402         return nullptr;
1403     }
1404 
1405     StoreSite = Succ;
1406 
1407     // If this is an assignment expression, we can track the value
1408     // being assigned.
1409     if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1410       if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1411         if (BO->isAssignmentOp())
1412           InitE = BO->getRHS();
1413 
1414     // If this is a call entry, the variable should be a parameter.
1415     // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1416     // 'this' should never be NULL, but this visitor isn't just for NULL and
1417     // UndefinedVal.)
1418     if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1419       if (const auto *VR = dyn_cast<VarRegion>(R)) {
1420 
1421         const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1422 
1423         ProgramStateManager &StateMgr = BRC.getStateManager();
1424         CallEventManager &CallMgr = StateMgr.getCallEventManager();
1425 
1426         CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1427                                                 Succ->getState());
1428         InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1429         IsParam = true;
1430       }
1431     }
1432 
1433     // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1434     // is wrapped inside of it.
1435     if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1436       InitE = TmpR->getExpr();
1437   }
1438 
1439   if (!StoreSite)
1440     return nullptr;
1441 
1442   Satisfied = true;
1443 
1444   // If we have an expression that provided the value, try to track where it
1445   // came from.
1446   if (InitE) {
1447     if (!IsParam)
1448       InitE = InitE->IgnoreParenCasts();
1449 
1450     bugreporter::trackExpressionValue(
1451         StoreSite, InitE, BR, TKind, EnableNullFPSuppression);
1452   }
1453 
1454   if (TKind == TrackingKind::Condition &&
1455       !OriginSFC->isParentOf(StoreSite->getStackFrame()))
1456     return nullptr;
1457 
1458   // Okay, we've found the binding. Emit an appropriate message.
1459   SmallString<256> sbuf;
1460   llvm::raw_svector_ostream os(sbuf);
1461 
1462   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1463     const Stmt *S = PS->getStmt();
1464     const char *action = nullptr;
1465     const auto *DS = dyn_cast<DeclStmt>(S);
1466     const auto *VR = dyn_cast<VarRegion>(R);
1467 
1468     if (DS) {
1469       action = R->canPrintPretty() ? "initialized to " :
1470                                      "Initializing to ";
1471     } else if (isa<BlockExpr>(S)) {
1472       action = R->canPrintPretty() ? "captured by block as " :
1473                                      "Captured by block as ";
1474       if (VR) {
1475         // See if we can get the BlockVarRegion.
1476         ProgramStateRef State = StoreSite->getState();
1477         SVal V = StoreSite->getSVal(S);
1478         if (const auto *BDR =
1479               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1480           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1481             if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
1482               BR.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
1483                   *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC));
1484           }
1485         }
1486       }
1487     }
1488     if (action)
1489       showBRDiagnostics(action, os, R, V, DS);
1490 
1491   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
1492     if (const auto *VR = dyn_cast<VarRegion>(R))
1493       showBRParamDiagnostics(os, VR, V);
1494   }
1495 
1496   if (os.str().empty())
1497     showBRDefaultDiagnostics(os, R, V);
1498 
1499   if (TKind == bugreporter::TrackingKind::Condition)
1500     os << WillBeUsedForACondition;
1501 
1502   // Construct a new PathDiagnosticPiece.
1503   ProgramPoint P = StoreSite->getLocation();
1504   PathDiagnosticLocation L;
1505   if (P.getAs<CallEnter>() && InitE)
1506     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1507                                P.getLocationContext());
1508 
1509   if (!L.isValid() || !L.asLocation().isValid())
1510     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1511 
1512   if (!L.isValid() || !L.asLocation().isValid())
1513     return nullptr;
1514 
1515   return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1516 }
1517 
1518 //===----------------------------------------------------------------------===//
1519 // Implementation of TrackConstraintBRVisitor.
1520 //===----------------------------------------------------------------------===//
1521 
1522 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1523   static int tag = 0;
1524   ID.AddPointer(&tag);
1525   ID.AddBoolean(Assumption);
1526   ID.Add(Constraint);
1527 }
1528 
1529 /// Return the tag associated with this visitor.  This tag will be used
1530 /// to make all PathDiagnosticPieces created by this visitor.
1531 const char *TrackConstraintBRVisitor::getTag() {
1532   return "TrackConstraintBRVisitor";
1533 }
1534 
1535 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1536   if (IsZeroCheck)
1537     return N->getState()->isNull(Constraint).isUnderconstrained();
1538   return (bool)N->getState()->assume(Constraint, !Assumption);
1539 }
1540 
1541 PathDiagnosticPieceRef TrackConstraintBRVisitor::VisitNode(
1542     const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) {
1543   const ExplodedNode *PrevN = N->getFirstPred();
1544   if (IsSatisfied)
1545     return nullptr;
1546 
1547   // Start tracking after we see the first state in which the value is
1548   // constrained.
1549   if (!IsTrackingTurnedOn)
1550     if (!isUnderconstrained(N))
1551       IsTrackingTurnedOn = true;
1552   if (!IsTrackingTurnedOn)
1553     return nullptr;
1554 
1555   // Check if in the previous state it was feasible for this constraint
1556   // to *not* be true.
1557   if (isUnderconstrained(PrevN)) {
1558     IsSatisfied = true;
1559 
1560     // As a sanity check, make sure that the negation of the constraint
1561     // was infeasible in the current state.  If it is feasible, we somehow
1562     // missed the transition point.
1563     assert(!isUnderconstrained(N));
1564 
1565     // We found the transition point for the constraint.  We now need to
1566     // pretty-print the constraint. (work-in-progress)
1567     SmallString<64> sbuf;
1568     llvm::raw_svector_ostream os(sbuf);
1569 
1570     if (Constraint.getAs<Loc>()) {
1571       os << "Assuming pointer value is ";
1572       os << (Assumption ? "non-null" : "null");
1573     }
1574 
1575     if (os.str().empty())
1576       return nullptr;
1577 
1578     // Construct a new PathDiagnosticPiece.
1579     ProgramPoint P = N->getLocation();
1580     PathDiagnosticLocation L =
1581       PathDiagnosticLocation::create(P, BRC.getSourceManager());
1582     if (!L.isValid())
1583       return nullptr;
1584 
1585     auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1586     X->setTag(getTag());
1587     return std::move(X);
1588   }
1589 
1590   return nullptr;
1591 }
1592 
1593 //===----------------------------------------------------------------------===//
1594 // Implementation of SuppressInlineDefensiveChecksVisitor.
1595 //===----------------------------------------------------------------------===//
1596 
1597 SuppressInlineDefensiveChecksVisitor::
1598 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1599     : V(Value) {
1600   // Check if the visitor is disabled.
1601   AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1602   if (!Options.ShouldSuppressInlinedDefensiveChecks)
1603     IsSatisfied = true;
1604 
1605   assert(N->getState()->isNull(V).isConstrainedTrue() &&
1606          "The visitor only tracks the cases where V is constrained to 0");
1607 }
1608 
1609 void SuppressInlineDefensiveChecksVisitor::Profile(
1610     llvm::FoldingSetNodeID &ID) const {
1611   static int id = 0;
1612   ID.AddPointer(&id);
1613   ID.Add(V);
1614 }
1615 
1616 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1617   return "IDCVisitor";
1618 }
1619 
1620 PathDiagnosticPieceRef
1621 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1622                                                 BugReporterContext &BRC,
1623                                                 PathSensitiveBugReport &BR) {
1624   const ExplodedNode *Pred = Succ->getFirstPred();
1625   if (IsSatisfied)
1626     return nullptr;
1627 
1628   // Start tracking after we see the first state in which the value is null.
1629   if (!IsTrackingTurnedOn)
1630     if (Succ->getState()->isNull(V).isConstrainedTrue())
1631       IsTrackingTurnedOn = true;
1632   if (!IsTrackingTurnedOn)
1633     return nullptr;
1634 
1635   // Check if in the previous state it was feasible for this value
1636   // to *not* be null.
1637   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1638     IsSatisfied = true;
1639 
1640     assert(Succ->getState()->isNull(V).isConstrainedTrue());
1641 
1642     // Check if this is inlined defensive checks.
1643     const LocationContext *CurLC =Succ->getLocationContext();
1644     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1645     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
1646       BR.markInvalid("Suppress IDC", CurLC);
1647       return nullptr;
1648     }
1649 
1650     // Treat defensive checks in function-like macros as if they were an inlined
1651     // defensive check. If the bug location is not in a macro and the
1652     // terminator for the current location is in a macro then suppress the
1653     // warning.
1654     auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1655 
1656     if (!BugPoint)
1657       return nullptr;
1658 
1659     ProgramPoint CurPoint = Succ->getLocation();
1660     const Stmt *CurTerminatorStmt = nullptr;
1661     if (auto BE = CurPoint.getAs<BlockEdge>()) {
1662       CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1663     } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1664       const Stmt *CurStmt = SP->getStmt();
1665       if (!CurStmt->getBeginLoc().isMacroID())
1666         return nullptr;
1667 
1668       CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1669       CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
1670     } else {
1671       return nullptr;
1672     }
1673 
1674     if (!CurTerminatorStmt)
1675       return nullptr;
1676 
1677     SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1678     if (TerminatorLoc.isMacroID()) {
1679       SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1680 
1681       // Suppress reports unless we are in that same macro.
1682       if (!BugLoc.isMacroID() ||
1683           getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1684         BR.markInvalid("Suppress Macro IDC", CurLC);
1685       }
1686       return nullptr;
1687     }
1688   }
1689   return nullptr;
1690 }
1691 
1692 //===----------------------------------------------------------------------===//
1693 // TrackControlDependencyCondBRVisitor.
1694 //===----------------------------------------------------------------------===//
1695 
1696 namespace {
1697 /// Tracks the expressions that are a control dependency of the node that was
1698 /// supplied to the constructor.
1699 /// For example:
1700 ///
1701 ///   cond = 1;
1702 ///   if (cond)
1703 ///     10 / 0;
1704 ///
1705 /// An error is emitted at line 3. This visitor realizes that the branch
1706 /// on line 2 is a control dependency of line 3, and tracks it's condition via
1707 /// trackExpressionValue().
1708 class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
1709   const ExplodedNode *Origin;
1710   ControlDependencyCalculator ControlDeps;
1711   llvm::SmallSet<const CFGBlock *, 32> VisitedBlocks;
1712 
1713 public:
1714   TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
1715   : Origin(O), ControlDeps(&O->getCFG()) {}
1716 
1717   void Profile(llvm::FoldingSetNodeID &ID) const override {
1718     static int x = 0;
1719     ID.AddPointer(&x);
1720   }
1721 
1722   PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1723                                    BugReporterContext &BRC,
1724                                    PathSensitiveBugReport &BR) override;
1725 };
1726 } // end of anonymous namespace
1727 
1728 static std::shared_ptr<PathDiagnosticEventPiece>
1729 constructDebugPieceForTrackedCondition(const Expr *Cond,
1730                                        const ExplodedNode *N,
1731                                        BugReporterContext &BRC) {
1732 
1733   if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE ||
1734       !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
1735     return nullptr;
1736 
1737   std::string ConditionText = Lexer::getSourceText(
1738       CharSourceRange::getTokenRange(Cond->getSourceRange()),
1739                                      BRC.getSourceManager(),
1740                                      BRC.getASTContext().getLangOpts());
1741 
1742   return std::make_shared<PathDiagnosticEventPiece>(
1743       PathDiagnosticLocation::createBegin(
1744           Cond, BRC.getSourceManager(), N->getLocationContext()),
1745           (Twine() + "Tracking condition '" + ConditionText + "'").str());
1746 }
1747 
1748 static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context) {
1749   if (B->succ_size() != 2)
1750     return false;
1751 
1752   const CFGBlock *Then = B->succ_begin()->getReachableBlock();
1753   const CFGBlock *Else = (B->succ_begin() + 1)->getReachableBlock();
1754 
1755   if (!Then || !Else)
1756     return false;
1757 
1758   if (Then->isInevitablySinking() != Else->isInevitablySinking())
1759     return true;
1760 
1761   // For the following condition the following CFG would be built:
1762   //
1763   //                          ------------->
1764   //                         /              \
1765   //                       [B1] -> [B2] -> [B3] -> [sink]
1766   // assert(A && B || C);            \       \
1767   //                                  -----------> [go on with the execution]
1768   //
1769   // It so happens that CFGBlock::getTerminatorCondition returns 'A' for block
1770   // B1, 'A && B' for B2, and 'A && B || C' for B3. Let's check whether we
1771   // reached the end of the condition!
1772   if (const Stmt *ElseCond = Else->getTerminatorCondition())
1773     if (const auto *BinOp = dyn_cast<BinaryOperator>(ElseCond))
1774       if (BinOp->isLogicalOp())
1775         return isAssertlikeBlock(Else, Context);
1776 
1777   return false;
1778 }
1779 
1780 PathDiagnosticPieceRef
1781 TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
1782                                                BugReporterContext &BRC,
1783                                                PathSensitiveBugReport &BR) {
1784   // We can only reason about control dependencies within the same stack frame.
1785   if (Origin->getStackFrame() != N->getStackFrame())
1786     return nullptr;
1787 
1788   CFGBlock *NB = const_cast<CFGBlock *>(N->getCFGBlock());
1789 
1790   // Skip if we already inspected this block.
1791   if (!VisitedBlocks.insert(NB).second)
1792     return nullptr;
1793 
1794   CFGBlock *OriginB = const_cast<CFGBlock *>(Origin->getCFGBlock());
1795 
1796   // TODO: Cache CFGBlocks for each ExplodedNode.
1797   if (!OriginB || !NB)
1798     return nullptr;
1799 
1800   if (isAssertlikeBlock(NB, BRC.getASTContext()))
1801     return nullptr;
1802 
1803   if (ControlDeps.isControlDependent(OriginB, NB)) {
1804     // We don't really want to explain for range loops. Evidence suggests that
1805     // the only thing that leads to is the addition of calls to operator!=.
1806     if (llvm::isa_and_nonnull<CXXForRangeStmt>(NB->getTerminatorStmt()))
1807       return nullptr;
1808 
1809     if (const Expr *Condition = NB->getLastCondition()) {
1810       // Keeping track of the already tracked conditions on a visitor level
1811       // isn't sufficient, because a new visitor is created for each tracked
1812       // expression, hence the BugReport level set.
1813       if (BR.addTrackedCondition(N)) {
1814         bugreporter::trackExpressionValue(
1815             N, Condition, BR, bugreporter::TrackingKind::Condition,
1816             /*EnableNullFPSuppression=*/false);
1817         return constructDebugPieceForTrackedCondition(Condition, N, BRC);
1818       }
1819     }
1820   }
1821 
1822   return nullptr;
1823 }
1824 
1825 //===----------------------------------------------------------------------===//
1826 // Implementation of trackExpressionValue.
1827 //===----------------------------------------------------------------------===//
1828 
1829 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1830                                                      const ExplodedNode *N) {
1831   if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1832     if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1833       if (!VD->getType()->isReferenceType())
1834         return nullptr;
1835       ProgramStateManager &StateMgr = N->getState()->getStateManager();
1836       MemRegionManager &MRMgr = StateMgr.getRegionManager();
1837       return MRMgr.getVarRegion(VD, N->getLocationContext());
1838     }
1839   }
1840 
1841   // FIXME: This does not handle other kinds of null references,
1842   // for example, references from FieldRegions:
1843   //   struct Wrapper { int &ref; };
1844   //   Wrapper w = { *(int *)0 };
1845   //   w.ref = 1;
1846 
1847   return nullptr;
1848 }
1849 
1850 /// \return A subexpression of {@code Ex} which represents the
1851 /// expression-of-interest.
1852 static const Expr *peelOffOuterExpr(const Expr *Ex,
1853                                     const ExplodedNode *N) {
1854   Ex = Ex->IgnoreParenCasts();
1855   if (const auto *FE = dyn_cast<FullExpr>(Ex))
1856     return peelOffOuterExpr(FE->getSubExpr(), N);
1857   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1858     return peelOffOuterExpr(OVE->getSourceExpr(), N);
1859   if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1860     const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1861     if (PropRef && PropRef->isMessagingGetter()) {
1862       const Expr *GetterMessageSend =
1863           POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1864       assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1865       return peelOffOuterExpr(GetterMessageSend, N);
1866     }
1867   }
1868 
1869   // Peel off the ternary operator.
1870   if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1871     // Find a node where the branching occurred and find out which branch
1872     // we took (true/false) by looking at the ExplodedGraph.
1873     const ExplodedNode *NI = N;
1874     do {
1875       ProgramPoint ProgPoint = NI->getLocation();
1876       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1877         const CFGBlock *srcBlk = BE->getSrc();
1878         if (const Stmt *term = srcBlk->getTerminatorStmt()) {
1879           if (term == CO) {
1880             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1881             if (TookTrueBranch)
1882               return peelOffOuterExpr(CO->getTrueExpr(), N);
1883             else
1884               return peelOffOuterExpr(CO->getFalseExpr(), N);
1885           }
1886         }
1887       }
1888       NI = NI->getFirstPred();
1889     } while (NI);
1890   }
1891 
1892   if (auto *BO = dyn_cast<BinaryOperator>(Ex))
1893     if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1894       return peelOffOuterExpr(SubEx, N);
1895 
1896   if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
1897     if (UO->getOpcode() == UO_LNot)
1898       return peelOffOuterExpr(UO->getSubExpr(), N);
1899 
1900     // FIXME: There's a hack in our Store implementation that always computes
1901     // field offsets around null pointers as if they are always equal to 0.
1902     // The idea here is to report accesses to fields as null dereferences
1903     // even though the pointer value that's being dereferenced is actually
1904     // the offset of the field rather than exactly 0.
1905     // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1906     // This code interacts heavily with this hack; otherwise the value
1907     // would not be null at all for most fields, so we'd be unable to track it.
1908     if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
1909       if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
1910         return peelOffOuterExpr(DerefEx, N);
1911   }
1912 
1913   return Ex;
1914 }
1915 
1916 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1917 /// was computed.
1918 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1919                                                  const Expr *Inner) {
1920   while (N) {
1921     if (N->getStmtForDiagnostics() == Inner)
1922       return N;
1923     N = N->getFirstPred();
1924   }
1925   return N;
1926 }
1927 
1928 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
1929                                        const Expr *E,
1930                                        PathSensitiveBugReport &report,
1931                                        bugreporter::TrackingKind TKind,
1932                                        bool EnableNullFPSuppression) {
1933 
1934   if (!E || !InputNode)
1935     return false;
1936 
1937   const Expr *Inner = peelOffOuterExpr(E, InputNode);
1938   const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
1939   if (!LVNode)
1940     return false;
1941 
1942   ProgramStateRef LVState = LVNode->getState();
1943   const StackFrameContext *SFC = LVNode->getStackFrame();
1944 
1945   // We only track expressions if we believe that they are important. Chances
1946   // are good that control dependencies to the tracking point are also improtant
1947   // because of this, let's explain why we believe control reached this point.
1948   // TODO: Shouldn't we track control dependencies of every bug location, rather
1949   // than only tracked expressions?
1950   if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions)
1951     report.addVisitor(std::make_unique<TrackControlDependencyCondBRVisitor>(
1952           InputNode));
1953 
1954   // The message send could be nil due to the receiver being nil.
1955   // At this point in the path, the receiver should be live since we are at the
1956   // message send expr. If it is nil, start tracking it.
1957   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
1958     trackExpressionValue(
1959         LVNode, Receiver, report, TKind, EnableNullFPSuppression);
1960 
1961   // Track the index if this is an array subscript.
1962   if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
1963     trackExpressionValue(
1964         LVNode, Arr->getIdx(), report, TKind, /*EnableNullFPSuppression*/false);
1965 
1966   // See if the expression we're interested refers to a variable.
1967   // If so, we can track both its contents and constraints on its value.
1968   if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1969     SVal LVal = LVNode->getSVal(Inner);
1970 
1971     const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
1972     bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1973 
1974     // If this is a C++ reference to a null pointer, we are tracking the
1975     // pointer. In addition, we should find the store at which the reference
1976     // got initialized.
1977     if (RR && !LVIsNull)
1978       if (auto KV = LVal.getAs<KnownSVal>())
1979         report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
1980             *KV, RR, EnableNullFPSuppression, TKind, SFC));
1981 
1982     // In case of C++ references, we want to differentiate between a null
1983     // reference and reference to null pointer.
1984     // If the LVal is null, check if we are dealing with null reference.
1985     // For those, we want to track the location of the reference.
1986     const MemRegion *R = (RR && LVIsNull) ? RR :
1987         LVNode->getSVal(Inner).getAsRegion();
1988 
1989     if (R) {
1990 
1991       // Mark both the variable region and its contents as interesting.
1992       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1993       report.addVisitor(
1994           std::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R), TKind));
1995 
1996       MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1997           LVNode, R, EnableNullFPSuppression, report, V);
1998 
1999       report.markInteresting(V, TKind);
2000       report.addVisitor(std::make_unique<UndefOrNullArgVisitor>(R));
2001 
2002       // If the contents are symbolic and null, find out when they became null.
2003       if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
2004         if (LVState->isNull(V).isConstrainedTrue())
2005           report.addVisitor(std::make_unique<TrackConstraintBRVisitor>(
2006               V.castAs<DefinedSVal>(), false));
2007 
2008       // Add visitor, which will suppress inline defensive checks.
2009       if (auto DV = V.getAs<DefinedSVal>())
2010         if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
2011             EnableNullFPSuppression)
2012           report.addVisitor(
2013               std::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
2014                                                                       LVNode));
2015 
2016       if (auto KV = V.getAs<KnownSVal>())
2017         report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
2018             *KV, R, EnableNullFPSuppression, TKind, SFC));
2019       return true;
2020     }
2021   }
2022 
2023   // If the expression is not an "lvalue expression", we can still
2024   // track the constraints on its contents.
2025   SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
2026 
2027   ReturnVisitor::addVisitorIfNecessary(
2028     LVNode, Inner, report, EnableNullFPSuppression, TKind);
2029 
2030   // Is it a symbolic value?
2031   if (auto L = V.getAs<loc::MemRegionVal>()) {
2032     report.addVisitor(std::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
2033 
2034     // FIXME: this is a hack for fixing a later crash when attempting to
2035     // dereference a void* pointer.
2036     // We should not try to dereference pointers at all when we don't care
2037     // what is written inside the pointer.
2038     bool CanDereference = true;
2039     if (const auto *SR = L->getRegionAs<SymbolicRegion>()) {
2040       if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
2041         CanDereference = false;
2042     } else if (L->getRegionAs<AllocaRegion>())
2043       CanDereference = false;
2044 
2045     // At this point we are dealing with the region's LValue.
2046     // However, if the rvalue is a symbolic region, we should track it as well.
2047     // Try to use the correct type when looking up the value.
2048     SVal RVal;
2049     if (ExplodedGraph::isInterestingLValueExpr(Inner))
2050       RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
2051     else if (CanDereference)
2052       RVal = LVState->getSVal(L->getRegion());
2053 
2054     if (CanDereference)
2055       if (auto KV = RVal.getAs<KnownSVal>())
2056         report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
2057             *KV, L->getRegion(), EnableNullFPSuppression, TKind, SFC));
2058 
2059     const MemRegion *RegionRVal = RVal.getAsRegion();
2060     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
2061       report.markInteresting(RegionRVal, TKind);
2062       report.addVisitor(std::make_unique<TrackConstraintBRVisitor>(
2063             loc::MemRegionVal(RegionRVal), /*assumption=*/false));
2064     }
2065   }
2066   return true;
2067 }
2068 
2069 //===----------------------------------------------------------------------===//
2070 // Implementation of NulReceiverBRVisitor.
2071 //===----------------------------------------------------------------------===//
2072 
2073 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
2074                                                  const ExplodedNode *N) {
2075   const auto *ME = dyn_cast<ObjCMessageExpr>(S);
2076   if (!ME)
2077     return nullptr;
2078   if (const Expr *Receiver = ME->getInstanceReceiver()) {
2079     ProgramStateRef state = N->getState();
2080     SVal V = N->getSVal(Receiver);
2081     if (state->isNull(V).isConstrainedTrue())
2082       return Receiver;
2083   }
2084   return nullptr;
2085 }
2086 
2087 PathDiagnosticPieceRef
2088 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2089                                 PathSensitiveBugReport &BR) {
2090   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
2091   if (!P)
2092     return nullptr;
2093 
2094   const Stmt *S = P->getStmt();
2095   const Expr *Receiver = getNilReceiver(S, N);
2096   if (!Receiver)
2097     return nullptr;
2098 
2099   llvm::SmallString<256> Buf;
2100   llvm::raw_svector_ostream OS(Buf);
2101 
2102   if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
2103     OS << "'";
2104     ME->getSelector().print(OS);
2105     OS << "' not called";
2106   }
2107   else {
2108     OS << "No method is called";
2109   }
2110   OS << " because the receiver is nil";
2111 
2112   // The receiver was nil, and hence the method was skipped.
2113   // Register a BugReporterVisitor to issue a message telling us how
2114   // the receiver was null.
2115   bugreporter::trackExpressionValue(
2116       N, Receiver, BR, bugreporter::TrackingKind::Thorough,
2117       /*EnableNullFPSuppression*/ false);
2118   // Issue a message saying that the method was skipped.
2119   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
2120                                      N->getLocationContext());
2121   return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
2122 }
2123 
2124 //===----------------------------------------------------------------------===//
2125 // Visitor that tries to report interesting diagnostics from conditions.
2126 //===----------------------------------------------------------------------===//
2127 
2128 /// Return the tag associated with this visitor.  This tag will be used
2129 /// to make all PathDiagnosticPieces created by this visitor.
2130 const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; }
2131 
2132 PathDiagnosticPieceRef
2133 ConditionBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2134                               PathSensitiveBugReport &BR) {
2135   auto piece = VisitNodeImpl(N, BRC, BR);
2136   if (piece) {
2137     piece->setTag(getTag());
2138     if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
2139       ev->setPrunable(true, /* override */ false);
2140   }
2141   return piece;
2142 }
2143 
2144 PathDiagnosticPieceRef
2145 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
2146                                   BugReporterContext &BRC,
2147                                   PathSensitiveBugReport &BR) {
2148   ProgramPoint ProgPoint = N->getLocation();
2149   const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
2150       ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
2151 
2152   // If an assumption was made on a branch, it should be caught
2153   // here by looking at the state transition.
2154   if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2155     const CFGBlock *SrcBlock = BE->getSrc();
2156     if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
2157       // If the tag of the previous node is 'Eagerly Assume...' the current
2158       // 'BlockEdge' has the same constraint information. We do not want to
2159       // report the value as it is just an assumption on the predecessor node
2160       // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
2161       const ProgramPointTag *PreviousNodeTag =
2162           N->getFirstPred()->getLocation().getTag();
2163       if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second)
2164         return nullptr;
2165 
2166       return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
2167     }
2168     return nullptr;
2169   }
2170 
2171   if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
2172     const ProgramPointTag *CurrentNodeTag = PS->getTag();
2173     if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second)
2174       return nullptr;
2175 
2176     bool TookTrue = CurrentNodeTag == Tags.first;
2177     return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
2178   }
2179 
2180   return nullptr;
2181 }
2182 
2183 PathDiagnosticPieceRef ConditionBRVisitor::VisitTerminator(
2184     const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
2185     const CFGBlock *dstBlk, PathSensitiveBugReport &R,
2186     BugReporterContext &BRC) {
2187   const Expr *Cond = nullptr;
2188 
2189   // In the code below, Term is a CFG terminator and Cond is a branch condition
2190   // expression upon which the decision is made on this terminator.
2191   //
2192   // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
2193   // and "x == 0" is the respective condition.
2194   //
2195   // Another example: in "if (x && y)", we've got two terminators and two
2196   // conditions due to short-circuit nature of operator "&&":
2197   // 1. The "if (x && y)" statement is a terminator,
2198   //    and "y" is the respective condition.
2199   // 2. Also "x && ..." is another terminator,
2200   //    and "x" is its condition.
2201 
2202   switch (Term->getStmtClass()) {
2203   // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
2204   // more tricky because there are more than two branches to account for.
2205   default:
2206     return nullptr;
2207   case Stmt::IfStmtClass:
2208     Cond = cast<IfStmt>(Term)->getCond();
2209     break;
2210   case Stmt::ConditionalOperatorClass:
2211     Cond = cast<ConditionalOperator>(Term)->getCond();
2212     break;
2213   case Stmt::BinaryOperatorClass:
2214     // When we encounter a logical operator (&& or ||) as a CFG terminator,
2215     // then the condition is actually its LHS; otherwise, we'd encounter
2216     // the parent, such as if-statement, as a terminator.
2217     const auto *BO = cast<BinaryOperator>(Term);
2218     assert(BO->isLogicalOp() &&
2219            "CFG terminator is not a short-circuit operator!");
2220     Cond = BO->getLHS();
2221     break;
2222   }
2223 
2224   Cond = Cond->IgnoreParens();
2225 
2226   // However, when we encounter a logical operator as a branch condition,
2227   // then the condition is actually its RHS, because LHS would be
2228   // the condition for the logical operator terminator.
2229   while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
2230     if (!InnerBO->isLogicalOp())
2231       break;
2232     Cond = InnerBO->getRHS()->IgnoreParens();
2233   }
2234 
2235   assert(Cond);
2236   assert(srcBlk->succ_size() == 2);
2237   const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
2238   return VisitTrueTest(Cond, BRC, R, N, TookTrue);
2239 }
2240 
2241 PathDiagnosticPieceRef
2242 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC,
2243                                   PathSensitiveBugReport &R,
2244                                   const ExplodedNode *N, bool TookTrue) {
2245   ProgramStateRef CurrentState = N->getState();
2246   ProgramStateRef PrevState = N->getFirstPred()->getState();
2247   const LocationContext *LCtx = N->getLocationContext();
2248 
2249   // If the constraint information is changed between the current and the
2250   // previous program state we assuming the newly seen constraint information.
2251   // If we cannot evaluate the condition (and the constraints are the same)
2252   // the analyzer has no information about the value and just assuming it.
2253   bool IsAssuming =
2254       !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
2255       CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef();
2256 
2257   // These will be modified in code below, but we need to preserve the original
2258   //  values in case we want to throw the generic message.
2259   const Expr *CondTmp = Cond;
2260   bool TookTrueTmp = TookTrue;
2261 
2262   while (true) {
2263     CondTmp = CondTmp->IgnoreParenCasts();
2264     switch (CondTmp->getStmtClass()) {
2265       default:
2266         break;
2267       case Stmt::BinaryOperatorClass:
2268         if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
2269                                    BRC, R, N, TookTrueTmp, IsAssuming))
2270           return P;
2271         break;
2272       case Stmt::DeclRefExprClass:
2273         if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
2274                                    BRC, R, N, TookTrueTmp, IsAssuming))
2275           return P;
2276         break;
2277       case Stmt::MemberExprClass:
2278         if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
2279                                    BRC, R, N, TookTrueTmp, IsAssuming))
2280           return P;
2281         break;
2282       case Stmt::UnaryOperatorClass: {
2283         const auto *UO = cast<UnaryOperator>(CondTmp);
2284         if (UO->getOpcode() == UO_LNot) {
2285           TookTrueTmp = !TookTrueTmp;
2286           CondTmp = UO->getSubExpr();
2287           continue;
2288         }
2289         break;
2290       }
2291     }
2292     break;
2293   }
2294 
2295   // Condition too complex to explain? Just say something so that the user
2296   // knew we've made some path decision at this point.
2297   // If it is too complex and we know the evaluation of the condition do not
2298   // repeat the note from 'BugReporter.cpp'
2299   if (!IsAssuming)
2300     return nullptr;
2301 
2302   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2303   if (!Loc.isValid() || !Loc.asLocation().isValid())
2304     return nullptr;
2305 
2306   return std::make_shared<PathDiagnosticEventPiece>(
2307       Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage);
2308 }
2309 
2310 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
2311                                       const Expr *ParentEx,
2312                                       raw_ostream &Out,
2313                                       BugReporterContext &BRC,
2314                                       PathSensitiveBugReport &report,
2315                                       const ExplodedNode *N,
2316                                       Optional<bool> &prunable,
2317                                       bool IsSameFieldName) {
2318   const Expr *OriginalExpr = Ex;
2319   Ex = Ex->IgnoreParenCasts();
2320 
2321   if (isa<GNUNullExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
2322       isa<CXXBoolLiteralExpr>(Ex) || isa<IntegerLiteral>(Ex) ||
2323       isa<FloatingLiteral>(Ex)) {
2324     // Use heuristics to determine if the expression is a macro
2325     // expanding to a literal and if so, use the macro's name.
2326     SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
2327     SourceLocation EndLoc = OriginalExpr->getEndLoc();
2328     if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
2329       const SourceManager &SM = BRC.getSourceManager();
2330       const LangOptions &LO = BRC.getASTContext().getLangOpts();
2331       if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
2332           Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
2333         CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
2334         Out << Lexer::getSourceText(R, SM, LO);
2335         return false;
2336       }
2337     }
2338   }
2339 
2340   if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
2341     const bool quotes = isa<VarDecl>(DR->getDecl());
2342     if (quotes) {
2343       Out << '\'';
2344       const LocationContext *LCtx = N->getLocationContext();
2345       const ProgramState *state = N->getState().get();
2346       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
2347                                                 LCtx).getAsRegion()) {
2348         if (report.isInteresting(R))
2349           prunable = false;
2350         else {
2351           const ProgramState *state = N->getState().get();
2352           SVal V = state->getSVal(R);
2353           if (report.isInteresting(V))
2354             prunable = false;
2355         }
2356       }
2357     }
2358     Out << DR->getDecl()->getDeclName().getAsString();
2359     if (quotes)
2360       Out << '\'';
2361     return quotes;
2362   }
2363 
2364   if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2365     QualType OriginalTy = OriginalExpr->getType();
2366     if (OriginalTy->isPointerType()) {
2367       if (IL->getValue() == 0) {
2368         Out << "null";
2369         return false;
2370       }
2371     }
2372     else if (OriginalTy->isObjCObjectPointerType()) {
2373       if (IL->getValue() == 0) {
2374         Out << "nil";
2375         return false;
2376       }
2377     }
2378 
2379     Out << IL->getValue();
2380     return false;
2381   }
2382 
2383   if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
2384     if (!IsSameFieldName)
2385       Out << "field '" << ME->getMemberDecl()->getName() << '\'';
2386     else
2387       Out << '\''
2388           << Lexer::getSourceText(
2389                  CharSourceRange::getTokenRange(Ex->getSourceRange()),
2390                  BRC.getSourceManager(), BRC.getASTContext().getLangOpts(), 0)
2391           << '\'';
2392   }
2393 
2394   return false;
2395 }
2396 
2397 PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
2398     const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
2399     PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue,
2400     bool IsAssuming) {
2401   bool shouldInvert = false;
2402   Optional<bool> shouldPrune;
2403 
2404   // Check if the field name of the MemberExprs is ambiguous. Example:
2405   // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
2406   bool IsSameFieldName = false;
2407   const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts());
2408   const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts());
2409 
2410   if (LhsME && RhsME)
2411     IsSameFieldName =
2412         LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName();
2413 
2414   SmallString<128> LhsString, RhsString;
2415   {
2416     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
2417     const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
2418                                        N, shouldPrune, IsSameFieldName);
2419     const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
2420                                        N, shouldPrune, IsSameFieldName);
2421 
2422     shouldInvert = !isVarLHS && isVarRHS;
2423   }
2424 
2425   BinaryOperator::Opcode Op = BExpr->getOpcode();
2426 
2427   if (BinaryOperator::isAssignmentOp(Op)) {
2428     // For assignment operators, all that we care about is that the LHS
2429     // evaluates to "true" or "false".
2430     return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
2431                                   TookTrue);
2432   }
2433 
2434   // For non-assignment operations, we require that we can understand
2435   // both the LHS and RHS.
2436   if (LhsString.empty() || RhsString.empty() ||
2437       !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
2438     return nullptr;
2439 
2440   // Should we invert the strings if the LHS is not a variable name?
2441   SmallString<256> buf;
2442   llvm::raw_svector_ostream Out(buf);
2443   Out << (IsAssuming ? "Assuming " : "")
2444       << (shouldInvert ? RhsString : LhsString) << " is ";
2445 
2446   // Do we need to invert the opcode?
2447   if (shouldInvert)
2448     switch (Op) {
2449       default: break;
2450       case BO_LT: Op = BO_GT; break;
2451       case BO_GT: Op = BO_LT; break;
2452       case BO_LE: Op = BO_GE; break;
2453       case BO_GE: Op = BO_LE; break;
2454     }
2455 
2456   if (!TookTrue)
2457     switch (Op) {
2458       case BO_EQ: Op = BO_NE; break;
2459       case BO_NE: Op = BO_EQ; break;
2460       case BO_LT: Op = BO_GE; break;
2461       case BO_GT: Op = BO_LE; break;
2462       case BO_LE: Op = BO_GT; break;
2463       case BO_GE: Op = BO_LT; break;
2464       default:
2465         return nullptr;
2466     }
2467 
2468   switch (Op) {
2469     case BO_EQ:
2470       Out << "equal to ";
2471       break;
2472     case BO_NE:
2473       Out << "not equal to ";
2474       break;
2475     default:
2476       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2477       break;
2478   }
2479 
2480   Out << (shouldInvert ? LhsString : RhsString);
2481   const LocationContext *LCtx = N->getLocationContext();
2482   const SourceManager &SM = BRC.getSourceManager();
2483 
2484   if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) ||
2485       isVarAnInterestingCondition(BExpr->getRHS(), N, &R))
2486     Out << WillBeUsedForACondition;
2487 
2488   // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
2489   std::string Message = Out.str();
2490   Message[0] = toupper(Message[0]);
2491 
2492   // If we know the value create a pop-up note to the value part of 'BExpr'.
2493   if (!IsAssuming) {
2494     PathDiagnosticLocation Loc;
2495     if (!shouldInvert) {
2496       if (LhsME && LhsME->getMemberLoc().isValid())
2497         Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM);
2498       else
2499         Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, LCtx);
2500     } else {
2501       if (RhsME && RhsME->getMemberLoc().isValid())
2502         Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM);
2503       else
2504         Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, LCtx);
2505     }
2506 
2507     return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
2508   }
2509 
2510   PathDiagnosticLocation Loc(Cond, SM, LCtx);
2511   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
2512   if (shouldPrune.hasValue())
2513     event->setPrunable(shouldPrune.getValue());
2514   return event;
2515 }
2516 
2517 PathDiagnosticPieceRef ConditionBRVisitor::VisitConditionVariable(
2518     StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
2519     PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) {
2520   // FIXME: If there's already a constraint tracker for this variable,
2521   // we shouldn't emit anything here (c.f. the double note in
2522   // test/Analysis/inlining/path-notes.c)
2523   SmallString<256> buf;
2524   llvm::raw_svector_ostream Out(buf);
2525   Out << "Assuming " << LhsString << " is ";
2526 
2527   if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
2528     return nullptr;
2529 
2530   const LocationContext *LCtx = N->getLocationContext();
2531   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2532 
2533   if (isVarAnInterestingCondition(CondVarExpr, N, &report))
2534     Out << WillBeUsedForACondition;
2535 
2536   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2537 
2538   if (isInterestingExpr(CondVarExpr, N, &report))
2539     event->setPrunable(false);
2540 
2541   return event;
2542 }
2543 
2544 PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
2545     const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
2546     PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
2547     bool IsAssuming) {
2548   const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
2549   if (!VD)
2550     return nullptr;
2551 
2552   SmallString<256> Buf;
2553   llvm::raw_svector_ostream Out(Buf);
2554 
2555   Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is ";
2556 
2557   if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
2558     return nullptr;
2559 
2560   const LocationContext *LCtx = N->getLocationContext();
2561 
2562   if (isVarAnInterestingCondition(DRE, N, &report))
2563     Out << WillBeUsedForACondition;
2564 
2565   // If we know the value create a pop-up note to the 'DRE'.
2566   if (!IsAssuming) {
2567     PathDiagnosticLocation Loc(DRE, BRC.getSourceManager(), LCtx);
2568     return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2569   }
2570 
2571   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2572   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2573 
2574   if (isInterestingExpr(DRE, N, &report))
2575     event->setPrunable(false);
2576 
2577   return std::move(event);
2578 }
2579 
2580 PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
2581     const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
2582     PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
2583     bool IsAssuming) {
2584   SmallString<256> Buf;
2585   llvm::raw_svector_ostream Out(Buf);
2586 
2587   Out << (IsAssuming ? "Assuming field '" : "Field '")
2588       << ME->getMemberDecl()->getName() << "' is ";
2589 
2590   if (!printValue(ME, Out, N, TookTrue, IsAssuming))
2591     return nullptr;
2592 
2593   const LocationContext *LCtx = N->getLocationContext();
2594   PathDiagnosticLocation Loc;
2595 
2596   // If we know the value create a pop-up note to the member of the MemberExpr.
2597   if (!IsAssuming && ME->getMemberLoc().isValid())
2598     Loc = PathDiagnosticLocation(ME->getMemberLoc(), BRC.getSourceManager());
2599   else
2600     Loc = PathDiagnosticLocation(Cond, BRC.getSourceManager(), LCtx);
2601 
2602   if (!Loc.isValid() || !Loc.asLocation().isValid())
2603     return nullptr;
2604 
2605   if (isVarAnInterestingCondition(ME, N, &report))
2606     Out << WillBeUsedForACondition;
2607 
2608   // If we know the value create a pop-up note.
2609   if (!IsAssuming)
2610     return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2611 
2612   auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2613   if (isInterestingExpr(ME, N, &report))
2614     event->setPrunable(false);
2615   return event;
2616 }
2617 
2618 bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
2619                                     const ExplodedNode *N, bool TookTrue,
2620                                     bool IsAssuming) {
2621   QualType Ty = CondVarExpr->getType();
2622 
2623   if (Ty->isPointerType()) {
2624     Out << (TookTrue ? "non-null" : "null");
2625     return true;
2626   }
2627 
2628   if (Ty->isObjCObjectPointerType()) {
2629     Out << (TookTrue ? "non-nil" : "nil");
2630     return true;
2631   }
2632 
2633   if (!Ty->isIntegralOrEnumerationType())
2634     return false;
2635 
2636   Optional<const llvm::APSInt *> IntValue;
2637   if (!IsAssuming)
2638     IntValue = getConcreteIntegerValue(CondVarExpr, N);
2639 
2640   if (IsAssuming || !IntValue.hasValue()) {
2641     if (Ty->isBooleanType())
2642       Out << (TookTrue ? "true" : "false");
2643     else
2644       Out << (TookTrue ? "not equal to 0" : "0");
2645   } else {
2646     if (Ty->isBooleanType())
2647       Out << (IntValue.getValue()->getBoolValue() ? "true" : "false");
2648     else
2649       Out << *IntValue.getValue();
2650   }
2651 
2652   return true;
2653 }
2654 
2655 constexpr llvm::StringLiteral ConditionBRVisitor::GenericTrueMessage;
2656 constexpr llvm::StringLiteral ConditionBRVisitor::GenericFalseMessage;
2657 
2658 bool ConditionBRVisitor::isPieceMessageGeneric(
2659     const PathDiagnosticPiece *Piece) {
2660   return Piece->getString() == GenericTrueMessage ||
2661          Piece->getString() == GenericFalseMessage;
2662 }
2663 
2664 //===----------------------------------------------------------------------===//
2665 // Implementation of LikelyFalsePositiveSuppressionBRVisitor.
2666 //===----------------------------------------------------------------------===//
2667 
2668 void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
2669     BugReporterContext &BRC, const ExplodedNode *N,
2670     PathSensitiveBugReport &BR) {
2671   // Here we suppress false positives coming from system headers. This list is
2672   // based on known issues.
2673   const AnalyzerOptions &Options = BRC.getAnalyzerOptions();
2674   const Decl *D = N->getLocationContext()->getDecl();
2675 
2676   if (AnalysisDeclContext::isInStdNamespace(D)) {
2677     // Skip reports within the 'std' namespace. Although these can sometimes be
2678     // the user's fault, we currently don't report them very well, and
2679     // Note that this will not help for any other data structure libraries, like
2680     // TR1, Boost, or llvm/ADT.
2681     if (Options.ShouldSuppressFromCXXStandardLibrary) {
2682       BR.markInvalid(getTag(), nullptr);
2683       return;
2684     } else {
2685       // If the complete 'std' suppression is not enabled, suppress reports
2686       // from the 'std' namespace that are known to produce false positives.
2687 
2688       // The analyzer issues a false use-after-free when std::list::pop_front
2689       // or std::list::pop_back are called multiple times because we cannot
2690       // reason about the internal invariants of the data structure.
2691       if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2692         const CXXRecordDecl *CD = MD->getParent();
2693         if (CD->getName() == "list") {
2694           BR.markInvalid(getTag(), nullptr);
2695           return;
2696         }
2697       }
2698 
2699       // The analyzer issues a false positive when the constructor of
2700       // std::__independent_bits_engine from algorithms is used.
2701       if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2702         const CXXRecordDecl *CD = MD->getParent();
2703         if (CD->getName() == "__independent_bits_engine") {
2704           BR.markInvalid(getTag(), nullptr);
2705           return;
2706         }
2707       }
2708 
2709       for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
2710            LCtx = LCtx->getParent()) {
2711         const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2712         if (!MD)
2713           continue;
2714 
2715         const CXXRecordDecl *CD = MD->getParent();
2716         // The analyzer issues a false positive on
2717         //   std::basic_string<uint8_t> v; v.push_back(1);
2718         // and
2719         //   std::u16string s; s += u'a';
2720         // because we cannot reason about the internal invariants of the
2721         // data structure.
2722         if (CD->getName() == "basic_string") {
2723           BR.markInvalid(getTag(), nullptr);
2724           return;
2725         }
2726 
2727         // The analyzer issues a false positive on
2728         //    std::shared_ptr<int> p(new int(1)); p = nullptr;
2729         // because it does not reason properly about temporary destructors.
2730         if (CD->getName() == "shared_ptr") {
2731           BR.markInvalid(getTag(), nullptr);
2732           return;
2733         }
2734       }
2735     }
2736   }
2737 
2738   // Skip reports within the sys/queue.h macros as we do not have the ability to
2739   // reason about data structure shapes.
2740   const SourceManager &SM = BRC.getSourceManager();
2741   FullSourceLoc Loc = BR.getLocation().asLocation();
2742   while (Loc.isMacroID()) {
2743     Loc = Loc.getSpellingLoc();
2744     if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2745       BR.markInvalid(getTag(), nullptr);
2746       return;
2747     }
2748   }
2749 }
2750 
2751 //===----------------------------------------------------------------------===//
2752 // Implementation of UndefOrNullArgVisitor.
2753 //===----------------------------------------------------------------------===//
2754 
2755 PathDiagnosticPieceRef
2756 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2757                                  PathSensitiveBugReport &BR) {
2758   ProgramStateRef State = N->getState();
2759   ProgramPoint ProgLoc = N->getLocation();
2760 
2761   // We are only interested in visiting CallEnter nodes.
2762   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2763   if (!CEnter)
2764     return nullptr;
2765 
2766   // Check if one of the arguments is the region the visitor is tracking.
2767   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2768   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2769   unsigned Idx = 0;
2770   ArrayRef<ParmVarDecl *> parms = Call->parameters();
2771 
2772   for (const auto ParamDecl : parms) {
2773     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2774     ++Idx;
2775 
2776     // Are we tracking the argument or its subregion?
2777     if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
2778       continue;
2779 
2780     // Check the function parameter type.
2781     assert(ParamDecl && "Formal parameter has no decl?");
2782     QualType T = ParamDecl->getType();
2783 
2784     if (!(T->isAnyPointerType() || T->isReferenceType())) {
2785       // Function can only change the value passed in by address.
2786       continue;
2787     }
2788 
2789     // If it is a const pointer value, the function does not intend to
2790     // change the value.
2791     if (T->getPointeeType().isConstQualified())
2792       continue;
2793 
2794     // Mark the call site (LocationContext) as interesting if the value of the
2795     // argument is undefined or '0'/'NULL'.
2796     SVal BoundVal = State->getSVal(R);
2797     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
2798       BR.markInteresting(CEnter->getCalleeContext());
2799       return nullptr;
2800     }
2801   }
2802   return nullptr;
2803 }
2804 
2805 //===----------------------------------------------------------------------===//
2806 // Implementation of FalsePositiveRefutationBRVisitor.
2807 //===----------------------------------------------------------------------===//
2808 
2809 FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
2810     : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
2811 
2812 void FalsePositiveRefutationBRVisitor::finalizeVisitor(
2813     BugReporterContext &BRC, const ExplodedNode *EndPathNode,
2814     PathSensitiveBugReport &BR) {
2815   // Collect new constraints
2816   VisitNode(EndPathNode, BRC, BR);
2817 
2818   // Create a refutation manager
2819   llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
2820   ASTContext &Ctx = BRC.getASTContext();
2821 
2822   // Add constraints to the solver
2823   for (const auto &I : Constraints) {
2824     const SymbolRef Sym = I.first;
2825     auto RangeIt = I.second.begin();
2826 
2827     llvm::SMTExprRef Constraints = SMTConv::getRangeExpr(
2828         RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
2829         /*InRange=*/true);
2830     while ((++RangeIt) != I.second.end()) {
2831       Constraints = RefutationSolver->mkOr(
2832           Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
2833                                              RangeIt->From(), RangeIt->To(),
2834                                              /*InRange=*/true));
2835     }
2836 
2837     RefutationSolver->addConstraint(Constraints);
2838   }
2839 
2840   // And check for satisfiability
2841   Optional<bool> isSat = RefutationSolver->check();
2842   if (!isSat.hasValue())
2843     return;
2844 
2845   if (!isSat.getValue())
2846     BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
2847 }
2848 
2849 PathDiagnosticPieceRef FalsePositiveRefutationBRVisitor::VisitNode(
2850     const ExplodedNode *N, BugReporterContext &, PathSensitiveBugReport &) {
2851   // Collect new constraints
2852   const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
2853   ConstraintRangeTy::Factory &CF =
2854       N->getState()->get_context<ConstraintRange>();
2855 
2856   // Add constraints if we don't have them yet
2857   for (auto const &C : NewCs) {
2858     const SymbolRef &Sym = C.first;
2859     if (!Constraints.contains(Sym)) {
2860       Constraints = CF.add(Constraints, Sym, C.second);
2861     }
2862   }
2863 
2864   return nullptr;
2865 }
2866 
2867 void FalsePositiveRefutationBRVisitor::Profile(
2868     llvm::FoldingSetNodeID &ID) const {
2869   static int Tag = 0;
2870   ID.AddPointer(&Tag);
2871 }
2872 
2873 //===----------------------------------------------------------------------===//
2874 // Implementation of TagVisitor.
2875 //===----------------------------------------------------------------------===//
2876 
2877 int NoteTag::Kind = 0;
2878 
2879 void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
2880   static int Tag = 0;
2881   ID.AddPointer(&Tag);
2882 }
2883 
2884 PathDiagnosticPieceRef TagVisitor::VisitNode(const ExplodedNode *N,
2885                                              BugReporterContext &BRC,
2886                                              PathSensitiveBugReport &R) {
2887   ProgramPoint PP = N->getLocation();
2888   const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
2889   if (!T)
2890     return nullptr;
2891 
2892   if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
2893     PathDiagnosticLocation Loc =
2894         PathDiagnosticLocation::create(PP, BRC.getSourceManager());
2895     auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
2896     Piece->setPrunable(T->isPrunable());
2897     return Piece;
2898   }
2899 
2900   return nullptr;
2901 }
2902