]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.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 0;
49   E = E->IgnoreParenCasts();
50
51   while (true) {
52     if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
53       assert(B->isAssignmentOp());
54       E = B->getLHS()->IgnoreParenCasts();
55       continue;
56     }
57     else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
58       if (U->getOpcode() == UO_Deref)
59         return U->getSubExpr()->IgnoreParenCasts();
60     }
61     else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
62       if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
63         return ME->getBase()->IgnoreParenCasts();
64       } 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 NULL;
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 NULL;
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 NULL;
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 0;
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   llvm::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   virtual void Profile(llvm::FoldingSetNodeID &ID) const {
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 0;
241
242     Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
243     if (!SP)
244       return 0;
245
246     const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
247     if (!Ret)
248       return 0;
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 0;
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 0;
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 0;
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 0;
347
348     if (CE->getCalleeContext() != StackFrame)
349       return 0;
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 0;
384   }
385
386   PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
387                                  const ExplodedNode *PrevN,
388                                  BugReporterContext &BRC,
389                                  BugReport &BR) {
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 0;
397     }
398
399     llvm_unreachable("Invalid visit mode!");
400   }
401
402   PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
403                                   const ExplodedNode *N,
404                                   BugReport &BR) {
405     if (EnableNullFPSuppression)
406       BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
407     return 0;
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 NULL;
457
458   const ExplodedNode *StoreSite = 0;
459   const Expr *InitE = 0;
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 NULL;
488
489     if (Pred->getState()->getSVal(R) == V) {
490       Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
491       if (!PS || PS->getLocationValue() != R)
492         return NULL;
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 NULL;
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() || V.getAs<loc::ConcreteInt>()) {
536       if (!IsParam)
537         InitE = InitE->IgnoreParenCasts();
538       bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
539                                          EnableNullFPSuppression);
540     } else {
541       ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
542                                            BR, EnableNullFPSuppression);
543     }
544   }
545
546   // Okay, we've found the binding. Emit an appropriate message.
547   SmallString<256> sbuf;
548   llvm::raw_svector_ostream os(sbuf);
549
550   if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
551     const Stmt *S = PS->getStmt();
552     const char *action = 0;
553     const DeclStmt *DS = dyn_cast<DeclStmt>(S);
554     const VarRegion *VR = dyn_cast<VarRegion>(R);
555
556     if (DS) {
557       action = R->canPrintPretty() ? "initialized to " :
558                                      "Initializing to ";
559     } else if (isa<BlockExpr>(S)) {
560       action = R->canPrintPretty() ? "captured by block as " :
561                                      "Captured by block as ";
562       if (VR) {
563         // See if we can get the BlockVarRegion.
564         ProgramStateRef State = StoreSite->getState();
565         SVal V = State->getSVal(S, PS->getLocationContext());
566         if (const BlockDataRegion *BDR =
567               dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
568           if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
569             if (Optional<KnownSVal> KV =
570                 State->getSVal(OriginalR).getAs<KnownSVal>())
571               BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR,
572                                                       EnableNullFPSuppression));
573           }
574         }
575       }
576     }
577
578     if (action) {
579       if (R->canPrintPretty()) {
580         R->printPretty(os);
581         os << " ";
582       }
583
584       if (V.getAs<loc::ConcreteInt>()) {
585         bool b = false;
586         if (R->isBoundable()) {
587           if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
588             if (TR->getValueType()->isObjCObjectPointerType()) {
589               os << action << "nil";
590               b = true;
591             }
592           }
593         }
594
595         if (!b)
596           os << action << "a null pointer value";
597       } else if (Optional<nonloc::ConcreteInt> CVal =
598                      V.getAs<nonloc::ConcreteInt>()) {
599         os << action << CVal->getValue();
600       }
601       else if (DS) {
602         if (V.isUndef()) {
603           if (isa<VarRegion>(R)) {
604             const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
605             if (VD->getInit()) {
606               os << (R->canPrintPretty() ? "initialized" : "Initializing")
607                  << " to a garbage value";
608             } else {
609               os << (R->canPrintPretty() ? "declared" : "Declaring")
610                  << " without an initial value";
611             }
612           }
613         }
614         else {
615           os << (R->canPrintPretty() ? "initialized" : "Initialized")
616              << " here";
617         }
618       }
619     }
620   } else if (StoreSite->getLocation().getAs<CallEnter>()) {
621     if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
622       const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
623
624       os << "Passing ";
625
626       if (V.getAs<loc::ConcreteInt>()) {
627         if (Param->getType()->isObjCObjectPointerType())
628           os << "nil object reference";
629         else
630           os << "null pointer value";
631       } else if (V.isUndef()) {
632         os << "uninitialized value";
633       } else if (Optional<nonloc::ConcreteInt> CI =
634                      V.getAs<nonloc::ConcreteInt>()) {
635         os << "the value " << CI->getValue();
636       } else {
637         os << "value";
638       }
639
640       // Printed parameter indexes are 1-based, not 0-based.
641       unsigned Idx = Param->getFunctionScopeIndex() + 1;
642       os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
643       if (R->canPrintPretty()) {
644         os << " ";
645         R->printPretty(os);
646       }
647     }
648   }
649
650   if (os.str().empty()) {
651     if (V.getAs<loc::ConcreteInt>()) {
652       bool b = false;
653       if (R->isBoundable()) {
654         if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
655           if (TR->getValueType()->isObjCObjectPointerType()) {
656             os << "nil object reference stored";
657             b = true;
658           }
659         }
660       }
661       if (!b) {
662         if (R->canPrintPretty())
663           os << "Null pointer value stored";
664         else
665           os << "Storing null pointer value";
666       }
667
668     } else if (V.isUndef()) {
669       if (R->canPrintPretty())
670         os << "Uninitialized value stored";
671       else
672         os << "Storing uninitialized value";
673
674     } else if (Optional<nonloc::ConcreteInt> CV =
675                    V.getAs<nonloc::ConcreteInt>()) {
676       if (R->canPrintPretty())
677         os << "The value " << CV->getValue() << " is assigned";
678       else
679         os << "Assigning " << CV->getValue();
680
681     } else {
682       if (R->canPrintPretty())
683         os << "Value assigned";
684       else
685         os << "Assigning value";
686     }
687     
688     if (R->canPrintPretty()) {
689       os << " to ";
690       R->printPretty(os);
691     }
692   }
693
694   // Construct a new PathDiagnosticPiece.
695   ProgramPoint P = StoreSite->getLocation();
696   PathDiagnosticLocation L;
697   if (P.getAs<CallEnter>() && InitE)
698     L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
699                                P.getLocationContext());
700   else
701     L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
702   if (!L.isValid())
703     return NULL;
704   return new PathDiagnosticEventPiece(L, os.str());
705 }
706
707 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
708   static int tag = 0;
709   ID.AddPointer(&tag);
710   ID.AddBoolean(Assumption);
711   ID.Add(Constraint);
712 }
713
714 /// Return the tag associated with this visitor.  This tag will be used
715 /// to make all PathDiagnosticPieces created by this visitor.
716 const char *TrackConstraintBRVisitor::getTag() {
717   return "TrackConstraintBRVisitor";
718 }
719
720 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
721   if (IsZeroCheck)
722     return N->getState()->isNull(Constraint).isUnderconstrained();
723   return N->getState()->assume(Constraint, !Assumption);
724 }
725
726 PathDiagnosticPiece *
727 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
728                                     const ExplodedNode *PrevN,
729                                     BugReporterContext &BRC,
730                                     BugReport &BR) {
731   if (IsSatisfied)
732     return NULL;
733
734   // Start tracking after we see the first state in which the value is
735   // constrained.
736   if (!IsTrackingTurnedOn)
737     if (!isUnderconstrained(N))
738       IsTrackingTurnedOn = true;
739   if (!IsTrackingTurnedOn)
740     return 0;
741
742   // Check if in the previous state it was feasible for this constraint
743   // to *not* be true.
744   if (isUnderconstrained(PrevN)) {
745
746     IsSatisfied = true;
747
748     // As a sanity check, make sure that the negation of the constraint
749     // was infeasible in the current state.  If it is feasible, we somehow
750     // missed the transition point.
751     assert(!isUnderconstrained(N));
752
753     // We found the transition point for the constraint.  We now need to
754     // pretty-print the constraint. (work-in-progress)
755     SmallString<64> sbuf;
756     llvm::raw_svector_ostream os(sbuf);
757
758     if (Constraint.getAs<Loc>()) {
759       os << "Assuming pointer value is ";
760       os << (Assumption ? "non-null" : "null");
761     }
762
763     if (os.str().empty())
764       return NULL;
765
766     // Construct a new PathDiagnosticPiece.
767     ProgramPoint P = N->getLocation();
768     PathDiagnosticLocation L =
769       PathDiagnosticLocation::create(P, BRC.getSourceManager());
770     if (!L.isValid())
771       return NULL;
772     
773     PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
774     X->setTag(getTag());
775     return X;
776   }
777
778   return NULL;
779 }
780
781 SuppressInlineDefensiveChecksVisitor::
782 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
783   : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
784
785     // Check if the visitor is disabled.
786     SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
787     assert(Eng && "Cannot file a bug report without an owning engine");
788     AnalyzerOptions &Options = Eng->getAnalysisManager().options;
789     if (!Options.shouldSuppressInlinedDefensiveChecks())
790       IsSatisfied = true;
791
792     assert(N->getState()->isNull(V).isConstrainedTrue() &&
793            "The visitor only tracks the cases where V is constrained to 0");
794 }
795
796 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
797   static int id = 0;
798   ID.AddPointer(&id);
799   ID.Add(V);
800 }
801
802 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
803   return "IDCVisitor";
804 }
805
806 PathDiagnosticPiece *
807 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
808                                                 const ExplodedNode *Pred,
809                                                 BugReporterContext &BRC,
810                                                 BugReport &BR) {
811   if (IsSatisfied)
812     return 0;
813
814   // Start tracking after we see the first state in which the value is null.
815   if (!IsTrackingTurnedOn)
816     if (Succ->getState()->isNull(V).isConstrainedTrue())
817       IsTrackingTurnedOn = true;
818   if (!IsTrackingTurnedOn)
819     return 0;
820
821   // Check if in the previous state it was feasible for this value
822   // to *not* be null.
823   if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
824     IsSatisfied = true;
825
826     assert(Succ->getState()->isNull(V).isConstrainedTrue());
827
828     // Check if this is inlined defensive checks.
829     const LocationContext *CurLC =Succ->getLocationContext();
830     const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
831     if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
832       BR.markInvalid("Suppress IDC", CurLC);
833   }
834   return 0;
835 }
836
837 static const MemRegion *getLocationRegionIfReference(const Expr *E,
838                                                      const ExplodedNode *N) {
839   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
840     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
841       if (!VD->getType()->isReferenceType())
842         return 0;
843       ProgramStateManager &StateMgr = N->getState()->getStateManager();
844       MemRegionManager &MRMgr = StateMgr.getRegionManager();
845       return MRMgr.getVarRegion(VD, N->getLocationContext());
846     }
847   }
848
849   // FIXME: This does not handle other kinds of null references,
850   // for example, references from FieldRegions:
851   //   struct Wrapper { int &ref; };
852   //   Wrapper w = { *(int *)0 };
853   //   w.ref = 1;
854
855   return 0;
856 }
857
858 static const Expr *peelOffOuterExpr(const Expr *Ex,
859                                     const ExplodedNode *N) {
860   Ex = Ex->IgnoreParenCasts();
861   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
862     return peelOffOuterExpr(EWC->getSubExpr(), N);
863   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
864     return peelOffOuterExpr(OVE->getSourceExpr(), N);
865
866   // Peel off the ternary operator.
867   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
868     // Find a node where the branching occured and find out which branch
869     // we took (true/false) by looking at the ExplodedGraph.
870     const ExplodedNode *NI = N;
871     do {
872       ProgramPoint ProgPoint = NI->getLocation();
873       if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
874         const CFGBlock *srcBlk = BE->getSrc();
875         if (const Stmt *term = srcBlk->getTerminator()) {
876           if (term == CO) {
877             bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
878             if (TookTrueBranch)
879               return peelOffOuterExpr(CO->getTrueExpr(), N);
880             else
881               return peelOffOuterExpr(CO->getFalseExpr(), N);
882           }
883         }
884       }
885       NI = NI->getFirstPred();
886     } while (NI);
887   }
888   return Ex;
889 }
890
891 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
892                                         const Stmt *S,
893                                         BugReport &report, bool IsArg,
894                                         bool EnableNullFPSuppression) {
895   if (!S || !N)
896     return false;
897
898   if (const Expr *Ex = dyn_cast<Expr>(S)) {
899     Ex = Ex->IgnoreParenCasts();
900     const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
901     if (Ex != PeeledEx)
902       S = PeeledEx;
903   }
904
905   const Expr *Inner = 0;
906   if (const Expr *Ex = dyn_cast<Expr>(S)) {
907     Ex = Ex->IgnoreParenCasts();
908     if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
909       Inner = Ex;
910   }
911
912   if (IsArg && !Inner) {
913     assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
914   } else {
915     // Walk through nodes until we get one that matches the statement exactly.
916     // Alternately, if we hit a known lvalue for the statement, we know we've
917     // gone too far (though we can likely track the lvalue better anyway).
918     do {
919       const ProgramPoint &pp = N->getLocation();
920       if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
921         if (ps->getStmt() == S || ps->getStmt() == Inner)
922           break;
923       } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
924         if (CEE->getCalleeContext()->getCallSite() == S ||
925             CEE->getCalleeContext()->getCallSite() == Inner)
926           break;
927       }
928       N = N->getFirstPred();
929     } while (N);
930
931     if (!N)
932       return false;
933   }
934   
935   ProgramStateRef state = N->getState();
936
937   // The message send could be nil due to the receiver being nil.
938   // At this point in the path, the receiver should be live since we are at the
939   // message send expr. If it is nil, start tracking it.
940   if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
941     trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
942
943
944   // See if the expression we're interested refers to a variable.
945   // If so, we can track both its contents and constraints on its value.
946   if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
947     const MemRegion *R = 0;
948
949     // Find the ExplodedNode where the lvalue (the value of 'Ex')
950     // was computed.  We need this for getting the location value.
951     const ExplodedNode *LVNode = N;
952     while (LVNode) {
953       if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
954         if (P->getStmt() == Inner)
955           break;
956       }
957       LVNode = LVNode->getFirstPred();
958     }
959     assert(LVNode && "Unable to find the lvalue node.");
960     ProgramStateRef LVState = LVNode->getState();
961     SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
962     
963     if (LVState->isNull(LVal).isConstrainedTrue()) {
964       // In case of C++ references, we want to differentiate between a null
965       // reference and reference to null pointer.
966       // If the LVal is null, check if we are dealing with null reference.
967       // For those, we want to track the location of the reference.
968       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
969         R = RR;
970     } else {
971       R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
972
973       // If this is a C++ reference to a null pointer, we are tracking the
974       // pointer. In additon, we should find the store at which the reference
975       // got initialized.
976       if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
977         if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
978           report.addVisitor(new FindLastStoreBRVisitor(*KV, RR,
979                                                       EnableNullFPSuppression));
980       }
981     }
982
983     if (R) {
984       // Mark both the variable region and its contents as interesting.
985       SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
986
987       report.markInteresting(R);
988       report.markInteresting(V);
989       report.addVisitor(new UndefOrNullArgVisitor(R));
990
991       // If the contents are symbolic, find out when they became null.
992       if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true)) {
993         BugReporterVisitor *ConstraintTracker =
994           new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
995         report.addVisitor(ConstraintTracker);
996
997         // Add visitor, which will suppress inline defensive checks.
998         if (LVState->isNull(V).isConstrainedTrue() &&
999             EnableNullFPSuppression) {
1000           BugReporterVisitor *IDCSuppressor =
1001             new SuppressInlineDefensiveChecksVisitor(V.castAs<DefinedSVal>(),
1002                                                      LVNode);
1003           report.addVisitor(IDCSuppressor);
1004         }
1005       }
1006
1007       if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1008         report.addVisitor(new FindLastStoreBRVisitor(*KV, R,
1009                                                      EnableNullFPSuppression));
1010       return true;
1011     }
1012   }
1013
1014   // If the expression is not an "lvalue expression", we can still
1015   // track the constraints on its contents.
1016   SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1017
1018   // If the value came from an inlined function call, we should at least make
1019   // sure that function isn't pruned in our output.
1020   if (const Expr *E = dyn_cast<Expr>(S))
1021     S = E->IgnoreParenCasts();
1022
1023   ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1024
1025   // Uncomment this to find cases where we aren't properly getting the
1026   // base value that was dereferenced.
1027   // assert(!V.isUnknownOrUndef());
1028   // Is it a symbolic value?
1029   if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1030     // At this point we are dealing with the region's LValue.
1031     // However, if the rvalue is a symbolic region, we should track it as well.
1032     // Try to use the correct type when looking up the value.
1033     SVal RVal;
1034     if (const Expr *E = dyn_cast<Expr>(S))
1035       RVal = state->getRawSVal(L.getValue(), E->getType());
1036     else
1037       RVal = state->getSVal(L->getRegion());
1038
1039     const MemRegion *RegionRVal = RVal.getAsRegion();
1040     report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
1041
1042     if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1043       report.markInteresting(RegionRVal);
1044       report.addVisitor(new TrackConstraintBRVisitor(
1045         loc::MemRegionVal(RegionRVal), false));
1046     }
1047   }
1048
1049   return true;
1050 }
1051
1052 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1053                                                  const ExplodedNode *N) {
1054   const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1055   if (!ME)
1056     return 0;
1057   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1058     ProgramStateRef state = N->getState();
1059     SVal V = state->getSVal(Receiver, N->getLocationContext());
1060     if (state->isNull(V).isConstrainedTrue())
1061       return Receiver;
1062   }
1063   return 0;
1064 }
1065
1066 PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1067                                                      const ExplodedNode *PrevN,
1068                                                      BugReporterContext &BRC,
1069                                                      BugReport &BR) {
1070   Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1071   if (!P)
1072     return 0;
1073
1074   const Stmt *S = P->getStmt();
1075   const Expr *Receiver = getNilReceiver(S, N);
1076   if (!Receiver)
1077     return 0;
1078
1079   llvm::SmallString<256> Buf;
1080   llvm::raw_svector_ostream OS(Buf);
1081
1082   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1083     OS << "'" << ME->getSelector().getAsString() << "' not called";
1084   }
1085   else {
1086     OS << "No method is called";
1087   }
1088   OS << " because the receiver is nil";
1089
1090   // The receiver was nil, and hence the method was skipped.
1091   // Register a BugReporterVisitor to issue a message telling us how
1092   // the receiver was null.
1093   bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1094                                      /*EnableNullFPSuppression*/ false);
1095   // Issue a message saying that the method was skipped.
1096   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1097                                      N->getLocationContext());
1098   return new PathDiagnosticEventPiece(L, OS.str());
1099 }
1100
1101 // Registers every VarDecl inside a Stmt with a last store visitor.
1102 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1103                                                 const Stmt *S,
1104                                                 bool EnableNullFPSuppression) {
1105   const ExplodedNode *N = BR.getErrorNode();
1106   std::deque<const Stmt *> WorkList;
1107   WorkList.push_back(S);
1108
1109   while (!WorkList.empty()) {
1110     const Stmt *Head = WorkList.front();
1111     WorkList.pop_front();
1112
1113     ProgramStateRef state = N->getState();
1114     ProgramStateManager &StateMgr = state->getStateManager();
1115
1116     if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1117       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1118         const VarRegion *R =
1119         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1120
1121         // What did we load?
1122         SVal V = state->getSVal(S, N->getLocationContext());
1123
1124         if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1125           // Register a new visitor with the BugReport.
1126           BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R,
1127                                                    EnableNullFPSuppression));
1128         }
1129       }
1130     }
1131
1132     for (Stmt::const_child_iterator I = Head->child_begin();
1133         I != Head->child_end(); ++I)
1134       WorkList.push_back(*I);
1135   }
1136 }
1137
1138 //===----------------------------------------------------------------------===//
1139 // Visitor that tries to report interesting diagnostics from conditions.
1140 //===----------------------------------------------------------------------===//
1141
1142 /// Return the tag associated with this visitor.  This tag will be used
1143 /// to make all PathDiagnosticPieces created by this visitor.
1144 const char *ConditionBRVisitor::getTag() {
1145   return "ConditionBRVisitor";
1146 }
1147
1148 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1149                                                    const ExplodedNode *Prev,
1150                                                    BugReporterContext &BRC,
1151                                                    BugReport &BR) {
1152   PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1153   if (piece) {
1154     piece->setTag(getTag());
1155     if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1156       ev->setPrunable(true, /* override */ false);
1157   }
1158   return piece;
1159 }
1160
1161 PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1162                                                        const ExplodedNode *Prev,
1163                                                        BugReporterContext &BRC,
1164                                                        BugReport &BR) {
1165   
1166   ProgramPoint progPoint = N->getLocation();
1167   ProgramStateRef CurrentState = N->getState();
1168   ProgramStateRef PrevState = Prev->getState();
1169   
1170   // Compare the GDMs of the state, because that is where constraints
1171   // are managed.  Note that ensure that we only look at nodes that
1172   // were generated by the analyzer engine proper, not checkers.
1173   if (CurrentState->getGDM().getRoot() ==
1174       PrevState->getGDM().getRoot())
1175     return 0;
1176   
1177   // If an assumption was made on a branch, it should be caught
1178   // here by looking at the state transition.
1179   if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1180     const CFGBlock *srcBlk = BE->getSrc();    
1181     if (const Stmt *term = srcBlk->getTerminator())
1182       return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1183     return 0;
1184   }
1185   
1186   if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1187     // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1188     // violation.
1189     const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =      
1190       cast<GRBugReporter>(BRC.getBugReporter()).
1191         getEngine().geteagerlyAssumeBinOpBifurcationTags();
1192
1193     const ProgramPointTag *tag = PS->getTag();
1194     if (tag == tags.first)
1195       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1196                            BRC, BR, N);
1197     if (tag == tags.second)
1198       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1199                            BRC, BR, N);
1200                            
1201     return 0;
1202   }
1203     
1204   return 0;
1205 }
1206
1207 PathDiagnosticPiece *
1208 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1209                                     const ExplodedNode *N,
1210                                     const CFGBlock *srcBlk,
1211                                     const CFGBlock *dstBlk,
1212                                     BugReport &R,
1213                                     BugReporterContext &BRC) {
1214   const Expr *Cond = 0;
1215   
1216   switch (Term->getStmtClass()) {
1217   default:
1218     return 0;
1219   case Stmt::IfStmtClass:
1220     Cond = cast<IfStmt>(Term)->getCond();
1221     break;
1222   case Stmt::ConditionalOperatorClass:
1223     Cond = cast<ConditionalOperator>(Term)->getCond();
1224     break;
1225   }      
1226
1227   assert(Cond);
1228   assert(srcBlk->succ_size() == 2);
1229   const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1230   return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1231 }
1232
1233 PathDiagnosticPiece *
1234 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1235                                   bool tookTrue,
1236                                   BugReporterContext &BRC,
1237                                   BugReport &R,
1238                                   const ExplodedNode *N) {
1239   
1240   const Expr *Ex = Cond;
1241   
1242   while (true) {
1243     Ex = Ex->IgnoreParenCasts();
1244     switch (Ex->getStmtClass()) {
1245       default:
1246         return 0;
1247       case Stmt::BinaryOperatorClass:
1248         return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1249                              R, N);
1250       case Stmt::DeclRefExprClass:
1251         return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1252                              R, N);
1253       case Stmt::UnaryOperatorClass: {
1254         const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1255         if (UO->getOpcode() == UO_LNot) {
1256           tookTrue = !tookTrue;
1257           Ex = UO->getSubExpr();
1258           continue;
1259         }
1260         return 0;
1261       }
1262     }
1263   }
1264 }
1265
1266 bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1267                                       BugReporterContext &BRC,
1268                                       BugReport &report,
1269                                       const ExplodedNode *N,
1270                                       Optional<bool> &prunable) {
1271   const Expr *OriginalExpr = Ex;
1272   Ex = Ex->IgnoreParenCasts();
1273
1274   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1275     const bool quotes = isa<VarDecl>(DR->getDecl());
1276     if (quotes) {
1277       Out << '\'';
1278       const LocationContext *LCtx = N->getLocationContext();
1279       const ProgramState *state = N->getState().getPtr();
1280       if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1281                                                 LCtx).getAsRegion()) {
1282         if (report.isInteresting(R))
1283           prunable = false;
1284         else {
1285           const ProgramState *state = N->getState().getPtr();
1286           SVal V = state->getSVal(R);
1287           if (report.isInteresting(V))
1288             prunable = false;
1289         }
1290       }
1291     }
1292     Out << DR->getDecl()->getDeclName().getAsString();
1293     if (quotes)
1294       Out << '\'';
1295     return quotes;
1296   }
1297   
1298   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1299     QualType OriginalTy = OriginalExpr->getType();
1300     if (OriginalTy->isPointerType()) {
1301       if (IL->getValue() == 0) {
1302         Out << "null";
1303         return false;
1304       }
1305     }
1306     else if (OriginalTy->isObjCObjectPointerType()) {
1307       if (IL->getValue() == 0) {
1308         Out << "nil";
1309         return false;
1310       }
1311     }
1312     
1313     Out << IL->getValue();
1314     return false;
1315   }
1316   
1317   return false;
1318 }
1319
1320 PathDiagnosticPiece *
1321 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1322                                   const BinaryOperator *BExpr,
1323                                   const bool tookTrue,
1324                                   BugReporterContext &BRC,
1325                                   BugReport &R,
1326                                   const ExplodedNode *N) {
1327   
1328   bool shouldInvert = false;
1329   Optional<bool> shouldPrune;
1330   
1331   SmallString<128> LhsString, RhsString;
1332   {
1333     llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1334     const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1335                                        shouldPrune);
1336     const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1337                                        shouldPrune);
1338     
1339     shouldInvert = !isVarLHS && isVarRHS;    
1340   }
1341   
1342   BinaryOperator::Opcode Op = BExpr->getOpcode();
1343
1344   if (BinaryOperator::isAssignmentOp(Op)) {
1345     // For assignment operators, all that we care about is that the LHS
1346     // evaluates to "true" or "false".
1347     return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1348                                   BRC, R, N);
1349   }
1350
1351   // For non-assignment operations, we require that we can understand
1352   // both the LHS and RHS.
1353   if (LhsString.empty() || RhsString.empty())
1354     return 0;
1355   
1356   // Should we invert the strings if the LHS is not a variable name?
1357   SmallString<256> buf;
1358   llvm::raw_svector_ostream Out(buf);
1359   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1360
1361   // Do we need to invert the opcode?
1362   if (shouldInvert)
1363     switch (Op) {
1364       default: break;
1365       case BO_LT: Op = BO_GT; break;
1366       case BO_GT: Op = BO_LT; break;
1367       case BO_LE: Op = BO_GE; break;
1368       case BO_GE: Op = BO_LE; break;
1369     }
1370
1371   if (!tookTrue)
1372     switch (Op) {
1373       case BO_EQ: Op = BO_NE; break;
1374       case BO_NE: Op = BO_EQ; break;
1375       case BO_LT: Op = BO_GE; break;
1376       case BO_GT: Op = BO_LE; break;
1377       case BO_LE: Op = BO_GT; break;
1378       case BO_GE: Op = BO_LT; break;
1379       default:
1380         return 0;
1381     }
1382   
1383   switch (Op) {
1384     case BO_EQ:
1385       Out << "equal to ";
1386       break;
1387     case BO_NE:
1388       Out << "not equal to ";
1389       break;
1390     default:
1391       Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1392       break;
1393   }
1394   
1395   Out << (shouldInvert ? LhsString : RhsString);
1396   const LocationContext *LCtx = N->getLocationContext();
1397   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1398   PathDiagnosticEventPiece *event =
1399     new PathDiagnosticEventPiece(Loc, Out.str());
1400   if (shouldPrune.hasValue())
1401     event->setPrunable(shouldPrune.getValue());
1402   return event;
1403 }
1404
1405 PathDiagnosticPiece *
1406 ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1407                                            const Expr *CondVarExpr,
1408                                            const bool tookTrue,
1409                                            BugReporterContext &BRC,
1410                                            BugReport &report,
1411                                            const ExplodedNode *N) {
1412   // FIXME: If there's already a constraint tracker for this variable,
1413   // we shouldn't emit anything here (c.f. the double note in
1414   // test/Analysis/inlining/path-notes.c)
1415   SmallString<256> buf;
1416   llvm::raw_svector_ostream Out(buf);
1417   Out << "Assuming " << LhsString << " is ";
1418   
1419   QualType Ty = CondVarExpr->getType();
1420
1421   if (Ty->isPointerType())
1422     Out << (tookTrue ? "not null" : "null");
1423   else if (Ty->isObjCObjectPointerType())
1424     Out << (tookTrue ? "not nil" : "nil");
1425   else if (Ty->isBooleanType())
1426     Out << (tookTrue ? "true" : "false");
1427   else if (Ty->isIntegralOrEnumerationType())
1428     Out << (tookTrue ? "non-zero" : "zero");
1429   else
1430     return 0;
1431
1432   const LocationContext *LCtx = N->getLocationContext();
1433   PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1434   PathDiagnosticEventPiece *event =
1435     new PathDiagnosticEventPiece(Loc, Out.str());
1436
1437   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1438     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1439       const ProgramState *state = N->getState().getPtr();
1440       if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1441         if (report.isInteresting(R))
1442           event->setPrunable(false);
1443       }
1444     }
1445   }
1446   
1447   return event;
1448 }
1449   
1450 PathDiagnosticPiece *
1451 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1452                                   const DeclRefExpr *DR,
1453                                   const bool tookTrue,
1454                                   BugReporterContext &BRC,
1455                                   BugReport &report,
1456                                   const ExplodedNode *N) {
1457
1458   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1459   if (!VD)
1460     return 0;
1461   
1462   SmallString<256> Buf;
1463   llvm::raw_svector_ostream Out(Buf);
1464     
1465   Out << "Assuming '";
1466   VD->getDeclName().printName(Out);
1467   Out << "' is ";
1468     
1469   QualType VDTy = VD->getType();
1470   
1471   if (VDTy->isPointerType())
1472     Out << (tookTrue ? "non-null" : "null");
1473   else if (VDTy->isObjCObjectPointerType())
1474     Out << (tookTrue ? "non-nil" : "nil");
1475   else if (VDTy->isScalarType())
1476     Out << (tookTrue ? "not equal to 0" : "0");
1477   else
1478     return 0;
1479   
1480   const LocationContext *LCtx = N->getLocationContext();
1481   PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1482   PathDiagnosticEventPiece *event =
1483     new PathDiagnosticEventPiece(Loc, Out.str());
1484   
1485   const ProgramState *state = N->getState().getPtr();
1486   if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1487     if (report.isInteresting(R))
1488       event->setPrunable(false);
1489     else {
1490       SVal V = state->getSVal(R);
1491       if (report.isInteresting(V))
1492         event->setPrunable(false);
1493     }
1494   }
1495   return event;
1496 }
1497
1498
1499 // FIXME: Copied from ExprEngineCallAndReturn.cpp.
1500 static bool isInStdNamespace(const Decl *D) {
1501   const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
1502   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
1503   if (!ND)
1504     return false;
1505
1506   while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
1507     ND = Parent;
1508
1509   return ND->getName() == "std";
1510 }
1511
1512
1513 PathDiagnosticPiece *
1514 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1515                                                     const ExplodedNode *N,
1516                                                     BugReport &BR) {
1517   // Here we suppress false positives coming from system headers. This list is
1518   // based on known issues.
1519
1520   // Skip reports within the 'std' namespace. Although these can sometimes be
1521   // the user's fault, we currently don't report them very well, and
1522   // Note that this will not help for any other data structure libraries, like
1523   // TR1, Boost, or llvm/ADT.
1524   ExprEngine &Eng = BRC.getBugReporter().getEngine();
1525   AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1526   if (Options.shouldSuppressFromCXXStandardLibrary()) {
1527     const LocationContext *LCtx = N->getLocationContext();
1528     if (isInStdNamespace(LCtx->getDecl())) {
1529       BR.markInvalid(getTag(), 0);
1530       return 0;
1531     }
1532   }
1533
1534   // Skip reports within the sys/queue.h macros as we do not have the ability to
1535   // reason about data structure shapes.
1536   SourceManager &SM = BRC.getSourceManager();
1537   FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1538   while (Loc.isMacroID()) {
1539     if (SM.isInSystemMacro(Loc) &&
1540        (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
1541       BR.markInvalid(getTag(), 0);
1542       return 0;
1543     }
1544     Loc = Loc.getSpellingLoc();
1545   }
1546
1547   return 0;
1548 }
1549
1550 PathDiagnosticPiece *
1551 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1552                                   const ExplodedNode *PrevN,
1553                                   BugReporterContext &BRC,
1554                                   BugReport &BR) {
1555
1556   ProgramStateRef State = N->getState();
1557   ProgramPoint ProgLoc = N->getLocation();
1558
1559   // We are only interested in visiting CallEnter nodes.
1560   Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1561   if (!CEnter)
1562     return 0;
1563
1564   // Check if one of the arguments is the region the visitor is tracking.
1565   CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1566   CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1567   unsigned Idx = 0;
1568   for (CallEvent::param_iterator I = Call->param_begin(),
1569                                  E = Call->param_end(); I != E; ++I, ++Idx) {
1570     const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1571
1572     // Are we tracking the argument or its subregion?
1573     if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1574       continue;
1575
1576     // Check the function parameter type.
1577     const ParmVarDecl *ParamDecl = *I;
1578     assert(ParamDecl && "Formal parameter has no decl?");
1579     QualType T = ParamDecl->getType();
1580
1581     if (!(T->isAnyPointerType() || T->isReferenceType())) {
1582       // Function can only change the value passed in by address.
1583       continue;
1584     }
1585     
1586     // If it is a const pointer value, the function does not intend to
1587     // change the value.
1588     if (T->getPointeeType().isConstQualified())
1589       continue;
1590
1591     // Mark the call site (LocationContext) as interesting if the value of the 
1592     // argument is undefined or '0'/'NULL'.
1593     SVal BoundVal = State->getSVal(R);
1594     if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1595       BR.markInteresting(CEnter->getCalleeContext());
1596       return 0;
1597     }
1598   }
1599   return 0;
1600 }