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