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